Skip to main content

srt_runtime/
km_refresh.rs

1//! SEK-rotation ("KM Refresh") driver — `draft-sharabayko-srt-01` §6.1.6 (KM
2//! Refresh), curated at `private/specs-verified/rules/srt-crypto.md` ("KM Refresh — §6.1.6").
3//!
4//! Sans-IO: [`KmRefreshDriver::on_packet_sent`] / [`KmRefreshDriver::tick`]
5//! take a caller-supplied packet count — this crate never reads a wall clock
6//! or a socket (the same contract as [`crate::handshake_sm`] / [`crate::arq`]
7//! / [`crate::tsbpd`]). The driver only tracks *when* to rotate and *which*
8//! parity is active; it does not generate, wrap, or send key material
9//! itself — the actual SEK PRNG/wrap/Key-Material-message send is the
10//! caller's job (mirroring [`crate::handshake_sm::CryptoConfig`]'s design:
11//! this crate's sans-IO core never owns a CSPRNG), triggered by
12//! [`KmRefreshEvent::PreAnnounce`].
13//!
14//! # Thresholds (§6.1.6, "Recommended values")
15//!
16//! - **KM Refresh Period = `2^25` packets**: how long a key stays active
17//!   before switchover.
18//! - **KM Pre-Announcement Period = `4000` packets**: how long *before*
19//!   switchover the new key is announced, and — symmetrically — how long
20//!   *after* switchover the old key stays valid before decommission. "Both
21//!   keys are valid in parallel for `2 * Pre-Announcement Period`", to
22//!   tolerate late/retransmitted packets that were encrypted under the old
23//!   key.
24//!
25//! All three thresholds are measured from the start of the *current* active
26//! key's epoch (packet 0 of that key):
27//!
28//! ```text
29//! 0 ── refresh - pre_announce ── refresh ── refresh + pre_announce
30//!      PreAnnounce fires         Switchover  Decommission fires
31//!      (generate + wrap +       (old key     (old key dropped)
32//!       ready next key)          still valid)
33//! ```
34//!
35//! [`KmRefreshThresholds::RECOMMENDED`] is the spec's `2^25`/`4000` pair;
36//! `tests/it/km_refresh.rs` drives the same state machine with a scaled-down
37//! threshold pair so the test suite does not need `2^25` real iterations —
38//! the state machine logic is identical, only the threshold constants
39//! differ.
40
41use alloc::vec::Vec;
42
43use broadcast_core::error::InvalidField;
44
45use crate::error::Error;
46
47/// Which of the two alternating SEKs (`draft-sharabayko-srt-01` §3.1's data
48/// packet `KK` field / §6.1.6's odd/even alternation) is meant.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize))]
51#[non_exhaustive]
52pub enum KeyParity {
53    /// The even-numbered SEK.
54    Even,
55    /// The odd-numbered SEK.
56    Odd,
57}
58
59impl KeyParity {
60    /// The other parity — every rotation alternates (§6.1.6).
61    pub fn other(self) -> Self {
62        match self {
63            KeyParity::Even => KeyParity::Odd,
64            KeyParity::Odd => KeyParity::Even,
65        }
66    }
67
68    /// Spec label.
69    pub fn name(&self) -> &'static str {
70        match self {
71            KeyParity::Even => "even",
72            KeyParity::Odd => "odd",
73        }
74    }
75}
76
77broadcast_core::impl_spec_display!(KeyParity);
78
79/// Packets one key may encrypt before its keystream repeats: the AES-CTR counter is the salt
80/// XOR the 31-bit packet sequence number (§6.1.2).
81pub const KEYSTREAM_PACKETS: u64 = 1 << 31;
82
83/// KM Refresh packet-count thresholds (`draft-sharabayko-srt-01` §6.1.6).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct KmRefreshThresholds {
87    refresh_period: u64,
88    pre_announcement_period: u64,
89}
90
91impl KmRefreshThresholds {
92    /// The draft's own recommended values (§6.1.6): `2^25` packets refresh
93    /// period, `4000` packets pre-announcement period.
94    pub const RECOMMENDED: KmRefreshThresholds = KmRefreshThresholds {
95        refresh_period: 1 << 25,
96        pre_announcement_period: 4000,
97    };
98
99    /// Thresholds for `refresh_period` packets between switchovers and a
100    /// `pre_announcement_period` ahead of it.
101    ///
102    /// # Errors
103    ///
104    /// [`Error::InvalidField`] unless `0 < pre_announcement_period <
105    /// refresh_period <= KEYSTREAM_PACKETS - pre_announcement_period`: a zero period would
106    /// rotate on every packet, a pre-announcement at or past the refresh point would announce
107    /// the next key only once it had already replaced the current one, and a key kept for
108    /// `KEYSTREAM_PACKETS` (2^31) packets would repeat its keystream, because the cipher counter
109    /// follows the 31-bit packet sequence number.
110    pub fn new(refresh_period: u64, pre_announcement_period: u64) -> Result<Self, Error> {
111        if pre_announcement_period == 0 || pre_announcement_period >= refresh_period {
112            return Err(Error::InvalidField(InvalidField::new(
113                "pre_announcement_period",
114                "must be non-zero and below refresh_period",
115            )));
116        }
117        if refresh_period > KEYSTREAM_PACKETS - pre_announcement_period {
118            return Err(Error::InvalidField(InvalidField::new(
119                "refresh_period",
120                "must leave a pre-announcement below the 2^31 packets one key may encrypt",
121            )));
122        }
123        Ok(KmRefreshThresholds {
124            refresh_period,
125            pre_announcement_period,
126        })
127    }
128
129    /// Packets an active key is used for before switchover.
130    pub const fn refresh_period(&self) -> u64 {
131        self.refresh_period
132    }
133
134    /// Packets before switchover the next key is announced, and after
135    /// switchover the old key stays valid.
136    pub const fn pre_announcement_period(&self) -> u64 {
137        self.pre_announcement_period
138    }
139}
140
141/// One state transition [`KmRefreshDriver::on_packet_sent`] /
142/// [`KmRefreshDriver::tick`] can fire (`draft-sharabayko-srt-01` §6.1.6).
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum KmRefreshEvent {
146    /// `refresh_period - pre_announcement_period` packets sent under the
147    /// active key: generate, wrap, and send a fresh SEK for `next_parity`
148    /// now (§6.1.5's Key Material exchange, driven out-of-band of this
149    /// driver — see the module doc).
150    PreAnnounce {
151        /// The parity the newly-generated key will use.
152        next_parity: KeyParity,
153    },
154    /// `refresh_period` packets sent under the active key: start encrypting
155    /// *new* outgoing packets with `new_active` from now on. The previous
156    /// key remains valid for decrypting late/retransmitted packets until
157    /// [`KmRefreshEvent::Decommission`] fires for it.
158    Switchover {
159        /// The parity now active for new packets.
160        new_active: KeyParity,
161    },
162    /// `pre_announcement_period` packets after switchover: the previous key
163    /// may be dropped — no more retransmits will need it (§6.1.6, "both keys
164    /// valid in parallel for `2 * Pre-Announcement Period`").
165    Decommission {
166        /// The parity being retired.
167        retired: KeyParity,
168    },
169}
170
171/// Sans-IO SEK-rotation state machine (`draft-sharabayko-srt-01` §6.1.6).
172///
173/// Tracks which [`KeyParity`] is currently active and fires
174/// [`KmRefreshEvent`]s as the packet count crosses the configured
175/// [`KmRefreshThresholds`]. Does not hold key material itself — see the
176/// module doc. Rotates indefinitely: once a cycle's [`KmRefreshEvent::Decommission`]
177/// fires, the next cycle's thresholds are armed again against the new active
178/// key's epoch.
179#[derive(Debug, Clone, PartialEq)]
180pub struct KmRefreshDriver {
181    thresholds: KmRefreshThresholds,
182    active: KeyParity,
183    /// Packet count at which `active` most recently became active (`0` for
184    /// the initial key negotiated at handshake time).
185    epoch_start: u64,
186    /// Total packets sent so far (monotonic).
187    total_sent: u64,
188    pre_announced: bool,
189    switched_over: bool,
190    decommissioned: bool,
191}
192
193impl KmRefreshDriver {
194    /// A fresh driver. `initial_parity` is the SEK negotiated at handshake
195    /// time (this crate's handshake convention is [`KeyParity::Even`] — see
196    /// `crate::handshake_sm::build_key_material_extension`, `crypto` feature
197    /// only).
198    pub fn new(thresholds: KmRefreshThresholds, initial_parity: KeyParity) -> Self {
199        KmRefreshDriver {
200            thresholds,
201            active: initial_parity,
202            epoch_start: 0,
203            total_sent: 0,
204            pre_announced: false,
205            switched_over: false,
206            decommissioned: false,
207        }
208    }
209
210    /// The currently-active parity for *new* outgoing packets.
211    pub fn active_parity(&self) -> KeyParity {
212        self.active
213    }
214
215    /// Total packets recorded via [`Self::on_packet_sent`]/[`Self::tick`].
216    pub fn total_sent(&self) -> u64 {
217        self.total_sent
218    }
219
220    /// Whether `parity`'s key should still be considered held/valid. The
221    /// active key always is; the just-retired key is too, from switchover
222    /// until decommission (§6.1.6's "both keys valid in parallel" transition
223    /// window) — a data packet under either may legitimately arrive during
224    /// that window (in-flight or retransmitted).
225    pub fn is_key_valid(&self, parity: KeyParity) -> bool {
226        if parity == self.active {
227            return true;
228        }
229        self.switched_over && !self.decommissioned
230    }
231
232    /// Record `n` more packets sent under the active key and return any
233    /// [`KmRefreshEvent`]s newly crossed, in spec order (PreAnnounce,
234    /// Switchover, Decommission). A single call can fire more than one event
235    /// if `n` is large enough to cross multiple thresholds at once.
236    pub fn on_packet_sent(&mut self, n: u64) -> Vec<KmRefreshEvent> {
237        self.total_sent = self.total_sent.saturating_add(n);
238        let mut events = Vec::new();
239        let pre_announce_at = self
240            .thresholds
241            .refresh_period
242            .saturating_sub(self.thresholds.pre_announcement_period);
243        loop {
244            let since_epoch = self.total_sent.saturating_sub(self.epoch_start);
245            let mut crossed = false;
246
247            if !self.pre_announced && since_epoch >= pre_announce_at {
248                self.pre_announced = true;
249                crossed = true;
250                events.push(KmRefreshEvent::PreAnnounce {
251                    next_parity: self.active.other(),
252                });
253            }
254
255            if !self.switched_over && since_epoch >= self.thresholds.refresh_period {
256                self.switched_over = true;
257                crossed = true;
258                let new_active = self.active.other();
259                self.active = new_active;
260                // The new epoch starts exactly at the switchover point, so the
261                // decommission threshold below (measured from `epoch_start`) is
262                // `pre_announcement_period` packets *after* switchover — §6.1.6's
263                // `refresh_period + pre_announcement_period`, not
264                // `2 * refresh_period + pre_announcement_period`.
265                self.epoch_start += self.thresholds.refresh_period;
266                events.push(KmRefreshEvent::Switchover { new_active });
267            }
268
269            if self.switched_over && !self.decommissioned {
270                let since_switchover = self.total_sent.saturating_sub(self.epoch_start);
271                if since_switchover >= self.thresholds.pre_announcement_period {
272                    self.decommissioned = true;
273                    crossed = true;
274                    events.push(KmRefreshEvent::Decommission {
275                        retired: self.active.other(),
276                    });
277                    // Arm the next cycle: `epoch_start` already marks the
278                    // current key's start, so the next PreAnnounce/Switchover
279                    // are correctly measured from here.
280                    self.pre_announced = false;
281                    self.switched_over = false;
282                    self.decommissioned = false;
283                }
284            }
285
286            if !crossed {
287                break;
288            }
289        }
290
291        events
292    }
293
294    /// Record exactly one packet sent — convenience wrapper over
295    /// [`Self::on_packet_sent`].
296    pub fn tick(&mut self) -> Vec<KmRefreshEvent> {
297        self.on_packet_sent(1)
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use alloc::string::ToString;
305
306    const SCALED: KmRefreshThresholds = KmRefreshThresholds {
307        refresh_period: 100,
308        pre_announcement_period: 10,
309    };
310
311    #[test]
312    fn recommended_thresholds_match_spec_values() {
313        assert_eq!(KmRefreshThresholds::RECOMMENDED.refresh_period(), 1 << 25);
314        assert_eq!(
315            KmRefreshThresholds::RECOMMENDED.pre_announcement_period(),
316            4000
317        );
318    }
319
320    #[test]
321    fn new_rejects_degenerate_thresholds() {
322        for (refresh, pre_announce) in [(0, 0), (100, 0), (100, 100), (100, 101)] {
323            assert!(
324                matches!(
325                    KmRefreshThresholds::new(refresh, pre_announce),
326                    Err(Error::InvalidField(_))
327                ),
328                "refresh {refresh}, pre-announce {pre_announce} must be rejected"
329            );
330        }
331        assert!(KmRefreshThresholds::new(KEYSTREAM_PACKETS, 4000).is_err());
332        assert!(KmRefreshThresholds::new(u64::MAX, 4000).is_err());
333        assert!(KmRefreshThresholds::new(KEYSTREAM_PACKETS - 3999, 4000).is_err());
334        assert!(KmRefreshThresholds::new(KEYSTREAM_PACKETS - 4000, 4000).is_ok());
335        let t = KmRefreshThresholds::new(100, 10).unwrap();
336        assert_eq!(t.refresh_period(), 100);
337        assert_eq!(t.pre_announcement_period(), 10);
338    }
339
340    #[test]
341    fn one_batch_larger_than_a_refresh_period_rotates_every_cycle_it_crosses() {
342        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
343        let events = d.on_packet_sent(295);
344        assert_eq!(
345            events,
346            alloc::vec![
347                KmRefreshEvent::PreAnnounce {
348                    next_parity: KeyParity::Odd
349                },
350                KmRefreshEvent::Switchover {
351                    new_active: KeyParity::Odd
352                },
353                KmRefreshEvent::Decommission {
354                    retired: KeyParity::Even
355                },
356                KmRefreshEvent::PreAnnounce {
357                    next_parity: KeyParity::Even
358                },
359                KmRefreshEvent::Switchover {
360                    new_active: KeyParity::Even
361                },
362                KmRefreshEvent::Decommission {
363                    retired: KeyParity::Odd
364                },
365                KmRefreshEvent::PreAnnounce {
366                    next_parity: KeyParity::Odd
367                },
368            ]
369        );
370        assert_eq!(d.active_parity(), KeyParity::Even);
371        assert_eq!(d.total_sent(), 295);
372    }
373
374    #[test]
375    fn key_parity_alternates_and_labels() {
376        assert_eq!(KeyParity::Even.other(), KeyParity::Odd);
377        assert_eq!(KeyParity::Odd.other(), KeyParity::Even);
378        assert_eq!(KeyParity::Even.to_string(), "even");
379        assert_eq!(KeyParity::Odd.to_string(), "odd");
380    }
381
382    #[test]
383    fn fires_pre_announce_switchover_decommission_in_order() {
384        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
385        assert_eq!(d.active_parity(), KeyParity::Even);
386        assert!(d.is_key_valid(KeyParity::Even));
387        assert!(!d.is_key_valid(KeyParity::Odd));
388
389        // Just before pre-announce: nothing fires.
390        assert_eq!(d.on_packet_sent(89), Vec::new());
391        assert_eq!(d.active_parity(), KeyParity::Even);
392
393        // Crosses 90 (100 - 10): PreAnnounce for the *other* (Odd) parity.
394        assert_eq!(
395            d.on_packet_sent(1),
396            alloc::vec![KmRefreshEvent::PreAnnounce {
397                next_parity: KeyParity::Odd
398            }]
399        );
400        // Active key hasn't changed yet.
401        assert_eq!(d.active_parity(), KeyParity::Even);
402        assert!(d.is_key_valid(KeyParity::Even));
403        assert!(!d.is_key_valid(KeyParity::Odd));
404
405        // Re-crossing the same threshold does not re-fire. (total: 91)
406        assert_eq!(d.on_packet_sent(1), Vec::new());
407
408        // Crosses 100: Switchover to Odd.
409        assert_eq!(d.on_packet_sent(8), Vec::new()); // total 99, not yet
410        assert_eq!(
411            d.on_packet_sent(1), // total 100
412            alloc::vec![KmRefreshEvent::Switchover {
413                new_active: KeyParity::Odd
414            }]
415        );
416        assert_eq!(d.active_parity(), KeyParity::Odd);
417        // Both keys valid during the transition window.
418        assert!(d.is_key_valid(KeyParity::Odd));
419        assert!(d.is_key_valid(KeyParity::Even));
420
421        // Crosses 110 (100 + 10): Decommission the old (Even) key.
422        assert_eq!(d.on_packet_sent(9), Vec::new()); // total 109
423        assert_eq!(
424            d.on_packet_sent(1), // total 110
425            alloc::vec![KmRefreshEvent::Decommission {
426                retired: KeyParity::Even
427            }]
428        );
429        assert_eq!(d.active_parity(), KeyParity::Odd);
430        assert!(d.is_key_valid(KeyParity::Odd));
431        assert!(!d.is_key_valid(KeyParity::Even), "old key must be dropped");
432    }
433
434    #[test]
435    fn large_jump_fires_all_three_events_in_one_call() {
436        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
437        let events = d.on_packet_sent(115);
438        assert_eq!(
439            events,
440            alloc::vec![
441                KmRefreshEvent::PreAnnounce {
442                    next_parity: KeyParity::Odd
443                },
444                KmRefreshEvent::Switchover {
445                    new_active: KeyParity::Odd
446                },
447                KmRefreshEvent::Decommission {
448                    retired: KeyParity::Even
449                },
450            ]
451        );
452        assert_eq!(d.active_parity(), KeyParity::Odd);
453        assert!(!d.is_key_valid(KeyParity::Even));
454    }
455
456    #[test]
457    fn tick_is_a_single_packet_and_rotation_repeats_forever() {
458        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
459        let mut all = Vec::new();
460        for _ in 0..250 {
461            all.extend(d.tick());
462        }
463        assert_eq!(d.total_sent(), 250);
464        // Two full cycles of 100 packets each fit in 250 ticks: expect two
465        // full PreAnnounce/Switchover/Decommission triples, alternating
466        // parity, plus one more PreAnnounce (at 90 packets into the third
467        // 100-packet cycle, i.e. total 290 — not reached at 250) which does
468        // NOT fire yet.
469        let switchovers: Vec<_> = all
470            .iter()
471            .filter(|e| matches!(e, KmRefreshEvent::Switchover { .. }))
472            .collect();
473        assert_eq!(switchovers.len(), 2);
474        assert_eq!(
475            switchovers[0],
476            &KmRefreshEvent::Switchover {
477                new_active: KeyParity::Odd
478            }
479        );
480        assert_eq!(
481            switchovers[1],
482            &KmRefreshEvent::Switchover {
483                new_active: KeyParity::Even
484            }
485        );
486        assert_eq!(d.active_parity(), KeyParity::Even);
487    }
488}