Skip to main content

openmls/key_packages/
key_package_in.rs

1//! Incoming KeyPackages. This modules contains deserialization and validation
2//! of KeyPackages.
3
4use crate::{
5    ciphersuite::{signable::*, *},
6    credentials::*,
7    extensions::{AnyObject, Extensions},
8    group::LeafNodeLifetimePolicy,
9    treesync::node::leaf_node::{LeafNodeIn, VerifiableLeafNode},
10    versions::ProtocolVersion,
11};
12use openmls_traits::{crypto::OpenMlsCrypto, types::Ciphersuite};
13use serde::{Deserialize, Serialize};
14use tls_codec::{
15    Serialize as TlsSerializeTrait, TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize,
16};
17
18use super::{
19    errors::KeyPackageVerifyError, InitKey, KeyPackage, KeyPackageTbs, SIGNATURE_KEY_PACKAGE_LABEL,
20};
21
22#[cfg(any(feature = "test-utils", test))]
23use super::KeyPackageBundle;
24
25/// Intermediary struct for deserialization of a [`KeyPackageIn`].
26struct VerifiableKeyPackage {
27    payload: KeyPackageTbs,
28    signature: Signature,
29}
30
31impl VerifiableKeyPackage {
32    fn new(payload: KeyPackageTbs, signature: Signature) -> Self {
33        Self { payload, signature }
34    }
35}
36
37impl Verifiable for VerifiableKeyPackage {
38    type VerifiedStruct = KeyPackage;
39
40    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
41        self.payload.tls_serialize_detached()
42    }
43
44    fn signature(&self) -> &Signature {
45        &self.signature
46    }
47
48    fn label(&self) -> &str {
49        SIGNATURE_KEY_PACKAGE_LABEL
50    }
51
52    fn verify(
53        self,
54        crypto: &impl OpenMlsCrypto,
55        pk: &OpenMlsSignaturePublicKey,
56    ) -> Result<Self::VerifiedStruct, SignatureError> {
57        self.verify_no_out(crypto, pk)?;
58
59        Ok(KeyPackage {
60            payload: self.payload,
61            signature: self.signature,
62            serialized_payload: None,
63        })
64    }
65}
66
67impl VerifiedStruct for KeyPackage {}
68
69/// The unsigned payload of a key package.
70///
71/// ```text
72/// struct {
73///     ProtocolVersion version;
74///     CipherSuite cipher_suite;
75///     HPKEPublicKey init_key;
76///     LeafNode leaf_node;
77///     Extension extensions<V>;
78/// } KeyPackageTBS;
79/// ```
80#[derive(
81    Debug,
82    Clone,
83    PartialEq,
84    TlsSize,
85    TlsSerialize,
86    TlsDeserialize,
87    TlsDeserializeBytes,
88    Serialize,
89    Deserialize,
90)]
91struct KeyPackageTbsIn {
92    protocol_version: ProtocolVersion,
93    ciphersuite: Ciphersuite,
94    init_key: InitKey,
95    leaf_node: LeafNodeIn,
96    extensions: Extensions<AnyObject>,
97}
98
99/// The key package struct.
100#[derive(
101    Debug,
102    PartialEq,
103    Clone,
104    Serialize,
105    Deserialize,
106    TlsSerialize,
107    TlsDeserialize,
108    TlsDeserializeBytes,
109    TlsSize,
110)]
111pub struct KeyPackageIn {
112    payload: KeyPackageTbsIn,
113    signature: Signature,
114}
115
116impl KeyPackageIn {
117    /// Returns a [`CredentialWithKey`] from the unverified payload
118    pub fn unverified_credential(&self) -> CredentialWithKey {
119        let credential = self.payload.leaf_node.credential().clone();
120        let signature_key = self.payload.leaf_node.signature_key().clone();
121        CredentialWithKey {
122            credential,
123            signature_key,
124        }
125    }
126
127    /// Returns the ciphersuite this key package claims, before validation.
128    pub(crate) fn unverified_ciphersuite(&self) -> Ciphersuite {
129        self.payload.ciphersuite
130    }
131
132    /// Verify that this key package is valid:
133    /// * verify that the ciphersuite is supported by the crypto provider
134    /// * verify that the signature on this key package is valid
135    /// * verify that the signature on the leaf node is valid
136    /// * verify that all extensions are supported by the leaf node
137    /// * make sure that the lifetime is valid
138    /// * make sure that the init key and the encryption key are different
139    /// * make sure that the protocol version is valid
140    ///
141    /// Returns a [`KeyPackage`] after having verified the signature or a
142    /// [`KeyPackageVerifyError`] otherwise.
143    pub fn validate(
144        self,
145        crypto: &impl OpenMlsCrypto,
146        protocol_version: ProtocolVersion,
147    ) -> Result<KeyPackage, KeyPackageVerifyError> {
148        self.validate_with_lifetime_policy(crypto, protocol_version, LeafNodeLifetimePolicy::Verify)
149    }
150
151    /// Like [`Self::validate`], but checks the lifetime under
152    /// `lifetime_policy`. [`Self::validate`] uses
153    /// [`LeafNodeLifetimePolicy::Verify`].
154    pub fn validate_with_lifetime_policy(
155        self,
156        crypto: &impl OpenMlsCrypto,
157        protocol_version: ProtocolVersion,
158        lifetime_policy: LeafNodeLifetimePolicy,
159    ) -> Result<KeyPackage, KeyPackageVerifyError> {
160        let ciphersuite = self.payload.ciphersuite;
161        crypto
162            .supports(ciphersuite)
163            .map_err(|_| KeyPackageVerifyError::UnsupportedCiphersuite(ciphersuite))?;
164
165        // We first need to verify the LeafNode inside the KeyPackage
166        let leaf_node = self.payload.leaf_node.clone().into_verifiable_leaf_node();
167
168        let signature_key = &OpenMlsSignaturePublicKey::from_signature_key(
169            self.payload.leaf_node.signature_key().clone(),
170            self.payload.ciphersuite.signature_algorithm(),
171        );
172
173        // https://validation.openmls.tech/#valn0108
174        let leaf_node = match leaf_node {
175            VerifiableLeafNode::KeyPackage(leaf_node) => leaf_node
176                .verify(crypto, signature_key)
177                .map_err(|_| KeyPackageVerifyError::InvalidLeafNodeSignature)?,
178            _ => return Err(KeyPackageVerifyError::InvalidLeafNodeSourceType),
179        };
180
181        // Verify that the protocol version is valid
182        // https://validation.openmls.tech/#valn0201
183        if !self.version_is_supported(protocol_version) {
184            return Err(KeyPackageVerifyError::InvalidProtocolVersion);
185        }
186
187        // Verify that the encryption key and the init key are different
188        // https://validation.openmls.tech/#valn0204
189        if leaf_node.encryption_key().key() == self.payload.init_key.key() {
190            return Err(KeyPackageVerifyError::InitKeyEqualsEncryptionKey);
191        }
192
193        let key_package_tbs = KeyPackageTbs {
194            protocol_version: self.payload.protocol_version,
195            ciphersuite: self.payload.ciphersuite,
196            init_key: self.payload.init_key,
197            leaf_node,
198            extensions: self.payload.extensions.try_into()?,
199        };
200
201        // Verify the KeyPackage signature
202        // https://validation.openmls.tech/#valn0203
203        let key_package = VerifiableKeyPackage::new(key_package_tbs, self.signature)
204            .verify(crypto, signature_key)
205            .map_err(|_| KeyPackageVerifyError::InvalidSignature)?;
206
207        // Extension included in the extensions or leaf_node.extensions fields
208        // MUST be included in the leaf_node.capabilities field.
209        if !key_package
210            .payload
211            .leaf_node
212            .capabilities()
213            .contains_extensions(&key_package.payload.extensions)
214        {
215            return Err(KeyPackageVerifyError::UnsupportedExtension);
216        }
217
218        #[cfg(feature = "extensions-draft")]
219        if key_package.has_malformed_last_resort_component() {
220            return Err(KeyPackageVerifyError::MalformedLastResortComponent);
221        }
222
223        // Ensure validity of the life time extension in the leaf node.
224        if let Some(life_time) = key_package.payload.leaf_node.life_time() {
225            life_time.validate_with_policy(lifetime_policy)?;
226        } else {
227            // This assumes that we only verify key packages with leaf nodes
228            // that were created for the key package.
229            return Err(KeyPackageVerifyError::MissingLifetime);
230        }
231
232        Ok(key_package)
233    }
234
235    /// Returns true if the protocol version is supported by this key package and
236    /// false otherwise.
237    pub(crate) fn version_is_supported(&self, protocol_version: ProtocolVersion) -> bool {
238        self.payload.protocol_version == protocol_version
239    }
240
241    /// Assume that the signature is valid and return the [`KeyPackage`].
242    ///
243    /// # Safety
244    ///
245    /// The caller must guarantee that the key package is verified.
246    #[cfg(feature = "unchecked-conversions")]
247    pub fn into_unchecked(self) -> KeyPackage {
248        let payload = KeyPackageTbs {
249            protocol_version: self.payload.protocol_version,
250            ciphersuite: self.payload.ciphersuite,
251            init_key: self.payload.init_key,
252            leaf_node: self.payload.leaf_node.into_unchecked(),
253            extensions: self.payload.extensions.into_unchecked(),
254        };
255        KeyPackage {
256            payload,
257            signature: self.signature,
258            serialized_payload: None,
259        }
260    }
261}
262
263#[cfg(any(feature = "test-utils", test))]
264impl From<KeyPackageTbsIn> for KeyPackageTbs {
265    fn from(value: KeyPackageTbsIn) -> Self {
266        KeyPackageTbs {
267            protocol_version: value.protocol_version,
268            ciphersuite: value.ciphersuite,
269            init_key: value.init_key,
270            leaf_node: value.leaf_node.into(),
271            extensions: value.extensions.coerce(),
272        }
273    }
274}
275
276impl From<KeyPackageTbs> for KeyPackageTbsIn {
277    fn from(value: KeyPackageTbs) -> Self {
278        Self {
279            protocol_version: value.protocol_version,
280            ciphersuite: value.ciphersuite,
281            init_key: value.init_key,
282            leaf_node: value.leaf_node.into(),
283            extensions: value.extensions.into(),
284        }
285    }
286}
287
288impl From<KeyPackage> for KeyPackageIn {
289    fn from(value: KeyPackage) -> Self {
290        Self {
291            payload: value.payload.into(),
292            signature: value.signature,
293        }
294    }
295}
296
297#[cfg(any(feature = "test-utils", test))]
298impl From<KeyPackageBundle> for KeyPackageIn {
299    fn from(value: KeyPackageBundle) -> Self {
300        Self {
301            payload: value.key_package.payload.into(),
302            signature: value.key_package.signature,
303        }
304    }
305}
306
307#[cfg(any(feature = "test-utils", test))]
308impl From<KeyPackageIn> for KeyPackage {
309    fn from(value: KeyPackageIn) -> Self {
310        Self {
311            payload: value.payload.into(),
312            signature: value.signature,
313            serialized_payload: None,
314        }
315    }
316}