simulcrypt 0.2.2

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
use derive_more::Display;
use rand::Rng;

/// Crypto period parity: selects which physical CSA slot to update.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Display)]
pub enum Parity {
    /// Slot for even crypto period numbers.
    #[display("even")]
    Even,
    /// Slot for odd crypto period numbers.
    #[display("odd")]
    Odd,
}

impl Parity {
    /// Parity of a crypto period number: even -> [`Parity::Even`], odd -> [`Parity::Odd`].
    #[must_use]
    pub const fn from_cp_number(cp_number: u16) -> Self {
        if cp_number & 1 == 0 {
            Parity::Even
        } else {
            Parity::Odd
        }
    }
}

/// Result of one CW rotation step.
///
/// `current` is the slot this rotation left untouched (the ECMG already knows it under `cp_number`
/// from the previous step); `next` is the slot just overwritten (the lead CW for `cp_number + 1`,
/// sent to the ECMG in advance). `active` is what goes to the scrambler at this moment, and it is
/// NOT the freshly overwritten slot but `current` - the key the ECMG already received under
/// `cp_number` on the previous step. The fresh `next` only goes into `CW_PROVISION` and reaches the
/// scrambler one step later, when it becomes `current`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CwAdvance {
    /// Crypto period number paired with `current` in `CW_PROVISION`.
    pub cp_number: u16,
    /// Parity of `cp_number`, the period `active` is loaded for.
    pub parity: Parity,
    /// Key to load into the scrambler right now (equal to `current`).
    pub active: [u8; 8],
    /// Key the ECMG already knows under `cp_number`.
    pub current: [u8; 8],
    /// Freshly generated key - the lead CW for `cp_number + 1`.
    pub next: [u8; 8],
}

/// Control word pair generator for one CW group. Pure module, no tokio.
///
/// Holds two physical slots: an even `cw_number` overwrites slot 0, an odd one slot 1. On init slot
/// 1 is pre-filled and `cw_number = 0`.
#[derive(Debug)]
pub struct CwGenerator {
    slots: [[u8; 8]; 2],
    cw_number: u16,
}

impl CwGenerator {
    /// Creates a generator with the odd slot pre-filled with a random key. `cp_number()` is 0.
    pub fn new(rng: &mut impl Rng) -> Self {
        let mut slots = [[0u8; 8]; 2];
        Self::fill_key(&mut slots[1], rng);

        Self {
            slots,
            cw_number: 0,
        }
    }

    /// Generates the CW for the next crypto period and advances the counter.
    pub fn advance(&mut self, rng: &mut impl Rng) -> CwAdvance {
        let written = (self.cw_number & 1) as usize;
        let kept = 1 - written;

        Self::fill_key(&mut self.slots[written], rng);

        let current_cp = self.cw_number;
        let next_cp = self.cw_number.wrapping_add(1);

        let advance = CwAdvance {
            cp_number: current_cp,
            parity: Parity::from_cp_number(current_cp),
            active: self.slots[kept],
            current: self.slots[kept],
            next: self.slots[written],
        };

        self.cw_number = next_cp;
        advance
    }

    /// `key[3]`/`key[7]` are the DVB-CSA check bytes and must match the reference formula,
    /// otherwise receivers cannot descramble the stream.
    fn fill_key(key: &mut [u8; 8], rng: &mut impl Rng) {
        rng.fill_bytes(key);
        key[3] = key[0].wrapping_add(key[1]).wrapping_add(key[2]);
        key[7] = key[4].wrapping_add(key[5]).wrapping_add(key[6]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Deterministic test RNG: yields counter bytes instead of random ones.
    struct StepRng(u8);

    impl rand::TryRng for StepRng {
        type Error = std::convert::Infallible;

        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
            let mut buf = [0u8; 4];
            self.try_fill_bytes(&mut buf)?;
            Ok(u32::from_le_bytes(buf))
        }

        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
            let mut buf = [0u8; 8];
            self.try_fill_bytes(&mut buf)?;
            Ok(u64::from_le_bytes(buf))
        }

        fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
            for byte in dst {
                *byte = self.0;
                self.0 = self.0.wrapping_add(1);
            }
            Ok(())
        }
    }

    fn checksum_fix(mut key: [u8; 8]) -> [u8; 8] {
        key[3] = key[0].wrapping_add(key[1]).wrapping_add(key[2]);
        key[7] = key[4].wrapping_add(key[5]).wrapping_add(key[6]);
        key
    }

    #[test]
    fn checksum_bytes_match_csa_formula() {
        let mut rng = StepRng(0);
        let mut key = [0u8; 8];
        CwGenerator::fill_key(&mut key, &mut rng);

        assert_eq!(key[3], key[0].wrapping_add(key[1]).wrapping_add(key[2]));
        assert_eq!(key[7], key[4].wrapping_add(key[5]).wrapping_add(key[6]));
    }

    #[test]
    fn init_prefills_odd_slot_only() {
        let mut rng = StepRng(1);
        let generator = CwGenerator::new(&mut rng);

        assert_eq!(generator.slots[0], [0u8; 8]);
        assert_ne!(generator.slots[1], [0u8; 8]);
        assert_eq!(generator.cw_number, 0);
    }

    #[test]
    fn first_advance_writes_even_slot_and_keeps_init_key_as_current() {
        let mut rng = StepRng(1);
        let mut generator = CwGenerator::new(&mut rng);
        let init_odd_key = generator.slots[1];

        let step = generator.advance(&mut rng);

        assert_eq!(step.cp_number, 0);
        assert_eq!(step.parity, Parity::Even); // cp_number == 0
        assert_eq!(step.current, init_odd_key); // untouched slot
        assert_eq!(step.next, generator.slots[0]); // freshly written slot
        // The scrambler always uses `current`, not the slot just written - it applies a key
        // ECMG already confirmed a period ago.
        assert_eq!(step.active, step.current);
        assert_eq!(generator.cw_number, 1);
    }

    #[test]
    fn second_advance_writes_odd_slot_and_keeps_first_advance_key_as_current() {
        let mut rng = StepRng(1);
        let mut generator = CwGenerator::new(&mut rng);
        let first = generator.advance(&mut rng);

        let second = generator.advance(&mut rng);

        assert_eq!(second.cp_number, 1);
        assert_eq!(second.parity, Parity::Odd); // cp_number == 1
        assert_eq!(second.current, first.next); // slot written by the previous advance
        assert_eq!(second.next, generator.slots[1]);
        assert_eq!(second.active, second.current);
    }

    /// Vectors produced by an independent C implementation of the same control word algorithm
    /// (`tests/vectors/cw_reference.c`), with the same deterministic byte source as `StepRng` here:
    ///
    /// ```text
    /// cc -O2 -o cw_reference tests/vectors/cw_reference.c && ./cw_reference 1 8
    /// ```
    #[test]
    fn matches_independent_reference_vectors() {
        const VECTORS: [(u16, &str, &str); 8] = [
            (0, "0102030605060712", "090a0b1e0d0e0f2a"),
            (1, "090a0b1e0d0e0f2a", "1112133615161742"),
            (2, "1112133615161742", "191a1b4e1d1e1f5a"),
            (3, "191a1b4e1d1e1f5a", "2122236625262772"),
            (4, "2122236625262772", "292a2b7e2d2e2f8a"),
            (5, "292a2b7e2d2e2f8a", "31323396353637a2"),
            (6, "31323396353637a2", "393a3bae3d3e3fba"),
            (7, "393a3bae3d3e3fba", "414243c6454647d2"),
        ];

        fn hex8(s: &str) -> [u8; 8] {
            let mut out = [0u8; 8];
            for (i, byte) in out.iter_mut().enumerate() {
                *byte = u8::from_str_radix(&s[i * 2 .. i * 2 + 2], 16).unwrap();
            }
            out
        }

        let mut rng = StepRng(1);
        let mut generator = CwGenerator::new(&mut rng);

        for (cp_number, current_hex, next_hex) in VECTORS {
            let step = generator.advance(&mut rng);
            assert_eq!(step.cp_number, cp_number);
            assert_eq!(
                step.current,
                hex8(current_hex),
                "current mismatch at cp={cp_number}"
            );
            assert_eq!(step.next, hex8(next_hex), "next mismatch at cp={cp_number}");
            assert_eq!(
                step.active, step.current,
                "active must equal current at cp={cp_number}"
            );
        }
    }

    #[test]
    fn advance_alternates_written_slot_across_many_periods() {
        let mut rng = StepRng(7);
        let mut generator = CwGenerator::new(&mut rng);

        for cw_number in 0 .. 8u16 {
            let before = generator.slots;
            let step = generator.advance(&mut rng);
            let written = (cw_number & 1) as usize;
            let kept = 1 - written;

            assert_eq!(step.current, checksum_fix(before[kept]));
            assert_eq!(step.next, checksum_fix(generator.slots[written]));
            assert_ne!(before[written], generator.slots[written]);
            assert_eq!(before[kept], generator.slots[kept]);
        }
    }
}