AACS pipeline reshape + TrueHD metadata + central consts + clippy/fmt clean

- AACS: delete in-lib keydb parser (Step 3); boil-down primitives
  (mk_from_dk/vuk_from_mk/uk_from_vuk) + newtypes; KeySource->get_uk(ctx)+
  ResolveCtx; Unlocker->unlock()->Result<Vid,UnlockError> + AacsCertUnlocker;
  OEM bus-key gate (AacsBusKeyUnavailable); structured ResolutionTrace (Step 4).
- TrueHD: sample-rate from major-sync, Atmos label, 44.1k AU duration.
- consts: central media/format constants module; 17 duplicate const-defs
  centralized (sector/TS-packet/source-packet); mpls stream-entry + category
  codes named.
- clippy --all-targets -D warnings clean (1.86); fmt clean; 2199 lib tests.
This commit is contained in:
Matthew Jackson
2026-06-26 12:19:24 -07:00
parent 05729f5dfe
commit decb87a250
48 changed files with 2208 additions and 2031 deletions
+200
View File
@@ -0,0 +1,200 @@
//! AACS derivation "boil-down" — one public home for the key chain.
//!
//! Thin newtypes at the API boundary and three wrapper functions over the
//! existing crypto. Nothing here re-implements a primitive: every function
//! delegates to the already-audited code in [`super::keys`] and
//! [`super::variants`], so the boil-down cannot drift from production math.
//!
//! The newtypes wrap bare `[u8; 16]` ONLY at this boundary — the crypto
//! internals continue to operate on raw arrays. They exist so a caller threads
//! the chain `DK → MK → VUK → UK` without confusing one 16-byte secret for
//! another, not to refactor the resolver.
//!
//! Chain (matches `aacs::keys::resolve_keys_classical` path 1 and
//! `aacs::keys::resolve_keys_v21` path 1 byte-for-byte):
//!
//! ```text
//! mk_from_dk(device_keys, mkb, vid) → MediaKey (Km)
//! vuk_from_mk(MediaKey, Vid) → Vuk (= AES-G(Km, VID))
//! uk_from_vuk(Vuk, enc_title_keys) → [UnitKey] (decrypt_unit_key each)
//! ```
use super::keys::{decrypt_unit_key, derive_vuk};
use super::types::DeviceKey;
use super::variants::{KEY_CORRECTION_DATA_PLACEHOLDER, derive_media_key_variant, walk_mkb};
/// Volume ID (16 bytes) — read from the disc via the SCSI handshake / OEM path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Vid(pub [u8; 16]);
/// Media Key (Km, 16 bytes) — the MKB-scoped key derived from device keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MediaKey(pub [u8; 16]);
/// Volume Unique Key (VUK / Kvu, 16 bytes) — derived from `MediaKey` + `Vid`,
/// decrypts the per-disc encrypted title keys in `Unit_Key_RO.inf`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Vuk(pub [u8; 16]);
/// One decrypted per-CPS-unit AACS title key.
///
/// `idx` is the POSITIONAL index of the encrypted title key within the slice
/// handed to [`uk_from_vuk`] (i.e. its order in `Unit_Key_RO.inf`'s key-storage
/// area). The CPS-unit *number* association (the `u32` in
/// `ResolvedKeys::unit_keys`) is a higher-level concern owned by
/// [`super::keys::parse_unit_key_ro`], which pairs each positional key with its
/// declared CPS unit; this primitive only does the AES, so it surfaces position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitKey {
pub idx: u32,
pub key: [u8; 16],
}
/// Derive the Volume Unique Key from a Media Key and Volume ID.
///
/// Wraps [`derive_vuk`] verbatim: `VUK = AES-128-ECB-DECRYPT(MK, VID) XOR VID`.
/// This is byte-identical to the inline `derive_vuk(&mk, ctx.volume_id)` call in
/// every classical resolver path AND to the `Kvu = AES-G(Km, VID)` step inside
/// [`derive_media_key_variant`] (AES-G and `derive_vuk` are the same math), so
/// `vuk_from_mk(mk_from_dk(..)?, vid)` reproduces the V21 variant VUK exactly.
pub fn vuk_from_mk(mk: MediaKey, vid: Vid) -> Vuk {
Vuk(derive_vuk(&mk.0, &vid.0))
}
/// Decrypt the disc's encrypted title keys with a VUK.
///
/// Wraps [`decrypt_unit_key`] (AES-128-ECB-DECRYPT) per entry, mirroring the
/// `derive_uks` closure in `resolve_keys_classical` / `resolve_keys_v21`. The
/// returned `UnitKey::idx` is the slice position; pair with CPS-unit numbers via
/// [`super::keys::parse_unit_key_ro`] when the numbering matters.
pub fn uk_from_vuk(vuk: Vuk, enc_title_keys: &[[u8; 16]]) -> Vec<UnitKey> {
enc_title_keys
.iter()
.enumerate()
.map(|(i, enc)| UnitKey {
idx: i as u32,
key: decrypt_unit_key(&vuk.0, enc),
})
.collect()
}
/// Derive the Media Key (Km) from device keys via the Media Key Variant chain.
///
/// Wraps [`walk_mkb`] + [`derive_media_key_variant`] with exactly the arguments
/// `resolve_keys_v21` path 1 passes: the placeholder Key Correction Data and the
/// disc Volume ID. Returns the FIRST tuple element `Km` (the Media Key) — the
/// resolver treats `Km` as the media key and derives the VUK from it as
/// `Kvu = AES-G(Km, VID)`, which equals [`vuk_from_mk`]`(MediaKey(km), vid)`. The
/// variant fn's second element is that already-derived `Kvu`; returning `Km`
/// keeps this primitive at the "media key" level so the chain composes.
///
/// Because the integrator KCD is unavailable in-tree (the placeholder is
/// rejected by the variant chain), this returns `Err` for every real disc today
/// — byte-for-byte identical to `resolve_keys_v21` path 1, which the resolver
/// also leaves unreachable in production. All variant-chain failures collapse to
/// [`Error::AacsMkUnavailable`] (E7018): no numeric distinction is load-bearing
/// at this boundary, and the variant error carries no English to preserve.
pub fn mk_from_dk(
device_keys: &[DeviceKey],
mkb: &[u8],
vid: Vid,
) -> Result<MediaKey, crate::error::Error> {
let records = walk_mkb(mkb);
match derive_media_key_variant(
&records,
device_keys,
&KEY_CORRECTION_DATA_PLACEHOLDER,
&vid.0,
) {
Ok((km, _kvu)) => Ok(MediaKey(km)),
Err(_) => Err(crate::error::Error::AacsMkUnavailable),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aacs::decrypt::aes_ecb_encrypt;
use crate::aacs::keys::{decrypt_unit_key, derive_vuk};
/// `vuk_from_mk` must equal the inline `derive_vuk` path bit-for-bit, for
/// several known (MK, VID) vectors.
#[test]
fn vuk_from_mk_matches_inline_derive_vuk() {
let cases: [([u8; 16], [u8; 16]); 3] = [
([0x5A; 16], [0xA5; 16]),
([0x11; 16], [0x22; 16]),
(
[
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F,
],
[
0xF0, 0xE1, 0xD2, 0xC3, 0xB4, 0xA5, 0x96, 0x87, 0x78, 0x69, 0x5A, 0x4B, 0x3C,
0x2D, 0x1E, 0x0F,
],
),
];
for (mk, vid) in cases {
let inline = derive_vuk(&mk, &vid);
let boiled = vuk_from_mk(MediaKey(mk), Vid(vid));
assert_eq!(boiled.0, inline, "vuk_from_mk must equal derive_vuk");
}
}
/// `uk_from_vuk` must equal the inline `decrypt_unit_key` path bit-for-bit
/// and carry positional indices 0..n. Built by encrypting known plaintext
/// title keys under the VUK (the same primitive the resolver inverts).
#[test]
fn uk_from_vuk_matches_inline_decrypt_unit_key() {
let vuk = [0x5Au8; 16];
let plain_keys = [[0x11u8; 16], [0x22u8; 16], [0xCDu8; 16]];
let enc: Vec<[u8; 16]> = plain_keys
.iter()
.map(|k| aes_ecb_encrypt(&vuk, k))
.collect();
let boiled = uk_from_vuk(Vuk(vuk), &enc);
assert_eq!(boiled.len(), enc.len());
for (i, uk) in boiled.iter().enumerate() {
assert_eq!(uk.idx, i as u32, "idx must be the positional index");
// Matches the inline derive_uks closure: decrypt_unit_key(vuk, enc).
assert_eq!(uk.key, decrypt_unit_key(&vuk, &enc[i]));
// And recovers the original plaintext title key.
assert_eq!(
uk.key, plain_keys[i],
"VUK roundtrip recovers the title key"
);
}
}
/// `uk_from_vuk` on an empty slice yields no keys (no panic, no phantom idx).
#[test]
fn uk_from_vuk_empty_is_empty() {
assert!(uk_from_vuk(Vuk([0u8; 16]), &[]).is_empty());
}
/// `mk_from_dk` returns `Err(AacsMkUnavailable)` for the placeholder-KCD
/// path that production also leaves unreachable — never a wrong key, never a
/// panic — on both an empty MKB and a non-variant MKB.
#[test]
fn mk_from_dk_errors_without_integrator_kcd() {
let dk = DeviceKey {
key: [0x11; 16],
node: 1,
uv: 1,
u_mask_shift: 0,
};
// Empty MKB → not a variant MKB → Err.
let e = mk_from_dk(std::slice::from_ref(&dk), &[], Vid([0x09; 16]));
assert!(matches!(e, Err(crate::error::Error::AacsMkUnavailable)));
// A variant-looking MKB (0x82 record) still cannot complete without the
// integrator KCD, so it also errors — never silently yields a key.
let mut mkb: Vec<u8> = Vec::new();
mkb.extend_from_slice(&[0x82, 0x00, 0x00, 0x14]); // variant data record
mkb.extend_from_slice(&[0xAB; 16]);
let e2 = mk_from_dk(&[dk], &mkb, Vid([0x09; 16]));
assert!(matches!(e2, Err(crate::error::Error::AacsMkUnavailable)));
}
}
+23 -23
View File
@@ -14,7 +14,7 @@ pub(crate) const AACS_IV: [u8; 16] = [
pub const ALIGNED_UNIT_LEN: usize = 6144;
/// An AACS aligned unit spans this many 2048-byte sectors (3).
pub const ALIGNED_UNIT_SECTORS: u32 = (ALIGNED_UNIT_LEN / SECTOR_LEN) as u32;
pub const ALIGNED_UNIT_SECTORS: u32 = (ALIGNED_UNIT_LEN / SECTOR_BYTES) as u32;
/// Whether `lba` sits on an AACS aligned-unit boundary, measured **relative to
/// the encrypted region's base LBA** (`unit_base` = the clip/extent `start_lba`,
@@ -40,11 +40,9 @@ pub fn is_unit_aligned(lba: u32, unit_base: u32) -> bool {
lba.saturating_sub(unit_base) % ALIGNED_UNIT_SECTORS == 0
}
/// Size of one sector.
const SECTOR_LEN: usize = 2048;
use crate::consts::SECTOR_BYTES;
/// Transport stream packet spacing in Blu-ray m2ts (192 bytes = 4 TP_extra + 188 TS).
const TS_PACKET_LEN: usize = 192;
use crate::consts::BD_SOURCE_PACKET_BYTES;
/// TS sync byte.
const TS_SYNC: u8 = 0x47;
@@ -133,7 +131,7 @@ pub fn ts_sync_count(unit: &[u8]) -> usize {
if unit[offset] == TS_SYNC {
count += 1;
}
offset += TS_PACKET_LEN;
offset += BD_SOURCE_PACKET_BYTES;
}
count
}
@@ -141,9 +139,9 @@ pub fn ts_sync_count(unit: &[u8]) -> usize {
/// Number of BD-TS packets in the unit — the maximum possible sync count.
pub fn ts_packet_total(unit: &[u8]) -> usize {
// One sync byte per 192-byte BD-TS packet (at offset 4 of each). The old
// `(len - 4) / TS_PACKET_LEN + 1` over-counted by one for lengths of the
// `(len - 4) / BD_SOURCE_PACKET_BYTES + 1` over-counted by one for lengths of the
// form `4 + k·192`.
unit.len() / TS_PACKET_LEN
unit.len() / BD_SOURCE_PACKET_BYTES
}
fn ts_syncs_intact(unit: &[u8]) -> bool {
@@ -298,14 +296,14 @@ pub fn decrypt_unit_try_keys(unit: &mut [u8], unit_keys: &[[u8; 16]]) -> Option<
/// Remove bus encryption from an aligned unit (AACS 2.0 / UHD).
/// Bus encryption uses read_data_key, decrypting bytes 16..2047 of each 2048-byte sector.
pub fn decrypt_bus(unit: &mut [u8], read_data_key: &[u8; 16]) {
for sector_start in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_LEN) {
if sector_start + SECTOR_LEN > unit.len() {
for sector_start in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_BYTES) {
if sector_start + SECTOR_BYTES > unit.len() {
break;
}
// First 16 bytes of each sector are plaintext
aes_cbc_decrypt(
read_data_key,
&mut unit[sector_start + 16..sector_start + SECTOR_LEN],
&mut unit[sector_start + 16..sector_start + SECTOR_BYTES],
);
}
}
@@ -385,7 +383,7 @@ mod tests {
let mut off = 4;
while off < ALIGNED_UNIT_LEN {
unit[off] = TS_SYNC;
off += TS_PACKET_LEN;
off += BD_SOURCE_PACKET_BYTES;
}
let key = [0u8; 16];
assert!(!is_aacs_scrambled(&unit));
@@ -401,7 +399,9 @@ mod tests {
let unit = vec![0u8; ALIGNED_UNIT_LEN];
assert_eq!(ts_packet_total(&unit), 32);
// Confirm the loop visits exactly that many stride positions.
let visited = (4..ALIGNED_UNIT_LEN).step_by(TS_PACKET_LEN).count();
let visited = (4..ALIGNED_UNIT_LEN)
.step_by(BD_SOURCE_PACKET_BYTES)
.count();
assert_eq!(visited, ts_packet_total(&unit));
}
@@ -419,7 +419,7 @@ mod tests {
let mut placed = 0;
while off < ALIGNED_UNIT_LEN && placed < n {
unit[off] = TS_SYNC;
off += TS_PACKET_LEN;
off += BD_SOURCE_PACKET_BYTES;
placed += 1;
}
unit
@@ -443,7 +443,7 @@ mod tests {
let mut off = 4;
while off < ALIGNED_UNIT_LEN {
clear[off] = TS_SYNC;
off += TS_PACKET_LEN;
off += BD_SOURCE_PACKET_BYTES;
}
assert_eq!(ts_sync_count(&clear), 32);
assert!(
@@ -500,7 +500,7 @@ mod tests {
let mut offset = 4;
while offset < ALIGNED_UNIT_LEN {
plain[offset] = TS_SYNC;
offset += TS_PACKET_LEN;
offset += BD_SOURCE_PACKET_BYTES;
}
// No flag set: CBC-encrypting the body below scrambles packets 1..31's
// TS syncs, which is exactly what `is_aacs_scrambled` (raw-sync) detects.
@@ -541,7 +541,7 @@ mod tests {
if unit[off] == TS_SYNC {
count += 1;
}
off += TS_PACKET_LEN;
off += BD_SOURCE_PACKET_BYTES;
}
// Assert against the single canonical packet count, not the old
// `(len - 4) / 192 + 1` form that `ts_packet_total` corrected away from.
@@ -584,7 +584,7 @@ mod tests {
let mut off = 4;
while off < ALIGNED_UNIT_LEN {
unit[off] = TS_SYNC;
off += TS_PACKET_LEN;
off += BD_SOURCE_PACKET_BYTES;
}
unit
}
@@ -877,10 +877,10 @@ mod tests {
// Forward: CBC-encrypt unit[s+16 .. s+2048] per sector under AACS IV.
let cipher = Aes128::new(GenericArray::from_slice(&rdk));
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_LEN) {
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_BYTES) {
let mut prev = AACS_IV;
let body = s + 16;
let end = s + SECTOR_LEN;
let end = s + SECTOR_BYTES;
let nblocks = (end - body) / 16;
for i in 0..nblocks {
let off = body + i * 16;
@@ -901,7 +901,7 @@ mod tests {
"decrypt_bus must invert per-sector bus encrypt"
);
// Each sector's first 16 bytes equal the original (never touched).
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_LEN) {
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_BYTES) {
assert_eq!(&unit[s..s + 16], &plain[s..s + 16]);
}
}
@@ -934,9 +934,9 @@ mod tests {
aacs_encrypt_unit(&mut unit, &unit_key);
// Layer 2: bus-encrypt on top (per-sector, bytes 16..2048).
let cipher = Aes128::new(GenericArray::from_slice(&rdk));
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_LEN) {
for s in (0..ALIGNED_UNIT_LEN).step_by(SECTOR_BYTES) {
let mut prev = AACS_IV;
for i in 0..((SECTOR_LEN - 16) / 16) {
for i in 0..((SECTOR_BYTES - 16) / 16) {
let off = s + 16 + i * 16;
for j in 0..16 {
unit[off + j] ^= prev[j];
+33 -16
View File
@@ -1573,27 +1573,44 @@ mod tests {
#[test]
fn test_verify_host_cert_from_keydb() {
// Verify the host cert from our KEYDB
let keydb_path = match std::env::var("KEYDB_PATH").ok() {
// Exercise verify_cert against a real AACS 1.0 host certificate.
//
// libfreemkv no longer parses keydb.cfg (the parser lives in
// freemkv-keysources), so the cert bytes are read from a raw 92-byte
// certificate file named by HOST_CERT_PATH instead of being pulled
// from a parsed KeyDb. This keeps verify_cert (private to this module,
// so it cannot move to keysources) covered against genuine LA-signed
// bytes without re-introducing a keydb dependency here. Inert in CI
// (env unset), matching the prior KEYDB_PATH gating.
let cert_path = match std::env::var("HOST_CERT_PATH").ok() {
Some(p) => std::path::PathBuf::from(p),
None => return, // skip if KEYDB_PATH not set
None => return,
};
if !keydb_path.exists() {
if !cert_path.exists() {
return;
}
let certificate = match std::fs::read(&cert_path) {
Ok(b) => b,
Err(_) => return,
};
let db = crate::aacs::KeyDb::load(&keydb_path).unwrap();
if let Some(hc) = db.host_certs.first() {
let valid = verify_cert(&hc.certificate);
eprintln!(
"Host cert verification: {}",
if valid { "PASS" } else { "FAIL" }
);
// Note: our cert is revoked but should still have valid LA signature
// If it doesn't verify, the LA public key might be wrong
if !valid {
eprintln!(" (cert may use different LA key or format)");
}
// Direct HostCert construction — no parser. Only `certificate` feeds
// verify_cert; the other fields are inert placeholders.
let hc = crate::aacs::HostCert {
private_key: [0u8; 20],
certificate,
private_key_v2: None,
certificate_v2: None,
};
let valid = verify_cert(&hc.certificate);
eprintln!(
"Host cert verification: {}",
if valid { "PASS" } else { "FAIL" }
);
// Note: a revoked cert should still carry a valid LA signature.
// If it doesn't verify, the LA public key might be wrong.
if !valid {
eprintln!(" (cert may use different LA key or format)");
}
}
-1011
View File
File diff suppressed because it is too large Load Diff
+107 -307
View File
@@ -1,7 +1,7 @@
//! AACS key resolution — VUK derivation, MKB processing, disc hash, unit key parsing.
use super::decrypt::aes_ecb_decrypt;
use super::keydb::DeviceKey;
use super::types::DeviceKey;
// ── AACS version ────────────────────────────────────────────────────────────
@@ -1529,16 +1529,10 @@ fn match_keydb_unit_keys(
#[cfg(test)]
mod tests {
use super::super::decrypt::{ALIGNED_UNIT_LEN, aes_ecb_encrypt};
use super::super::keydb::{DiscEntry, KeyDb};
use super::super::provider::SuppliedKey;
use super::super::types::DiscEntry;
use super::*;
/// Get KEYDB path from KEYDB_PATH environment variable. Returns None if not set or not found.
fn keydb_path() -> Option<std::path::PathBuf> {
let path = std::path::PathBuf::from(std::env::var("KEYDB_PATH").ok()?);
if path.exists() { Some(path) } else { None }
}
/// Finding #5 regression: parse_unit_key_ro must REJECT a Unit_Key_RO.inf
/// whose declared `num_unit_keys` exceeds the keys actually present in the
/// buffer, instead of silently returning a short list. A truncated list
@@ -1604,135 +1598,24 @@ mod tests {
let _ = derive_media_key_from_dk(&mkb, &[dk]);
}
#[test]
fn test_vuk_derivation() {
// Pick any UHD entry with a known MK, VID, and VUK from KEYDB.
// VUK = AES-DEC(MK, VID) XOR VID
let path = match keydb_path() {
Some(p) => p,
None => return,
};
let db = KeyDb::load(&path).unwrap();
// Find a disc with both MK, disc_id, and VUK so we can verify derivation
let entry = db
.disc_entries
.values()
.find(|e| e.media_key.is_some() && e.disc_id.is_some() && e.vuk.is_some())
.expect("No disc with MK + VID + VUK");
let mk = entry.media_key.unwrap();
let vid = entry.disc_id.unwrap();
let expected_vuk = entry.vuk.unwrap();
let derived = derive_vuk(&mk, &vid);
assert_eq!(
derived, expected_vuk,
"VUK derivation failed for disc: {} (hash {})",
entry.title, entry.disc_hash
);
eprintln!("VUK derivation verified for: {}", entry.title);
}
#[test]
fn test_decrypt_unit_key_from_vuk() {
// Test the full chain: VUK → decrypt encrypted unit key → unit key
// Use a known disc from KEYDB that has both VUK and unit keys
let path = match keydb_path() {
Some(p) => p,
None => return,
};
let db = KeyDb::load(&path).unwrap();
// Find a disc with VUK and unit keys
let entry = db
.disc_entries
.values()
.find(|e| e.vuk.is_some() && !e.unit_keys.is_empty())
.expect("No disc with VUK + unit keys");
eprintln!(
"Testing unit key decrypt for: {} ({})",
entry.title, entry.disc_hash
);
eprintln!(" VUK: {:02X?}", entry.vuk.unwrap());
for (num, key) in &entry.unit_keys {
eprintln!(" Unit key {}: {:02X?}", num, key);
}
// The unit keys in KEYDB are already decrypted — we can verify the chain
// by encrypting with VUK and then decrypting
let vuk = entry.vuk.unwrap();
for (num, expected_uk) in &entry.unit_keys {
let encrypted = aes_ecb_encrypt(&vuk, expected_uk);
// VUK → encrypted unit key → unit key roundtrip. The keydb-sourced
// variant of this test (which scanned a real KEYDB for VUK + unit
// keys) moved to freemkv-keysources; this rebuilt version exercises
// the same AES-G primitive (decrypt_unit_key ∘ aes_ecb_encrypt under a
// VUK) with directly-constructed material, so it needs no parser and
// keeps the crypto covered in libfreemkv. `aes_ecb_encrypt` is
// pub(crate), reachable here but not from keysources — the reason this
// half stays.
use super::super::decrypt::aes_ecb_encrypt;
let vuk = [0x5Au8; 16];
// A few representative "decrypted" unit keys.
for expected_uk in [[0x11u8; 16], [0x22u8; 16], [0xCDu8; 16]] {
let encrypted = aes_ecb_encrypt(&vuk, &expected_uk);
let decrypted = decrypt_unit_key(&vuk, &encrypted);
assert_eq!(
&decrypted, expected_uk,
"Unit key {} roundtrip failed for {}",
num, entry.title
);
assert_eq!(decrypted, expected_uk, "unit key roundtrip under VUK");
}
eprintln!(" All {} unit key roundtrips passed", entry.unit_keys.len());
}
#[test]
fn test_decrypt_real_unit() {
// Try decrypting a real encrypted aligned unit from a UHD sample.
// This disc is AACS 2.0 (BEE) so unit key alone won't work —
// we need bus decryption first. But this verifies the pipeline.
// Path comes from ENCRYPTED_UNIT_PATH (same env-driven pattern as the
// KEYDB_PATH / MKB_SAMPLE_DIR fixtures); no-ops in CI when unset.
let unit_path = match std::env::var("ENCRYPTED_UNIT_PATH").ok() {
Some(p) => std::path::PathBuf::from(p),
None => return,
};
if !unit_path.exists() {
return;
}
let original = std::fs::read(&unit_path).unwrap();
assert_eq!(original.len(), ALIGNED_UNIT_LEN);
assert!(
super::super::decrypt::is_aacs_scrambled(&original),
"Unit should be encrypted"
);
let kp = match keydb_path() {
Some(p) => p,
None => return,
};
let db = KeyDb::load(&kp).unwrap();
// Candidate entries: any UHD entry that carries unit keys.
let candidate_entries: Vec<&DiscEntry> = db
.disc_entries
.values()
.filter(|e| !e.unit_keys.is_empty())
.collect();
eprintln!("Found {} entries with unit keys", candidate_entries.len());
// Try each entry's unit keys
for entry in &candidate_entries {
let keys: Vec<[u8; 16]> = entry.unit_keys.iter().map(|(_, k)| *k).collect();
let mut unit = original.clone();
if let Some(res) = super::super::decrypt::decrypt_unit_try_keys(&mut unit, &keys) {
eprintln!(
"SUCCESS: Decrypted with entry {} ({res:?})",
entry.disc_hash
);
// Count TS sync bytes
let ts = (0..32).filter(|&i| unit[4 + i * 192] == 0x47).count();
eprintln!(" TS sync bytes: {}/32", ts);
return;
}
}
// Expected: none work because this is AACS 2.0 and needs bus decryption first
eprintln!("No unit key worked (expected for AACS 2.0 BEE disc — needs read_data_key)");
}
#[test]
@@ -1834,7 +1717,7 @@ mod tests {
mkb.extend_from_slice(&[0xAB; 16]);
mkb.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
let records_len = mkb.len();
mkb.extend(std::iter::repeat(0u8).take(128 * 1024)); // padding
mkb.extend(std::iter::repeat_n(0u8, 128 * 1024)); // padding
assert_eq!(mkb_content_len(&mkb), records_len);
// No padding → returns the full length.
assert_eq!(mkb_content_len(&mkb[..records_len]), records_len);
@@ -1869,7 +1752,7 @@ mod tests {
mkb.extend_from_slice(&[0xAB; 16]);
mkb.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
let records_len = mkb.len();
mkb.extend(std::iter::repeat(0u8).take(1024));
mkb.extend(std::iter::repeat_n(0u8, 1024));
assert_eq!(
trim_mkb(mkb).len(),
records_len,
@@ -2197,44 +2080,6 @@ mod tests {
assert_eq!(mkb_find_mk_dv(&mkb), Some(expected));
}
#[test]
fn test_resolve_keys_vuk_path() {
// Test the full resolve chain using VUK path
let path = match keydb_path() {
Some(p) => p,
None => return,
};
let db = KeyDb::load(&path).unwrap();
// Find any BD entry that carries a VUK and unit keys, then exercise
// the lookup-by-hash + VUK-derivation chain against it.
let entry = db
.disc_entries
.values()
.find(|e| e.vuk.is_some() && !e.unit_keys.is_empty() && e.disc_id.is_some());
if entry.is_none() {
return;
}
let entry = entry.unwrap();
let vuk = entry.vuk.unwrap();
let vid = entry.disc_id.unwrap();
let hash_hex = format!("0x{}", entry.disc_hash.trim_start_matches("0x"));
// We need the actual Unit_Key_RO.inf from the disc to compute disc hash.
// Since we don't have it, we can at least test that the KEYDB lookup
// works with a known hash.
let found = db.find_disc(&hash_hex);
assert!(found.is_some());
assert_eq!(found.unwrap().vuk, Some(vuk));
// Verify VUK derivation if we have MK + VID
if let Some(mk) = entry.media_key {
let derived = derive_vuk(&mk, &vid);
assert_eq!(derived, vuk, "VUK derivation mismatch");
eprintln!("VUK derivation verified");
}
}
/// Build a minimal Unit_Key_RO.inf with `num_unit_keys = 1`. The
/// disc hash won't be in any synthetic keydb so path 1 misses,
/// which lets us isolate the path-2/3/4 short-circuit behavior.
@@ -2262,23 +2107,18 @@ mod tests {
let uk_ro = minimal_unit_key_ro();
let zero_vid = [0u8; 16];
// Populate keydb with a non-matching VID entry (path 2 would
// miss anyway) plus dummy processing/device keys (paths 3/4
// would also miss, but the short-circuit means they're never
// attempted).
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
"0xDEADBEEF".to_string(),
DiscEntry {
disc_hash: "0xDEADBEEF".to_string(),
title: "fixture".to_string(),
media_key: Some([0x11u8; 16]),
disc_id: Some([0x22u8; 16]),
vuk: None,
unit_keys: Vec::new(),
},
);
keydb.processing_keys.push([0u8; 16]);
// A provider carrying a dummy processing key but NO disc entry that
// matches this disc. `disc_entry: None` preserves the negative-miss
// the test asserts: with VID=0, paths 1/2/3 are skipped and the
// path-4/5 hash lookup must MISS (a SuppliedKey returns its
// disc_entry unconditionally, so the planted entry would WRONGLY hit
// path 4 — None keeps the miss).
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: vec![[0u8; 16]],
media_keys: Vec::new(),
disc_entry: None,
};
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
@@ -2307,19 +2147,20 @@ mod tests {
// keyed lowercase too, so we have to lowercase here.
let hash_hex = disc_hash_hex(&hash).to_lowercase();
let mut keydb = KeyDb::empty();
let known_vuk = [0xABu8; 16];
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "fixture".to_string(),
media_key: None,
disc_id: None,
vuk: Some(known_vuk),
unit_keys: Vec::new(),
},
);
}),
};
let vid = [0u8; 16];
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
@@ -2349,18 +2190,19 @@ mod tests {
// `minimal_unit_key_ro` declares CPS unit 1; supply a matching
// pre-decrypted unit key in the KEYDB entry.
let known_uk = [0xCDu8; 16];
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "fixture".to_string(),
media_key: None,
disc_id: None,
vuk: None,
unit_keys: vec![(1, known_uk)],
},
);
}),
};
let vid = [0u8; 16];
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
@@ -2377,7 +2219,6 @@ mod tests {
assert_eq!(resolved.key_source, 5);
assert_eq!(resolved.unit_keys, vec![(1, known_uk)]);
}
#[test]
fn resolve_keys_path5_rejects_partial_unit_key_coverage() {
// If the disc declares a CPS unit that's not in the KEYDB
@@ -2388,20 +2229,20 @@ mod tests {
let uk_ro = minimal_unit_key_ro();
let hash = disc_hash(&uk_ro);
let hash_hex = disc_hash_hex(&hash).to_lowercase();
// KEYDB has a key for CPS unit 99, but the disc declares unit 1.
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "fixture".to_string(),
media_key: None,
disc_id: None,
vuk: None,
unit_keys: vec![(99, [0xEEu8; 16])],
},
);
}),
};
let vid = [0u8; 16];
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
@@ -2417,17 +2258,14 @@ mod tests {
"partial CPS-unit coverage must not produce a half-decrypted result"
);
}
#[test]
fn resolve_keys_path2_5_mk_pool_brute_resolves_unkeyed_disc() {
// The keyless-disc case: this disc's own hash/VID are NOT in keydb, but its
// Media Key IS — filed under a sibling disc that shares its MKB. Path
// 2.5 must km_verifies that MK against the MKB and resolve.
use super::super::decrypt::aes_ecb_encrypt as enc;
let km = [0x11u8; 16];
let vid = [0x22u8; 16];
// MKB: 0x10 type/version + 0x86 verify record whose mk_dv decrypts under
// km to the AACS verify magic, so km_verifies(mkb, km) == true.
let mut vd = [0u8; 16];
@@ -2439,26 +2277,21 @@ mod tests {
probe::km_verifies(&mkb, &km),
"fixture: km must verify the MKB"
);
// This disc's inf (its hash will NOT be in keydb).
let uk_ro = minimal_unit_key_ro();
// keydb: a SIBLING disc carries our km, keyed by the sibling's own
// hash + VID (neither matches THIS disc) — so only the MK-pool brute
// (km_verifies) can find it.
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
"0xsibling".to_string(),
DiscEntry {
disc_hash: "0xsibling".to_string(),
title: "sibling".to_string(),
media_key: Some(km),
disc_id: Some([0x99u8; 16]),
vuk: None,
unit_keys: Vec::new(),
},
);
// The sibling's MK is lifted directly into the MK pool: a KeyDb
// aggregated per-disc media_keys into media_keys(), but SuppliedKey
// does NOT harvest its disc_entry's media_key — it has an explicit
// media_keys field. `disc_entry: None` preserves the miss on this
// disc's own hash/VID (the sibling matches neither), so ONLY the
// MK-pool brute (km_verifies) can resolve it — exactly the path under
// test.
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: vec![km],
disc_entry: None,
};
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
unit_key_ro: &uk_ro,
@@ -2479,7 +2312,6 @@ mod tests {
"VUK must derive from the verified Km + this disc's VID"
);
}
#[test]
fn test_content_cert_parse() {
// AACS 1.0 cert
@@ -2489,7 +2321,6 @@ mod tests {
let cc = parse_content_cert(&data).unwrap();
assert_eq!(cc.version, AacsVersion::V10);
assert!(!cc.bus_encryption);
// AACS 2.0 with bus encryption
data[0] = 0x01; // AACS 2.0
data[1] = 0x01; // bus encryption enabled
@@ -2497,13 +2328,10 @@ mod tests {
assert_eq!(cc.version, AacsVersion::V20);
assert!(cc.bus_encryption);
}
// ════════════════════════════════════════════════════════════════════
// Hardening additions
// ════════════════════════════════════════════════════════════════════
// ── VUK derivation: spec relation VUK = AES-D(MK, VID) XOR VID ─────────
#[test]
fn derive_vuk_matches_spec_relation_explicitly() {
// Independently compute AES-ECB-D(mk, vid) XOR vid and confirm
@@ -2524,7 +2352,6 @@ mod tests {
}
assert_eq!(derive_vuk(&mk, &vid), expected);
}
#[test]
fn decrypt_unit_key_is_plain_aes_ecb_decrypt_under_vuk() {
// The encrypted unit key in Unit_Key_RO.inf is AES-ECB-E(VUK, uk);
@@ -2536,9 +2363,7 @@ mod tests {
let enc_uk = enc(&vuk, &uk);
assert_eq!(decrypt_unit_key(&vuk, &enc_uk), uk);
}
// ── Unit_Key_RO stride: 48 (V10) vs 64 (V20/V21) ──────────────────────
/// Build a Unit_Key_RO.inf carrying `num_uk` keys at a given stride,
/// where key `i` is filled with byte `0x10 + i`. uk_pos = 0x60.
fn build_unit_key_ro(num_uk: usize, stride: usize) -> Vec<u8> {
@@ -2561,7 +2386,6 @@ mod tests {
}
data
}
#[test]
fn stride_v10_is_48_v20_is_64_and_picks_distinct_keys() {
// AACS 1.0 stride = 48, AACS 2.0/2.1 stride = 64 (keys.rs:30-35).
@@ -2574,7 +2398,6 @@ mod tests {
assert_eq!(v20.encrypted_keys.len(), 2);
assert_eq!(v20.encrypted_keys[0].1, [0x10; 16]);
assert_eq!(v20.encrypted_keys[1].1, [0x11; 16]);
// Same buffer, V10 stride: key 1 still lands at uk_pos+48, but key 2
// is read at +48 (not +64) so it is NOT the planted 0x11 block.
let v10 = parse_unit_key_ro(&data, AacsVersion::V10).unwrap();
@@ -2584,7 +2407,6 @@ mod tests {
"48-byte stride must read different bytes than 64-byte stride"
);
}
#[test]
fn v21_uses_same_64_byte_stride_as_v20() {
// V21 shares V20's 64-byte stride (the enum match groups V20|V21).
@@ -2594,15 +2416,12 @@ mod tests {
assert_eq!(v20.encrypted_keys, v21.encrypted_keys);
assert_eq!(v21.version, AacsVersion::V21);
}
// ── parse_unit_key_ro: early returns / boundaries ──────────────────────
#[test]
fn parse_unit_key_ro_rejects_too_short_header() {
// < 20 bytes → None (header fields at 16-18 would index OOB).
assert!(parse_unit_key_ro(&[0u8; 19], AacsVersion::V10).is_none());
}
#[test]
fn parse_unit_key_ro_rejects_uk_pos_past_end() {
// uk_pos points past the buffer → the `uk_pos + 2 > len` guard
@@ -2611,7 +2430,6 @@ mod tests {
data[0..4].copy_from_slice(&1000u32.to_be_bytes()); // uk_pos = 1000
assert!(parse_unit_key_ro(&data, AacsVersion::V10).is_none());
}
#[test]
fn parse_unit_key_ro_zero_keys_returns_empty_set() {
// num_unit_keys == 0 → a valid file with no encrypted keys (early
@@ -2625,7 +2443,6 @@ mod tests {
assert!(parsed.encrypted_keys.is_empty());
assert_eq!(parsed.app_type, 1);
}
#[test]
fn parse_unit_key_ro_truncated_key_region_returns_none() {
// keys_start + 16 > len → None (the first key can't fit).
@@ -2635,7 +2452,6 @@ mod tests {
data[uk_pos + 1] = 1; // 1 key declared
assert!(parse_unit_key_ro(&data, AacsVersion::V10).is_none());
}
#[test]
fn parse_unit_key_ro_rejects_when_keys_run_off_end() {
// Finding #5: 3 keys declared but the buffer holds only 2 strides plus
@@ -2656,7 +2472,6 @@ mod tests {
"a buffer declaring more keys than it contains must be rejected"
);
}
#[test]
fn parse_unit_key_ro_app_type_and_skb_flag() {
// app_type at [16], num_bdmv_dir at [17], use_skb_mkb = bit 7 of [18].
@@ -2673,7 +2488,6 @@ mod tests {
let p2 = parse_unit_key_ro(&data, AacsVersion::V10).unwrap();
assert!(!p2.use_skb_mkb);
}
#[test]
fn parse_unit_key_ro_cps_unit_numbers_are_1_based() {
// The disc's CPS unit numbers are emitted as (i+1) — keys.rs:162.
@@ -2684,7 +2498,6 @@ mod tests {
vec![1, 2, 3]
);
}
#[test]
fn parse_unit_key_ro_title_cps_mapping_first_play_top_menu_then_titles() {
// [20..22] first_play, [22..24] top_menu, [24..26] num_titles, then
@@ -2698,9 +2511,7 @@ mod tests {
let p = parse_unit_key_ro(&data, AacsVersion::V20).unwrap();
assert_eq!(p.title_cps_unit, vec![7, 9, 3, 4]);
}
// ── MKB record framing: rec_len is BE24 incl. 4-byte header ────────────
#[test]
fn mkb_version_uses_be24_length_and_reads_offset_8() {
// Type 0x10, BE24 length 0x0C (12). Body starts at pos+4: Type field
@@ -2712,7 +2523,6 @@ mod tests {
// version = 0x01020304.
assert_eq!(mkb_version(&mkb), Some(0x0102_0304));
}
#[test]
fn mkb_type_category_c_20_is_uhd() {
// Type 0x10 record, BE24 length 0x0C (12). MKBType field (body
@@ -2729,7 +2539,6 @@ mod tests {
assert_eq!(MkbType::from_raw(MKB_21_CATEGORY_C), MkbType::CategoryC21);
assert_eq!(MkbType::CategoryC21.generation(), AacsVersion::V21);
}
#[test]
fn mkb_type_prerecorded_is_bluray_v10() {
// Type 0x10 record with MKB_TYPE_4_PRERECORDED (0x00041003) — a
@@ -2742,7 +2551,6 @@ mod tests {
assert!(!MkbType::Prerecorded.is_uhd());
assert_eq!(MkbType::Prerecorded.generation(), AacsVersion::V10);
}
#[test]
fn mkb_type_none_when_no_0x10_record() {
// A buffer whose only record is a 0x81 (verify-media-key) record and
@@ -2752,7 +2560,6 @@ mod tests {
assert_eq!(mkb_type(&mkb), None);
assert_eq!(mkb_is_uhd(&mkb), None);
}
#[test]
fn mkb_find_mk_dv_skips_short_verify_record() {
// A 0x81 record with rec_len < 20 carries no full mk_dv; the finder
@@ -2765,7 +2572,6 @@ mod tests {
mkb.extend_from_slice(&[0x00; 4]);
assert_eq!(mkb_find_mk_dv(&mkb), Some(expected));
}
#[test]
fn mkb_find_mk_dv_stops_on_overrun_length() {
// A rec_len that runs past the buffer ends the walk (break), so no
@@ -2773,7 +2579,6 @@ mod tests {
let mkb = [0x81, 0x00, 0xFF, 0xFF, 0x00, 0x00]; // claims 65535 bytes
assert_eq!(mkb_find_mk_dv(&mkb), None);
}
#[test]
fn mkb_find_mk_dv_stops_on_zero_length_record() {
// rec_len < 4 (here 0) breaks the walk — guards against an infinite
@@ -2781,9 +2586,7 @@ mod tests {
let mkb = [0x81, 0x00, 0x00, 0x00, 0x99];
assert_eq!(mkb_find_mk_dv(&mkb), None);
}
// ── mkb_content_len / trim_mkb ─────────────────────────────────────────
#[test]
fn mkb_content_len_stops_at_zero_type_padding_byte() {
// A type==0 byte marks the start of padding (records done). Two real
@@ -2794,14 +2597,12 @@ mod tests {
mkb.extend_from_slice(&[0x00, 0x00, 0x00, 0x08]); // padding starts (type 0)
assert_eq!(mkb_content_len(&mkb), content);
}
#[test]
fn mkb_content_len_returns_full_len_when_no_padding() {
let mut mkb = vec![0x10, 0x00, 0x00, 0x08, 0, 0, 0, 1];
mkb.extend_from_slice(&[0x05, 0x00, 0x00, 0x08, 9, 9, 9, 9]);
assert_eq!(mkb_content_len(&mkb), mkb.len());
}
#[test]
fn trim_mkb_leaves_exactly_sized_buffer_untouched() {
// n == mkb.len() (no padding) → the `n < mkb.len()` guard is false,
@@ -2809,15 +2610,12 @@ mod tests {
let mkb = vec![0x10, 0x00, 0x00, 0x08, 0, 0, 0, 1];
assert_eq!(trim_mkb(mkb.clone()), mkb);
}
// ── Content Certificate parsing ────────────────────────────────────────
#[test]
fn parse_content_cert_rejects_short_buffer() {
// < 8 bytes → None (cc_id slice [2..8] would index OOB).
assert!(parse_content_cert(&[0x00; 7]).is_none());
}
#[test]
fn parse_content_cert_extracts_cc_id_and_nonzero_type_is_v20() {
// [0]=type, [1]=bus-enc bit0, [2..8]=cc_id. Any non-0x00 type → V20.
@@ -2830,7 +2628,6 @@ mod tests {
assert_eq!(cc.cc_id, [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
assert!(!cc.bus_encryption);
}
#[test]
fn parse_content_cert_bus_encryption_only_reads_bit0() {
// bus_encryption = (data[1] & 0x01) != 0. A high bit set (0x02) with
@@ -2841,9 +2638,7 @@ mod tests {
data[1] = 0x03; // bit 0 set
assert!(parse_content_cert(&data).unwrap().bus_encryption);
}
// ── resolve: version → stride wiring + V21 upgrade on variant MKB ──────
#[test]
fn resolve_keys_v2_upgrades_to_v21_on_variant_mkb() {
// resolve_keys_v2 parses with the V20 64-byte stride but upgrades the
@@ -2852,19 +2647,19 @@ mod tests {
let uk_ro = build_unit_key_ro(1, 64);
let hash = disc_hash(&uk_ro);
let hash_hex = disc_hash_hex(&hash).to_lowercase();
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "fixture".to_string(),
media_key: None,
disc_id: None,
vuk: Some([0x5Au8; 16]),
unit_keys: Vec::new(),
},
);
}),
};
// MKB with a 0x83 variant record makes is_variant_mkb true.
let mut mkb = vec![0x10, 0x00, 0x00, 0x08, 0, 0, 0, 1];
@@ -2893,18 +2688,19 @@ mod tests {
let uk_ro = build_unit_key_ro(1, 64);
let hash = disc_hash(&uk_ro);
let hash_hex = disc_hash_hex(&hash).to_lowercase();
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "f".to_string(),
media_key: None,
disc_id: None,
vuk: Some([0x5Au8; 16]),
unit_keys: Vec::new(),
},
);
}),
};
let mkb = vec![0x10, 0x00, 0x00, 0x08, 0, 0, 0, 1];
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
@@ -2923,18 +2719,19 @@ mod tests {
let uk_ro = build_unit_key_ro(1, 48);
let hash = disc_hash(&uk_ro);
let hash_hex = disc_hash_hex(&hash).to_lowercase();
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "f".to_string(),
media_key: None,
disc_id: None,
vuk: Some([1u8; 16]),
unit_keys: Vec::new(),
},
);
}),
};
// Content cert: AACS2 + bus encryption enabled.
let mut cc = vec![0u8; 8];
cc[0] = 0x01;
@@ -2960,18 +2757,19 @@ mod tests {
let hash = disc_hash(&data);
let hash_hex = disc_hash_hex(&hash).to_lowercase();
let vuk = [0x77u8; 16];
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "f".to_string(),
media_key: None,
disc_id: None,
vuk: Some(vuk),
unit_keys: Vec::new(),
},
);
}),
};
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
unit_key_ro: &data,
@@ -2997,18 +2795,19 @@ mod tests {
let uk_ro = minimal_unit_key_ro();
let vid = [0x42u8; 16];
let mk = [0x24u8; 16];
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
"0xnotthishash".to_string(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: "0xnotthishash".to_string(),
title: "sibling".to_string(),
media_key: Some(mk),
disc_id: Some(vid),
vuk: None,
unit_keys: Vec::new(),
},
);
}),
};
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
unit_key_ro: &uk_ro,
@@ -3282,18 +3081,19 @@ mod tests {
let uk_ro = build_unit_key_ro(1, 64);
let hash_hex = disc_hash_hex(&disc_hash(&uk_ro)).to_lowercase();
let vuk = [0x77u8; 16];
let mut keydb = KeyDb::empty();
keydb.disc_entries.insert(
hash_hex.clone(),
DiscEntry {
let keydb = SuppliedKey {
device_keys: Vec::new(),
processing_keys: Vec::new(),
media_keys: Vec::new(),
disc_entry: Some(DiscEntry {
disc_hash: hash_hex,
title: "f".to_string(),
media_key: None,
disc_id: None,
vuk: Some(vuk),
unit_keys: Vec::new(),
},
);
}),
};
let providers: &[&dyn super::super::KeyProvider] = &[&keydb];
let ctx = ResolveContext {
unit_key_ro: &uk_ro,
+9 -2
View File
@@ -14,13 +14,20 @@
//! The VUK decrypts title keys from AACS/Unit_Key_RO.inf on disc.
//! Title keys decrypt m2ts stream content (AES-128-CBC).
pub mod boil;
pub mod decrypt;
pub mod handshake;
pub mod keydb;
pub mod keys;
pub mod provider;
pub mod trace;
pub mod types;
pub mod variants;
// Boil-down derivation primitives (thin newtypes + wrappers over the crypto).
pub use boil::{MediaKey, UnitKey, Vid, Vuk, mk_from_dk, uk_from_vuk, vuk_from_mk};
// Structured, English-free resolution trace.
pub use trace::{KeyNode, KeyOutcome, KeyStep, ResolutionTrace, UnlockOutcome, UnlockStep};
// Explicit re-exports — only items needed by external consumers and sibling crate modules.
// AES primitives (aes_ecb_encrypt, aes_ecb_decrypt, aes_cbc_decrypt) are pub(crate) in decrypt.rs.
pub use decrypt::{
@@ -28,7 +35,6 @@ pub use decrypt::{
decrypt_unit_full, decrypt_unit_try_keys, is_aacs_scrambled, is_unit_aligned, ts_packet_total,
ts_sync_count, unit_key_validates,
};
pub use keydb::{DeviceKey, DiscEntry, HostCert, KeyDb};
pub use keys::probe;
pub use keys::{
AacsVersion, ContentCert, MKB_20_CATEGORY_C, MKB_21_CATEGORY_C, MKB_TYPE_3_RECORDABLE,
@@ -40,6 +46,7 @@ pub use keys::{
resolve_keys_v21, resolve_keys_with_reason, trim_mkb,
};
pub use provider::KeyProvider;
pub use types::{DeviceKey, DiscEntry, HostCert};
pub use variants::{
KEY_CORRECTION_DATA_PLACEHOLDER, MediaKeyVariantError, MkbRecord, ProcessingKeyMatch,
derive_media_key_variant, is_variant_mkb, variant_nonce, walk_mkb, walk_processing_key,
+1 -1
View File
@@ -37,7 +37,7 @@
//! [`lookup_disc_by_hash`]: KeyProvider::lookup_disc_by_hash
//! [`lookup_disc_by_vid`]: KeyProvider::lookup_disc_by_vid
use super::keydb::{DeviceKey, DiscEntry, HostCert};
use super::types::{DeviceKey, DiscEntry, HostCert};
/// Source of AACS key material.
///
+144
View File
@@ -0,0 +1,144 @@
//! Structured resolution trace — what the unlock + key-resolution attempt did.
//!
//! No user-facing English. Every step's STATE is a typed enum variant;
//! applications RENDER these into localized text (the library never does). This
//! module only DEFINES the shape and is wired through the resolve/handshake
//! return path far enough to compile.
//!
//! The `who` of each step is the source's `label()` / unlocker's `name()` — a
//! stable identifier string (a NAME, like a codec id, NOT user-facing prose),
//! carried verbatim so an app renderer never has to match an enum back to a name
//! it already has. Only the OUTCOME / path enums are structured states the app
//! maps to i18n English.
/// The full trace of a resolution attempt: the unlock phase, then the
/// key-resolution phase.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ResolutionTrace {
/// One step per unlocker consulted, in consultation order.
pub unlock: Vec<UnlockStep>,
/// One step per key source consulted, in consultation order.
pub keys: Vec<KeyStep>,
}
impl ResolutionTrace {
/// An empty trace (no steps recorded).
pub fn new() -> Self {
Self::default()
}
}
// ── Unlock phase ────────────────────────────────────────────────────────────
/// One unlocker's contribution to the unlock phase. `who` is the unlocker's
/// `name()` (a stable identifier, e.g. `"LibreDrive"`), carried verbatim.
#[derive(Debug, Clone, PartialEq)]
pub struct UnlockStep {
pub who: String,
pub outcome: UnlockOutcome,
}
/// What an unlocker did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnlockOutcome {
/// The drive was unlocked (or already usable) and a VID is available.
Unlocked,
/// This unlocker cannot unlock this drive's firmware.
FirmwareNotUnlockable,
/// No non-revoked host cert was usable for the auth attempt. `mkb` is the
/// disc MKB generation when known.
NoUsableHostCert { mkb: Option<u32> },
/// Every available host cert was revoked on this drive's HRL. `mkb` is the
/// disc MKB generation when known.
CertRevoked { mkb: Option<u32> },
/// The drive rejected the auth handshake (non-revocation rejection / wedge).
HandshakeRejected,
/// Auth succeeded (or was skipped) but the Volume ID could not be read.
VidUnavailable,
}
// ── Key-resolution phase ────────────────────────────────────────────────────
/// One key source's contribution to the key-resolution phase, including the
/// derivation path it walked. `who` is the source's `label()` (a stable
/// identifier, e.g. `"keydb"` / `"online"`), carried verbatim.
#[derive(Debug, Clone, PartialEq)]
pub struct KeyStep {
pub who: String,
pub path: Vec<KeyNode>,
pub outcome: KeyOutcome,
}
/// A node on the derivation path a source walked. Ordered as encountered; not
/// every path hits every node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyNode {
/// The source matched this disc (by hash / VID).
MatchedDisc,
/// The source had no entry for this disc.
NoEntry,
/// Pre-decrypted unit keys were found.
FoundUnitKeys,
/// A VUK was found.
FoundVuk,
/// A Media Key was found.
FoundMediaKey,
/// A VID is required to proceed.
NeedVid,
/// The VID came from the unlock phase.
VidFromUnlock,
/// The VID came from the keydb entry.
VidFromKeydb,
/// No VID was available.
NoVid,
/// A VUK was derived (from MK + VID).
DerivedVuk,
/// Unit keys were derived (from VUK).
DerivedUnitKeys,
}
/// The terminal outcome of a source's resolution attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyOutcome {
/// Usable unit keys were produced.
Resolved,
/// Derivation material existed but no VID was available to finish.
MissingVid,
/// No usable key from this source.
NoKey,
}
#[cfg(test)]
mod tests {
use super::*;
/// The trace types are constructible, derive the required traits, and an
/// empty trace round-trips. Pins the structural contract apps build against.
#[test]
fn trace_is_constructible_and_comparable() {
let t = ResolutionTrace {
unlock: vec![UnlockStep {
who: "AACS cert".to_string(),
outcome: UnlockOutcome::NoUsableHostCert { mkb: Some(68) },
}],
keys: vec![KeyStep {
who: "keydb".to_string(),
path: vec![
KeyNode::MatchedDisc,
KeyNode::FoundVuk,
KeyNode::DerivedUnitKeys,
],
outcome: KeyOutcome::Resolved,
}],
};
// Clone + PartialEq (derive contract the renderers rely on).
assert_eq!(t.clone(), t);
// `who` is the source's name carried verbatim.
assert_eq!(t.keys[0].who, "keydb");
assert_eq!(t.unlock[0].who, "AACS cert");
// Default / new is empty.
assert_eq!(ResolutionTrace::new(), ResolutionTrace::default());
assert!(ResolutionTrace::new().unlock.is_empty());
assert!(ResolutionTrace::new().keys.is_empty());
}
}
+45
View File
@@ -0,0 +1,45 @@
//! AACS primitive types shared across the resolve chain.
//!
//! These structs describe AACS key material (device keys, host
//! certificates, per-disc entries). They carry no parsing logic — the
//! keydb.cfg format lives in the `freemkv-keysources` crate. libfreemkv
//! owns only the crypto and these value types that flow through it.
/// A device key for MKB subset-difference tree processing.
#[derive(Debug, Clone)]
pub struct DeviceKey {
pub key: [u8; 16],
pub node: u16,
pub uv: u32,
pub u_mask_shift: u8,
}
/// Host certificate + private key for AACS SCSI authentication.
#[derive(Debug, Clone)]
pub struct HostCert {
/// AACS 1.0: 20 bytes. AACS 2.0: 32 bytes.
pub private_key: [u8; 20],
/// AACS 1.0: 92 bytes. AACS 2.0: 132 bytes.
pub certificate: Vec<u8>,
/// AACS 2.0 host private key (P-256, 32 bytes). None for AACS 1.0 only.
pub private_key_v2: Option<[u8; 32]>,
/// AACS 2.0 host certificate (type 0x11). None for AACS 1.0 only.
pub certificate_v2: Option<Vec<u8>>,
}
/// A per-disc entry from the key database.
#[derive(Debug, Clone)]
pub struct DiscEntry {
/// Disc hash (20 bytes, hex)
pub disc_hash: String,
/// Disc title
pub title: String,
/// Media Key (16 bytes) — from MKB processing
pub media_key: Option<[u8; 16]>,
/// Disc ID (16 bytes)
pub disc_id: Option<[u8; 16]>,
/// Volume Unique Key (16 bytes) — decrypts title keys
pub vuk: Option<[u8; 16]>,
/// Unit keys (title keys) indexed by CPS unit number
pub unit_keys: Vec<(u32, [u8; 16])>,
}
+1 -1
View File
@@ -56,7 +56,7 @@
//! variant path.
use super::decrypt::aes_ecb_decrypt;
use super::keydb::DeviceKey;
use super::types::DeviceKey;
// ── Public constants ──────────────────────────────────────────────────────