Skip to main content

openmls/schedule/
psk.rs

1//! # Preshared keys.
2
3use std::borrow::Borrow;
4
5use openmls_traits::{random::OpenMlsRand, storage::StorageProvider as StorageProviderTrait};
6use serde::{Deserialize, Serialize};
7use tls_codec::{Serialize as TlsSerializeTrait, VLBytes};
8
9use super::*;
10#[cfg(feature = "extensions-draft")]
11use crate::component::ComponentId;
12use crate::{
13    group::{GroupEpoch, GroupId},
14    schedule::psk::store::ResumptionPskStore,
15    storage::{OpenMlsProvider, StorageProvider},
16};
17
18/// Resumption PSK usage.
19///
20/// ```c
21/// // draft-ietf-mls-protocol-19
22/// enum {
23///   reserved(0),
24///   application(1),
25///   reinit(2),
26///   branch(3),
27///   (255)
28/// } ResumptionPSKUsage;
29/// ```
30#[derive(
31    Clone,
32    Copy,
33    Debug,
34    PartialEq,
35    Eq,
36    PartialOrd,
37    Ord,
38    Hash,
39    Deserialize,
40    Serialize,
41    TlsDeserialize,
42    TlsDeserializeBytes,
43    TlsSerialize,
44    TlsSize,
45)]
46#[repr(u8)]
47pub enum ResumptionPskUsage {
48    /// Application.
49    Application = 1,
50    /// Resumption PSK used for group reinitialization.
51    ///
52    /// Note: "Resumption PSKs with usage `reinit` MUST NOT be used in other contexts (than reinitialization)."
53    Reinit = 2,
54    /// Resumption PSK used for subgroup branching.
55    ///
56    /// Note: "Resumption PSKs with usage `branch` MUST NOT be used in other contexts (than subgroup branching)."
57    Branch = 3,
58}
59
60/// External PSK.
61#[derive(
62    Debug,
63    PartialEq,
64    Eq,
65    PartialOrd,
66    Ord,
67    Clone,
68    Hash,
69    Deserialize,
70    Serialize,
71    TlsDeserialize,
72    TlsDeserializeBytes,
73    TlsSerialize,
74    TlsSize,
75)]
76pub struct ExternalPsk {
77    psk_id: VLBytes,
78}
79
80impl ExternalPsk {
81    /// Create a new `ExternalPsk` from a PSK ID
82    pub fn new(psk_id: Vec<u8>) -> Self {
83        Self {
84            psk_id: psk_id.into(),
85        }
86    }
87
88    /// Return the PSK ID
89    pub fn psk_id(&self) -> &[u8] {
90        self.psk_id.as_slice()
91    }
92}
93
94/// Contains the secret part of the PSK as well as the
95/// public part that is used as a marker for injection into the key schedule.
96#[derive(Serialize, Deserialize, TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize)]
97pub(crate) struct PskBundle {
98    secret: Secret,
99}
100
101/// Resumption PSK.
102#[derive(
103    Clone,
104    Debug,
105    PartialEq,
106    Eq,
107    PartialOrd,
108    Ord,
109    Deserialize,
110    Serialize,
111    TlsDeserialize,
112    TlsDeserializeBytes,
113    TlsSerialize,
114    TlsSize,
115    Hash,
116)]
117pub struct ResumptionPsk {
118    pub(crate) usage: ResumptionPskUsage,
119    pub(crate) psk_group_id: GroupId,
120    pub(crate) psk_epoch: GroupEpoch,
121}
122
123impl ResumptionPsk {
124    /// Create a new `ResumptionPsk`
125    pub fn new(usage: ResumptionPskUsage, psk_group_id: GroupId, psk_epoch: GroupEpoch) -> Self {
126        Self {
127            usage,
128            psk_group_id,
129            psk_epoch,
130        }
131    }
132
133    /// Return the usage
134    pub fn usage(&self) -> ResumptionPskUsage {
135        self.usage
136    }
137
138    /// Return the `GroupId`
139    pub fn psk_group_id(&self) -> &GroupId {
140        &self.psk_group_id
141    }
142
143    /// Return the `GroupEpoch`
144    pub fn psk_epoch(&self) -> GroupEpoch {
145        self.psk_epoch
146    }
147}
148
149/// Application PSK according to the [draft-ietf-mls-extensions]
150///
151/// [draft-ietf-mls-protocol]: https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions-09#name-pre-shared-keys-psks
152#[cfg(feature = "extensions-draft")]
153#[derive(
154    Clone,
155    Debug,
156    PartialEq,
157    Eq,
158    PartialOrd,
159    Ord,
160    Deserialize,
161    Serialize,
162    TlsDeserialize,
163    TlsDeserializeBytes,
164    TlsSerialize,
165    TlsSize,
166    Hash,
167)]
168pub struct ApplicationPsk {
169    pub(crate) component_id: ComponentId,
170    pub(crate) psk_id: VLBytes,
171}
172
173#[cfg(feature = "extensions-draft")]
174impl ApplicationPsk {
175    /// Create a new `ApplicationPsk`
176    pub fn new(component_id: ComponentId, psk_id: VLBytes) -> Self {
177        Self {
178            component_id,
179            psk_id,
180        }
181    }
182
183    /// Return the `ComponentId`
184    pub fn component_id(&self) -> ComponentId {
185        self.component_id
186    }
187
188    /// Return the `psk_id`
189    pub fn psk_id(&self) -> &[u8] {
190        self.psk_id.as_slice()
191    }
192}
193
194/// The different PSK types.
195#[derive(
196    Clone,
197    Debug,
198    PartialEq,
199    Eq,
200    PartialOrd,
201    Ord,
202    Deserialize,
203    Serialize,
204    TlsDeserialize,
205    TlsDeserializeBytes,
206    TlsSerialize,
207    TlsSize,
208    Hash,
209)]
210#[repr(u8)]
211pub enum Psk {
212    /// An external PSK provided by the application.
213    #[tls_codec(discriminant = 1)]
214    External(ExternalPsk),
215    /// A resumption PSK derived from the MLS key schedule.
216    #[tls_codec(discriminant = 2)]
217    Resumption(ResumptionPsk),
218    #[cfg(feature = "extensions-draft")]
219    /// An application component PSK.
220    #[tls_codec(discriminant = 3)]
221    Application(ApplicationPsk),
222}
223
224/// ```c
225/// // RFC 9420 and draft-ietf-mls-extensions-09
226/// enum {
227///   reserved(0),
228///   external(1),
229///   resumption(2),
230///   // draft-ietf-mls-extensions-09
231///   application(3),
232///   (255)
233/// } PSKType;
234/// ```
235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
236#[repr(u8)]
237pub enum PskType {
238    /// An external PSK.
239    External = 1,
240    /// A resumption PSK.
241    Resumption = 2,
242    #[cfg(feature = "extensions-draft")]
243    /// An application component PSK.
244    Application = 3,
245}
246
247/// A `PreSharedKeyID` is used to uniquely identify the PSKs that get injected
248/// in the key schedule.
249///
250/// ```c
251/// // draft-ietf-mls-protocol-19
252/// struct {
253///   PSKType psktype;
254///   select (PreSharedKeyID.psktype) {
255///     case external:
256///       opaque psk_id<V>;
257///
258///     case resumption:
259///       ResumptionPSKUsage usage;
260///       opaque psk_group_id<V>;
261///       uint64 psk_epoch;
262///   };
263///   opaque psk_nonce<V>;
264/// } PreSharedKeyID;
265/// ```
266#[derive(
267    Clone,
268    Debug,
269    PartialEq,
270    Eq,
271    PartialOrd,
272    Ord,
273    Deserialize,
274    Serialize,
275    TlsDeserialize,
276    TlsDeserializeBytes,
277    TlsSerialize,
278    TlsSize,
279    Hash,
280)]
281pub struct PreSharedKeyId {
282    pub(crate) psk: Psk,
283    pub(crate) psk_nonce: VLBytes,
284}
285
286impl PreSharedKeyId {
287    /// Construct a `PreSharedKeyID` with a random nonce.
288    pub fn new(
289        ciphersuite: Ciphersuite,
290        rand: &impl OpenMlsRand,
291        psk: Psk,
292    ) -> Result<Self, CryptoError> {
293        let psk_nonce = rand
294            .random_vec(ciphersuite.hash_length())
295            .map_err(|_| CryptoError::InsufficientRandomness)?
296            .into();
297
298        Ok(Self { psk, psk_nonce })
299    }
300
301    /// Construct an external `PreSharedKeyID`.
302    pub fn external(psk_id: Vec<u8>, psk_nonce: Vec<u8>) -> Self {
303        let psk = Psk::External(ExternalPsk::new(psk_id));
304
305        Self {
306            psk,
307            psk_nonce: psk_nonce.into(),
308        }
309    }
310
311    /// Construct a resumption `PreSharedKeyID`.
312    pub fn resumption(
313        usage: ResumptionPskUsage,
314        psk_group_id: GroupId,
315        psk_epoch: GroupEpoch,
316        psk_nonce: Vec<u8>,
317    ) -> Self {
318        let psk = Psk::Resumption(ResumptionPsk::new(usage, psk_group_id, psk_epoch));
319
320        Self {
321            psk,
322            psk_nonce: psk_nonce.into(),
323        }
324    }
325
326    /// Construct an application `PreSharedKeyID`.
327    #[cfg(feature = "extensions-draft")]
328    pub fn application(component_id: ComponentId, psk_id: Vec<u8>, psk_nonce: Vec<u8>) -> Self {
329        let psk = Psk::Application(ApplicationPsk::new(component_id, psk_id.into()));
330
331        Self {
332            psk,
333            psk_nonce: psk_nonce.into(),
334        }
335    }
336
337    /// Return the PSK.
338    pub fn psk(&self) -> &Psk {
339        &self.psk
340    }
341
342    /// Return the PSK nonce.
343    pub fn psk_nonce(&self) -> &[u8] {
344        self.psk_nonce.as_slice()
345    }
346
347    // ----- Key Store -----------------------------------------------------------------------------
348
349    /// Save this `PreSharedKeyId` in the keystore.
350    ///
351    /// Note: The nonce is not saved as it must be unique for each time it's being applied.
352    #[openmls_traits::maybe_async]
353    pub async fn store<Provider: OpenMlsProvider>(
354        &self,
355        provider: &Provider,
356        psk: &[u8],
357    ) -> Result<(), PskError> {
358        let psk_bundle = {
359            let secret = Secret::from_slice(psk);
360
361            PskBundle { secret }
362        };
363
364        provider
365            .storage()
366            .write_psk(&self.psk, &psk_bundle)
367            .await
368            .map_err(|_| PskError::Storage)
369    }
370
371    // ----- Validation ----------------------------------------------------------------------------
372
373    /// Checks that the nonce is of length `KDF.Nh`
374    ///
375    /// ValSem401: The nonce of a PreSharedKeyID must have length KDF.Nh
376    /// https://validation.openmls.tech/#valn0803
377    pub(crate) fn validate_nonce(&self, ciphersuite: Ciphersuite) -> Result<(), PskError> {
378        let expected_nonce_length = ciphersuite.hash_length();
379        let got_nonce_length = self.psk_nonce().len();
380
381        if expected_nonce_length != got_nonce_length {
382            return Err(PskError::NonceLengthMismatch {
383                expected: expected_nonce_length,
384                got: got_nonce_length,
385            });
386        }
387        Ok(())
388    }
389
390    /// Validates the list of PSKs in a Welcome message:
391    ///
392    /// * ValSem401 (https://validation.openmls.tech/#valn0803)
393    /// * https://validation.openmls.tech/#valn1401 (2/2)
394    pub(crate) fn validate_in_welcome(
395        psk_ids: &[PreSharedKeyId],
396        ciphersuite: Ciphersuite,
397    ) -> Result<(), PskError> {
398        let mut contained_resumption_usage: Option<ResumptionPskUsage> = None;
399        for id in psk_ids {
400            // ValSem401
401            // https://validation.openmls.tech/#valn0803
402            id.validate_nonce(ciphersuite)?;
403
404            // https://validation.openmls.tech/#valn1401 (2/2)
405            // If a PreSharedKeyID has type resumption with usage reinit or branch, verify that it is the only such PSK.
406            match id.psk() {
407                Psk::Resumption(resumption_psk) => match resumption_psk.usage {
408                    ResumptionPskUsage::Application => {
409                        return Err(PskError::UsageMismatch {
410                            allowed: vec![ResumptionPskUsage::Reinit, ResumptionPskUsage::Branch],
411                            got: resumption_psk.usage,
412                        });
413                    }
414                    ResumptionPskUsage::Reinit | ResumptionPskUsage::Branch => {
415                        if let Some(previous_usage) = contained_resumption_usage {
416                            if previous_usage == resumption_psk.usage {
417                                return Err(PskError::UsageDuplicate {
418                                    usage: previous_usage,
419                                });
420                            } else {
421                                return Err(PskError::UsageConflict {
422                                    first: previous_usage,
423                                    second: resumption_psk.usage,
424                                });
425                            }
426                        } else {
427                            contained_resumption_usage = Some(resumption_psk.usage);
428                        };
429                    }
430                },
431                Psk::External(_) => {}
432                #[cfg(feature = "extensions-draft")]
433                Psk::Application(_) => {}
434            };
435        }
436        Ok(())
437    }
438}
439
440#[cfg(test)]
441impl PreSharedKeyId {
442    pub(crate) fn new_with_nonce(psk: Psk, psk_nonce: Vec<u8>) -> Self {
443        Self {
444            psk,
445            psk_nonce: psk_nonce.into(),
446        }
447    }
448}
449
450/// `PskLabel` is used in the final concatentation of PSKs before they are
451/// injected in the key schedule.
452///
453/// ```c
454/// // draft-ietf-mls-protocol-19
455/// struct {
456///     PreSharedKeyID id;
457///     uint16 index;
458///     uint16 count;
459/// } PSKLabel;
460/// ```
461#[derive(TlsSerialize, TlsSize)]
462pub(crate) struct PskLabel<'a> {
463    pub(crate) id: &'a PreSharedKeyId,
464    pub(crate) index: u16,
465    pub(crate) count: u16,
466}
467
468impl<'a> PskLabel<'a> {
469    /// Create a new `PskLabel`
470    fn new(id: &'a PreSharedKeyId, index: u16, count: u16) -> Self {
471        Self { id, index, count }
472    }
473}
474
475/// This contains the `psk-secret` calculated from the PSKs contained in a
476/// Commit or a PreSharedKey proposal.
477#[derive(Clone)]
478pub struct PskSecret {
479    secret: Secret,
480}
481
482impl PskSecret {
483    /// Create a new `PskSecret` from PSK IDs and PSKs
484    ///
485    /// ```text
486    /// psk_extracted_[i] = KDF.Extract(0, psk_[i])
487    /// psk_input_[i] = ExpandWithLabel(psk_extracted_[i], "derived psk", PSKLabel, KDF.Nh)
488    ///
489    /// psk_secret_[0] = 0
490    /// psk_secret_[i] = KDF.Extract(psk_input[i-1], psk_secret_[i-1])
491    /// psk_secret     = psk_secret[n]
492    /// ```
493    pub(crate) fn new(
494        crypto: &impl OpenMlsCrypto,
495        ciphersuite: Ciphersuite,
496        psks: Vec<(impl Borrow<PreSharedKeyId>, Secret)>,
497    ) -> Result<Self, PskError> {
498        // Check that we don't have too many PSKs
499        let num_psks = u16::try_from(psks.len()).map_err(|_| PskError::TooManyKeys)?;
500
501        // Following comments are from `draft-ietf-mls-protocol-19`.
502        //
503        // psk_secret_[0] = 0
504        let mut psk_secret = Secret::zero(ciphersuite);
505
506        for (index, (psk_id, psk)) in psks.into_iter().enumerate() {
507            // psk_extracted_[i] = KDF.Extract(0, psk_[i])
508            let psk_extracted = {
509                let zero_secret = Secret::zero(ciphersuite);
510                zero_secret
511                    .hkdf_extract(crypto, ciphersuite, &psk)
512                    .map_err(LibraryError::unexpected_crypto_error)?
513            };
514
515            // psk_input_[i] = ExpandWithLabel( psk_extracted_[i], "derived psk", PSKLabel, KDF.Nh)
516            let psk_input = {
517                let psk_label = PskLabel::new(psk_id.borrow(), index as u16, num_psks)
518                    .tls_serialize_detached()
519                    .map_err(LibraryError::missing_bound_check)?;
520
521                psk_extracted
522                    .kdf_expand_label(
523                        crypto,
524                        ciphersuite,
525                        "derived psk",
526                        &psk_label,
527                        ciphersuite.hash_length(),
528                    )
529                    .map_err(LibraryError::unexpected_crypto_error)?
530            };
531
532            // psk_secret_[i] = KDF.Extract(psk_input_[i-1], psk_secret_[i-1])
533            psk_secret = psk_input
534                .hkdf_extract(crypto, ciphersuite, &psk_secret)
535                .map_err(LibraryError::unexpected_crypto_error)?;
536        }
537
538        Ok(Self { secret: psk_secret })
539    }
540
541    /// Return the inner secret
542    pub(crate) fn secret(&self) -> &Secret {
543        &self.secret
544    }
545
546    #[cfg(any(feature = "test-utils", feature = "crypto-debug", test))]
547    pub(crate) fn as_slice(&self) -> &[u8] {
548        self.secret.as_slice()
549    }
550}
551
552#[cfg(any(feature = "test-utils", test))]
553impl From<Secret> for PskSecret {
554    fn from(secret: Secret) -> Self {
555        Self { secret }
556    }
557}
558
559/// Load PSKs from storage and arguments
560///
561/// # Arguments
562///
563/// * `storage` - Storage provider to fetch `External` PSKs from
564/// * `resumption_psk_store` - past application resumption PSKs of this group
565/// * `group_id` - application resumption PSKs must match this `psk_group_id`.
566///   If `None`, no resumption PSKs of usage `application` are allowed.
567/// * `foreign_resumption_psk` - resumption PSK of usage `reinit` or `branch` from predecessor/parent group
568/// * `psk_ids` - IDs to load
569#[openmls_traits::maybe_async]
570pub(crate) async fn load_psks<'p, Storage: StorageProvider>(
571    storage: &Storage,
572    resumption_psk_store: &ResumptionPskStore,
573    group_id: Option<&GroupId>,
574    foreign_resumption_psk: Option<(&PreSharedKeyId, ResumptionPskSecret)>,
575    psk_ids: &'p [PreSharedKeyId],
576) -> Result<Vec<(&'p PreSharedKeyId, Secret)>, PskError> {
577    let mut psk_bundles = Vec::new();
578    let mut foreign_resumption_psk = foreign_resumption_psk;
579
580    for psk_id in psk_ids.iter() {
581        log_crypto!(trace, "PSK store {:?}", resumption_psk_store);
582
583        match &psk_id.psk {
584            Psk::Resumption(resumption) => {
585                let psk_secret = match resumption.usage() {
586                    // Application PSKs are looked up by their own epoch.
587                    ResumptionPskUsage::Application => {
588                        let Some(group_id) = group_id else {
589                            // If the group ID is not yet known (i.e. when processing a Welcome),
590                            // usage Application cannot be used.
591                            return Err(PskError::NotAllowed);
592                        };
593                        if &resumption.psk_group_id != group_id {
594                            // The Application resumption PSK does not refer to this group.
595                            return Err(PskError::DifferentGroupId {
596                                expected: group_id.clone(),
597                                got: resumption.psk_group_id.clone(),
598                            });
599                        }
600                        if let Some(psk_bundle) = resumption_psk_store.get(resumption.psk_epoch()) {
601                            (psk_id, psk_bundle.secret.clone())
602                        } else {
603                            // The Application resumption PSK either points to a future epoch or is already evicted.
604                            return Err(PskError::KeyNotFound);
605                        }
606                    }
607                    // The branch and reinit PSK is not in this group's resumption store: it
608                    // comes from the parent or predecessor group.
609                    ResumptionPskUsage::Branch | ResumptionPskUsage::Reinit => {
610                        match foreign_resumption_psk.take() {
611                            Some((foreign_psk_id, foreign_psk_secret))
612                                if foreign_psk_id == psk_id =>
613                            {
614                                (psk_id, foreign_psk_secret.secret)
615                            }
616                            _ => return Err(PskError::KeyNotFound),
617                        }
618                    }
619                };
620                psk_bundles.push(psk_secret);
621            }
622            Psk::External(_) => {
623                let psk_bundle: Option<PskBundle> = storage
624                    .psk(psk_id.psk())
625                    .await
626                    .map_err(|_| PskError::KeyNotFound)?;
627                if let Some(psk_bundle) = psk_bundle {
628                    psk_bundles.push((psk_id, psk_bundle.secret));
629                } else {
630                    return Err(PskError::KeyNotFound);
631                }
632            }
633            #[cfg(feature = "extensions-draft")]
634            Psk::Application(_) => {
635                let psk_bundle: Option<PskBundle> = storage
636                    .psk(psk_id.psk())
637                    .await
638                    .map_err(|_| PskError::KeyNotFound)?;
639                if let Some(psk_bundle) = psk_bundle {
640                    psk_bundles.push((psk_id, psk_bundle.secret));
641                } else {
642                    return Err(PskError::KeyNotFound);
643                }
644            }
645        }
646    }
647
648    Ok(psk_bundles)
649}
650
651/// This module contains a store that can hold a rollover list of resumption PSKs.
652pub mod store {
653    use serde::{Deserialize, Serialize};
654
655    use crate::{group::GroupEpoch, schedule::ResumptionPskSecret};
656
657    /// Resumption PSK store.
658    ///
659    /// This is where the resumption PSKs are kept in a rollover list.
660    #[derive(Debug, Serialize, Deserialize)]
661    #[cfg_attr(any(test, feature = "test-utils"), derive(Clone, PartialEq))]
662    pub(crate) struct ResumptionPskStore {
663        max_number_of_secrets: usize,
664        resumption_psk: Vec<(GroupEpoch, ResumptionPskSecret)>,
665        cursor: usize,
666    }
667
668    impl ResumptionPskStore {
669        /// Creates a new store with a given maximum size of `number_of_secrets`.
670        pub(crate) fn new(max_number_of_secrets: usize) -> Self {
671            Self {
672                max_number_of_secrets,
673                resumption_psk: vec![],
674                cursor: 0,
675            }
676        }
677
678        /// Adds a new entry to the store.
679        pub(crate) fn add(&mut self, epoch: GroupEpoch, resumption_psk: ResumptionPskSecret) {
680            if self.max_number_of_secrets == 0 {
681                return;
682            }
683            let item = (epoch, resumption_psk);
684            if self.resumption_psk.len() < self.max_number_of_secrets {
685                self.resumption_psk.push(item);
686                self.cursor += 1;
687            } else {
688                self.cursor += 1;
689                self.cursor %= self.resumption_psk.len();
690                self.resumption_psk[self.cursor] = item;
691            }
692        }
693
694        /// Searches an entry for a given epoch number and if found, returns the
695        /// corresponding resumption psk.
696        pub(crate) fn get(&self, epoch: GroupEpoch) -> Option<&ResumptionPskSecret> {
697            self.resumption_psk
698                .iter()
699                .find(|&(e, _s)| e == &epoch)
700                .map(|(_e, s)| s)
701        }
702    }
703
704    #[cfg(test)]
705    impl ResumptionPskStore {
706        pub(crate) fn cursor(&self) -> usize {
707            self.cursor
708        }
709    }
710}