v1.0.0-rc.1
CSS keyless decrypt (Stevenson), AACS 1.0/2.0/2.1, MPEG-2 DVD, multi-OS SCSI, multipass recovery, mux highway, audit hardening
This commit is contained in:
+163
-141
@@ -1,52 +1,16 @@
|
||||
//! CSS drive authentication — full key hierarchy.
|
||||
//! CSS drive bus-authentication — read-unlock primitive.
|
||||
//!
|
||||
//! Protocol:
|
||||
//! 1. Bus authentication (challenge-response) → bus key
|
||||
//! 2. Read disc key block (READ DVD STRUCTURE) → XOR with bus key → decrypt with player keys → disc key
|
||||
//! 3. Read title key (REPORT KEY format 0x04) → XOR with bus key → decrypt with disc key → title key
|
||||
//! A CSS-enforcing DVD drive refuses to return scrambled sectors until a
|
||||
//! CSS bus-auth handshake has run for the title. [`unlock_css_reads`]
|
||||
//! issues that classic handshake (bus auth → disc-key REPORT KEY → bus
|
||||
//! auth → title-key REPORT KEY) purely for its SCSI side effect of
|
||||
//! unlocking scrambled-sector reads. The bytes the handshake returns are
|
||||
//! NOT used as keys: the descramble title key is recovered keylessly by
|
||||
//! the Stevenson known-plaintext attack (see [`super::crack_key`]).
|
||||
|
||||
use crate::drive::Drive;
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
// ── Built-in public DVD CSS player keys ────────────────────────────────────
|
||||
//
|
||||
// These 31 5-byte player keys are long-public CSS inputs. With them
|
||||
// compiled in, DVD ripping works with no external key file required.
|
||||
|
||||
const PLAYER_KEYS: [[u8; 5]; 31] = [
|
||||
[0x01, 0xaf, 0xe3, 0x12, 0x80],
|
||||
[0x12, 0x11, 0xca, 0x04, 0x3b],
|
||||
[0x14, 0x0c, 0x9e, 0xd0, 0x09],
|
||||
[0x14, 0x71, 0x35, 0xba, 0xe2],
|
||||
[0x1a, 0xa4, 0x33, 0x21, 0xa6],
|
||||
[0x26, 0xec, 0xc4, 0xa7, 0x4e],
|
||||
[0x2c, 0xb2, 0xc1, 0x09, 0xee],
|
||||
[0x2f, 0x25, 0x9e, 0x96, 0xdd],
|
||||
[0x33, 0x2f, 0x49, 0x6c, 0xe0],
|
||||
[0x35, 0x5b, 0xc1, 0x31, 0x0f],
|
||||
[0x36, 0x67, 0xb2, 0xe3, 0x85],
|
||||
[0x39, 0x3d, 0xf1, 0xf1, 0xbd],
|
||||
[0x3b, 0x31, 0x34, 0x0d, 0x91],
|
||||
[0x45, 0xed, 0x28, 0xeb, 0xd3],
|
||||
[0x48, 0xb7, 0x6c, 0xce, 0x69],
|
||||
[0x4b, 0x65, 0x0d, 0xc1, 0xee],
|
||||
[0x4c, 0xbb, 0xf5, 0x5b, 0x23],
|
||||
[0x51, 0x67, 0x67, 0xc5, 0xe0],
|
||||
[0x53, 0x94, 0xe1, 0x75, 0xbf],
|
||||
[0x57, 0x2c, 0x8b, 0x31, 0xae],
|
||||
[0x63, 0xdb, 0x4c, 0x5b, 0x4a],
|
||||
[0x7b, 0x1e, 0x5e, 0x2b, 0x57],
|
||||
[0x85, 0xf3, 0x85, 0xa0, 0xe0],
|
||||
[0xab, 0x1e, 0xe7, 0x7b, 0x72],
|
||||
[0xab, 0x36, 0xe3, 0xeb, 0x76],
|
||||
[0xb1, 0xb8, 0xf9, 0x38, 0x03],
|
||||
[0xb8, 0x5d, 0xd8, 0x53, 0xbd],
|
||||
[0xbf, 0x92, 0xc3, 0xb0, 0xe2],
|
||||
[0xcf, 0x1a, 0xb2, 0xf8, 0x0a],
|
||||
[0xec, 0xa0, 0xcf, 0xb3, 0xff],
|
||||
[0xfc, 0x95, 0xa9, 0x87, 0x35],
|
||||
];
|
||||
|
||||
// ── CryptKey tables ───────────────────────────────────────────────────────
|
||||
|
||||
const CRYPT_TAB0: [u8; 256] = [
|
||||
@@ -153,34 +117,51 @@ const PERM_VARIANT: [[u8; 32]; 2] = [
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Perform CSS bus authentication only.
|
||||
pub fn authenticate(drive: &mut Drive) -> Result<()> {
|
||||
let (_, _) = bus_auth(drive)?;
|
||||
Ok(())
|
||||
/// CSS bus-auth **unlock** primitive.
|
||||
///
|
||||
/// Issues the full classic CSS handshake (bus auth → disc-key REPORT KEY →
|
||||
/// bus auth → title-key REPORT KEY) purely to unlock the drive's
|
||||
/// scrambled-sector read gating. The bytes returned by the handshake are
|
||||
/// discarded — the descramble title key is recovered keylessly elsewhere
|
||||
/// (the Stevenson known-plaintext attack in [`super::crack_key`]).
|
||||
pub fn unlock_css_reads(drive: &mut Drive, lba: u32) -> Result<()> {
|
||||
let t0 = std::time::Instant::now();
|
||||
tracing::info!(target: "freemkv::css", phase = "unlock_css_reads", lba, "begin");
|
||||
let r = unlock_css_reads_inner(drive, lba);
|
||||
tracing::info!(
|
||||
target: "freemkv::css",
|
||||
phase = "unlock_css_reads",
|
||||
lba,
|
||||
ok = r.is_ok(),
|
||||
elapsed_ms = t0.elapsed().as_millis() as u64,
|
||||
"end"
|
||||
);
|
||||
r
|
||||
}
|
||||
|
||||
/// Full CSS key extraction: bus auth → disc key → title key.
|
||||
pub fn authenticate_and_read_title_key(drive: &mut Drive, lba: u32) -> Result<[u8; 5]> {
|
||||
// Session 1: bus auth → disc key (AGID consumed by READ_DVD_STRUCTURE)
|
||||
let (agid, bus_key) = bus_auth(drive)?;
|
||||
let disc_key = read_disc_key(drive, agid, &bus_key)?;
|
||||
fn unlock_css_reads_inner(drive: &mut Drive, lba: u32) -> Result<()> {
|
||||
tracing::debug!(target: "freemkv::css", lba, "css unlock: begin");
|
||||
// Session 1: bus auth → disc-key REPORT KEY (AGID consumed by
|
||||
// READ_DVD_STRUCTURE). The block contents are unused; this is issued
|
||||
// purely for the bus-auth unlock side effect.
|
||||
let (agid, _bus_key) = bus_auth(drive).inspect_err(|e| {
|
||||
tracing::warn!(target: "freemkv::css", error_code = e.code(), "css unlock: bus_auth(1) failed");
|
||||
})?;
|
||||
tracing::debug!(target: "freemkv::css", agid, "css unlock: bus_auth(1) ok");
|
||||
read_disc_key(drive, agid).inspect_err(|e| {
|
||||
tracing::warn!(target: "freemkv::css", error_code = e.code(), "css unlock: read_disc_key failed");
|
||||
})?;
|
||||
tracing::debug!(target: "freemkv::css", "css unlock: disc-key REPORT KEY ok");
|
||||
|
||||
// Session 2: fresh bus auth → title key (needs separate AGID)
|
||||
let (agid2, bus_key2) = bus_auth(drive)?;
|
||||
let encrypted_title = read_raw_title_key(drive, agid2, lba)?;
|
||||
|
||||
// Decrypt title key: XOR with bus key, then decrypt with disc key
|
||||
let mut title_key = [0u8; 5];
|
||||
for i in 0..5 {
|
||||
title_key[i] = encrypted_title[i] ^ bus_key2[i];
|
||||
}
|
||||
|
||||
if title_key == [0u8; 5] {
|
||||
return Ok(title_key);
|
||||
}
|
||||
|
||||
let title_key = super::lfsr::decrypt_key(0xFF, &disc_key, &title_key);
|
||||
Ok(title_key)
|
||||
// Session 2: fresh bus auth → title-key REPORT KEY (needs separate AGID).
|
||||
let (agid2, _bus_key2) = bus_auth(drive).inspect_err(|e| {
|
||||
tracing::warn!(target: "freemkv::css", error_code = e.code(), "css unlock: bus_auth(2) failed");
|
||||
})?;
|
||||
read_raw_title_key(drive, agid2, lba).inspect_err(|e| {
|
||||
tracing::warn!(target: "freemkv::css", error_code = e.code(), "css unlock: read_raw_title_key failed");
|
||||
})?;
|
||||
tracing::debug!(target: "freemkv::css", "css unlock: ok");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Step 1: Bus Authentication ────────────────────────────────────────────
|
||||
@@ -295,7 +276,10 @@ fn bus_auth(drive: &mut Drive) -> Result<(u8, [u8; 5])> {
|
||||
|
||||
// ── Step 2: Disc Key ──────────────────────────────────────────────────────
|
||||
|
||||
fn read_disc_key(drive: &mut Drive, agid: u8, bus_key: &[u8; 5]) -> Result<[u8; 5]> {
|
||||
/// Issue the disc-key REPORT KEY (READ DVD STRUCTURE, format 0x02) purely
|
||||
/// for the bus-auth unlock side effect. The returned block contents are
|
||||
/// not used — the descramble title key is recovered keylessly elsewhere.
|
||||
fn read_disc_key(drive: &mut Drive, agid: u8) -> Result<()> {
|
||||
let scsi = drive.scsi_mut();
|
||||
|
||||
// READ DVD STRUCTURE, format 0x02 (disc key), 2048+4 bytes
|
||||
@@ -318,56 +302,14 @@ fn read_disc_key(drive: &mut Drive, agid: u8, bus_key: &[u8; 5]) -> Result<[u8;
|
||||
);
|
||||
dvd_result.map_err(|_| Error::CssAuthFailed)?;
|
||||
|
||||
// Disc key block starts at offset 4 (skip 4-byte header)
|
||||
let disc_key_block = &mut buf[4..4 + 2048];
|
||||
|
||||
// XOR with reversed bus key (per libdvdcss)
|
||||
for (i, byte) in disc_key_block.iter_mut().enumerate() {
|
||||
*byte ^= bus_key[4 - (i % 5)];
|
||||
}
|
||||
|
||||
// Try each player key against each of 408 disc key entries.
|
||||
// Each entry in the block is the disc key encrypted with a specific player
|
||||
// key. We collect every decryption and accept the disc key as soon as two
|
||||
// independent decryptions agree on the same 5-byte value (the agreement may
|
||||
// come from two different player keys or from one player key decrypting two
|
||||
// different entries to the same value).
|
||||
//
|
||||
// NOTE: this is a collision heuristic, not the canonical CSS disc-key
|
||||
// self-verification (which decrypts the verification entry with the
|
||||
// candidate and checks the result equals the candidate). A coincidental
|
||||
// collision among the ~12,648 candidate decryptions could in principle
|
||||
// accept a wrong disc key; in practice a chance collision on 5 bytes is
|
||||
// improbable enough to serve as the validity check, and this path is the
|
||||
// production DVD disc-key recovery. Left as-is to avoid regressing it
|
||||
// without a real disc-key-block test vector to validate against.
|
||||
let mut candidates: Vec<[u8; 5]> = Vec::new();
|
||||
|
||||
for player_key in PLAYER_KEYS.iter() {
|
||||
for pos in 0..408 {
|
||||
let offset = pos * 5;
|
||||
if offset + 5 > disc_key_block.len() {
|
||||
break;
|
||||
}
|
||||
let mut enc = [0u8; 5];
|
||||
enc.copy_from_slice(&disc_key_block[offset..offset + 5]);
|
||||
let candidate = super::lfsr::decrypt_key(0x00, player_key, &enc);
|
||||
|
||||
// Accept on the first agreement between two independent decryptions.
|
||||
if candidates.contains(&candidate) {
|
||||
return Ok(candidate);
|
||||
}
|
||||
candidates.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::CssAuthFailed)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Step 3: Title Key ─────────────────────────────────────────────────────
|
||||
|
||||
/// Read the raw (bus-encrypted) title key bytes from the drive.
|
||||
fn read_raw_title_key(drive: &mut Drive, agid: u8, lba: u32) -> Result<[u8; 5]> {
|
||||
/// Issue the title-key REPORT KEY (format 0x04) purely for the bus-auth
|
||||
/// unlock side effect. The returned key bytes are not used.
|
||||
fn read_raw_title_key(drive: &mut Drive, agid: u8, lba: u32) -> Result<()> {
|
||||
let scsi = drive.scsi_mut();
|
||||
let mut cdb = [0u8; 12];
|
||||
cdb[0] = crate::scsi::SCSI_REPORT_KEY;
|
||||
@@ -388,11 +330,7 @@ fn read_raw_title_key(drive: &mut Drive, agid: u8, lba: u32) -> Result<[u8; 5]>
|
||||
);
|
||||
result.map_err(|_| Error::CssAuthFailed)?;
|
||||
|
||||
let mut key = [0u8; 5];
|
||||
for i in 0..5 {
|
||||
key[i] = buf[5 + (4 - i)];
|
||||
}
|
||||
Ok(key)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── CSSCryptKey ───────────────────────────────────────────────────────────
|
||||
@@ -556,6 +494,110 @@ fn send_key_cdb(agid: u8, format: u8, param_len: u16) -> [u8; 12] {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// SECURITY REGRESSION GUARD: no instrumentation in libfreemkv may emit
|
||||
/// raw key material. Scan every source file for a `tracing` field that
|
||||
/// binds a forbidden key name to a value-producing expression (`= expr`
|
||||
/// or `%expr` / `?expr`). The only allowed forms are a string literal
|
||||
/// (e.g. `disc_key = "<redacted>"`) or a `_fp` fingerprint field.
|
||||
///
|
||||
/// This is a source-scan test (not a runtime capture) so it stays cheap
|
||||
/// and catches re-introductions at compile/CI time.
|
||||
#[test]
|
||||
fn no_key_bytes_in_instrumentation() {
|
||||
use std::path::Path;
|
||||
|
||||
// Forbidden field names whose VALUES must never be logged.
|
||||
const FORBIDDEN: &[&str] = &[
|
||||
"title_key",
|
||||
"disc_key",
|
||||
"unit_key",
|
||||
"vuk",
|
||||
"player_key",
|
||||
"bus_key",
|
||||
];
|
||||
|
||||
fn scan_dir(dir: &Path, forbidden: &[&str], violations: &mut Vec<String>) {
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e,
|
||||
Err(_) => return,
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
scan_dir(&path, forbidden, violations);
|
||||
continue;
|
||||
}
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
|
||||
continue;
|
||||
}
|
||||
let src = match std::fs::read_to_string(&path) {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for (lineno, line) in src.lines().enumerate() {
|
||||
let trimmed = line.trim_start();
|
||||
// Only inspect tracing instrumentation lines.
|
||||
if !(trimmed.contains("tracing::")
|
||||
|| trimmed.starts_with("debug!")
|
||||
|| trimmed.starts_with("info!")
|
||||
|| trimmed.starts_with("warn!")
|
||||
|| trimmed.starts_with("trace!")
|
||||
|| trimmed.starts_with("error!"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// This guard test itself contains the forbidden names.
|
||||
if path.file_name().and_then(|n| n.to_str()) == Some("auth.rs")
|
||||
&& line.contains("FORBIDDEN")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for &name in forbidden {
|
||||
// A fingerprint field (`<name>_fp = ...`) is allowed.
|
||||
// Match `<name>` followed by optional fingerprint
|
||||
// suffix then `=` and a value that is NOT a string
|
||||
// literal redaction marker.
|
||||
if let Some(idx) = line.find(name) {
|
||||
let after = &line[idx + name.len()..];
|
||||
let after = after.trim_start();
|
||||
// `<name>_fp` / `<name>_id` etc. are safe.
|
||||
if after.starts_with('_') {
|
||||
continue;
|
||||
}
|
||||
// Must be a field binding `name = ...`.
|
||||
let Some(rest) = after.strip_prefix('=') else {
|
||||
continue;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
// Redaction string literal is the only allowed value.
|
||||
if rest.starts_with('"') {
|
||||
continue;
|
||||
}
|
||||
// Anything else (`%expr`, `?expr`, bare expr) leaks bytes.
|
||||
violations.push(format!(
|
||||
"{}:{}: forbidden key field `{}` logged with a value: {}",
|
||||
path.display(),
|
||||
lineno + 1,
|
||||
name,
|
||||
line.trim()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Walk up from this file (src/css/auth.rs) to the crate `src` root.
|
||||
let src_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut violations = Vec::new();
|
||||
scan_dir(&src_root, FORBIDDEN, &mut violations);
|
||||
assert!(
|
||||
violations.is_empty(),
|
||||
"key material logged in instrumentation:\n{}",
|
||||
violations.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crypt_key_is_deterministic() {
|
||||
let challenge: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
@@ -586,11 +628,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn player_keys_count() {
|
||||
assert_eq!(PLAYER_KEYS.len(), 31);
|
||||
}
|
||||
|
||||
// ── CSS constant-table integrity ───────────────────────────────────────
|
||||
|
||||
/// Each PERM_CHALLENGE row is a permutation of indices 0..10 (it reorders
|
||||
@@ -644,21 +681,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 31 built-in player keys are all distinct. Duplicate keys would
|
||||
/// waste disc-key trials and could mask a copy-paste error in the table.
|
||||
///
|
||||
/// Grounding: PLAYER_KEYS is the set of long-public CSS player keys; each
|
||||
/// is a unique 5-byte key.
|
||||
/// Mutation: set PLAYER_KEYS[1] = PLAYER_KEYS[0] -> duplicate assert fires.
|
||||
#[test]
|
||||
fn player_keys_are_distinct() {
|
||||
for (i, ki) in PLAYER_KEYS.iter().enumerate() {
|
||||
for (j, kj) in PLAYER_KEYS.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(ki, kj, "player keys {i} and {j} collide");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── crypt_key behaviour ────────────────────────────────────────────────
|
||||
|
||||
/// crypt_key result depends on every challenge byte. The challenge is
|
||||
|
||||
@@ -1,523 +0,0 @@
|
||||
//! CSS title key recovery — Stevenson's divide-and-conquer attack (1999).
|
||||
//!
|
||||
//! Given a scrambled DVD sector with known plaintext (MPEG-2 PES headers),
|
||||
//! this would recover the 5-byte title key by:
|
||||
//!
|
||||
//! 1. Computing `TAB1[ciphertext] ^ plaintext` to cancel the TAB1 output
|
||||
//! mangling and expose the raw LFSR-combination keystream
|
||||
//! 2. Iterating all 2^16 LFSR1 states
|
||||
//! 3. For each: deducing what LFSR0 must produce, then verifying
|
||||
//!
|
||||
//! NOTE: this recovery path is currently non-functional. It models the
|
||||
//! textbook direct-seed CSS cipher, whereas the in-repo descrambler
|
||||
//! ([`super::lfsr::descramble_sector`]) seeds its LFSRs from a key that
|
||||
//! has been run through an additional `decrypt_key` mangling step. The two
|
||||
//! are therefore inconsistent and [`recover_title_key`] never returns a key
|
||||
//! for a sector scrambled by this crate's own descrambler. The production
|
||||
//! DVD path does NOT use this fallback — it derives the title key over SCSI
|
||||
//! ([`super::auth::authenticate_and_read_title_key`]). See the ignored
|
||||
//! regression test below.
|
||||
//!
|
||||
//! Algorithm: Frank A. Stevenson, "Divide and conquer attack" (1999).
|
||||
|
||||
use super::tables::{TAB1, TAB2, TAB3, TAB4, TAB5};
|
||||
|
||||
/// Sector layout constants.
|
||||
const SECTOR_SIZE: usize = 2048;
|
||||
const ENCRYPTED_START: usize = 0x80; // byte 128
|
||||
const SEED_OFFSET: usize = 0x54; // sector seed at bytes 0x54-0x58
|
||||
const FLAG_BYTE: usize = 0x14;
|
||||
|
||||
/// Recover the CSS title key from a scrambled sector using known plaintext.
|
||||
///
|
||||
/// The `plain` slice should contain the expected plaintext of the encrypted
|
||||
/// region (bytes 0x80+). For MPEG-2 sectors, the first bytes are typically
|
||||
/// a PES header: `00 00 01 [stream_id] ...`
|
||||
///
|
||||
/// Returns the recovered 5-byte title key, or `None` if recovery fails.
|
||||
///
|
||||
/// NOTE: see the module docs — this attack models the textbook direct-seed
|
||||
/// CSS cipher and is inconsistent with this crate's descrambler, so it
|
||||
/// currently returns `None` even for an exact known plaintext. It is not on
|
||||
/// the production DVD decrypt path.
|
||||
pub fn recover_title_key(sector: &[u8], plain: &[u8]) -> Option<[u8; 5]> {
|
||||
if sector.len() < SECTOR_SIZE || plain.len() < 10 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let flags = (sector[FLAG_BYTE] >> 4) & 0x03;
|
||||
if flags == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let crypted = §or[ENCRYPTED_START..];
|
||||
let seed = §or[SEED_OFFSET..SEED_OFFSET + 5];
|
||||
|
||||
// Phase 1: Cancel the TAB1 mangling layer and subtract the known plaintext.
|
||||
// The CSS cipher applies TAB1 as an output permutation. Computing
|
||||
// `buf[i] = TAB1[crypted[i]] ^ plain[i]` both undoes that permutation and
|
||||
// XORs out the known plaintext, leaving the raw LFSR-combination keystream
|
||||
// bytes for the attack to match against.
|
||||
let mut buf = [0u8; 10];
|
||||
for i in 0..10 {
|
||||
if i >= crypted.len() || i >= plain.len() {
|
||||
return None;
|
||||
}
|
||||
buf[i] = TAB1[crypted[i] as usize] ^ plain[i];
|
||||
}
|
||||
|
||||
// Phase 2: Stevenson attack — iterate all 2^16 LFSR1 initial states
|
||||
let mut result_key = [0u8; 5];
|
||||
let mut found = false;
|
||||
|
||||
'outer: for i_try in 0u32..0x10000 {
|
||||
let mut t1 = (i_try >> 8) | 0x100;
|
||||
let mut t2 = i_try & 0xFF;
|
||||
let mut t5: u32 = 0;
|
||||
|
||||
// Clock LFSR1 forward 4 steps to reconstruct LFSR0 state
|
||||
let mut t3: u32 = 0;
|
||||
|
||||
for &buf_byte in buf.iter().take(4) {
|
||||
// Advance LFSR1
|
||||
let t4 = TAB2[t2 as usize] ^ TAB3[t1 as usize];
|
||||
t2 = t1 >> 1;
|
||||
t1 = ((t1 & 1) << 8) ^ t4 as u32;
|
||||
let t4_perm = TAB5[t4 as usize];
|
||||
|
||||
// Deduce LFSR0 output from the buffer and LFSR1 output
|
||||
let mut t6 = buf_byte as u32;
|
||||
if t5 > 0 {
|
||||
t6 = (t6 + 0xFF) & 0xFF;
|
||||
}
|
||||
if t6 < t4_perm as u32 {
|
||||
t6 += 0x100;
|
||||
}
|
||||
t6 -= t4_perm as u32;
|
||||
t5 += t6 + t4_perm as u32;
|
||||
let t6_inv = TAB4[t6 as usize & 0xFF];
|
||||
|
||||
// Build LFSR0 candidate from deduced output bytes.
|
||||
// wrapping_shl: the accumulator is a rolling 32-bit window;
|
||||
// the top byte is intentionally shifted out. Matches the
|
||||
// release-mode wrap (no behaviour change) without a debug
|
||||
// overflow panic.
|
||||
t3 = t3.wrapping_shl(8) | t6_inv as u32;
|
||||
t5 >>= 8;
|
||||
}
|
||||
|
||||
let candidate = t3;
|
||||
|
||||
// Phase 3: Validate — clock 6 more steps and check against buffer
|
||||
let mut valid = true;
|
||||
for &buf_byte in buf.iter().skip(4) {
|
||||
let t4 = TAB2[t2 as usize] ^ TAB3[t1 as usize];
|
||||
t2 = t1 >> 1;
|
||||
t1 = ((t1 & 1) << 8) ^ t4 as u32;
|
||||
let t4_perm = TAB5[t4 as usize];
|
||||
|
||||
// Clock LFSR0 forward. wrapping_shl keeps the rolling 32-bit
|
||||
// window semantics (top byte shifted out) identical to the
|
||||
// release build while avoiding a debug overflow panic.
|
||||
let t6 = ((((((t3 >> 8) ^ t3) >> 1) ^ t3) >> 3) ^ t3) >> 7;
|
||||
t3 = t3.wrapping_shl(8) | (t6 & 0xFF);
|
||||
let t6_perm = TAB4[(t6 & 0xFF) as usize];
|
||||
|
||||
t5 += t6_perm as u32 + t4_perm as u32;
|
||||
if (t5 & 0xFF) as u8 != buf_byte {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
t5 >>= 8;
|
||||
}
|
||||
|
||||
if !valid {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Phase 4: Recover the initial LFSR0 state from the candidate
|
||||
t3 = candidate;
|
||||
let mut recovery_ok = true;
|
||||
for _ in 0..4 {
|
||||
let t1_byte = t3 & 0xFF;
|
||||
t3 >>= 8;
|
||||
// Brute-force the byte that was shifted in
|
||||
let mut found_j = false;
|
||||
for j in 0u32..256 {
|
||||
t3 = (t3 & 0x1FFFF) | (j << 17);
|
||||
let t6 = ((((((t3 >> 8) ^ t3) >> 1) ^ t3) >> 3) ^ t3) >> 7;
|
||||
if (t6 & 0xFF) == t1_byte {
|
||||
found_j = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found_j {
|
||||
recovery_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !recovery_ok {
|
||||
continue 'outer;
|
||||
}
|
||||
|
||||
// Convert LFSR0 initial state back to key bytes
|
||||
let t4 = (t3 >> 1).wrapping_sub(4);
|
||||
for t5_off in 0u32..8 {
|
||||
let val = t4.wrapping_add(t5_off);
|
||||
// Reconstruction probe: val can sit near u32::MAX, so the
|
||||
// (val*2 + 8 - (val & 7)) expression must wrap rather than
|
||||
// panic in debug. wrapping_* reproduces the release result
|
||||
// exactly (the comparison against t3 is unaffected).
|
||||
if val.wrapping_mul(2).wrapping_add(8).wrapping_sub(val & 7) == t3 {
|
||||
result_key[0] = (i_try >> 8) as u8;
|
||||
result_key[1] = (i_try & 0xFF) as u8;
|
||||
result_key[2] = (val & 0xFF) as u8;
|
||||
result_key[3] = ((val >> 8) & 0xFF) as u8;
|
||||
result_key[4] = ((val >> 16) & 0xFF) as u8;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return None;
|
||||
}
|
||||
|
||||
// XOR with sector seed to get the actual title key
|
||||
result_key[0] ^= seed[0];
|
||||
result_key[1] ^= seed[1];
|
||||
result_key[2] ^= seed[2];
|
||||
result_key[3] ^= seed[3];
|
||||
result_key[4] ^= seed[4];
|
||||
|
||||
Some(result_key)
|
||||
}
|
||||
|
||||
/// Crack the CSS title key from an encrypted sector using an MPEG-2
|
||||
/// pattern attack.
|
||||
///
|
||||
/// Detects the PES header pattern at byte 0x80 and uses it as known
|
||||
/// plaintext. This is a best-effort fallback for the SCSI auth path
|
||||
/// (see [`super::resolve`]): it only succeeds on a sector whose
|
||||
/// encrypted region begins with one of the tried PES header patterns,
|
||||
/// and returns `None` otherwise. The production DVD path obtains the
|
||||
/// title key via drive authentication, not cracking.
|
||||
pub fn crack_title_key(sector: &[u8]) -> Option<[u8; 5]> {
|
||||
if sector.len() < SECTOR_SIZE {
|
||||
return None;
|
||||
}
|
||||
|
||||
let flags = (sector[FLAG_BYTE] >> 4) & 0x03;
|
||||
if flags == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The PES header at byte 0x80 typically starts with 00 00 01 [stream_id].
|
||||
// The next bytes are PES length and flags. We need at least 10 bytes of
|
||||
// known plaintext for the Stevenson attack.
|
||||
//
|
||||
// Strategy: try common PES patterns. The first 3 bytes are always 00 00 01.
|
||||
// The stream_id varies. Bytes 4-9 depend on PES header structure.
|
||||
//
|
||||
// For a standard PES with PTS:
|
||||
// 00 00 01 [id] [len_hi] [len_lo] [flags] [flags2] [hdr_len] [PTS...]
|
||||
//
|
||||
// We try multiple stream IDs and use zeros for unknown bytes (most common).
|
||||
|
||||
// Try many PES header patterns at byte 0x80.
|
||||
// Structure: 00 00 01 [stream_id] [len_hi] [len_lo] [flags1] [flags2] [hdr_len] [data]
|
||||
// 24 padding-stream + 144 video/audio + 1 navigation = 169 patterns.
|
||||
let mut patterns: Vec<[u8; 10]> = Vec::with_capacity(169);
|
||||
|
||||
// Padding stream (0xBE): payload is 0xFF bytes, various lengths
|
||||
for len_hi in 0u8..8 {
|
||||
for len_lo_top in [0x00u8, 0x80, 0xFF] {
|
||||
patterns.push([
|
||||
0x00, 0x00, 0x01, 0xBE, len_hi, len_lo_top, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Video (0xE0) and audio (0xBD, 0xC0) with typical PES headers
|
||||
for &sid in &[0xE0u8, 0xBD, 0xC0] {
|
||||
for &flags1 in &[0x80u8, 0x81, 0x84, 0x85, 0x8C, 0x8D] {
|
||||
for &flags2 in &[0x00u8, 0x05, 0x80, 0xC0] {
|
||||
let hdr_len = if flags2 & 0x80 != 0 { 0x05u8 } else { 0x00 };
|
||||
let pts0 = if flags2 & 0x80 != 0 { 0x21u8 } else { 0x00 };
|
||||
// Try with several PES lengths
|
||||
for &len_hi in &[0x00u8, 0x07] {
|
||||
patterns.push([
|
||||
0x00, 0x00, 0x01, sid, len_hi, 0x00, flags1, flags2, hdr_len, pts0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation pack system header (0xBB)
|
||||
patterns.push([0x00, 0x00, 0x01, 0xBB, 0x00, 0x12, 0x80, 0xC4, 0xE1, 0x04]);
|
||||
|
||||
for pattern in &patterns {
|
||||
if let Some(key) = recover_title_key(sector, pattern) {
|
||||
let mut test = sector.to_vec();
|
||||
super::lfsr::descramble_sector(&key, &mut test);
|
||||
if test[0x80] == 0x00 && test[0x81] == 0x00 && test[0x82] == 0x01 {
|
||||
return Some(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn crack_unscrambled_returns_none() {
|
||||
let sector = vec![0u8; 2048];
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
/// Regression: the LFSR0 reconstruction arithmetic must not overflow
|
||||
/// (panic) in a debug build for scrambled sector content. Exercises
|
||||
/// the full 2^16 Stevenson search via recover_title_key directly (the
|
||||
/// overflow site), with the assertion simply that it does not panic.
|
||||
/// recover_title_key is used rather than crack_title_key to avoid
|
||||
/// re-running the search for all 169 PES patterns.
|
||||
#[test]
|
||||
fn crack_scrambled_sectors_never_overflow() {
|
||||
for seed in 0u32..4 {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = 0x30; // scramble flag set
|
||||
let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(1);
|
||||
for b in sector.iter_mut().skip(0x80) {
|
||||
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
*b = (x >> 16) as u8;
|
||||
}
|
||||
for (i, b) in sector[SEED_OFFSET..SEED_OFFSET + 5].iter_mut().enumerate() {
|
||||
*b = seed.wrapping_add(i as u32) as u8;
|
||||
}
|
||||
let plain = [0x00u8, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
let _ = recover_title_key(§or, &plain);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crack_too_short_returns_none() {
|
||||
let sector = vec![0u8; 100];
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recover_needs_10_bytes_plain() {
|
||||
let sector = vec![0u8; 2048];
|
||||
let short_plain = [0u8; 5];
|
||||
assert!(recover_title_key(§or, &short_plain).is_none());
|
||||
}
|
||||
|
||||
// ── recover_title_key early-return guards ──────────────────────────────
|
||||
|
||||
/// recover_title_key requires a full 2048-byte sector. A sector exactly
|
||||
/// one byte short of SECTOR_SIZE must be rejected (None) and must not
|
||||
/// index out of bounds reading the seed at 0x54..0x59 or the body at
|
||||
/// 0x80+.
|
||||
///
|
||||
/// Grounding: `if sector.len() < SECTOR_SIZE { return None }` with
|
||||
/// SECTOR_SIZE == 2048.
|
||||
/// Mutation: change `< SECTOR_SIZE` to `< 0x80` -> a 2047-byte sector with
|
||||
/// the flag set would proceed and (since seed slice 0x54..0x59 still fits)
|
||||
/// could return Some/panic; the None assert fires.
|
||||
#[test]
|
||||
fn recover_rejects_sector_one_byte_short() {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE - 1];
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
let plain = [0x00u8, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
assert!(recover_title_key(§or, &plain).is_none());
|
||||
}
|
||||
|
||||
/// A full-size but UNSCRAMBLED sector (flag bits 4-5 clear) must return
|
||||
/// None before doing any attack work — there is nothing to recover.
|
||||
///
|
||||
/// Grounding: `let flags = (sector[FLAG_BYTE] >> 4) & 0x03; if flags == 0
|
||||
/// { return None }`.
|
||||
/// Mutation: change the flag mask `& 0x03` to `& 0x00` (always 0) makes it
|
||||
/// always return None — caught by the scrambled-path tests; conversely
|
||||
/// removing the early return would let it run the attack on clear data.
|
||||
/// Here we pin the clear-flag rejection: with flag byte 0x00 -> None.
|
||||
#[test]
|
||||
fn recover_rejects_unscrambled_sector() {
|
||||
let sector = vec![0x00u8; SECTOR_SIZE];
|
||||
let plain = [0x00u8, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
assert!(recover_title_key(§or, &plain).is_none());
|
||||
}
|
||||
|
||||
/// recover_title_key's flag test uses bits 4-5 only (same field as the
|
||||
/// descrambler). A sector whose byte 0x14 has only bit 6 (0x40) or bit 7
|
||||
/// (0x80) set is NOT scrambled and must return None.
|
||||
///
|
||||
/// Grounding: `(sector[FLAG_BYTE] >> 4) & 0x03` — 0x40>>4&3==0,
|
||||
/// 0x80>>4&3==0.
|
||||
/// Mutation: widen the mask to `& 0x0F` -> 0x40 would look scrambled and
|
||||
/// the attack would run; this asserts None for 0x40/0x80.
|
||||
#[test]
|
||||
fn recover_high_flag_bits_are_not_scramble() {
|
||||
let plain = [0x00u8, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
for &flag in &[0x40u8, 0x80, 0xC0] {
|
||||
let mut sector = vec![0x11u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = flag;
|
||||
assert!(
|
||||
recover_title_key(§or, &plain).is_none(),
|
||||
"flag {flag:#04x} has scramble bits clear; recover must return None"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── crack_title_key early-return guards (flag uses bits 4-5) ────────────
|
||||
|
||||
/// crack_title_key uses the same bits-4-5 scramble field. A sector with
|
||||
/// only bit 6/7 of byte 0x14 set is not scrambled -> None, without running
|
||||
/// the 169-pattern search on clear data.
|
||||
///
|
||||
/// Grounding: `(sector[FLAG_BYTE] >> 4) & 0x03`.
|
||||
/// Mutation: widen mask -> 0x40 treated as scrambled; this asserts None.
|
||||
#[test]
|
||||
fn crack_high_flag_bits_are_not_scramble() {
|
||||
for &flag in &[0x40u8, 0x80, 0xC0] {
|
||||
let mut sector = vec![0x11u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = flag;
|
||||
assert!(
|
||||
crack_title_key(§or).is_none(),
|
||||
"flag {flag:#04x} clear scramble bits -> crack must return None"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// crack_title_key on a sector exactly one byte short of 2048 returns None
|
||||
/// at the size guard — no out-of-bounds read of the body/seed.
|
||||
///
|
||||
/// Grounding: `if sector.len() < SECTOR_SIZE { return None }`.
|
||||
/// Mutation: lower the guard to `< 0x80` -> a 2047-byte scrambled sector
|
||||
/// would run the attack (and could panic indexing 0x800); None asserts it.
|
||||
#[test]
|
||||
fn crack_rejects_sector_one_byte_short() {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE - 1];
|
||||
if sector.len() > FLAG_BYTE {
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
}
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
/// crack_title_key must never panic on a fully scrambled sector regardless
|
||||
/// of seed/body content — it runs the 169-pattern Stevenson search, each
|
||||
/// of which exercises the LFSR0 reconstruction arithmetic that previously
|
||||
/// overflowed in debug. This drives the FULL crack entry point (not just
|
||||
/// recover_title_key) across several pseudo-random scrambled sectors.
|
||||
///
|
||||
/// Grounding: wrapping_* arithmetic in recover_title_key must hold for all
|
||||
/// inputs; "never panic" property.
|
||||
/// Mutation: replace a `wrapping_shl`/`wrapping_mul` with the plain
|
||||
/// operator -> debug build panics on overflow for some seed, this test
|
||||
/// fails.
|
||||
#[test]
|
||||
fn crack_full_path_never_panics() {
|
||||
for seed in 0u32..3 {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(7);
|
||||
for b in sector.iter_mut().skip(0x80) {
|
||||
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
*b = (x >> 16) as u8;
|
||||
}
|
||||
for (i, b) in sector[SEED_OFFSET..SEED_OFFSET + 5].iter_mut().enumerate() {
|
||||
*b = (seed.wrapping_add(i as u32) ^ 0xA5) as u8;
|
||||
}
|
||||
let _ = crack_title_key(§or);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a scrambled sector with known plaintext (both an MPEG PES header
|
||||
/// at 0x80 and an exact-plaintext probe), then assert that the Stevenson
|
||||
/// recovery actually recovers a key whose descramble round-trips the body.
|
||||
///
|
||||
/// This is the regression gate for the CSS crack/recover path. It is
|
||||
/// `#[ignore]`d because that path is currently non-functional: the
|
||||
/// recovery models the textbook direct-seed cipher, whereas this crate's
|
||||
/// [`descramble_sector`] seeds from a `decrypt_key`-mangled key, so the
|
||||
/// two are inconsistent and recovery returns `None`. When the crack
|
||||
/// algorithm is re-derived against this crate's actual descrambler, this
|
||||
/// test must pass with `--ignored` removed. The production DVD path does
|
||||
/// not use crack/recover (it authenticates over SCSI), so the broken
|
||||
/// fallback does not affect shipped behavior.
|
||||
#[test]
|
||||
#[ignore = "CSS crack/recover path is non-functional vs this crate's descrambler; \
|
||||
see module docs. Regression gate for a future fix."]
|
||||
fn css_crack_recovers_key_from_scrambled_sector() {
|
||||
use super::super::lfsr::descramble_sector;
|
||||
|
||||
let title_key: [u8; 5] = [0x42, 0x13, 0x37, 0xBE, 0xEF];
|
||||
|
||||
// Build a plaintext MPEG-2 sector
|
||||
let mut plaintext = vec![0x00u8; SECTOR_SIZE];
|
||||
|
||||
// Pack header at byte 0: 00 00 01 BA
|
||||
plaintext[0] = 0x00;
|
||||
plaintext[1] = 0x00;
|
||||
plaintext[2] = 0x01;
|
||||
plaintext[3] = 0xBA;
|
||||
|
||||
// Scramble flag at byte 0x14
|
||||
plaintext[FLAG_BYTE] = 0x30;
|
||||
|
||||
// Sector seed at bytes 0x54-0x58
|
||||
plaintext[SEED_OFFSET..SEED_OFFSET + 5].copy_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55]);
|
||||
|
||||
// PES header at byte 0x80: 00 00 01 E0 (video stream) with PTS.
|
||||
let exact_plain: [u8; 10] = [0x00, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
plaintext[0x80..0x80 + 10].copy_from_slice(&exact_plain);
|
||||
|
||||
let original_plaintext = plaintext.clone();
|
||||
|
||||
// "Scramble" the sector by XORing the keystream over the plaintext.
|
||||
descramble_sector(&title_key, &mut plaintext);
|
||||
|
||||
// descramble_sector cleared the flag; restore it so the cracker sees
|
||||
// the sector as encrypted.
|
||||
plaintext[FLAG_BYTE] = 0x30;
|
||||
|
||||
// 1) Pattern-guessing entry point must recover a key.
|
||||
let cracked = crack_title_key(&plaintext);
|
||||
assert!(
|
||||
cracked.is_some(),
|
||||
"crack_title_key returned None for a sector scrambled with a known key"
|
||||
);
|
||||
let cracked = cracked.unwrap();
|
||||
let mut body = plaintext.clone();
|
||||
descramble_sector(&cracked, &mut body);
|
||||
assert_eq!(
|
||||
&body[0x80..SECTOR_SIZE],
|
||||
&original_plaintext[0x80..SECTOR_SIZE],
|
||||
"crack_title_key key did not round-trip the body"
|
||||
);
|
||||
|
||||
// 2) Exact known plaintext must also recover a round-tripping key.
|
||||
let recovered = recover_title_key(&plaintext, &exact_plain);
|
||||
assert!(
|
||||
recovered.is_some(),
|
||||
"recover_title_key returned None for exact known plaintext"
|
||||
);
|
||||
let recovered = recovered.unwrap();
|
||||
let mut body2 = plaintext.clone();
|
||||
descramble_sector(&recovered, &mut body2);
|
||||
assert_eq!(
|
||||
&body2[0x80..SECTOR_SIZE],
|
||||
&original_plaintext[0x80..SECTOR_SIZE],
|
||||
"recover_title_key key did not round-trip the body"
|
||||
);
|
||||
}
|
||||
}
|
||||
+153
-261
@@ -13,53 +13,21 @@
|
||||
|
||||
use super::tables::{TAB1, TAB2, TAB3, TAB4, TAB5};
|
||||
|
||||
/// Seed the 32-bit LFSR0 register from the 5-byte working key, applying
|
||||
/// the per-byte TAB4 bit-reversal. Shared by [`descramble_sector`] and
|
||||
/// [`decrypt_key`] so the seeding lives in one place.
|
||||
#[inline]
|
||||
fn seed_lfsr0(key: &[u8; 5]) -> u32 {
|
||||
let lfsr0: u32 = ((key[4] as u32) << 17)
|
||||
| ((key[3] as u32) << 9)
|
||||
| (((key[2] as u32) << 1) + 8 - (key[2] as u32 & 7));
|
||||
(TAB4[(lfsr0 & 0xFF) as usize] as u32) << 24
|
||||
| (TAB4[((lfsr0 >> 8) & 0xFF) as usize] as u32) << 16
|
||||
| (TAB4[((lfsr0 >> 16) & 0xFF) as usize] as u32) << 8
|
||||
| TAB4[((lfsr0 >> 24) & 0xFF) as usize] as u32
|
||||
}
|
||||
|
||||
/// One CSS keystream step. Advances both LFSRs, folds their permuted
|
||||
/// outputs into `combined` (carry kept across calls), and returns the
|
||||
/// low keystream byte. `invert` XORs the LFSR0 output index (0x00 on the
|
||||
/// descramble path, 0xFF on the key-decrypt path).
|
||||
#[inline]
|
||||
fn css_step(
|
||||
lfsr1_lo: &mut u32,
|
||||
lfsr1_hi: &mut u32,
|
||||
lfsr0: &mut u32,
|
||||
combined: &mut u32,
|
||||
invert: u8,
|
||||
) -> u8 {
|
||||
let o_lfsr1 = TAB2[*lfsr1_hi as usize] ^ TAB3[*lfsr1_lo as usize];
|
||||
*lfsr1_hi = *lfsr1_lo >> 1;
|
||||
*lfsr1_lo = ((*lfsr1_lo & 1) << 8) ^ o_lfsr1 as u32;
|
||||
|
||||
let o_lfsr0 = (((((((*lfsr0 >> 8) ^ *lfsr0) >> 1) ^ *lfsr0) >> 3) ^ *lfsr0) >> 7) as u8;
|
||||
*lfsr0 = (*lfsr0 >> 8) | ((o_lfsr0 as u32) << 24);
|
||||
|
||||
*combined += TAB5[o_lfsr1 as usize] as u32 + TAB4[(o_lfsr0 ^ invert) as usize] as u32;
|
||||
let out = (*combined & 0xFF) as u8;
|
||||
*combined >>= 8;
|
||||
out
|
||||
}
|
||||
|
||||
/// Descramble a CSS-encrypted DVD sector in place.
|
||||
///
|
||||
/// The sector seed (bytes 0x54-0x58) is XORed with the title key to produce
|
||||
/// the per-sector key. Bytes 0x80..0x800 (128..2048) are then decrypted
|
||||
/// using the two-LFSR keystream.
|
||||
/// Exact port of libdvdcss `dvdcss_unscramble` (css.c). The two content
|
||||
/// LFSRs are seeded **directly** from `title_key XOR sector_seed` — there is
|
||||
/// no `decrypt_key` mangling on this path (that is the disc/title-key
|
||||
/// hierarchy, not the content cipher). Bytes 0x80..0x800 are recovered with
|
||||
/// `*p = TAB1[*p] ^ (i_t5 & 0xff)`.
|
||||
///
|
||||
/// The scramble flag at byte 0x14 (bits 4-5) indicates encryption.
|
||||
/// After descrambling, the flag is cleared.
|
||||
/// The scramble flag at byte 0x14 (bits 4-5) indicates encryption. Like
|
||||
/// libdvdcss, the flag byte is NOT modified here — the caller treats a
|
||||
/// nonzero `sector[0x14] & 0x30` as "needs unscrambling" and the descramble
|
||||
/// is its own inverse, so re-running it on plaintext would re-scramble.
|
||||
/// (freemkv historically cleared the flag; we keep clearing it so callers
|
||||
/// and the existing tests can distinguish a descrambled sector. This does
|
||||
/// not affect the recovered body.)
|
||||
///
|
||||
/// No-op (returns without modifying `sector`) in two cases:
|
||||
/// - `sector.len() < 2048`: the encrypted region (0x80..0x800) is not
|
||||
@@ -67,6 +35,21 @@ fn css_step(
|
||||
/// left untouched. The `debug_assert!` flags this misuse in debug/test
|
||||
/// builds; a DVD sector is always exactly 2048 bytes.
|
||||
/// - scramble flags are zero: the sector is not CSS-encrypted.
|
||||
///
|
||||
/// Design reference: libdvdcss `dvdcss_unscramble`. The combiner mirrors
|
||||
/// `css.c` line-for-line:
|
||||
/// ```text
|
||||
/// i_t1 = (key[0] ^ sec[0x54]) | 0x100;
|
||||
/// i_t2 = key[1] ^ sec[0x55];
|
||||
/// i_t3 = (key[2]|key[3]<<8|key[4]<<16) ^ (sec[0x56]|sec[0x57]<<8|sec[0x58]<<16);
|
||||
/// i_t4 = i_t3 & 7; i_t3 = i_t3*2 + 8 - i_t4;
|
||||
/// // per byte over 0x80..0x800:
|
||||
/// i_t4 = TAB2[i_t2] ^ TAB3[i_t1];
|
||||
/// i_t2 = i_t1 >> 1; i_t1 = ((i_t1 & 1) << 8) ^ i_t4; i_t4 = TAB5[i_t4];
|
||||
/// i_t6 = (((((((i_t3>>3)^i_t3)>>1)^i_t3)>>8)^i_t3)>>5) & 0xff;
|
||||
/// i_t3 = (i_t3 << 8) | i_t6; i_t6 = TAB4[i_t6];
|
||||
/// i_t5 += i_t6 + i_t4; *p = TAB1[*p] ^ (i_t5 & 0xff); i_t5 >>= 8;
|
||||
/// ```
|
||||
pub fn descramble_sector(title_key: &[u8; 5], sector: &mut [u8]) {
|
||||
debug_assert!(
|
||||
sector.len() >= 2048,
|
||||
@@ -76,101 +59,111 @@ pub fn descramble_sector(title_key: &[u8; 5], sector: &mut [u8]) {
|
||||
return;
|
||||
}
|
||||
|
||||
let flags = (sector[0x14] >> 4) & 0x03;
|
||||
if flags == 0 {
|
||||
// libdvdcss: `if( !(p_sec[0x14] & 0x30) ) return;`
|
||||
if sector[0x14] & 0x30 == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Per-sector key = title_key XOR sector_seed (bytes 0x54-0x58)
|
||||
let key = [
|
||||
title_key[0] ^ sector[0x54],
|
||||
title_key[1] ^ sector[0x55],
|
||||
title_key[2] ^ sector[0x56],
|
||||
title_key[3] ^ sector[0x57],
|
||||
title_key[4] ^ sector[0x58],
|
||||
];
|
||||
// LFSR1: seeded directly from (key ^ seed) — NO decrypt_key.
|
||||
let mut i_t1: u32 = ((title_key[0] ^ sector[0x54]) as u32) | 0x100;
|
||||
let mut i_t2: u32 = (title_key[1] ^ sector[0x55]) as u32;
|
||||
|
||||
// Decrypt the key through the CSS mangling function to get the working key.
|
||||
// The sector seed is bytes 0x54..0x59 (5 bytes).
|
||||
let seed: [u8; 5] = [
|
||||
sector[0x54],
|
||||
sector[0x55],
|
||||
sector[0x56],
|
||||
sector[0x57],
|
||||
sector[0x58],
|
||||
];
|
||||
let working_key = decrypt_key(0xFF, &key, &seed);
|
||||
// LFSR0 (i_t3): 24-bit feedback register seeded from the remaining three
|
||||
// key/seed bytes, then transformed `i_t3 = i_t3*2 + 8 - (i_t3 & 7)`.
|
||||
let mut i_t3: u32 = (((title_key[2] as u32)
|
||||
| ((title_key[3] as u32) << 8)
|
||||
| ((title_key[4] as u32) << 16))
|
||||
^ ((sector[0x56] as u32) | ((sector[0x57] as u32) << 8) | ((sector[0x58] as u32) << 16)))
|
||||
& 0xFF_FFFF;
|
||||
let i_t4_seed = i_t3 & 7;
|
||||
i_t3 = i_t3 * 2 + 8 - i_t4_seed;
|
||||
|
||||
// Generate keystream and XOR with encrypted region
|
||||
let mut lfsr1_lo: u32 = working_key[0] as u32 | 0x100;
|
||||
let mut lfsr1_hi: u32 = working_key[1] as u32;
|
||||
let mut lfsr0: u32 = seed_lfsr0(&working_key);
|
||||
let mut i_t5: u32 = 0;
|
||||
|
||||
let mut combined: u32 = 0;
|
||||
|
||||
// Generate 1920 keystream bytes (for sector bytes 128..2048) and XOR them
|
||||
// into the encrypted region. Each keystream byte is the carrying sum of the
|
||||
// TAB5-permuted LFSR1 output and the TAB4-permuted LFSR0 output. No TAB1
|
||||
// permutation is applied to the ciphertext here (TAB1 is only used inside
|
||||
// decrypt_key); the working key was already produced by decrypt_key above,
|
||||
// so this keystream is paired with that mangling step, not a plain
|
||||
// direct-seed unscramble. No invert is applied on the LFSR0 output.
|
||||
for byte in sector.iter_mut().take(2048).skip(128) {
|
||||
let ks = css_step(
|
||||
&mut lfsr1_lo,
|
||||
&mut lfsr1_hi,
|
||||
&mut lfsr0,
|
||||
&mut combined,
|
||||
0x00,
|
||||
);
|
||||
*byte ^= ks;
|
||||
// Advance LFSR1.
|
||||
let mut i_t4 = (TAB2[i_t2 as usize] ^ TAB3[i_t1 as usize]) as u32;
|
||||
i_t2 = i_t1 >> 1;
|
||||
i_t1 = ((i_t1 & 1) << 8) ^ i_t4;
|
||||
i_t4 = TAB5[i_t4 as usize] as u32;
|
||||
|
||||
// Advance LFSR0 (i_t3) and fold both outputs into i_t5.
|
||||
let mut i_t6 = (((((((i_t3 >> 3) ^ i_t3) >> 1) ^ i_t3) >> 8) ^ i_t3) >> 5) & 0xFF;
|
||||
i_t3 = (i_t3 << 8) | i_t6;
|
||||
i_t6 = TAB4[i_t6 as usize] as u32;
|
||||
i_t5 += i_t6 + i_t4;
|
||||
|
||||
*byte = TAB1[*byte as usize] ^ (i_t5 & 0xFF) as u8;
|
||||
i_t5 >>= 8;
|
||||
}
|
||||
|
||||
// Clear scramble flags
|
||||
// libdvdcss leaves byte 0x14 untouched; freemkv clears the scramble bits
|
||||
// so downstream code and tests can tell a sector was descrambled.
|
||||
sector[0x14] &= 0xCF;
|
||||
}
|
||||
|
||||
/// CSS key decryption / mangling function.
|
||||
/// Exact inverse of [`descramble_sector`]: turn a plaintext sector body into
|
||||
/// CSS ciphertext under `title_key`.
|
||||
///
|
||||
/// Decrypts `p_crypted` using `p_key` with the CSS two-LFSR cipher.
|
||||
/// The `invert` parameter controls the XOR applied to LFSR0 output
|
||||
/// (0x00 for disc key decryption, 0xFF for title key / sector key).
|
||||
pub(crate) fn decrypt_key(invert: u8, p_key: &[u8; 5], p_crypted: &[u8; 5]) -> [u8; 5] {
|
||||
let mut lfsr1_lo: u32 = p_key[0] as u32 | 0x100;
|
||||
let mut lfsr1_hi: u32 = p_key[1] as u32;
|
||||
let mut lfsr0: u32 = seed_lfsr0(p_key);
|
||||
|
||||
let mut combined: u32 = 0;
|
||||
let mut k = [0u8; 5];
|
||||
|
||||
// TAB5 for LFSR1 output, TAB4 for LFSR0^invert (per libdvdcss css_DecryptKey).
|
||||
for byte in &mut k {
|
||||
*byte = css_step(
|
||||
&mut lfsr1_lo,
|
||||
&mut lfsr1_hi,
|
||||
&mut lfsr0,
|
||||
&mut combined,
|
||||
invert,
|
||||
);
|
||||
/// Descramble computes `plain = TAB1[cipher] ^ (i_t5 & 0xff)`, so the
|
||||
/// inverse is `cipher = TAB1_INV[plain ^ (i_t5 & 0xff)]` with the identical
|
||||
/// LFSR keystream. The keystream derivation is byte-for-byte the same as
|
||||
/// `descramble_sector` (libdvdcss `dvdcss_unscramble`); only the final
|
||||
/// substitution differs. Bytes 0x80..0x800 are rewritten in place; the
|
||||
/// scramble flag is set to 0x10 so a subsequent descramble runs.
|
||||
///
|
||||
/// Not on any production read path — it exists so the key-recovery tests
|
||||
/// (and any caller that needs to produce a known CSS-encrypted sector) can
|
||||
/// build genuine ciphertext rather than approximating it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scramble_sector(title_key: &[u8; 5], sector: &mut [u8]) {
|
||||
if sector.len() < 2048 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Two rounds of chained XOR through TAB1
|
||||
let mut result = [0u8; 5];
|
||||
result[4] = k[4] ^ TAB1[p_crypted[4] as usize] ^ p_crypted[3];
|
||||
result[3] = k[3] ^ TAB1[p_crypted[3] as usize] ^ p_crypted[2];
|
||||
result[2] = k[2] ^ TAB1[p_crypted[2] as usize] ^ p_crypted[1];
|
||||
result[1] = k[1] ^ TAB1[p_crypted[1] as usize] ^ p_crypted[0];
|
||||
result[0] = k[0] ^ TAB1[p_crypted[0] as usize] ^ result[4];
|
||||
let mut i_t1: u32 = ((title_key[0] ^ sector[0x54]) as u32) | 0x100;
|
||||
let mut i_t2: u32 = (title_key[1] ^ sector[0x55]) as u32;
|
||||
let mut i_t3: u32 = (((title_key[2] as u32)
|
||||
| ((title_key[3] as u32) << 8)
|
||||
| ((title_key[4] as u32) << 16))
|
||||
^ ((sector[0x56] as u32) | ((sector[0x57] as u32) << 8) | ((sector[0x58] as u32) << 16)))
|
||||
& 0xFF_FFFF;
|
||||
let i_t4_seed = i_t3 & 7;
|
||||
i_t3 = i_t3 * 2 + 8 - i_t4_seed;
|
||||
|
||||
result[4] = k[4] ^ TAB1[result[4] as usize] ^ result[3];
|
||||
result[3] = k[3] ^ TAB1[result[3] as usize] ^ result[2];
|
||||
result[2] = k[2] ^ TAB1[result[2] as usize] ^ result[1];
|
||||
result[1] = k[1] ^ TAB1[result[1] as usize] ^ result[0];
|
||||
result[0] = k[0] ^ TAB1[result[0] as usize];
|
||||
let mut i_t5: u32 = 0;
|
||||
|
||||
result
|
||||
for byte in sector.iter_mut().take(2048).skip(128) {
|
||||
let mut i_t4 = (TAB2[i_t2 as usize] ^ TAB3[i_t1 as usize]) as u32;
|
||||
i_t2 = i_t1 >> 1;
|
||||
i_t1 = ((i_t1 & 1) << 8) ^ i_t4;
|
||||
i_t4 = TAB5[i_t4 as usize] as u32;
|
||||
|
||||
let mut i_t6 = (((((((i_t3 >> 3) ^ i_t3) >> 1) ^ i_t3) >> 8) ^ i_t3) >> 5) & 0xFF;
|
||||
i_t3 = (i_t3 << 8) | i_t6;
|
||||
i_t6 = TAB4[i_t6 as usize] as u32;
|
||||
i_t5 += i_t6 + i_t4;
|
||||
|
||||
// Inverse of `*p = TAB1[*p] ^ ks`: apply ks then TAB1's inverse.
|
||||
*byte = (*TAB1_INV)[(*byte ^ (i_t5 & 0xFF) as u8) as usize];
|
||||
i_t5 >>= 8;
|
||||
}
|
||||
|
||||
// Mark the sector scrambled so the descrambler will process it.
|
||||
sector[0x14] = (sector[0x14] & 0xCF) | 0x10;
|
||||
}
|
||||
|
||||
/// Inverse permutation of [`TAB1`], built at first use. `TAB1` is a
|
||||
/// bijection on 0..256, so `TAB1_INV[TAB1[x]] == x`.
|
||||
#[cfg(test)]
|
||||
static TAB1_INV: std::sync::LazyLock<[u8; 256]> = std::sync::LazyLock::new(|| {
|
||||
let mut inv = [0u8; 256];
|
||||
for (i, &v) in TAB1.iter().enumerate() {
|
||||
inv[v as usize] = i as u8;
|
||||
}
|
||||
inv
|
||||
});
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -185,6 +178,34 @@ mod tests {
|
||||
assert_eq!(sector, original);
|
||||
}
|
||||
|
||||
/// Cross-check `descramble_sector` against the EXACT output of libdvdcss
|
||||
/// `dvdcss_unscramble` (css.c) for a fixed sector, computed from the
|
||||
/// reference C semantics with the reference tables. Pins the content
|
||||
/// cipher to libdvdcss byte-for-byte.
|
||||
///
|
||||
/// key = 42 13 37 BE EF, seed (0x54..0x59) = DE AD BE EF 42, body = 0xAA.
|
||||
#[test]
|
||||
fn descramble_matches_libdvdcss_unscramble_vector() {
|
||||
let key = [0x42, 0x13, 0x37, 0xBE, 0xEF];
|
||||
let mut sector = vec![0xAAu8; 2048];
|
||||
sector[0x14] = 0x30;
|
||||
sector[0x54..0x59].copy_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF, 0x42]);
|
||||
descramble_sector(&key, &mut sector);
|
||||
assert_eq!(
|
||||
§or[0x80..0x90],
|
||||
&[
|
||||
0x81, 0x92, 0x24, 0xA2, 0x46, 0x70, 0x3C, 0x64, 0xA6, 0x91, 0x84, 0xF5, 0x1F, 0x98,
|
||||
0xA0, 0x31
|
||||
],
|
||||
"descramble body head must match libdvdcss dvdcss_unscramble"
|
||||
);
|
||||
assert_eq!(
|
||||
§or[0x7F8..0x800],
|
||||
&[0x46, 0x94, 0x80, 0x0E, 0x67, 0x36, 0x65, 0xBC],
|
||||
"descramble body tail must match libdvdcss dvdcss_unscramble"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descramble_modifies_scrambled() {
|
||||
let key = [0x01, 0x02, 0x03, 0x04, 0x05];
|
||||
@@ -215,69 +236,14 @@ mod tests {
|
||||
assert_eq!(sector[0x14] & 0x30, 0x00);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decrypt_key_produces_output() {
|
||||
let key = [0x12, 0x34, 0x56, 0x78, 0x9A];
|
||||
let crypted = [0xAB, 0xCD, 0xEF, 0x01, 0x23];
|
||||
let result = decrypt_key(0xFF, &key, &crypted);
|
||||
// Should produce a 5-byte result different from input
|
||||
assert_ne!(result, key);
|
||||
assert_ne!(result, [0u8; 5]);
|
||||
}
|
||||
|
||||
/// css_decrypt_key_roundtrip
|
||||
/// Test 2: descramble inverts scramble over the body.
|
||||
///
|
||||
/// decrypt_key is not a simple encrypt/decrypt pair — it is a one-way mangling
|
||||
/// function. However, we can verify consistency: calling it twice with the same
|
||||
/// parameters produces the same output, and varying the invert byte changes
|
||||
/// the LFSR0 contribution predictably.
|
||||
/// The content cipher is NOT a plain XOR involution (it applies TAB1 to
|
||||
/// the ciphertext: `plain = TAB1[cipher] ^ ks`). The true inverse is
|
||||
/// [`scramble_sector`]. Scrambling a plaintext body and then descrambling
|
||||
/// with the same key must reproduce the original body exactly.
|
||||
#[test]
|
||||
fn css_decrypt_key_roundtrip() {
|
||||
let keys: &[[u8; 5]] = &[
|
||||
[0x12, 0x34, 0x56, 0x78, 0x9A],
|
||||
[0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
|
||||
[0xAB, 0xCD, 0xEF, 0x01, 0x23],
|
||||
];
|
||||
let crypted_inputs: &[[u8; 5]] = &[
|
||||
[0x11, 0x22, 0x33, 0x44, 0x55],
|
||||
[0xAA, 0xBB, 0xCC, 0xDD, 0xEE],
|
||||
[0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
];
|
||||
|
||||
for key in keys {
|
||||
for crypted in crypted_inputs {
|
||||
// decrypt_key with invert=0x00 and invert=0xFF should give different results
|
||||
let r0 = decrypt_key(0x00, key, crypted);
|
||||
let rff = decrypt_key(0xFF, key, crypted);
|
||||
|
||||
// The two results differ because the invert byte XORs the LFSR0 output
|
||||
// They should not be equal (except by extreme coincidence)
|
||||
// More importantly, both should be deterministic
|
||||
let r0_again = decrypt_key(0x00, key, crypted);
|
||||
let rff_again = decrypt_key(0xFF, key, crypted);
|
||||
assert_eq!(r0, r0_again, "decrypt_key(0x00) not deterministic");
|
||||
assert_eq!(rff, rff_again, "decrypt_key(0xFF) not deterministic");
|
||||
|
||||
// With different invert values, the keystream differs
|
||||
assert_ne!(
|
||||
r0, rff,
|
||||
"invert=0x00 and 0xFF gave same result for key {:?}",
|
||||
key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Test 2: descramble_modifies_encrypted_region
|
||||
///
|
||||
/// descramble_sector XORs a keystream into bytes 128..2048. The keystream
|
||||
/// depends only on (title_key, sector_seed), so applying descramble twice
|
||||
/// with the scramble flag restored between calls re-XORs the same keystream
|
||||
/// and restores the original encrypted region — the keystream XOR is its
|
||||
/// own inverse. This pins the cipher's involution property over the body.
|
||||
#[test]
|
||||
fn css_descramble_modifies_encrypted_region() {
|
||||
fn css_descramble_inverts_scramble_over_body() {
|
||||
let title_key = [0x42, 0x13, 0x37, 0xBE, 0xEF];
|
||||
|
||||
let mut sector = vec![0xAAu8; 2048];
|
||||
@@ -285,11 +251,10 @@ mod tests {
|
||||
sector[0x54..0x59].copy_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF, 0x42]);
|
||||
|
||||
let original = sector.clone();
|
||||
descramble_sector(&title_key, &mut sector);
|
||||
|
||||
// Flag cleared
|
||||
assert_eq!(sector[0x14] & 0x30, 0x00);
|
||||
// Header (0..128) unchanged except flag byte
|
||||
// Scramble the plaintext body into ciphertext.
|
||||
scramble_sector(&title_key, &mut sector);
|
||||
// Header (0..128) unchanged except the flag byte (set by scramble).
|
||||
for i in 0..128 {
|
||||
if i == 0x14 {
|
||||
continue;
|
||||
@@ -299,15 +264,13 @@ mod tests {
|
||||
// Encrypted region modified
|
||||
assert_ne!(§or[128..256], &original[128..256]);
|
||||
|
||||
// Round-trip: restore the scramble flag and descramble again. The same
|
||||
// keystream is regenerated (it depends only on title_key + seed, both
|
||||
// unchanged), so the body is restored to its original bytes.
|
||||
sector[0x14] = 0x30;
|
||||
// Descramble restores the plaintext body byte-for-byte.
|
||||
descramble_sector(&title_key, &mut sector);
|
||||
assert_eq!(sector[0x14] & 0x30, 0x00, "flag cleared after descramble");
|
||||
assert_eq!(
|
||||
§or[128..2048],
|
||||
&original[128..2048],
|
||||
"double descramble did not restore the encrypted region"
|
||||
"descramble(scramble(body)) did not restore the body"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -542,75 +505,4 @@ mod tests {
|
||||
"different seeds must descramble differently"
|
||||
);
|
||||
}
|
||||
|
||||
// ── decrypt_key chained-XOR dependency structure ───────────────────────
|
||||
|
||||
/// css_DecryptKey's two TAB1 rounds form a fixed dependency chain. After
|
||||
/// both rounds, `result[0]` is the last value computed and depends on the
|
||||
/// full key/crypted state; but the FIRST-round seed for `result[4]` is
|
||||
/// `k[4] ^ TAB1[p_crypted[4]] ^ p_crypted[3]`. Changing ONLY p_crypted[4]
|
||||
/// must change the output (p_crypted[4] feeds result[4] which propagates).
|
||||
///
|
||||
/// Grounding: lines computing result[4] use p_crypted[4] and p_crypted[3].
|
||||
/// Mutation: in `result[4] = k[4] ^ TAB1[p_crypted[4]] ^ p_crypted[3]`
|
||||
/// drop the `TAB1[p_crypted[4]]` term -> output stops depending on
|
||||
/// p_crypted[4], this assert fires.
|
||||
#[test]
|
||||
fn decrypt_key_depends_on_every_crypted_byte() {
|
||||
let key = [0x12, 0x34, 0x56, 0x78, 0x9A];
|
||||
let base = [0xAB, 0xCD, 0xEF, 0x01, 0x23];
|
||||
let base_out = decrypt_key(0xFF, &key, &base);
|
||||
for i in 0..5 {
|
||||
let mut c = base;
|
||||
c[i] ^= 0x01;
|
||||
assert_ne!(
|
||||
decrypt_key(0xFF, &key, &c),
|
||||
base_out,
|
||||
"flipping crypted byte {i} did not change the decrypted key"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Likewise every key byte feeds the LFSR seeding (key[0],key[1] seed
|
||||
/// LFSR1; key[2..5] seed LFSR0 via seed_lfsr0). Flipping any single key
|
||||
/// byte must change the output.
|
||||
///
|
||||
/// Grounding: lfsr1_lo=key[0]|0x100, lfsr1_hi=key[1], seed_lfsr0(key) uses
|
||||
/// key[2],key[3],key[4].
|
||||
/// Mutation: in seed_lfsr0 drop the `(key[4] as u32) << 17` term -> key[4]
|
||||
/// no longer influences LFSR0, this assert fires for i==4.
|
||||
#[test]
|
||||
fn decrypt_key_depends_on_every_key_byte() {
|
||||
let base_key = [0x12, 0x34, 0x56, 0x78, 0x9A];
|
||||
let crypted = [0xAB, 0xCD, 0xEF, 0x01, 0x23];
|
||||
let base_out = decrypt_key(0xFF, &base_key, &crypted);
|
||||
for i in 0..5 {
|
||||
let mut k = base_key;
|
||||
k[i] ^= 0x01;
|
||||
assert_ne!(
|
||||
decrypt_key(0xFF, &k, &crypted),
|
||||
base_out,
|
||||
"flipping key byte {i} did not change the decrypted key"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The invert byte (0x00 vs 0xFF) selects the LFSR0 output index in
|
||||
/// css_step via `TAB4[(o_lfsr0 ^ invert) as usize]`. For a non-degenerate
|
||||
/// key it must change the keystream and hence the result. (Pins that the
|
||||
/// invert parameter is actually wired into the LFSR0 path, distinguishing
|
||||
/// the disc-key vs title-key code paths.)
|
||||
///
|
||||
/// Grounding: css_step's `TAB4[(o_lfsr0 ^ invert)]`.
|
||||
/// Mutation: hardcode `invert` to 0 inside css_step -> r0 == rff, fails.
|
||||
#[test]
|
||||
fn decrypt_key_invert_changes_result() {
|
||||
let key = [0x12, 0x34, 0x56, 0x78, 0x9A];
|
||||
let crypted = [0xAB, 0xCD, 0xEF, 0x01, 0x23];
|
||||
assert_ne!(
|
||||
decrypt_key(0x00, &key, &crypted),
|
||||
decrypt_key(0xFF, &key, &crypted),
|
||||
"invert must alter the LFSR0 keystream"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+94
-91
@@ -2,29 +2,24 @@
|
||||
//!
|
||||
//! CSS uses a weak 40-bit LFSR stream cipher (broken since 1999).
|
||||
//!
|
||||
//! The production entry point is [`resolve`]. Two title-key acquisition
|
||||
//! paths exist behind it:
|
||||
//! - The SCSI auth path drives bus authentication with the compiled-in CSS
|
||||
//! player keys and reads the title key from the drive (the production DVD
|
||||
//! path on a live drive).
|
||||
//! - The crack fallback ([`crack_key`]) needs no keys — it attempts the
|
||||
//! Stevenson known-plaintext attack on MPEG-2 PES headers. (Currently
|
||||
//! non-functional; see the `crack` module docs.)
|
||||
//! The title key is recovered keylessly: [`crack_key`] runs the Stevenson
|
||||
//! known-plaintext attack (see the [`stevenson`] module) on the scrambled
|
||||
//! data, needing no player keys, disc-key crack, or external key file.
|
||||
//! Sectors are then decrypted with [`descramble_sector`].
|
||||
//!
|
||||
//! Usage:
|
||||
//! ```rust,ignore
|
||||
//! if let Some(state) = css::resolve(&mut ctx) {
|
||||
//! if let Some(state) = css::crack_key(reader, extents, batch) {
|
||||
//! css::descramble_sector(&state, &mut sector);
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub mod auth;
|
||||
pub mod crack;
|
||||
pub mod lfsr;
|
||||
pub mod stevenson;
|
||||
pub(crate) mod tables;
|
||||
|
||||
use crate::disc::Extent;
|
||||
use crate::drive::Drive;
|
||||
use crate::sector::SectorSource;
|
||||
|
||||
/// CSS decryption state for a DVD title.
|
||||
@@ -34,89 +29,97 @@ pub struct CssState {
|
||||
pub title_key: [u8; 5],
|
||||
}
|
||||
|
||||
/// Inputs for CSS key acquisition.
|
||||
/// Recover the CSS title key with no keys, by scanning scrambled sectors and
|
||||
/// running the Stevenson known-plaintext attack (see the [`stevenson`] module).
|
||||
///
|
||||
/// The acquisition path depends on which inputs the caller supplies:
|
||||
///
|
||||
/// - With `drive` + `auth_lba` set, [`resolve`] runs the full SCSI bus
|
||||
/// auth + title-key path (live BU40N / DVD drive).
|
||||
/// - With `reader` + `extents` set, [`resolve`] falls back to the
|
||||
/// crack path (Stevenson known-plaintext attack on encrypted PES
|
||||
/// headers; works on disc images and on drives whose CSS auth path
|
||||
/// is unavailable).
|
||||
///
|
||||
/// The `drive` (auth) path always wins when both modes are populated.
|
||||
pub struct CssContext<'a> {
|
||||
/// Live SCSI drive — when present, [`resolve`] tries the auth path.
|
||||
pub drive: Option<&'a mut Drive>,
|
||||
/// LBA of a known-scrambled sector for the auth path's title-key
|
||||
/// query. Required when `drive` is set.
|
||||
pub auth_lba: Option<u32>,
|
||||
/// Sector source for the crack path.
|
||||
pub reader: Option<&'a mut dyn SectorSource>,
|
||||
/// Extents to scan for the crack path. Required when `reader` is
|
||||
/// set.
|
||||
pub extents: Option<&'a [Extent]>,
|
||||
/// The crib comes from `AttackPattern`: a scrambled sector's cleartext region
|
||||
/// (bytes 0x00..0x80) often ends in a short-period repeating run (stuffing /
|
||||
/// constant fill); the attack assumes that run continues across the 0x80
|
||||
/// boundary into the encrypted region, giving the known plaintext the 2^16
|
||||
/// LFSR recovery needs. We scan up to 50000 scrambled sectors across the
|
||||
/// extents and return the first sector that yields a key — no player keys, no
|
||||
/// disc-key crack. Works on a live drive (after bus-auth unlocks reads) and on
|
||||
/// disc images alike.
|
||||
pub fn crack_key(
|
||||
reader: &mut dyn SectorSource,
|
||||
extents: &[Extent],
|
||||
batch_sectors: u16,
|
||||
) -> Option<CssState> {
|
||||
crack_key_halt(reader, extents, batch_sectors, None)
|
||||
}
|
||||
|
||||
/// Acquire a CSS title key using whichever inputs the context provides.
|
||||
/// [`crack_key`] with an optional cooperative-cancellation token.
|
||||
///
|
||||
/// Order of attempts:
|
||||
/// 1. SCSI auth path (when `drive` and `auth_lba` are set).
|
||||
/// 2. Crack path (when `reader` and `extents` are set).
|
||||
///
|
||||
/// Returns `None` if neither path is configured or both fail.
|
||||
pub fn resolve(ctx: &mut CssContext<'_>) -> Option<CssState> {
|
||||
if let (Some(drive), Some(lba)) = (ctx.drive.as_deref_mut(), ctx.auth_lba) {
|
||||
if let Ok(title_key) = auth::authenticate_and_read_title_key(drive, lba) {
|
||||
return Some(CssState { title_key });
|
||||
}
|
||||
}
|
||||
if let (Some(reader), Some(extents)) = (ctx.reader.as_deref_mut(), ctx.extents) {
|
||||
return crack_key(reader, extents);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Crack the CSS title key by scanning scrambled sectors across extents and
|
||||
/// applying a known-plaintext attack on MPEG-2 PES headers.
|
||||
///
|
||||
/// The Stevenson attack needs a sector where a PES header starts at byte
|
||||
/// 0x80 (start of the encrypted region). This only happens when a new PES
|
||||
/// packet begins at exactly sector offset 128. We scan up to 50000
|
||||
/// scrambled sectors sequentially across all extents.
|
||||
///
|
||||
/// NOTE: the underlying recovery ([`crack::recover_title_key`]) is currently
|
||||
/// non-functional against this crate's descrambler (see `crack` module
|
||||
/// docs), so this scan returns `None`. The production DVD path uses the SCSI
|
||||
/// auth path, not this crack fallback.
|
||||
pub fn crack_key(reader: &mut dyn SectorSource, extents: &[Extent]) -> Option<CssState> {
|
||||
/// "No silent hangs": the crack scans up to 50_000 sectors, which on a live
|
||||
/// drive hitting bad sectors can take a long time. This variant polls `halt`
|
||||
/// once per batch (the same cadence sweep/patch use) so an operator Stop or a
|
||||
/// scan-level watchdog can interrupt the scan, and emits a
|
||||
/// `freemkv::heartbeat` beat ("css_crack") each batch so a stuck scan is
|
||||
/// visible in the log.
|
||||
pub fn crack_key_halt(
|
||||
reader: &mut dyn SectorSource,
|
||||
extents: &[Extent],
|
||||
batch_sectors: u16,
|
||||
halt: Option<&crate::halt::Halt>,
|
||||
) -> Option<CssState> {
|
||||
// Batch the reads: a live optical drive at 1 sector/read is glacial, and the
|
||||
// crack only needs to FIND one scrambled sector whose 0x80 plaintext matches
|
||||
// a known PES header. `batch_sectors` MUST be sized to the source — a drive
|
||||
// rejects a READ(10) larger than its per-command max (DVD = 16) and
|
||||
// `Drive::read` does not chunk, so an over-large batch fails every read and
|
||||
// scans nothing. Callers pass `detect_max_batch_sectors(device_path)` for a
|
||||
// live drive, a file-safe value for an image, or 1 to force per-sector.
|
||||
let batch = (batch_sectors.max(1)) as u32;
|
||||
let mut tried = 0u32;
|
||||
let max_tries = 50_000;
|
||||
let max_tries = 50_000u32;
|
||||
let mut buf = vec![0u8; batch as usize * 2048];
|
||||
let mut hb = crate::progress::Heartbeat::new("css_crack");
|
||||
|
||||
// Reused across every scanned sector; read_sectors overwrites all 2048
|
||||
// bytes on success, so no re-zeroing is needed between iterations.
|
||||
let mut buf = vec![0u8; 2048];
|
||||
|
||||
for ext in extents {
|
||||
let mut i = 0;
|
||||
'outer: for (extent_idx, ext) in extents.iter().enumerate() {
|
||||
let mut i = 0u32;
|
||||
while i < ext.sector_count && tried < max_tries {
|
||||
// Every scanned sector counts toward the cap, so a long run
|
||||
// of unscrambled sectors can't read past the budget.
|
||||
tried += 1;
|
||||
if reader
|
||||
.read_sectors(ext.start_lba + i, 1, &mut buf, true)
|
||||
.is_ok()
|
||||
&& is_scrambled(&buf)
|
||||
{
|
||||
if let Some(key) = crack::crack_title_key(&buf) {
|
||||
return Some(CssState { title_key: key });
|
||||
// Cooperative cancellation — poll once per batch, the same cadence
|
||||
// sweep/patch use, so a Stop / watchdog can interrupt the scan.
|
||||
if let Some(h) = halt {
|
||||
if h.is_cancelled() {
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if tried >= max_tries {
|
||||
break;
|
||||
// Liveness beacon: a long scan over a damaged disc stays visible.
|
||||
// The heartbeat is time-throttled; only when it actually beats do
|
||||
// we emit the crack-specific context (tried/lba/extent_idx).
|
||||
if hb.tick(tried as u64, max_tries as u64) {
|
||||
tracing::debug!(
|
||||
target: "freemkv::heartbeat",
|
||||
phase = "css_crack",
|
||||
tried,
|
||||
lba = ext.start_lba + i,
|
||||
extent_idx,
|
||||
"scanning"
|
||||
);
|
||||
}
|
||||
let n = (ext.sector_count - i).min(batch);
|
||||
let want = n as usize * 2048;
|
||||
match reader.read_sectors(ext.start_lba + i, n as u16, &mut buf[..want], true) {
|
||||
Ok(_) => {
|
||||
for s in 0..n as usize {
|
||||
tried += 1;
|
||||
let sect = &buf[s * 2048..(s + 1) * 2048];
|
||||
if is_scrambled(sect) {
|
||||
if let Some(key) = stevenson::crack_title_key(sect) {
|
||||
return Some(CssState { title_key: key });
|
||||
}
|
||||
}
|
||||
if tried >= max_tries {
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A failed batch (bad sectors) still counts toward the budget so a
|
||||
// damaged region can't loop forever; skip ahead by the batch.
|
||||
Err(_) => tried += n,
|
||||
}
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +262,7 @@ mod tests {
|
||||
start_lba: 0,
|
||||
sector_count: 200_000,
|
||||
}];
|
||||
let res = crack_key(&mut src, &extents);
|
||||
let res = crack_key(&mut src, &extents, 1);
|
||||
assert!(res.is_none(), "clear sectors yield no key");
|
||||
assert_eq!(
|
||||
src.reads.borrow().len(),
|
||||
@@ -288,7 +291,7 @@ mod tests {
|
||||
sector_count: 40_000,
|
||||
},
|
||||
];
|
||||
let res = crack_key(&mut src, &extents);
|
||||
let res = crack_key(&mut src, &extents, 1);
|
||||
assert!(res.is_none());
|
||||
assert_eq!(
|
||||
src.reads.borrow().len(),
|
||||
@@ -311,7 +314,7 @@ mod tests {
|
||||
start_lba: 5_000,
|
||||
sector_count: 4,
|
||||
}];
|
||||
let _ = crack_key(&mut src, &extents);
|
||||
let _ = crack_key(&mut src, &extents, 1);
|
||||
let reads = src.reads.borrow();
|
||||
assert_eq!(
|
||||
&reads[..],
|
||||
@@ -338,7 +341,7 @@ mod tests {
|
||||
start_lba: 0,
|
||||
sector_count: 10,
|
||||
}];
|
||||
let res = crack_key(&mut src, &extents);
|
||||
let res = crack_key(&mut src, &extents, 1);
|
||||
assert!(res.is_none());
|
||||
assert_eq!(
|
||||
src.reads.borrow().len(),
|
||||
@@ -361,7 +364,7 @@ mod tests {
|
||||
start_lba: 42,
|
||||
sector_count: 0,
|
||||
}];
|
||||
let res = crack_key(&mut src, &extents);
|
||||
let res = crack_key(&mut src, &extents, 1);
|
||||
assert!(res.is_none());
|
||||
assert_eq!(
|
||||
src.reads.borrow().len(),
|
||||
@@ -377,7 +380,7 @@ mod tests {
|
||||
#[test]
|
||||
fn crack_key_no_extents_is_none() {
|
||||
let mut src = MockSource::new(0x30);
|
||||
let res = crack_key(&mut src, &[]);
|
||||
let res = crack_key(&mut src, &[], 1);
|
||||
assert!(res.is_none());
|
||||
assert_eq!(src.reads.borrow().len(), 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
//! CSS title-key recovery — Frank A. Stevenson's divide-and-conquer attack
|
||||
//! (1999), ported exactly from libdvdcss `RecoverTitleKey` + `AttackPattern`
|
||||
//! (css.c).
|
||||
//!
|
||||
//! Recovers the 5-byte CSS title key from a single scrambled DVD sector with
|
||||
//! no player keys and no disc-key crack, using only known plaintext.
|
||||
//!
|
||||
//! # The cipher this attacks
|
||||
//!
|
||||
//! The content descrambler ([`super::lfsr::descramble_sector`], = libdvdcss
|
||||
//! `dvdcss_unscramble`) seeds its two LFSRs **directly** from
|
||||
//! `key = title_key XOR sector_seed` (seed = `sector[0x54..0x59]`):
|
||||
//!
|
||||
//! ```text
|
||||
//! i_t1 = (key[0] ^ sec[0x54]) | 0x100; // LFSR1 low (9-bit)
|
||||
//! i_t2 = key[1] ^ sec[0x55]; // LFSR1 high
|
||||
//! i_t3 = (key[2]|key[3]<<8|key[4]<<16) ^ seed3; // LFSR0 (24-bit feedback)
|
||||
//! i_t3 = i_t3*2 + 8 - (i_t3 & 7);
|
||||
//! // per byte: *p = TAB1[*p] ^ (i_t5 & 0xff)
|
||||
//! ```
|
||||
//!
|
||||
//! There is NO `decrypt_key` mangling on the content path. So the recovery
|
||||
//! is a single inversion of `dvdcss_unscramble`, not the multi-stage
|
||||
//! working-key inversion the previous (non-CSS) implementation used.
|
||||
//!
|
||||
//! # The attack
|
||||
//!
|
||||
//! 1. **Known plaintext → keystream.** Because the descramble applies TAB1
|
||||
//! to the ciphertext, the per-byte keystream is
|
||||
//! `buf[i] = TAB1[cipher[i]] ^ plain[i]` (matching libdvdcss
|
||||
//! `RecoverTitleKey`'s `p_buffer`).
|
||||
//! 2. **Brute the 16-bit LFSR1 seed.** For each of 2^16 seeds, run LFSR1
|
||||
//! forward; for the first four steps deduce the LFSR0 output bytes from
|
||||
//! the keystream (carry-tracked), reconstructing `i_t3`. For the next six
|
||||
//! steps clock LFSR0 normally and check it reproduces the keystream — a
|
||||
//! wrong LFSR1 seed fails fast.
|
||||
//! 3. **Back-clock LFSR0.** Run four backward `i_t3` steps (each a 256-way
|
||||
//! search for the byte shifted in) to reach the initial state, then undo
|
||||
//! `i_t3 = i_t3*2 + 8 - (i_t3 & 7)` to recover key[2..5].
|
||||
//! 4. **XOR back the seed.** `key[0..5] ^= sector_seed[0..5]` (plain XOR —
|
||||
//! the descramble seeds directly, so there is no inversion).
|
||||
//!
|
||||
//! `AttackPattern` finds known plaintext for step 1: the longest periodic
|
||||
//! run in the cleartext `sec[0x00..0x80]`, assumed to continue into the
|
||||
//! encrypted region at 0x80.
|
||||
|
||||
use super::lfsr::descramble_sector;
|
||||
use super::tables::{TAB1, TAB2, TAB3, TAB4, TAB5};
|
||||
|
||||
/// Sector layout constants.
|
||||
const SECTOR_SIZE: usize = 2048;
|
||||
const ENCRYPTED_START: usize = 0x80; // byte 128
|
||||
const SEED_OFFSET: usize = 0x54; // sector seed at bytes 0x54-0x58
|
||||
const FLAG_BYTE: usize = 0x14;
|
||||
|
||||
/// RecoverTitleKey: recover the title key from cipher + known plaintext.
|
||||
///
|
||||
/// Exact port of libdvdcss `RecoverTitleKey` (css.c). `crypted` is the
|
||||
/// ciphertext starting at sector byte 0x80; `decrypted` is the matching
|
||||
/// known plaintext; `seed` is `sector[0x54..0x59]`. On success returns the
|
||||
/// recovered 5-byte title key; `None` if no LFSR seed reproduces the
|
||||
/// keystream.
|
||||
///
|
||||
/// At least 10 bytes of `crypted`/`decrypted` are required (the cipher is
|
||||
/// iterated 10 times: 4 to reconstruct LFSR0, 6 to validate).
|
||||
fn recover_title_key_from_plain(
|
||||
crypted: &[u8],
|
||||
decrypted: &[u8],
|
||||
seed: &[u8; 5],
|
||||
) -> Option<[u8; 5]> {
|
||||
if crypted.len() < 10 || decrypted.len() < 10 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// buf[i] = TAB1[cipher[i]] ^ plain[i] — the per-byte content keystream.
|
||||
let mut buffer = [0u8; 10];
|
||||
for (i, b) in buffer.iter_mut().enumerate() {
|
||||
*b = TAB1[crypted[i] as usize] ^ decrypted[i];
|
||||
}
|
||||
|
||||
let mut key = [0u8; 5];
|
||||
let mut found = false;
|
||||
|
||||
for i_try in 0u32..0x1_0000 {
|
||||
let mut i_t1 = (i_try >> 8) | 0x100;
|
||||
let mut i_t2 = i_try & 0xff;
|
||||
let mut i_t3: u32 = 0; // not needed yet
|
||||
let mut i_t5: u32 = 0;
|
||||
|
||||
// Iterate the cipher 4 times to reconstruct LFSR0 (i_t3).
|
||||
for &b in buffer.iter().take(4) {
|
||||
let i_t4 = (TAB2[i_t2 as usize] ^ TAB3[i_t1 as usize]) as u32;
|
||||
i_t2 = i_t1 >> 1;
|
||||
i_t1 = ((i_t1 & 1) << 8) ^ i_t4;
|
||||
let i_t4 = TAB5[i_t4 as usize] as u32;
|
||||
|
||||
// Deduce i_t6 (LFSR0 output, pre-TAB4) and the carry.
|
||||
let mut i_t6 = b as u32;
|
||||
if i_t5 != 0 {
|
||||
i_t6 = (i_t6 + 0xff) & 0xff;
|
||||
}
|
||||
if i_t6 < i_t4 {
|
||||
i_t6 += 0x100;
|
||||
}
|
||||
i_t6 -= i_t4;
|
||||
i_t5 += i_t6 + i_t4;
|
||||
let i_t6 = TAB4[i_t6 as usize] as u32;
|
||||
|
||||
i_t3 = (i_t3 << 8) | i_t6;
|
||||
i_t5 >>= 8;
|
||||
}
|
||||
|
||||
let i_candidate = i_t3;
|
||||
|
||||
// Iterate 6 more times to validate the candidate.
|
||||
let mut i = 4usize;
|
||||
while i < 10 {
|
||||
let i_t4 = (TAB2[i_t2 as usize] ^ TAB3[i_t1 as usize]) as u32;
|
||||
i_t2 = i_t1 >> 1;
|
||||
i_t1 = ((i_t1 & 1) << 8) ^ i_t4;
|
||||
let i_t4 = TAB5[i_t4 as usize] as u32;
|
||||
let mut i_t6 = (((((((i_t3 >> 3) ^ i_t3) >> 1) ^ i_t3) >> 8) ^ i_t3) >> 5) & 0xff;
|
||||
i_t3 = (i_t3 << 8) | i_t6;
|
||||
i_t6 = TAB4[i_t6 as usize] as u32;
|
||||
i_t5 += i_t6 + i_t4;
|
||||
if (i_t5 & 0xff) as u8 != buffer[i] {
|
||||
break;
|
||||
}
|
||||
i_t5 >>= 8;
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if i != 10 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Four backward steps of iterating i_t3 to deduce the initial state.
|
||||
i_t3 = i_candidate;
|
||||
for _ in 0..4 {
|
||||
let i_t1_byte = i_t3 & 0xff;
|
||||
i_t3 >>= 8;
|
||||
// Brute-force the byte shifted in (top byte of the 24-bit reg).
|
||||
for j in 0u32..256 {
|
||||
i_t3 = (i_t3 & 0x1_ffff) | (j << 17);
|
||||
let i_t6 = (((((((i_t3 >> 3) ^ i_t3) >> 1) ^ i_t3) >> 8) ^ i_t3) >> 5) & 0xff;
|
||||
if i_t6 == i_t1_byte {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Undo `i_t3 = i_t3*2 + 8 - (i_t3 & 7)` to recover key[2..5].
|
||||
let i_t4 = (i_t3 >> 1).wrapping_sub(4);
|
||||
for i_t5 in 0u32..8 {
|
||||
let val = i_t4.wrapping_add(i_t5);
|
||||
if val.wrapping_mul(2).wrapping_add(8).wrapping_sub(val & 7) == i_t3 {
|
||||
key[0] = (i_try >> 8) as u8;
|
||||
key[1] = (i_try & 0xff) as u8;
|
||||
key[2] = (val & 0xff) as u8;
|
||||
key[3] = ((val >> 8) & 0xff) as u8;
|
||||
key[4] = ((val >> 16) & 0xff) as u8;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// First fully-validated candidate wins. The 48-bit keystream constraint
|
||||
// makes a second match cryptographically negligible on real sectors, but
|
||||
// continuing would let a later spurious match overwrite a correct key.
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
for (k, &s) in key.iter_mut().zip(seed.iter()) {
|
||||
*k ^= s;
|
||||
}
|
||||
Some(key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Recover the CSS title key from a scrambled sector using a known plaintext
|
||||
/// for the encrypted region.
|
||||
///
|
||||
/// `plain` is the expected plaintext at byte 0x80 (at least 10 bytes).
|
||||
/// Returns the recovered key only if it actually descrambles the sector back
|
||||
/// to `plain` — guarding against the rare spurious LFSR-seed match.
|
||||
pub fn recover_title_key(sector: &[u8], plain: &[u8]) -> Option<[u8; 5]> {
|
||||
if sector.len() < SECTOR_SIZE || plain.len() < 10 {
|
||||
return None;
|
||||
}
|
||||
if sector[FLAG_BYTE] & 0x30 == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let seed: [u8; 5] = [
|
||||
sector[SEED_OFFSET],
|
||||
sector[SEED_OFFSET + 1],
|
||||
sector[SEED_OFFSET + 2],
|
||||
sector[SEED_OFFSET + 3],
|
||||
sector[SEED_OFFSET + 4],
|
||||
];
|
||||
|
||||
let crypted = §or[ENCRYPTED_START..ENCRYPTED_START + 10];
|
||||
let key = recover_title_key_from_plain(crypted, plain, &seed)?;
|
||||
|
||||
if descramble_matches(sector, &key, plain) {
|
||||
Some(key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify a title key by descrambling a copy of `sector` and checking the
|
||||
/// known plaintext reappears at byte 0x80.
|
||||
fn descramble_matches(sector: &[u8], title: &[u8; 5], plain: &[u8]) -> bool {
|
||||
let mut test = sector.to_vec();
|
||||
test[FLAG_BYTE] |= 0x10; // ensure scramble flag set for the descrambler
|
||||
descramble_sector(title, &mut test);
|
||||
let n = plain.len().min(SECTOR_SIZE - ENCRYPTED_START);
|
||||
test[ENCRYPTED_START..ENCRYPTED_START + n] == plain[..n]
|
||||
}
|
||||
|
||||
/// AttackPattern: find a repeating pattern just before the encrypted region
|
||||
/// and assume the plaintext at 0x80 continues it.
|
||||
///
|
||||
/// Exact port of libdvdcss `AttackPattern` (css.c). Scans cleartext
|
||||
/// `sec[0x00..0x80]` for the longest run that repeats with a cycle length in
|
||||
/// 2..0x2F. If the run is long enough (`plen > 3` and at least two full
|
||||
/// cycles), the known plaintext at 0x80 is taken to be the periodic run
|
||||
/// continuing forward, and [`recover_title_key_from_plain`] is applied.
|
||||
pub fn crack_title_key(sector: &[u8]) -> Option<[u8; 5]> {
|
||||
if sector.len() < SECTOR_SIZE {
|
||||
return None;
|
||||
}
|
||||
if sector[FLAG_BYTE] & 0x30 == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Runaway guard: a single sector's crack is a bounded 2^16 LFSR search and
|
||||
// should finish in well under a second on any modern CPU. If it ever
|
||||
// exceeds ~2s wall-clock, something pathological is happening — log it so a
|
||||
// hang is never silent.
|
||||
let crack_t0 = std::time::Instant::now();
|
||||
|
||||
let result = crack_title_key_inner(sector);
|
||||
|
||||
let elapsed = crack_t0.elapsed();
|
||||
if elapsed.as_secs_f64() > 2.0 {
|
||||
tracing::warn!(
|
||||
target: "freemkv::css",
|
||||
elapsed_ms = elapsed.as_millis() as u64,
|
||||
found = result.is_some(),
|
||||
"css crack: single-sector recovery exceeded 2s (runaway guard)"
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Inner body of [`crack_title_key`] — the actual AttackPattern search. Split
|
||||
/// out so the public entry point can wall-clock the whole attempt for the
|
||||
/// runaway guard without threading a timer through every return path.
|
||||
fn crack_title_key_inner(sector: &[u8]) -> Option<[u8; 5]> {
|
||||
if sector.len() < SECTOR_SIZE || sector[FLAG_BYTE] & 0x30 == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut best_plen: usize = 0;
|
||||
let mut best_p: usize = 0;
|
||||
|
||||
// For all cycle lengths from 2 to 0x2F.
|
||||
for i in 2usize..0x30 {
|
||||
// Count bytes that repeat with cycle length i, scanning backward from
|
||||
// 0x7F. `sec[0x7F - (j % i)] == sec[0x7F - j]`.
|
||||
let mut j = i + 1;
|
||||
while j < 0x80 && sector[0x7f - (j % i)] == sector[0x7f - j] {
|
||||
if j > best_plen {
|
||||
best_plen = j;
|
||||
best_p = i;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Need at least a few repeated bytes and at least one full cycle.
|
||||
if best_plen > 3 && best_p > 0 && best_plen / best_p >= 2 {
|
||||
let seed: [u8; 5] = [
|
||||
sector[SEED_OFFSET],
|
||||
sector[SEED_OFFSET + 1],
|
||||
sector[SEED_OFFSET + 2],
|
||||
sector[SEED_OFFSET + 3],
|
||||
sector[SEED_OFFSET + 4],
|
||||
];
|
||||
|
||||
// The known plaintext is the periodic run continuing past 0x80. The
|
||||
// crib starts at `0x80 - (best_plen/best_p)*best_p` and continues
|
||||
// through the encrypted region; the bytes at and after 0x80 are the
|
||||
// predicted plaintext (the pattern repeats with period best_p).
|
||||
let cycles = best_plen / best_p;
|
||||
let plain_start = 0x80 - cycles * best_p;
|
||||
|
||||
// The cipher is the 10 bytes at 0x80; the crib is their predicted
|
||||
// plaintext. The periodic run (period `best_p`) is known to continue
|
||||
// through 0x80, so each predicted byte is the run sample one or more
|
||||
// periods back: `sec[plain_start + (i % best_p)]`. For in-run offsets
|
||||
// (`plain_start + i < 0x80`) the run is exactly periodic, so this
|
||||
// equals `sec[plain_start + i]`; for offsets at/after 0x80 the raw
|
||||
// byte is ciphertext, so we MUST wrap within the period rather than
|
||||
// read it. (Reading `&sec[plain_start..+10]` directly — as before —
|
||||
// pulled ciphertext into the crib whenever the run covered fewer than
|
||||
// 10 bytes before 0x80, producing false-negative key recovery.)
|
||||
let crypted = §or[0x80..0x80 + 10];
|
||||
let mut plain = [0u8; 10];
|
||||
for (i, p) in plain.iter_mut().enumerate() {
|
||||
*p = sector[plain_start + (i % best_p)];
|
||||
}
|
||||
|
||||
if let Some(key) = recover_title_key_from_plain(crypted, &plain, &seed) {
|
||||
// Verify against the same predicted plaintext.
|
||||
if descramble_matches(sector, &key, &plain) {
|
||||
return Some(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::lfsr::scramble_sector;
|
||||
use super::*;
|
||||
|
||||
/// Build a synthetic scrambled sector for a given title key and seed,
|
||||
/// with `plain` placed as the plaintext at byte 0x80, scrambled with
|
||||
/// EXACTLY the cipher `descramble_sector` inverts. Returns
|
||||
/// (scrambled_sector, full_plaintext_body).
|
||||
fn synth_sector(title_key: &[u8; 5], seed: &[u8; 5], plain: &[u8]) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut plaintext = vec![0u8; SECTOR_SIZE];
|
||||
plaintext[0..4].copy_from_slice(&[0x00, 0x00, 0x01, 0xBA]);
|
||||
plaintext[FLAG_BYTE] = 0x10;
|
||||
plaintext[SEED_OFFSET..SEED_OFFSET + 5].copy_from_slice(seed);
|
||||
plaintext[ENCRYPTED_START..ENCRYPTED_START + plain.len()].copy_from_slice(plain);
|
||||
|
||||
let body = plaintext.clone();
|
||||
|
||||
// scramble_sector turns the plaintext body into ciphertext and sets
|
||||
// the scramble flag.
|
||||
scramble_sector(title_key, &mut plaintext);
|
||||
(plaintext, body)
|
||||
}
|
||||
|
||||
/// Build a synthetic scrambled sector whose CLEARTEXT (0x00..0x80) ends
|
||||
/// in a periodic run that continues into the encrypted region — the case
|
||||
/// `AttackPattern` (crack_title_key) is designed to crack.
|
||||
fn synth_periodic_sector(
|
||||
title_key: &[u8; 5],
|
||||
seed: &[u8; 5],
|
||||
period: usize,
|
||||
) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut plaintext = vec![0u8; SECTOR_SIZE];
|
||||
plaintext[FLAG_BYTE] = 0x10;
|
||||
|
||||
// A clean periodic run occupying the tail of the cleartext header
|
||||
// (RUN_START..0x80) and continuing into the encrypted region. This
|
||||
// mirrors a real VOB: a periodic data run just before the scrambled
|
||||
// part. The run must NOT overlap the seed bytes (0x54..0x59), or the
|
||||
// AttackPattern detector would break mid-run. The phase is anchored to
|
||||
// offset 0 so the run is consistent across the 0x80 boundary.
|
||||
// Just above the seed (0x54..0x59); gives a 39-byte run (0x59..0x80)
|
||||
// — enough for >=2 cycles of every tested period (<=19).
|
||||
const RUN_START: usize = 0x59;
|
||||
let pat: Vec<u8> = (0..period)
|
||||
.map(|k| (0xA0u8.wrapping_add(k as u8)) ^ 0x5A)
|
||||
.collect();
|
||||
for (i, b) in plaintext.iter_mut().enumerate().skip(RUN_START) {
|
||||
*b = pat[i % period];
|
||||
}
|
||||
|
||||
// Seed sits below the run, undisturbed.
|
||||
plaintext[SEED_OFFSET..SEED_OFFSET + 5].copy_from_slice(seed);
|
||||
|
||||
let body = plaintext.clone();
|
||||
scramble_sector(title_key, &mut plaintext);
|
||||
(plaintext, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crack_unscrambled_returns_none() {
|
||||
let sector = vec![0u8; 2048];
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crack_too_short_returns_none() {
|
||||
let sector = vec![0u8; 100];
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recover_needs_min_plain() {
|
||||
let sector = vec![0u8; 2048];
|
||||
let short_plain = [0u8; 4];
|
||||
assert!(recover_title_key(§or, &short_plain).is_none());
|
||||
}
|
||||
|
||||
/// The known plaintext used at byte 0x80 for the direct-recovery tests.
|
||||
/// A realistic MPEG-2 PES header start.
|
||||
const PES: [u8; 10] = [0x00, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x80, 0x80, 0x05, 0x21];
|
||||
|
||||
/// MANDATORY round-trip (Task C.1): synthesize a scrambled sector for a
|
||||
/// known (title_key, seed), then assert recover_title_key returns a key
|
||||
/// that descrambles the body back to plaintext. CSS title-key recovery is
|
||||
/// well-defined up to keys that scramble identically; we assert the full
|
||||
/// body round-trips (the true correctness property), and additionally
|
||||
/// that the EXACT key is returned for the common case.
|
||||
#[test]
|
||||
fn recover_round_trips_known_keys() {
|
||||
let cases: &[([u8; 5], [u8; 5])] = &[
|
||||
(
|
||||
[0x42, 0x13, 0x37, 0xBE, 0xEF],
|
||||
[0x11, 0x22, 0x33, 0x44, 0x55],
|
||||
),
|
||||
(
|
||||
[0x01, 0x02, 0x03, 0x04, 0x05],
|
||||
[0xDE, 0xAD, 0xBE, 0xEF, 0x42],
|
||||
),
|
||||
(
|
||||
[0xFE, 0xDC, 0xBA, 0x98, 0x76],
|
||||
[0x00, 0xFF, 0x80, 0x7F, 0x01],
|
||||
),
|
||||
(
|
||||
[0x9A, 0x78, 0x56, 0x34, 0x12],
|
||||
[0xA5, 0x5A, 0x0F, 0xF0, 0xCC],
|
||||
),
|
||||
(
|
||||
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
|
||||
[0x01, 0x01, 0x01, 0x01, 0x01],
|
||||
),
|
||||
];
|
||||
for (title_key, seed) in cases {
|
||||
let (mut sector, body) = synth_sector(title_key, seed, &PES);
|
||||
let recovered =
|
||||
recover_title_key(§or, &PES).expect("recover_title_key returned None");
|
||||
descramble_sector(&recovered, &mut sector);
|
||||
assert_eq!(
|
||||
§or[ENCRYPTED_START..SECTOR_SIZE],
|
||||
&body[ENCRYPTED_START..SECTOR_SIZE],
|
||||
"recovered key did not descramble the full body for \
|
||||
title={title_key:02x?} seed={seed:02x?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// MANDATORY (Task C.1): the AttackPattern entry point crack_title_key —
|
||||
/// no plaintext supplied — recovers a round-tripping key when the
|
||||
/// cleartext ends in a periodic run that continues into 0x80.
|
||||
#[test]
|
||||
fn crack_title_key_recovers_via_attack_pattern() {
|
||||
for &period in &[2usize, 3, 5, 8, 16] {
|
||||
let title_key = [0x42, 0x13, 0x37, 0xBE, 0xEF];
|
||||
let seed = [0x11, 0x22, 0x33, 0x44, 0x55];
|
||||
let (sector, body) = synth_periodic_sector(&title_key, &seed, period);
|
||||
|
||||
let cracked = crack_title_key(§or)
|
||||
.unwrap_or_else(|| panic!("crack_title_key returned None for period {period}"));
|
||||
let mut test = sector.clone();
|
||||
descramble_sector(&cracked, &mut test);
|
||||
assert_eq!(
|
||||
&test[ENCRYPTED_START..SECTOR_SIZE],
|
||||
&body[ENCRYPTED_START..SECTOR_SIZE],
|
||||
"crack_title_key key did not round-trip the body (period {period})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// recover_title_key_from_plain inverts dvdcss_unscramble exactly: scramble
|
||||
/// a known body, hand back the keystream-derived key, and the recovered
|
||||
/// key (XOR-back included) reproduces the plaintext.
|
||||
#[test]
|
||||
fn recovered_key_descrambles_back_to_plaintext() {
|
||||
let cases: &[([u8; 5], [u8; 5])] = &[
|
||||
(
|
||||
[0x42, 0x13, 0x37, 0xBE, 0xEF],
|
||||
[0x11, 0x22, 0x33, 0x44, 0x55],
|
||||
),
|
||||
(
|
||||
[0x9A, 0x78, 0x56, 0x34, 0x12],
|
||||
[0xA5, 0x5A, 0x0F, 0xF0, 0xCC],
|
||||
),
|
||||
(
|
||||
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
|
||||
[0x01, 0x01, 0x01, 0x01, 0x01],
|
||||
),
|
||||
];
|
||||
for (title_key, seed) in cases {
|
||||
let (mut sector, body) = synth_sector(title_key, seed, &PES);
|
||||
let recovered =
|
||||
recover_title_key(§or, &PES).expect("recover_title_key returned None");
|
||||
descramble_sector(&recovered, &mut sector);
|
||||
assert_eq!(
|
||||
§or[ENCRYPTED_START..SECTOR_SIZE],
|
||||
&body[ENCRYPTED_START..SECTOR_SIZE],
|
||||
"descramble with recovered key did not reproduce the body \
|
||||
for title={title_key:02x?} seed={seed:02x?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── early-return guards ────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn recover_rejects_sector_one_byte_short() {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE - 1];
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
assert!(recover_title_key(§or, &PES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recover_rejects_unscrambled_sector() {
|
||||
let sector = vec![0x00u8; SECTOR_SIZE];
|
||||
assert!(recover_title_key(§or, &PES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recover_high_flag_bits_are_not_scramble() {
|
||||
for &flag in &[0x40u8, 0x80, 0xC0] {
|
||||
let mut sector = vec![0x11u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = flag;
|
||||
assert!(
|
||||
recover_title_key(§or, &PES).is_none(),
|
||||
"flag {flag:#04x} has scramble bits clear; recover must return None"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crack_high_flag_bits_are_not_scramble() {
|
||||
for &flag in &[0x40u8, 0x80, 0xC0] {
|
||||
let mut sector = vec![0x11u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = flag;
|
||||
assert!(
|
||||
crack_title_key(§or).is_none(),
|
||||
"flag {flag:#04x} clear scramble bits -> crack must return None"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crack_rejects_sector_one_byte_short() {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE - 1];
|
||||
if sector.len() > FLAG_BYTE {
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
}
|
||||
assert!(crack_title_key(§or).is_none());
|
||||
}
|
||||
|
||||
/// crack_title_key must never panic on a fully scrambled sector with
|
||||
/// arbitrary (non-periodic) content — it just returns None.
|
||||
#[test]
|
||||
fn crack_full_path_never_panics() {
|
||||
for seed in 0u32..3 {
|
||||
let mut sector = vec![0u8; SECTOR_SIZE];
|
||||
sector[FLAG_BYTE] = 0x30;
|
||||
let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(7);
|
||||
for b in sector.iter_mut().skip(0x80) {
|
||||
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
*b = (x >> 16) as u8;
|
||||
}
|
||||
for (i, b) in sector[SEED_OFFSET..SEED_OFFSET + 5].iter_mut().enumerate() {
|
||||
*b = (seed.wrapping_add(i as u32) ^ 0xA5) as u8;
|
||||
}
|
||||
let _ = crack_title_key(§or);
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
-39
@@ -25,6 +25,8 @@ pub const TAB1: [u8; 256] = [
|
||||
];
|
||||
|
||||
/// Table 2: LFSR1 high-byte feedback permutation.
|
||||
///
|
||||
/// Byte-identical to libdvdcss `p_css_tab2` (csstables.h).
|
||||
pub const TAB2: [u8; 256] = [
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e,
|
||||
0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c,
|
||||
@@ -40,14 +42,18 @@ pub const TAB2: [u8; 256] = [
|
||||
0xa4, 0xa5, 0xa6, 0xa7, 0xa0, 0xa1, 0xa2, 0xa3, 0xad, 0xac, 0xaf, 0xae, 0xa9, 0xa8, 0xab, 0xaa,
|
||||
0xdb, 0xda, 0xd9, 0xd8, 0xdf, 0xde, 0xdd, 0xdc, 0xd2, 0xd3, 0xd0, 0xd1, 0xd6, 0xd7, 0xd4, 0xd5,
|
||||
0xc9, 0xc8, 0xcb, 0xca, 0xcd, 0xcc, 0xcf, 0xce, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
|
||||
0xed, 0xec, 0xef, 0xee, 0xe9, 0xe8, 0xeb, 0xea, 0xe4, 0xe5, 0xe6, 0xe7, 0xe0, 0xe1, 0xe2, 0xe3,
|
||||
0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf6, 0xf7, 0xf4, 0xf5, 0xf2, 0xf3, 0xf0, 0xf1,
|
||||
0xed, 0xec, 0xef, 0xee, 0xe9, 0xe8, 0xeb, 0xea, 0xe4, 0xe5, 0xe6, 0xe7, 0xe0, 0xe1, 0xe2, 0xe3,
|
||||
];
|
||||
|
||||
/// Table 3: LFSR1 9-bit low-word feedback table (512 entries).
|
||||
///
|
||||
/// Indexed by the 9-bit LFSR1 low word (the upper feedback bit makes the
|
||||
/// index 9-bit, hence 512 entries, not 256).
|
||||
/// Byte-identical to libdvdcss `p_css_tab3` (csstables.h): the 8-value
|
||||
/// block `BASE[i & 7]` repeated 64 times. The CSS LFSR1 step indexes this
|
||||
/// table with the 9-bit low register (0x100..=0x1FF), but only the low 3
|
||||
/// bits select the output — the high bits are ignored, hence the constant
|
||||
/// blocks. The 512-entry width simply lets the 9-bit index be used without
|
||||
/// masking.
|
||||
pub const TAB3: [u8; 512] = [
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
@@ -57,30 +63,30 @@ pub const TAB3: [u8; 512] = [
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe, 0x01, 0x25, 0x48, 0x6c, 0x93, 0xb7, 0xda, 0xfe,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd, 0x02, 0x26, 0x4b, 0x6f, 0x90, 0xb4, 0xd9, 0xfd,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc, 0x03, 0x27, 0x4a, 0x6e, 0x91, 0xb5, 0xd8, 0xfc,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff,
|
||||
];
|
||||
|
||||
/// Table 4: LFSR0 byte permutation (used in initialization and output).
|
||||
@@ -191,25 +197,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// TAB3 is generated by the CSS LFSR1 low-word rule:
|
||||
/// TAB3[i] == BASE[i & 7] ^ (i >> 7)
|
||||
/// where BASE = [0x00,0x24,0x49,0x6d,0x92,0xb6,0xdb,0xff] is the 8-value
|
||||
/// feedback block (BASE[j] is the 9-bit-spread of the 3 high feedback
|
||||
/// bits). The 9-bit index splits into a 3-bit selector (i & 7) and a
|
||||
/// 2-bit carry group (i >> 7) that XORs the base value. This pins all 512
|
||||
/// entries to one closed-form spec rule.
|
||||
/// TAB3 is the libdvdcss `p_css_tab3`: the 8-value feedback block
|
||||
/// BASE = [0x00,0x24,0x49,0x6d,0x92,0xb6,0xdb,0xff]
|
||||
/// repeated 64 times — `TAB3[i] == BASE[i & 7]`. The high bits of the
|
||||
/// 9-bit index do not affect the output (libdvdcss's LFSR1 step indexes
|
||||
/// with the full 9-bit low register but only `& 7` matters). This pins
|
||||
/// all 512 entries to the published table.
|
||||
///
|
||||
/// Derivation verified offline against the published TAB3 byte layout.
|
||||
/// Mutation: flip any single byte in the TAB3 literal (e.g. the 9th entry
|
||||
/// 0x00 -> 0x01) -> the formula check fails at that index.
|
||||
/// Mutation: flip any single byte in the TAB3 literal -> the formula
|
||||
/// check fails at that index.
|
||||
#[test]
|
||||
fn tab3_matches_lfsr1_generating_formula() {
|
||||
const BASE: [u8; 8] = [0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff];
|
||||
for i in 0..512usize {
|
||||
let expected = BASE[i & 7] ^ ((i >> 7) as u8);
|
||||
let expected = BASE[i & 7];
|
||||
assert_eq!(
|
||||
TAB3[i], expected,
|
||||
"TAB3[{i:#05x}] = {:#04x}, formula BASE[i&7]^(i>>7) = {expected:#04x}",
|
||||
"TAB3[{i:#05x}] = {:#04x}, formula BASE[i&7] = {expected:#04x}",
|
||||
TAB3[i]
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user