Skip to main content

sheathe_crypto/
pssh.rs

1//! Protection System Specific Header (`pssh`) box generation.
2//!
3//! A `pssh` box carries the per-DRM-system data a player hands to its CDM to
4//! obtain the content key. sheathe generates the boxes directly from the raw
5//! key (the same path Shaka Packager's `--protection_systems` takes), so no key
6//! server is involved:
7//!
8//! - **Common** (`1077efec…`) — a version-1 box listing the `KID`(s); no system
9//!   data. The W3C clear-key / `urn:mpeg:dash:mp4protection` family.
10//! - **Widevine** (`edef8ba9…`) — a version-0 box whose data is a
11//!   `WidevinePsshData` protobuf: the `KID` and the protection-scheme fourcc.
12//! - **PlayReady** (`9a04f079…`) — a version-0 box wrapping a PlayReady Object
13//!   that carries a UTF-16LE `WRMHEADER` 4.0.0.0 (KID, key length, ALGID, and a
14//!   checksum proving possession of the key).
15
16use crate::{ContentKey, Scheme};
17use aes::Aes128;
18use aes::cipher::{BlockCipherEncrypt, KeyInit};
19
20/// Common (clear-key family) System ID — `urn:mpeg:dash:mp4protection`.
21const COMMON_SYSTEM_ID: [u8; 16] = [
22    0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02, 0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b,
23];
24/// Widevine System ID.
25const WIDEVINE_SYSTEM_ID: [u8; 16] = [
26    0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d, 0x21, 0xed,
27];
28/// PlayReady System ID.
29const PLAYREADY_SYSTEM_ID: [u8; 16] = [
30    0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95,
31];
32
33/// A DRM protection system a `pssh` box can be generated for.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ProtectionSystem {
36    /// W3C Common / clear-key family (`urn:mpeg:dash:mp4protection`).
37    Common,
38    /// Google Widevine.
39    Widevine,
40    /// Microsoft PlayReady.
41    PlayReady,
42}
43
44impl ProtectionSystem {
45    /// Parse a case-insensitive system name (as used on the command line).
46    pub fn parse(name: &str) -> Option<Self> {
47        match name.trim().to_ascii_lowercase().as_str() {
48            "common" | "commonsystem" => Some(Self::Common),
49            "widevine" => Some(Self::Widevine),
50            "playready" => Some(Self::PlayReady),
51            _ => None,
52        }
53    }
54
55    /// The 16-byte DRM System ID written into the `pssh` box.
56    pub fn system_id(self) -> [u8; 16] {
57        match self {
58            Self::Common => COMMON_SYSTEM_ID,
59            Self::Widevine => WIDEVINE_SYSTEM_ID,
60            Self::PlayReady => PLAYREADY_SYSTEM_ID,
61        }
62    }
63
64    /// Build the complete `pssh` box for this system, protecting `key` under
65    /// `scheme`.
66    pub fn pssh_box(self, key: &ContentKey, scheme: Scheme) -> Vec<u8> {
67        self.pssh_box_ex(key, scheme, None)
68    }
69
70    /// Like [`Self::pssh_box`], with optional extra PlayReady header XML
71    /// (Shaka `--playready_extra_header_data`) spliced into the WRMHEADER.
72    pub fn pssh_box_ex(
73        self,
74        key: &ContentKey,
75        scheme: Scheme,
76        playready_extra: Option<&str>,
77    ) -> Vec<u8> {
78        match self {
79            Self::Common => assemble(self.system_id(), 1, &[key.kid], &[]),
80            Self::Widevine => assemble(self.system_id(), 0, &[], &widevine_data(key, scheme)),
81            Self::PlayReady => {
82                assemble(self.system_id(), 0, &[], &playready_data(key, scheme, playready_extra))
83            }
84        }
85    }
86}
87
88/// Assemble a `pssh` box. Version 1 carries a `KID` list; version 0 omits it.
89fn assemble(system_id: [u8; 16], version: u8, kids: &[[u8; 16]], data: &[u8]) -> Vec<u8> {
90    let mut body = Vec::new();
91    body.extend_from_slice(b"pssh");
92    body.push(version);
93    body.extend_from_slice(&[0, 0, 0]); // flags
94    body.extend_from_slice(&system_id);
95    if version >= 1 {
96        body.extend_from_slice(&(kids.len() as u32).to_be_bytes());
97        for kid in kids {
98            body.extend_from_slice(kid);
99        }
100    }
101    body.extend_from_slice(&(data.len() as u32).to_be_bytes());
102    body.extend_from_slice(data);
103
104    let mut out = ((body.len() + 4) as u32).to_be_bytes().to_vec();
105    out.extend_from_slice(&body);
106    out
107}
108
109/// `WidevinePsshData` protobuf: `key_id` (field 2) and `protection_scheme`
110/// (field 9, the scheme fourcc as a big-endian `uint32`).
111fn widevine_data(key: &ContentKey, scheme: Scheme) -> Vec<u8> {
112    let mut data = Vec::new();
113    data.push(0x12); // field 2 (key_id), wire type 2 (length-delimited)
114    data.push(0x10); // length 16
115    data.extend_from_slice(&key.kid);
116    data.push(0x48); // field 9 (protection_scheme), wire type 0 (varint)
117    put_varint(u32::from_be_bytes(scheme.scheme_type()), &mut data);
118    data
119}
120
121/// Append `value` as a protobuf base-128 varint.
122fn put_varint(mut value: u32, out: &mut Vec<u8>) {
123    loop {
124        let byte = (value & 0x7f) as u8;
125        value >>= 7;
126        if value == 0 {
127            out.push(byte);
128            return;
129        }
130        out.push(byte | 0x80);
131    }
132}
133
134/// A PlayReady Object wrapping a single Rights Management Header (`WRMHEADER`).
135fn playready_data(key: &ContentKey, scheme: Scheme, extra: Option<&str>) -> Vec<u8> {
136    let kid = playready_guid(&key.kid);
137    let kid_b64 = base64(&kid);
138    let checksum_b64 = base64(&playready_checksum(&key.key, &kid));
139    // CTR schemes use AESCTR; CBC schemes use AESCBC.
140    let algid = if scheme.is_cbc() { "AESCBC" } else { "AESCTR" };
141    let extra = extra.unwrap_or("");
142
143    let xml = format!(
144        "<WRMHEADER xmlns=\"http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader\" \
145         version=\"4.0.0.0\"><DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>{algid}</ALGID>\
146         </PROTECTINFO><KID>{kid_b64}</KID><CHECKSUM>{checksum_b64}</CHECKSUM>{extra}</DATA></WRMHEADER>"
147    );
148    let header: Vec<u8> = xml.encode_utf16().flat_map(u16::to_le_bytes).collect();
149
150    // One record: type 1 (Rights Management Header) + length + UTF-16LE header.
151    let record_len = header.len() as u16;
152    // PlayReady Object: total length (incl. itself) + record count + record.
153    let total_len = 4 + 2 + 2 + 2 + header.len();
154    let mut obj = Vec::with_capacity(total_len);
155    obj.extend_from_slice(&(total_len as u32).to_le_bytes());
156    obj.extend_from_slice(&1u16.to_le_bytes()); // record count
157    obj.extend_from_slice(&1u16.to_le_bytes()); // record type: RM header
158    obj.extend_from_slice(&record_len.to_le_bytes());
159    obj.extend_from_slice(&header);
160    obj
161}
162
163/// Reorder a `KID` into PlayReady's little-endian GUID byte order (the first
164/// three GUID fields are byte-swapped; the trailing eight bytes are unchanged).
165fn playready_guid(kid: &[u8; 16]) -> [u8; 16] {
166    let mut g = *kid;
167    g.swap(0, 3);
168    g.swap(1, 2);
169    g.swap(4, 5);
170    g.swap(6, 7);
171    g
172}
173
174/// PlayReady header checksum: the first 8 bytes of AES-128-ECB encrypting the
175/// (GUID-ordered) `KID` with the content key.
176fn playready_checksum(key: &[u8; 16], guid_kid: &[u8; 16]) -> [u8; 8] {
177    let cipher = Aes128::new_from_slice(key).expect("AES-128 key is 16 bytes");
178    let mut block = (*guid_kid).into();
179    cipher.encrypt_block(&mut block);
180    block[..8].try_into().unwrap()
181}
182
183/// Standard Base64 encoding (RFC 4648, with `=` padding).
184fn base64(input: &[u8]) -> String {
185    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
186    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
187    for chunk in input.chunks(3) {
188        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
189        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
190        out.push(ALPHABET[(n >> 18 & 0x3f) as usize] as char);
191        out.push(ALPHABET[(n >> 12 & 0x3f) as usize] as char);
192        out.push(if chunk.len() > 1 { ALPHABET[(n >> 6 & 0x3f) as usize] as char } else { '=' });
193        out.push(if chunk.len() > 2 { ALPHABET[(n & 0x3f) as usize] as char } else { '=' });
194    }
195    out
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    // KID/KEY used to capture the Shaka Packager oracle bytes below.
203    const KID: [u8; 16] = [
204        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
205        0xff,
206    ];
207    const KEY: [u8; 16] = [
208        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
209        0xff,
210    ];
211
212    fn key() -> ContentKey {
213        ContentKey { kid: KID, key: KEY }
214    }
215
216    fn hex(bytes: &[u8]) -> String {
217        bytes.iter().map(|b| format!("{b:02x}")).collect()
218    }
219
220    #[test]
221    fn base64_matches_known_vectors() {
222        assert_eq!(base64(b""), "");
223        assert_eq!(base64(b"f"), "Zg==");
224        assert_eq!(base64(b"fo"), "Zm8=");
225        assert_eq!(base64(b"foo"), "Zm9v");
226        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
227    }
228
229    #[test]
230    fn common_pssh_matches_shaka() {
231        let got = ProtectionSystem::Common.pssh_box(&key(), Scheme::Cenc);
232        assert_eq!(
233            hex(&got),
234            "0000003470737368010000001077efecc0b24d02ace33c1e52e2fb4b\
235             0000000111223344556677889900aabbccddeeff00000000"
236        );
237    }
238
239    #[test]
240    fn widevine_pssh_matches_shaka() {
241        let got = ProtectionSystem::Widevine.pssh_box(&key(), Scheme::Cenc);
242        assert_eq!(
243            hex(&got),
244            "000000387073736800000000edef8ba979d64acea3c827dcd51d21ed\
245             00000018121011223344556677889900aabbccddeeff48e3dc959b06"
246        );
247    }
248
249    #[test]
250    fn playready_pssh_matches_shaka() {
251        let got = ProtectionSystem::PlayReady.pssh_box(&key(), Scheme::Cenc);
252        // Full box captured byte-for-byte from Shaka `--protection_systems
253        // PlayReady` (the UTF-16LE WRMHEADER, swapped-GUID KID, and checksum).
254        let expected = concat!(
255            "0000022670737368000000009a04f07998404286ab92e65be0885f9500000206060200000100010",
256            "0fc013c00570052004d00480045004100440045005200200078006d006c006e0073003d002200680",
257            "07400740070003a002f002f0073006300680065006d00610073002e006d006900630072006f0073",
258            "006f00660074002e0063006f006d002f00440052004d002f00320030003000370",
259            "02f00300033002f0050006c0061007900520065006100640079004800650061006",
260            "4006500720022002000760065007200730069006f006e003d00220034002e0030",
261            "002e0030002e00300022003e003c0044004100540041003e003c00500052004f005",
262            "40045004300540049004e0046004f003e003c004b00450059004c0045004e003e0",
263            "0310036003c002f004b00450059004c0045004e003e003c0041004c00470049004",
264            "4003e004100450053004300540052003c002f0041004c004700490044003e003c0",
265            "02f00500052004f00540045004300540049004e0046004f003e003c004b0049004",
266            "4003e00520044004d006900450057005a0056006900480065005a0041004b00710",
267            "037007a004e00330075002f0077003d003d003c002f004b00490044003e003c004",
268            "3004800450043004b00530055004d003e00350041006100550053004600700056",
269            "004800640030003d003c002f0043004800450043004b00530055004d003e003c00",
270            "2f0044004100540041003e003c002f00570052004d004800450041004400450052003e00",
271        );
272        assert_eq!(hex(&got), expected);
273    }
274
275    #[test]
276    fn widevine_protection_scheme_tracks_fourcc() {
277        // Field 9 (protection_scheme) is the scheme fourcc as a big-endian u32,
278        // so cbcs differs from cenc only in the trailing varint while sharing the
279        // KID prefix (field 2).
280        let cenc = ProtectionSystem::Widevine.pssh_box(&key(), Scheme::Cenc);
281        let cbcs = ProtectionSystem::Widevine.pssh_box(&key(), Scheme::Cbcs);
282        assert_ne!(cenc, cbcs);
283        let kid_prefix = hex(&[&[0x12, 0x10][..], &KID].concat());
284        assert!(hex(&cenc).contains(&kid_prefix) && hex(&cbcs).contains(&kid_prefix));
285    }
286
287    #[test]
288    fn parse_is_case_insensitive() {
289        assert_eq!(ProtectionSystem::parse("Widevine"), Some(ProtectionSystem::Widevine));
290        assert_eq!(ProtectionSystem::parse("PLAYREADY"), Some(ProtectionSystem::PlayReady));
291        assert_eq!(ProtectionSystem::parse("commonsystem"), Some(ProtectionSystem::Common));
292        assert_eq!(ProtectionSystem::parse("nope"), None);
293    }
294}