Skip to main content

srt_runtime/
crypto.rs

1//! SRT payload encryption — `draft-sharabayko-srt-01` §6 ("Encryption").
2//!
3//! Spec grounding: `private/specs-verified/rules/srt-crypto.md` (curated §6, external-algorithm
4//! references grep-verified against RFC 3394 / RFC 8018 / RFC 2104 / FIPS 197
5//! / NIST SP 800-38A). Cross-refs: `private/specs-verified/rules/srt-rules.md` §"Key Material
6//! message — §3.2.2" (wire layout of `Salt`/`ICV`/`xSEK`/`oSEK`/`KLen`, all
7//! carried opaquely by [`crate::packet::KeyMaterial`]) and §"Data packet —
8//! §3.1" (`KK` field, [`crate::packet::EncryptionKeyField`]).
9//!
10//! This module adds the crypto *primitives* §6 names but does not restate:
11//!
12//! - **AES-CTR** payload encrypt/decrypt ([`aes_ctr_apply`]) — §6.2.2/§6.3.2.
13//! - **RFC 3394 AES key wrap/unwrap** of the SEK ([`wrap_sek`]/[`unwrap_sek`])
14//!   — §6.1.5/§6.2.1/§6.3.1.
15//! - **PBKDF2 (HMAC-SHA1) KEK derivation** from a passphrase
16//!   ([`derive_kek`]) — §6.1.4/§6.2.1/§6.3.1.
17//!
18//! Gated behind the `crypto` feature; the default/no_std packet-codec core
19//! (this crate's `--no-default-features` build) pulls none of these
20//! dependencies.
21//!
22//! # ⚠ The draft's two IV formulas (srt-crypto.md, "Conflicting IV formula")
23//!
24//! `draft-sharabayko-srt-01` gives **two different, unreconciled** formulas
25//! for the AES-CTR IV:
26//!
27//! - §6.1.2 (Overview): build a 128-bit `{80 zero bits | 32-bit packet index
28//!   | 16-bit block counter}` word and XOR its upper 112 bits with `IV =
29//!   MSB(112, Salt)`.
30//! - §6.2.2 (Encryption Process) / §6.3.2 (Decryption Process), verbatim and
31//!   identical in both places: `IV = (MSB(112, Salt) << 2) XOR (PktSeqNo)`.
32//!
33//! These are not algebraically the same construction, and the draft never
34//! reconciles them. No sample ciphertext exists anywhere in the draft to
35//! disambiguate by reproduction (`srt-crypto.md`, "No test vectors" note), so
36//! this module resolves it against the **reference implementation** instead:
37//! `libsrt` (`haivision/srt`) `haicrypt/hcrypt.h` `hcrypt_SetCtrIV` builds the
38//! counter as §6.1.2 describes — `{80 zero bits | 32-bit packet index | 16-bit
39//! block counter}` with `MSB(112, Salt)` XORed across the top 112 bits — and
40//! performs **no** `<< 2` shift. The §6.2.2/§6.3.2 `<< 2` is a draft-text
41//! artifact; implementing it literally yields a keystream no real SRT peer can
42//! decrypt. [`packet_counter`] therefore follows `hcrypt_SetCtrIV` (≡ the
43//! §6.1.2 layout), verified byte-for-byte against that macro in the tests.
44
45use aes::cipher::{KeyIvInit, StreamCipher};
46use aes::{Aes128, Aes192, Aes256};
47use aes_kw::{KeyInit, KwAes128, KwAes192, KwAes256};
48use alloc::vec;
49use alloc::vec::Vec;
50use broadcast_common::error::InvalidField;
51use core::result::Result::{Err, Ok};
52use ctr::Ctr128BE;
53use hmac::Hmac;
54use pbkdf2::pbkdf2;
55use sha1::Sha1;
56use zeroize::Zeroizing;
57
58use crate::error::{Error, Result};
59use crate::packet::EncryptionKeyField;
60
61/// PBKDF2 iteration count mandated by the draft (`Iter = 2048`,
62/// §6.1.4/§6.2.1/§6.3.1 — identical value at every citation).
63pub const PBKDF2_ITERATIONS: u32 = 2048;
64
65/// Length of the 128-bit Key Material `Salt` field in bytes (`SLen/4 = 4`
66/// words — the only salt length the draft defines, `srt-rules.md` §3.2.2).
67pub const SALT_LEN: usize = 16;
68
69/// Number of least-significant bytes of the 128-bit `Salt` fed to PBKDF2 as
70/// its salt argument (`LSB(64,Salt)`, §6.2.1/§6.3.1: 64 bits = 8 bytes). The
71/// remaining (most-significant) bytes of `Salt` feed the AES-CTR IV instead
72/// (§6.1.2/§6.2.2/§6.3.2).
73const PBKDF2_SALT_LEN: usize = 8;
74
75/// Number of most-significant bytes of the 128-bit `Salt` used to build the
76/// AES-CTR IV (`MSB(112, Salt)`, §6.1.2/§6.2.2/§6.3.2: 112 bits = 14 bytes).
77const IV_SALT_LEN: usize = 14;
78
79/// AES block size in bytes (FIPS 197) — also the AES-CTR counter width
80/// (§6.1.2: "The counter for AES-CTR is the size of the cipher's block, i.e.
81/// 128 bits").
82const AES_BLOCK_LEN: usize = 16;
83
84/// A key length not one of AES-128/192/256's 16/24/32 bytes (`KLen/4` ∈
85/// `{4,6,8}`, `srt-rules.md` §3.2.2).
86fn invalid_key_length(what: &'static str) -> Error {
87    Error::InvalidField(InvalidField {
88        field: what,
89        reason: "length must be 16, 24, or 32 bytes (AES-128/192/256)",
90    })
91}
92
93// ---------------------------------------------------------------------------
94// RFC 8018 PBKDF2 (HMAC-SHA1) — lowest-level entry point.
95// ---------------------------------------------------------------------------
96
97/// Run PBKDF2-HMAC-SHA1 (RFC 8018 §5.2 with the HMAC-SHA-1 PRF of
98/// Appendix B.1.1) with a caller-supplied salt and iteration count. This is
99/// the lowest-level `srt-runtime` function that performs PBKDF2-HMAC-SHA1;
100/// [`derive_kek`] is a thin wrapper that fixes the salt to `LSB(64, Salt)`
101/// and the iteration count to [`PBKDF2_ITERATIONS`].
102///
103/// `output`'s length determines `dkLen`; any non-negative length up to
104/// `(2^32 - 1) * 20` is accepted by the underlying primitive.
105pub fn pbkdf2_hmac_sha1(password: &[u8], salt: &[u8], iterations: u32, output: &mut [u8]) {
106    let (Ok(()) | Err(_)) = pbkdf2::<Hmac<Sha1>>(password, salt, iterations, output);
107}
108
109// ---------------------------------------------------------------------------
110// §6.1.4/§6.2.1/§6.3.1 — KEK derivation (passphrase path).
111// ---------------------------------------------------------------------------
112
113/// Derive the Key Encrypting Key (KEK) from the pre-shared passphrase
114/// (`draft-sharabayko-srt-01` §6.1.4, §6.2.1 sender / §6.3.1 receiver —
115/// identical formula both sides):
116///
117/// ```text
118/// KEK = PBKDF2(passphrase, LSB(64,Salt), Iter=2048, KLen)
119/// ```
120///
121/// `salt` is the Key Material message's 128-bit `Salt` field; `klen` is the
122/// desired KEK length in bytes (16/24/32, matching the handshake's
123/// Encryption Field / the Key Material message's `KLen/4` — "the KEK has to
124/// be at least as long as the SEK", §6.1.4).
125///
126/// The KEK is returned in a [`Zeroizing`] buffer, wiped when dropped.
127///
128/// # Errors
129/// [`Error::InvalidField`] if `klen` is not 16, 24, or 32.
130pub fn derive_kek(
131    passphrase: &[u8],
132    salt: &[u8; SALT_LEN],
133    klen: usize,
134) -> Result<Zeroizing<Vec<u8>>> {
135    if !matches!(klen, 16 | 24 | 32) {
136        return Err(invalid_key_length("KLen"));
137    }
138    // LSB(64, Salt): the low/least-significant 8 bytes of the 128-bit,
139    // big-endian-wire Salt.
140    let pbkdf2_salt = &salt[SALT_LEN - PBKDF2_SALT_LEN..];
141    let mut kek = Zeroizing::new(vec![0u8; klen]);
142    pbkdf2_hmac_sha1(passphrase, pbkdf2_salt, PBKDF2_ITERATIONS, &mut kek[..]);
143    Ok(kek)
144}
145
146/// One-entry cache for [`derive_kek`], keyed by the Key Material `Salt` and
147/// the requested `KLen` (the passphrase is fixed for the life of a
148/// connection). A peer can re-send the same Key Material message, and deriving
149/// the KEK costs a full 2048-iteration PBKDF2 run every time; the cache makes
150/// a repeat cost a comparison instead (#2840).
151pub(crate) struct KekCache {
152    entry: Option<CachedKek>,
153    /// Derivation count, so a test can prove a repeat is served from the
154    /// cache.
155    #[cfg(test)]
156    derivations: u64,
157}
158
159struct CachedKek {
160    salt: [u8; SALT_LEN],
161    klen: usize,
162    kek: Zeroizing<Vec<u8>>,
163}
164
165impl KekCache {
166    pub(crate) const fn new() -> Self {
167        KekCache {
168            entry: None,
169            #[cfg(test)]
170            derivations: 0,
171        }
172    }
173
174    /// The KEK for `(salt, klen)`, derived once and reused for an identical
175    /// request.
176    ///
177    /// # Errors
178    /// The same as [`derive_kek`].
179    pub(crate) fn derive(
180        &mut self,
181        passphrase: &[u8],
182        salt: &[u8; SALT_LEN],
183        klen: usize,
184    ) -> Result<Zeroizing<Vec<u8>>> {
185        if let Some(entry) = &self.entry
186            && entry.salt == *salt
187            && entry.klen == klen
188        {
189            return Ok(entry.kek.clone());
190        }
191        let kek = derive_kek(passphrase, salt, klen)?;
192        self.entry = Some(CachedKek {
193            salt: *salt,
194            klen,
195            kek: kek.clone(),
196        });
197        #[cfg(test)]
198        {
199            self.derivations = self.derivations.saturating_add(1);
200        }
201        Ok(kek)
202    }
203
204    /// How many PBKDF2 derivations this cache has performed.
205    #[cfg(test)]
206    pub(crate) fn derivations(&self) -> u64 {
207        self.derivations
208    }
209}
210
211// ---------------------------------------------------------------------------
212// §6.1.5/§6.2.1/§6.3.1 — RFC 3394 AES key wrap/unwrap of the SEK.
213// ---------------------------------------------------------------------------
214
215/// Wrap one or two SEKs with the KEK (RFC 3394 AES key wrap, external
216/// algorithm — `draft-sharabayko-srt-01` §6.1.5/§6.2.1: `Wrap = AESkw(KEK,
217/// SEK)`).
218///
219/// `plaintext_keys` is the concatenation of the SEK(s) being wrapped — one
220/// SEK's worth of bytes (Key Material `KK` = even/odd) or two concatenated
221/// SEKs (`KK` = both), per the Wrap-field length formula `n*KLen + 8` in
222/// `srt-rules.md` §"Key Material message — §3.2.2". Returns `(icv, wrapped)`
223/// to match [`crate::packet::KeyMaterial`]'s `icv`/`x_sek`/`o_sek` fields —
224/// RFC 3394's first 8-byte output block *is* the wrap's Integrity Check
225/// Vector (the encrypted default IV, RFC 3394 §2.2.3.1), and the remaining
226/// bytes are the wrapped key material, the same length as the input.
227///
228/// # Errors
229/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, or if
230/// `plaintext_keys.len()` is not a multiple of 8 bytes (RFC 3394 operates on
231/// 64-bit semiblocks).
232pub fn wrap_sek(kek: &[u8], plaintext_keys: &[u8]) -> Result<([u8; 8], Vec<u8>)> {
233    let mut out = vec![0u8; plaintext_keys.len() + 8];
234    match kek.len() {
235        16 => KwAes128::new_from_slice(kek)
236            .map_err(|_| invalid_key_length("KEK"))?
237            .wrap_key(plaintext_keys, &mut out)
238            .map(|_| ()),
239        24 => KwAes192::new_from_slice(kek)
240            .map_err(|_| invalid_key_length("KEK"))?
241            .wrap_key(plaintext_keys, &mut out)
242            .map(|_| ()),
243        32 => KwAes256::new_from_slice(kek)
244            .map_err(|_| invalid_key_length("KEK"))?
245            .wrap_key(plaintext_keys, &mut out)
246            .map(|_| ()),
247        _ => return Err(invalid_key_length("KEK")),
248    }
249    .map_err(|_| {
250        Error::InvalidField(InvalidField {
251            field: "SEK",
252            reason: "length must be a multiple of 8 bytes (RFC 3394 semiblocks)",
253        })
254    })?;
255    let mut icv = [0u8; 8];
256    icv.copy_from_slice(&out[..8]);
257    Ok((icv, out[8..].to_vec()))
258}
259
260/// Unwrap the SEK(s) with the KEK (inverse RFC 3394 AES key wrap —
261/// `draft-sharabayko-srt-01` §6.1.5/§6.3.1: `SEK = AESkuw(KEK, Wrap)`).
262///
263/// `icv`/`wrapped` are [`crate::packet::KeyMaterial`]'s `icv`/`x_sek` (or
264/// `o_sek`) fields. A wrap-integrity failure — wrong KEK (wrong passphrase)
265/// or corrupt wire data — is the spec's "it does not have the SEK" case
266/// (§6.1.5, L3799-3803/L3820-3823): a structured error, never a panic or
267/// silently-wrong plaintext.
268///
269/// # Errors
270/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, if
271/// `wrapped.len()` is not a multiple of 8 bytes, or if the RFC 3394
272/// integrity check fails.
273///
274/// The plaintext SEK(s) come back in a [`Zeroizing`] buffer, wiped when
275/// dropped.
276pub fn unwrap_sek(kek: &[u8], icv: &[u8; 8], wrapped: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
277    let mut input = Vec::with_capacity(8 + wrapped.len());
278    input.extend_from_slice(icv);
279    input.extend_from_slice(wrapped);
280    let mut out = Zeroizing::new(vec![0u8; wrapped.len()]);
281    let bad_wrap = || {
282        Error::InvalidField(InvalidField {
283            field: "AES key wrap",
284            reason: "integrity check failed (wrong KEK / passphrase, or corrupt wire data)",
285        })
286    };
287    match kek.len() {
288        16 => KwAes128::new_from_slice(kek)
289            .map_err(|_| invalid_key_length("KEK"))?
290            .unwrap_key(&input, &mut out[..])
291            .map(|_| ()),
292        24 => KwAes192::new_from_slice(kek)
293            .map_err(|_| invalid_key_length("KEK"))?
294            .unwrap_key(&input, &mut out[..])
295            .map(|_| ()),
296        32 => KwAes256::new_from_slice(kek)
297            .map_err(|_| invalid_key_length("KEK"))?
298            .unwrap_key(&input, &mut out[..])
299            .map(|_| ()),
300        _ => return Err(invalid_key_length("KEK")),
301    }
302    .map_err(|_| bad_wrap())?;
303    Ok(out)
304}
305
306// ---------------------------------------------------------------------------
307// §6.1.2/§6.2.2/§6.3.2 — AES-CTR payload encrypt/decrypt.
308// ---------------------------------------------------------------------------
309
310/// Compute the 128-bit AES-CTR initial counter for one data packet.
311///
312/// This follows the **reference SRT construction** (`libsrt` `haicrypt/hcrypt.h`,
313/// `hcrypt_SetCtrIV`), which is what real SRT peers use on the wire:
314///
315/// ```text
316/// memset(iv, 0, 16);              // all 16 bytes zeroed
317/// memcpy(&iv[10], &pki, 4);       // 32-bit packet index at bytes [10..14]
318/// iv[0..14] ^= salt[0..14];       // XOR MSB(112, Salt) across the top 14 bytes
319/// // iv[14..16] = per-packet AES-block counter, starts 0
320/// //
321/// //  byte:  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
322/// //        +-----------------------+-----------+-----+
323/// //        |          0s           |    pki    | ctr |
324/// //        +-----------------------+-----------+-----+
325/// ```
326///
327/// **On the draft's `IV = (MSB(112, Salt) << 2) XOR PktSeqNo` (§6.2.2/§6.3.2):**
328/// the `<< 2` is a known artifact/typo of the draft text — the reference
329/// implementation does **no** left shift. Implementing the `<< 2` literally
330/// produces a keystream no real SRT peer can decrypt, so this function follows
331/// `hcrypt_SetCtrIV` (which is equivalent to §6.1.2's field layout: packet index
332/// in bits `[47:16]`, block counter in `[15:0]`). See the module doc's
333/// "conflicting IV formula" note.
334///
335/// The low 16 bits (`counter[14..16]`) are the per-packet AES-block counter,
336/// left at `0` here — a standard 128-bit big-endian CTR increments the whole
337/// counter per block, which only touches these low bits as long as a single
338/// packet's payload stays under `2^16` AES blocks (1 MiB); every SRT payload
339/// (bounded by a UDP datagram) is far smaller.
340///
341/// `pkt_seq_no` is the data packet's 31-bit Packet Sequence Number
342/// (`draft-sharabayko-srt-01` §3.1); bit 31 (the `F` header bit) is never part
343/// of it.
344pub fn packet_counter(salt: &[u8; SALT_LEN], pkt_seq_no: u32) -> [u8; AES_BLOCK_LEN] {
345    let mut counter = [0u8; AES_BLOCK_LEN];
346    // 32-bit packet index at bytes [10..14] (hcrypt.h: `memcpy(&iv[10], pki, 4)`).
347    counter[10..14].copy_from_slice(&pkt_seq_no.to_be_bytes());
348    // XOR MSB(112, Salt) — the top 14 bytes of the Salt — across bytes [0..14]
349    // (hcrypt.h: `hcrypt_XorStream(&iv[0], nonce, 112/8)`). No left shift.
350    for i in 0..IV_SALT_LEN {
351        counter[i] ^= salt[i];
352    }
353    // counter[14..16] stays 0 — the block counter starts at 0 for this packet.
354    counter
355}
356
357/// AES-CTR encrypt/decrypt one data packet's payload **in place**
358/// (`draft-sharabayko-srt-01` §6.2.2/§6.3.2). CTR mode is its own inverse —
359/// `EncryptedPayload = AES_CTR_Encrypt(SEK, IV, UnencryptedPayload)` and
360/// `DecryptedPayload = AES_CTR_Encrypt(SEK, IV, EncryptedPayload)` are the
361/// same operation (XOR with the same keystream), so this one function serves
362/// both directions.
363///
364/// `sek` selects AES-128/192/256 by its length (16/24/32 bytes); `salt` and
365/// `pkt_seq_no` feed [`packet_counter`]. No padding is applied or expected —
366/// CTR is a stream cipher (§6.1.1).
367///
368/// # Errors
369/// [`Error::InvalidField`] if `sek.len()` is not 16, 24, or 32.
370pub fn aes_ctr_apply(
371    sek: &[u8],
372    salt: &[u8; SALT_LEN],
373    pkt_seq_no: u32,
374    data: &mut [u8],
375) -> Result<()> {
376    let counter = packet_counter(salt, pkt_seq_no);
377    match sek.len() {
378        16 => {
379            let mut cipher =
380                Ctr128BE::<Aes128>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
381            cipher.apply_keystream(data);
382        }
383        24 => {
384            let mut cipher =
385                Ctr128BE::<Aes192>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
386            cipher.apply_keystream(data);
387        }
388        32 => {
389            let mut cipher =
390                Ctr128BE::<Aes256>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
391            cipher.apply_keystream(data);
392        }
393        _ => return Err(bad_sek()),
394    }
395    Ok(())
396}
397
398fn bad_sek() -> Error {
399    invalid_key_length("SEK")
400}
401
402// ---------------------------------------------------------------------------
403// §3.1 `KK` — select the active SEK by odd/even parity.
404// ---------------------------------------------------------------------------
405
406/// Select the SEK to use for a data packet from its `KK` field
407/// (`draft-sharabayko-srt-01` §3.1/§6.1.6): `even`/`odd` are the two SEKs
408/// currently held (both may be live during the `±`KM-Pre-Announcement-Period`
409/// rekey transition window, §6.1.6).
410///
411/// # Errors
412/// [`Error::InvalidField`] if the packet is unencrypted (`KK = NotEncrypted`)
413/// or carries the control-packet-only reserved value, or if the selected
414/// parity's SEK is not currently held (e.g. not yet unwrapped, or already
415/// decommissioned — §6.3, step 11: such packets "must be dropped").
416pub fn select_sek<'a>(
417    key_flag: EncryptionKeyField,
418    even: Option<&'a [u8]>,
419    odd: Option<&'a [u8]>,
420) -> Result<&'a [u8]> {
421    let no_sek = |parity: &'static str| {
422        Error::InvalidField(InvalidField {
423            field: "SEK",
424            reason: match parity {
425                "even" => "even key not currently held",
426                _ => "odd key not currently held",
427            },
428        })
429    };
430    match key_flag {
431        EncryptionKeyField::Even => even.ok_or_else(|| no_sek("even")),
432        EncryptionKeyField::Odd => odd.ok_or_else(|| no_sek("odd")),
433        EncryptionKeyField::NotEncrypted => Err(Error::InvalidField(InvalidField {
434            field: "KK",
435            reason: "packet is not encrypted (KK=00b)",
436        })),
437        EncryptionKeyField::Reserved(_) => Err(Error::InvalidField(InvalidField {
438            field: "KK",
439            reason: "reserved value (11b) is control-packet-only, not valid on a data packet",
440        })),
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use broadcast_common::error::InvalidField;
447
448    use super::*;
449
450    // -----------------------------------------------------------------
451    // RFC 3394 §4.1 — "Wrap 128 bits of Key Data with a 128-bit KEK".
452    // <https://datatracker.ietf.org/doc/html/rfc3394#section-4.1>
453    // -----------------------------------------------------------------
454    const RFC3394_KEK_128: [u8; 16] = [
455        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
456        0x0F,
457    ];
458    const RFC3394_KEY_DATA_128: [u8; 16] = [
459        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
460        0xFF,
461    ];
462    const RFC3394_WRAPPED_128: [u8; 24] = [
463        0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B,
464        0x82, 0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5,
465    ];
466
467    #[test]
468    fn rfc3394_wrap_matches_worked_vector() {
469        let (icv, wrapped) = wrap_sek(&RFC3394_KEK_128, &RFC3394_KEY_DATA_128).unwrap();
470        assert_eq!(&icv[..], &RFC3394_WRAPPED_128[..8]);
471        assert_eq!(wrapped.as_slice(), &RFC3394_WRAPPED_128[8..]);
472    }
473
474    // -----------------------------------------------------------------
475    // packet_counter known-answer, hand-derived from libsrt
476    // haicrypt/hcrypt.h `hcrypt_SetCtrIV`:
477    //   memset(iv,0,16); memcpy(&iv[10], pki, 4); iv[0..14] ^= salt[0..14];
478    // For salt = 01 02 … 10 and pki = 0x11223344:
479    //   [0..10]  = salt[0..10]                = 01 02 03 04 05 06 07 08 09 0A
480    //   [10]     = salt[10]^0x11 = 0x0B^0x11  = 1A
481    //   [11]     = salt[11]^0x22 = 0x0C^0x22  = 2E
482    //   [12]     = salt[12]^0x33 = 0x0D^0x33  = 3E
483    //   [13]     = salt[13]^0x44 = 0x0E^0x44  = 4A
484    //   [14..16] = 00 00                        (block counter, salt[14..] unused)
485    // The old `MSB(112,Salt) << 2` construction gives byte[0]=0x04 (not 0x01)
486    // and different [10..14] — this test BITES against that regression.
487    // -----------------------------------------------------------------
488    #[test]
489    fn packet_counter_matches_libsrt_hcrypt_setctriv() {
490        let salt: [u8; SALT_LEN] = [
491            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
492            0x0F, 0x10,
493        ];
494        let expected: [u8; AES_BLOCK_LEN] = [
495            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x1A, 0x2E, 0x3E, 0x4A,
496            0x00, 0x00,
497        ];
498        let got = packet_counter(&salt, 0x1122_3344);
499        assert_eq!(got, expected, "counter must match hcrypt_SetCtrIV (no <<2)");
500        // Explicit guard against the buggy left-shift construction.
501        assert_eq!(got[0], 0x01, "byte 0 is pure salt, not the <<2 value 0x04");
502    }
503
504    #[test]
505    fn rfc3394_unwrap_matches_worked_vector() {
506        let mut icv = [0u8; 8];
507        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
508        let recovered = unwrap_sek(&RFC3394_KEK_128, &icv, &RFC3394_WRAPPED_128[8..]).unwrap();
509        assert_eq!(recovered.as_slice(), &RFC3394_KEY_DATA_128[..]);
510    }
511
512    #[test]
513    fn rfc3394_unwrap_rejects_wrong_kek() {
514        let mut icv = [0u8; 8];
515        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
516        let mut wrong_kek = RFC3394_KEK_128;
517        wrong_kek[0] ^= 0xFF;
518        assert!(matches!(
519            unwrap_sek(&wrong_kek, &icv, &RFC3394_WRAPPED_128[8..]),
520            Err(crate::error::Error::InvalidField(..))
521        ));
522    }
523
524    // -----------------------------------------------------------------
525    // SRT §6 payload round-trip (no spec test vectors exist for this —
526    // srt-crypto.md's "No test vectors" note — so this exercises the crate's
527    // own packet_counter + aes_ctr_apply against each other, not an
528    // external ground truth).
529    // -----------------------------------------------------------------
530
531    #[test]
532    fn srt_payload_round_trips_and_wrong_sek_does_not_recover() {
533        let sek = [0x42u8; 16];
534        let salt = [0x99u8; SALT_LEN];
535        let pkt_seq_no = 0x0123_4567u32;
536        let plaintext = b"SRT payload encryption round trip test vector.".to_vec();
537
538        let mut encrypted = plaintext.clone();
539        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut encrypted).unwrap();
540        assert_ne!(encrypted, plaintext, "encryption must change the bytes");
541
542        let mut decrypted = encrypted.clone();
543        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut decrypted).unwrap();
544        assert_eq!(
545            decrypted, plaintext,
546            "correct SEK must recover the plaintext"
547        );
548
549        let wrong_sek = [0x43u8; 16];
550        let mut wrongly_decrypted = encrypted;
551        aes_ctr_apply(&wrong_sek, &salt, pkt_seq_no, &mut wrongly_decrypted).unwrap();
552        assert_ne!(
553            wrongly_decrypted, plaintext,
554            "wrong SEK must not recover the plaintext"
555        );
556    }
557
558    #[test]
559    fn different_seq_no_gives_different_keystream() {
560        let sek = [0x11u8; 24];
561        let salt = [0x22u8; SALT_LEN];
562        let plaintext = [0u8; 32];
563
564        let mut a = plaintext;
565        aes_ctr_apply(&sek, &salt, 1, &mut a).unwrap();
566        let mut b = plaintext;
567        aes_ctr_apply(&sek, &salt, 2, &mut b).unwrap();
568        assert_ne!(a, b);
569    }
570
571    #[test]
572    fn kek_derivation_all_sizes_and_deterministic() {
573        for klen in [16usize, 24, 32] {
574            let salt = [0xABu8; SALT_LEN];
575            let kek1 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
576            let kek2 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
577            assert_eq!(kek1.len(), klen);
578            assert_eq!(kek1, kek2, "PBKDF2 is deterministic for the same inputs");
579
580            let different_salt = [0xACu8; SALT_LEN];
581            let kek3 = derive_kek(b"correct horse battery staple", &different_salt, klen).unwrap();
582            assert_ne!(kek1, kek3, "different salt must give a different KEK");
583        }
584    }
585
586    #[test]
587    fn invalid_klen_errs_without_panic() {
588        let salt = [0u8; SALT_LEN];
589        assert!(matches!(
590            derive_kek(b"pw", &salt, 20),
591            Err(crate::error::Error::InvalidField(..))
592        ));
593        assert!(matches!(
594            wrap_sek(&[0u8; 20], &[0u8; 16]),
595            Err(crate::error::Error::InvalidField(..))
596        ));
597        assert!(matches!(
598            aes_ctr_apply(&[0u8; 20], &salt, 0, &mut [0u8; 4]),
599            Err(crate::error::Error::InvalidField(..))
600        ));
601    }
602
603    #[test]
604    fn select_sek_picks_correct_parity_and_rejects_bad_flags() {
605        let even = [1u8; 16];
606        let odd = [2u8; 16];
607        assert_eq!(
608            select_sek(EncryptionKeyField::Even, Some(&even), Some(&odd)).unwrap(),
609            &even[..]
610        );
611        assert_eq!(
612            select_sek(EncryptionKeyField::Odd, Some(&even), Some(&odd)).unwrap(),
613            &odd[..]
614        );
615        assert!(matches!(
616            select_sek(EncryptionKeyField::Even, None, Some(&odd)),
617            Err(Error::InvalidField(..))
618        ));
619        assert!(matches!(
620            select_sek(EncryptionKeyField::NotEncrypted, Some(&even), Some(&odd)),
621            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
622        ));
623        assert!(matches!(
624            select_sek(EncryptionKeyField::Reserved(0b11), Some(&even), Some(&odd)),
625            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
626        ));
627        assert!(matches!(
628            select_sek(EncryptionKeyField::Even, None, Some(&odd)),
629            Err(Error::InvalidField(ref e)) if e.reason.contains("even")
630        ));
631        assert!(matches!(
632            select_sek(EncryptionKeyField::Odd, Some(&even), None),
633            Err(Error::InvalidField(ref e)) if e.reason.contains("odd")
634        ));
635    }
636
637    #[test]
638    fn both_seks_wrap_unwrap_round_trip() {
639        // KK=Both: two concatenated SEKs wrapped under one KEK/ICV, matching
640        // the Wrap-field length formula `n*KLen + 8` (`srt-rules.md` §3.2.2).
641        let kek = [0x77u8; 16];
642        let even_sek = [0xAAu8; 16];
643        let odd_sek = [0xBBu8; 16];
644        let mut plaintext = Vec::new();
645        plaintext.extend_from_slice(&even_sek);
646        plaintext.extend_from_slice(&odd_sek);
647
648        let (icv, wrapped) = wrap_sek(&kek, &plaintext).unwrap();
649        assert_eq!(wrapped.len(), 32);
650        let recovered = unwrap_sek(&kek, &icv, &wrapped).unwrap();
651        assert_eq!(&recovered[..], &plaintext[..]);
652        assert_eq!(&recovered[..16], &even_sek[..]);
653        assert_eq!(&recovered[16..], &odd_sek[..]);
654    }
655
656    /// #2840: an identical `(Salt, KLen)` request is served from the cache,
657    /// so a peer re-sending Key Material does not rerun PBKDF2. A different
658    /// salt or key length misses and derives again.
659    #[test]
660    fn kek_cache_derives_once_per_salt_and_length() {
661        let mut cache = KekCache::new();
662        let salt = [0x33u8; SALT_LEN];
663        let first = cache.derive(b"cache-passphrase", &salt, 16).unwrap();
664        let again = cache.derive(b"cache-passphrase", &salt, 16).unwrap();
665        assert_eq!(&first[..], &again[..]);
666        assert_eq!(cache.derivations(), 1, "same salt and length is a hit");
667
668        let other_salt = [0x44u8; SALT_LEN];
669        let third = cache.derive(b"cache-passphrase", &other_salt, 16).unwrap();
670        assert_ne!(&first[..], &third[..]);
671        assert_eq!(cache.derivations(), 2, "a new salt misses");
672
673        let longer = cache.derive(b"cache-passphrase", &salt, 24).unwrap();
674        assert_eq!(longer.len(), 24);
675        assert_eq!(cache.derivations(), 3, "a new length misses");
676    }
677}