mirror of
https://github.com/freemkv/libfreemkv.git
synced 2026-10-07 18:13:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
477bdf1835 | ||
|
|
4d83b69c20 | ||
|
|
7dbbfc6726 | ||
|
|
e635c9556f | ||
|
|
d7b5c30f5d | ||
|
|
739a276a39 | ||
|
|
5f1028a62a | ||
|
|
ea15d212de | ||
|
|
00673c8ec3 | ||
|
|
bfefb4cb5b |
+155
@@ -1,5 +1,160 @@
|
||||
# Changelog
|
||||
|
||||
## 0.25.11 (2026-05-21)
|
||||
|
||||
### Added
|
||||
|
||||
- **Libredrive raw-read VID path.** When the Mt1959 unlock response
|
||||
confirms both the active-mode (`MMkv`) and mode-ID (`LbDr`) markers,
|
||||
`Drive::is_libredrive_active()` returns true and `do_handshake`
|
||||
skips the AACS cert dance entirely — VID is retrieved via
|
||||
`READ_DISC_STRUCTURE` format 0x80 with AGID=0, and bus encryption
|
||||
is already off. This is what unblocks UHD ripping on drives whose
|
||||
leaked host cert is on the AACS HRL.
|
||||
- New `Error` variants for finer-grained AACS failure reporting:
|
||||
`AacsHostCertRejected` (E7015), `AacsLibredriveUnsupported`
|
||||
(E7016), `AacsVidUnavailable` (E7017), `AacsMkUnavailable`
|
||||
(E7018), `AacsVukNotInKeydb` (E7019). Lets CLIs/UIs render which
|
||||
piece of the AACS chain failed instead of always saying "no keys."
|
||||
|
||||
### Fixed
|
||||
|
||||
- `validate_processing_key` now matches libaacs `_validate_pk`
|
||||
exactly: XORs `uv` into `mk[12..16]` (was omitted), AES-decrypts
|
||||
`mk_dv` and checks the `01 23 45 67 89 AB CD EF` magic (was
|
||||
AES-encrypt + 12-zero check). Pre-fix, every non-zero-uv
|
||||
processing key was rejected — i.e. essentially every real disc.
|
||||
- `mkb_find_cvalues` now prefers record type `0x07` (AACS 2.x) and
|
||||
falls back to `0x05` (AACS 1.0), so the walker handles both
|
||||
generations without an out-of-band version flag.
|
||||
- `resolve_keys` short-circuits paths 2/3/4 when VID is the zero
|
||||
sentinel — saves cycles and emits an honest "VID unavailable" log
|
||||
instead of the misleading "all paths failed."
|
||||
- AES-CMAC VID verification gains NIST SP 800-38B KAT + round-trip
|
||||
+ mutation + all-zero-rejection tests.
|
||||
|
||||
### Removed
|
||||
|
||||
- **Built-in AACS keys** (added in 0.25.9). `src/aacs/builtin_keys.rs`
|
||||
deleted; `KeyDb::with_builtins`, `KeyDb::load_or_builtins`,
|
||||
`KeyDb::merge_from`, and internal dedup helpers gone. The
|
||||
compiled-in shortcut was a slim convenience that didn't move the
|
||||
hard problem (no v77+ DKs) and added a maintenance surface.
|
||||
- **Operator plugin slot** at `~/.config/freemkv/local_keys.cfg`
|
||||
(added in 0.25.9). `local_plugin_path` and `KeyDb::merge_local_plugin`
|
||||
removed. Single source: the main `keydb.cfg`.
|
||||
- `KeyDb::load` reverts to the pre-0.25.9 form — read the file or
|
||||
return I/O error; no layering, no fallback.
|
||||
- `Disc::scan` reverts to surfacing `KeydbLoad { path: "<no keydb
|
||||
in search paths>" }` for an encrypted disc with no keydb — same
|
||||
sentinel autorip's message switch already handles.
|
||||
|
||||
CSS player keys in `src/css/auth.rs` remain compiled in; they're
|
||||
1999-era public inputs separate from the AACS pipeline and were
|
||||
never part of the 0.25.9 additions.
|
||||
|
||||
## 0.25.9 (2026-05-20)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **MKB record-type identification.** `mkb_find_mk_dv` and `mkb_version`
|
||||
had their record-type constants swapped. The Verify Media Key record
|
||||
is Type 0x81 (AACS 1.0) or Type 0x86 (AACS 2.0/2.1), not 0x10. The
|
||||
Type-and-Version record is Type 0x10, not 0x81. PK and DK derivation
|
||||
paths therefore failed silently on every disc, masking how often the
|
||||
fallback paths could have succeeded. Fixed; mk_dv extracted at
|
||||
offset 4 of the verify record, MKB version read at offset 8 of the
|
||||
Type 0x10 record body. Tests added for both forms.
|
||||
|
||||
### Added
|
||||
|
||||
- **Built-in AACS keys.** Four device keys (covering MKB v01-v82+) and
|
||||
three processing keys (covering v63-v68) are now compiled into
|
||||
`libfreemkv` directly. DVDs and Blu-rays (AACS 1.0) decrypt with
|
||||
zero external files. Combined with the existing 31 CSS player keys
|
||||
in `css/auth.rs`, the library is self-sufficient for all DVD and
|
||||
AACS 1.0 content.
|
||||
- **Operator plugin slot.** `~/.config/freemkv/local_keys.cfg` is
|
||||
loaded automatically (same format as `keydb.cfg`) and layered
|
||||
additively on top of the built-ins and the main keydb.cfg. For
|
||||
operators who derive their own keys, this is the additive surface
|
||||
to drop them into — main keydb.cfg from upstream auto-update stays
|
||||
separate and overwritable.
|
||||
- `KeyDb::with_builtins()`, `KeyDb::load_or_builtins()`,
|
||||
`KeyDb::empty()` constructors.
|
||||
|
||||
### Changed
|
||||
|
||||
- `Disc::scan` no longer errors when keydb.cfg is absent. With
|
||||
built-ins covering DVD/BD, missing keydb is treated as "no UHD
|
||||
keys available" — the AACS 2.0 / UHD code path surfaces a
|
||||
specific error only when the disc actually needs keys that
|
||||
aren't in built-ins, main keydb, or local plugin.
|
||||
|
||||
## 0.25.8 (2026-05-20)
|
||||
|
||||
### Changed
|
||||
|
||||
- Synchronized to autorip 0.25.8. No libfreemkv code changes —
|
||||
unified versioning bump only. autorip 0.25.7 image was DOA
|
||||
(missing +x on the binary); see autorip changelog.
|
||||
|
||||
## 0.25.7 (2026-05-20)
|
||||
|
||||
### Fixed — BU40N firmware wedge on KEYDB-miss discs
|
||||
|
||||
`disc::encrypt::do_handshake` used to fire up to 16 AACS authenticate
|
||||
attempts back-to-back with no pause between them. Each attempt is
|
||||
5-10 SCSI REPORT_KEY/SEND_KEY exchanges. On a disc whose host cert
|
||||
isn't in our KEYDB (or one the drive rejects), that's 80-160 SCSI
|
||||
commands hammered at the drive in a few hundred milliseconds — and
|
||||
the BU40N (plus most consumer optical drives) responds by entering
|
||||
a fast-fail firmware wedge state where every subsequent CDB returns
|
||||
`ILLEGAL_REQUEST/INVALID_FIELD_IN_CDB` (sense 0x05/0x24) until the
|
||||
drive is physically power-cycled.
|
||||
|
||||
Live wedge event on rip1 2026-05-20 during a Barbie UHD scan
|
||||
(KEYDB miss) confirmed the diagnosis and motivated this fix.
|
||||
|
||||
Defence-in-depth:
|
||||
- `MAX_CERT_ATTEMPTS` capped at 3 (was 16). If three different
|
||||
host certs all fail, more won't help — the drive doesn't have a
|
||||
match.
|
||||
- 1-second sleep between attempts. Gives the drive's firmware time
|
||||
to recover internal state between auth challenges.
|
||||
- Bail immediately on any sense code with sense_key = 0x05
|
||||
(`ILLEGAL_REQUEST`). The drive isn't merely rejecting our cert
|
||||
— it's saying "I won't talk to you anymore" — so trying more
|
||||
certs would deepen the wedge.
|
||||
|
||||
## 0.25.6 (2026-05-20)
|
||||
|
||||
### Changed
|
||||
|
||||
- Synchronized to autorip 0.25.6 release. No behavioural changes.
|
||||
|
||||
## 0.25.5 (2026-05-20)
|
||||
|
||||
### Changed
|
||||
|
||||
- Synchronized to autorip 0.25.5 release. No behavioural changes.
|
||||
|
||||
## 0.25.4 (2026-05-20)
|
||||
|
||||
### Changed
|
||||
|
||||
- Synchronized to autorip 0.25.4 release. No behavioural changes
|
||||
in the library — the v0.25.4 release ships the autorip-side
|
||||
in-container NFS mount option.
|
||||
|
||||
## 0.25.3 (2026-05-19)
|
||||
|
||||
### Changed
|
||||
|
||||
- Synchronized to autorip 0.25.3 release. No behavioural changes
|
||||
in the library — the v0.25.3 release ships the autorip-side
|
||||
parallel mux pipeline.
|
||||
|
||||
## 0.25.2 (2026-05-19)
|
||||
|
||||
### Fixed
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "libfreemkv"
|
||||
version = "0.25.2"
|
||||
version = "0.25.11"
|
||||
edition = "2024"
|
||||
rust-version = "1.86"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
Rust library for 4K UHD / Blu-ray / DVD optical drives. Drive access, disc scanning, stream labels, AACS decryption, CSS decryption, KEYDB updates, and content reading in one crate. Bundled drive profiles — no external files needed.
|
||||
|
||||
Built-in keys cover DVDs and Blu-rays (AACS 1.0). For UHD (AACS 2.0 / 2.1) discs, an optional `keydb.cfg` supplies disc-specific volume unique keys.
|
||||
|
||||
**12+ MB/s** sustained read speeds on BD. Full init: unlock, firmware upload, speed calibration — all from pure Rust.
|
||||
|
||||
Multi-lingual by design — the library outputs structured data and numeric error codes, never English text. Build any UI or localization on top.
|
||||
@@ -121,7 +123,11 @@ loop {
|
||||
|
||||
Streams implement `FrameSource` (read) and/or `FrameSink` (write); direction is type-checked. `input()` / `output()` resolve URL strings to PES stream instances. All URLs use the `scheme://path` format — bare paths are rejected.
|
||||
|
||||
AACS decryption requires a KEYDB.cfg file. If available at `~/.config/aacs/KEYDB.cfg` or passed via `ScanOptions`, the library handles everything — handshake, key derivation, and per-sector decryption — without the application needing to know anything about encryption.
|
||||
### Keys
|
||||
|
||||
DVDs (CSS) decrypt out of the box — the 1999-era public player keys are compiled into the library.
|
||||
|
||||
Blu-rays and UHD (AACS) require a `keydb.cfg` at `~/.config/freemkv/keydb.cfg` (or passed via `ScanOptions`). The file holds all DKs, PKs, host certs, and per-disc VUKs. No AACS key material is compiled into the binary.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
+89
-2
@@ -1235,8 +1235,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_aes_cmac() {
|
||||
// Basic CMAC test — at minimum verify it produces consistent output
|
||||
fn test_aes_cmac_deterministic() {
|
||||
// Same (data, key) must always produce the same MAC.
|
||||
let key = [
|
||||
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
|
||||
0x4f, 0x3c,
|
||||
@@ -1248,6 +1248,93 @@ mod tests {
|
||||
assert_ne!(mac1, [0u8; 16]); // shouldn't be all zeros
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_aes_cmac_nist_kat_full_block() {
|
||||
// NIST SP 800-38B Appendix D.1, Example 2 (Mlen = 128):
|
||||
// K = 2b7e1516 28aed2a6 abf71588 09cf4f3c
|
||||
// M = 6bc1bee2 2e409f96 e93d7e11 7393172a
|
||||
// T = 070a16b4 6b4d4144 f79bdd9d d04a287c
|
||||
let key = [
|
||||
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
|
||||
0x4f, 0x3c,
|
||||
];
|
||||
let data = [
|
||||
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93,
|
||||
0x17, 0x2a,
|
||||
];
|
||||
let expected = [
|
||||
0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a,
|
||||
0x28, 0x7c,
|
||||
];
|
||||
let mac = aes_cmac_16(&data, &key);
|
||||
assert_eq!(mac, expected, "AES-CMAC-128 must match NIST SP 800-38B KAT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vid_mac_verify_roundtrip() {
|
||||
// Simulate the drive-side: pick a (bus_key, vid), compute the MAC, and
|
||||
// verify the host-side check accepts it. Then mutate VID and MAC each
|
||||
// in turn and verify both mutations cause a mismatch (the path that
|
||||
// would yield Error::AacsVidMac in read_volume_id).
|
||||
let bus_key = [
|
||||
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54,
|
||||
0x32, 0x10,
|
||||
];
|
||||
let vid = [
|
||||
0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
|
||||
0x77, 0x88,
|
||||
];
|
||||
|
||||
// Drive returns vid + mac where mac == AES-CMAC-128(bus_key, vid).
|
||||
let drive_mac = aes_cmac_16(&vid, &bus_key);
|
||||
let calc_mac = aes_cmac_16(&vid, &bus_key);
|
||||
assert_eq!(calc_mac, drive_mac, "honest drive: MACs must match");
|
||||
|
||||
// Mutate the MAC: a malicious drive that swapped VID but returned its
|
||||
// original MAC would produce a mismatch here.
|
||||
let mut bad_mac = drive_mac;
|
||||
bad_mac[0] ^= 0x01;
|
||||
assert_ne!(calc_mac, bad_mac, "mutated MAC must be rejected");
|
||||
|
||||
// Mutate the VID: even one bit of VID drift produces a wildly different
|
||||
// CMAC (this is what catches a substituted VID with a stale MAC).
|
||||
let mut bad_vid = vid;
|
||||
bad_vid[15] ^= 0x01;
|
||||
let calc_for_bad_vid = aes_cmac_16(&bad_vid, &bus_key);
|
||||
assert_ne!(
|
||||
calc_for_bad_vid, drive_mac,
|
||||
"MAC over mutated VID must not match original MAC"
|
||||
);
|
||||
|
||||
// Wrong bus key (e.g. handshake replayed against the wrong session)
|
||||
// also produces a different MAC over the same VID.
|
||||
let mut wrong_key = bus_key;
|
||||
wrong_key[0] ^= 0xff;
|
||||
let calc_with_wrong_key = aes_cmac_16(&vid, &wrong_key);
|
||||
assert_ne!(
|
||||
calc_with_wrong_key, drive_mac,
|
||||
"MAC under wrong bus key must not match"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vid_mac_all_zero_mac_rejected() {
|
||||
// Defensive: a buggy or hostile drive that returns all-zero MAC must
|
||||
// be rejected (the real MAC over any non-trivial VID is nearly never
|
||||
// 0...0). This guards against a class of "drive returned garbage"
|
||||
// failures masquerading as success.
|
||||
let bus_key = [
|
||||
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
|
||||
0x4f, 0x3c,
|
||||
];
|
||||
let vid = [
|
||||
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93,
|
||||
0x17, 0x2a,
|
||||
];
|
||||
let calc_mac = aes_cmac_16(&vid, &bus_key);
|
||||
assert_ne!(calc_mac, [0u8; 16], "real CMAC must not be all zeros");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_host_cert_from_keydb() {
|
||||
// Verify the host cert from our KEYDB
|
||||
|
||||
+12
-1
@@ -89,6 +89,17 @@ pub(crate) fn parse_hex20(s: &str) -> Option<[u8; 20]> {
|
||||
}
|
||||
|
||||
impl KeyDb {
|
||||
/// Construct an empty KeyDb. Used by unit tests; production code
|
||||
/// reaches a populated KeyDb via [`KeyDb::load`] or [`KeyDb::parse`].
|
||||
pub fn empty() -> Self {
|
||||
KeyDb {
|
||||
device_keys: Vec::new(),
|
||||
processing_keys: Vec::new(),
|
||||
host_certs: Vec::new(),
|
||||
disc_entries: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a KEYDB.cfg file from a string.
|
||||
pub fn parse(data: &str) -> Self {
|
||||
let mut db = KeyDb {
|
||||
@@ -152,7 +163,7 @@ impl KeyDb {
|
||||
db
|
||||
}
|
||||
|
||||
/// Load KEYDB.cfg from a file path.
|
||||
/// Load a KEYDB.cfg from disk.
|
||||
pub fn load(path: &std::path::Path) -> std::io::Result<Self> {
|
||||
let data = std::fs::read_to_string(path)?;
|
||||
Ok(Self::parse(&data))
|
||||
|
||||
+302
-53
@@ -1,6 +1,6 @@
|
||||
//! AACS key resolution — VUK derivation, MKB processing, disc hash, unit key parsing.
|
||||
|
||||
use super::decrypt::{aes_ecb_decrypt, aes_ecb_encrypt};
|
||||
use super::decrypt::aes_ecb_decrypt;
|
||||
use super::keydb::{DeviceKey, KeyDb};
|
||||
|
||||
// ── VUK derivation ──────────────────────────────────────────────────────────
|
||||
@@ -169,8 +169,9 @@ pub fn parse_unit_key_ro(data: &[u8], aacs2: bool) -> Option<UnitKeyFile> {
|
||||
/// This is the fast path — no subset-difference tree traversal needed.
|
||||
///
|
||||
/// MKB format:
|
||||
/// Record type 0x10 = Verify Media Key Record (has mk_dv)
|
||||
/// Record type 0x81 = Type and Version Record (has MKB version)
|
||||
/// Record type 0x10 = Type and Version Record (has MKB version)
|
||||
/// Record type 0x81 = Verify Media Key Record, AACS 1.0 (has mk_dv)
|
||||
/// Record type 0x86 = Verify Media Key Record, AACS 2.0/2.1 (has mk_dv)
|
||||
/// Record type 0x04 = Subset-Difference Index (has UVS entries)
|
||||
/// Record type 0x07 = Explicit Subset-Difference Record (has cvalues)
|
||||
pub fn derive_media_key_from_pk(mkb: &[u8], processing_keys: &[[u8; 16]]) -> Option<[u8; 16]> {
|
||||
@@ -208,46 +209,53 @@ pub fn derive_media_key_from_pk(mkb: &[u8], processing_keys: &[[u8; 16]]) -> Opt
|
||||
|
||||
/// Validate a processing key against a cvalue/UV pair.
|
||||
/// Returns the Media Key if valid.
|
||||
///
|
||||
/// Implements libaacs `_validate_pk` (aacs.c:98-133) per sgx.fail
|
||||
/// Appendix D.2 step 25:
|
||||
/// 1. `mk = AES-128D(pk, cvalue)`
|
||||
/// 2. `mk[12..16] ^= uv` (4 bytes XOR into the LAST 4 bytes only)
|
||||
/// 3. `dec_vd = AES-128D(mk, mk_dv)`
|
||||
/// 4. If `dec_vd[0..8] == 01 23 45 67 89 AB CD EF` → valid.
|
||||
///
|
||||
/// Previous implementation XOR'd the full 16-byte cvalue back into mk
|
||||
/// (extra step not in libaacs), skipped the uv XOR entirely, and used
|
||||
/// AES-128E + 12-zero-byte check instead of AES-128D + magic. Net effect
|
||||
/// was that correct processing keys were rejected whenever `uv != 0`,
|
||||
/// which is essentially every real disc.
|
||||
fn validate_processing_key(
|
||||
pk: &[u8; 16],
|
||||
cvalue: &[u8],
|
||||
_uv: &[u8],
|
||||
uv: &[u8],
|
||||
mk_dv: &[u8; 16],
|
||||
) -> Option<[u8; 16]> {
|
||||
if cvalue.len() < 16 {
|
||||
if cvalue.len() < 16 || uv.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
// mk = AES-DEC(pk, cvalue) XOR cvalue
|
||||
|
||||
// Step 1: mk = AES-128D(pk, cvalue)
|
||||
let mut cv = [0u8; 16];
|
||||
cv.copy_from_slice(&cvalue[..16]);
|
||||
let mut mk = aes_ecb_decrypt(pk, &cv);
|
||||
for i in 0..16 {
|
||||
mk[i] ^= cv[i];
|
||||
|
||||
// Step 2: XOR uv into the LAST 4 bytes of mk (mk[12..16]).
|
||||
// sgx.fail D.2 step 25 and libaacs aacs.c:118-120.
|
||||
for a in 0..4 {
|
||||
mk[12 + a] ^= uv[a];
|
||||
}
|
||||
|
||||
// Verify: AES-ECB(mk, mk_dv) should produce a specific pattern
|
||||
let _verify = aes_ecb_encrypt(&mk, mk_dv);
|
||||
// mk_dv verification: the first 12 bytes of AES(mk, mk_dv) should be all 0xDEADBEEF...
|
||||
// Actually per AACS spec: verify record value is AES(mk, all_zeros)
|
||||
// No — the mk_dv IS the verification value. We compute AES-ECB(mk, verify_data)
|
||||
// and check it matches.
|
||||
// From libaacs _validate_pk:
|
||||
// crypto_aes128d(pk, rec + a*16, mk) → decrypt cvalue with PK
|
||||
// mk[i] ^= rec[i] → XOR with cvalue
|
||||
// crypto_aes128e(mk, mk_dv, test) → encrypt mk_dv with derived mk
|
||||
// if first 12 bytes of test are zero → valid media key
|
||||
let test = aes_ecb_encrypt(&mk, mk_dv);
|
||||
// AACS spec: Verify Media Key record — first 12 bytes must be zero
|
||||
if test[..12] == [0u8; 12] {
|
||||
// Step 3 + 4: dec_vd = AES-128D(mk, mk_dv); verify magic.
|
||||
let dec_vd = aes_ecb_decrypt(&mk, mk_dv);
|
||||
const VERIFY_MAGIC: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
|
||||
if dec_vd[..8] == VERIFY_MAGIC {
|
||||
return Some(mk);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Find Verify Media Key Record (type 0x10) in MKB.
|
||||
/// Find Verify Media Key Record (type 0x81 for AACS 1.0, 0x86 for AACS 2.0/2.1) in MKB.
|
||||
fn mkb_find_mk_dv(mkb: &[u8]) -> Option<[u8; 16]> {
|
||||
let mut pos = 0;
|
||||
let mut type10_seen: Vec<(usize, usize)> = Vec::new();
|
||||
let mut verify_rec_seen: Vec<(u8, usize, usize)> = Vec::new();
|
||||
while pos + 4 <= mkb.len() {
|
||||
let rec_type = mkb[pos];
|
||||
let rec_len = u32::from_be_bytes([0, mkb[pos + 1], mkb[pos + 2], mkb[pos + 3]]) as usize;
|
||||
@@ -255,17 +263,18 @@ fn mkb_find_mk_dv(mkb: &[u8]) -> Option<[u8; 16]> {
|
||||
break;
|
||||
}
|
||||
|
||||
if rec_type == 0x10 {
|
||||
type10_seen.push((pos, rec_len));
|
||||
if rec_type == 0x81 || rec_type == 0x86 {
|
||||
verify_rec_seen.push((rec_type, pos, rec_len));
|
||||
}
|
||||
|
||||
if rec_type == 0x10 && rec_len >= 20 {
|
||||
// mk_dv is at offset 4 (after record header)
|
||||
if (rec_type == 0x81 || rec_type == 0x86) && rec_len >= 20 {
|
||||
// mk_dv is at offset 4 of the record (after the 4-byte header)
|
||||
let mut dv = [0u8; 16];
|
||||
dv.copy_from_slice(&mkb[pos + 4..pos + 20]);
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "mkb_mk_dv_found",
|
||||
rec_type,
|
||||
pos,
|
||||
rec_len,
|
||||
"mk_dv extracted from MKB"
|
||||
@@ -277,9 +286,9 @@ fn mkb_find_mk_dv(mkb: &[u8]) -> Option<[u8; 16]> {
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "mkb_mk_dv_not_found",
|
||||
type10_seen = ?type10_seen,
|
||||
verify_rec_seen = ?verify_rec_seen,
|
||||
scanned_bytes = pos,
|
||||
"no 0x10 record with rec_len>=20 found"
|
||||
"no 0x81/0x86 record with rec_len>=20 found"
|
||||
);
|
||||
None
|
||||
}
|
||||
@@ -302,8 +311,32 @@ fn mkb_find_subdiff_records(mkb: &[u8]) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Find Conditional Values (cvalues) record (type 0x07) in MKB.
|
||||
/// Find the Media Key Data Record (cvalues table) in an MKB.
|
||||
///
|
||||
/// libaacs hard-codes record type `0x05` (matches AACS 1.0 and BD type-3/4
|
||||
/// MKBs), but on AACS 2.x Category-C MKBs the cvalues table moved to
|
||||
/// record type `0x07` and `0x05` now carries the host-revocation
|
||||
/// signature. To stay correct on both lines we prefer `0x07` first (the
|
||||
/// AACS 2.x layout used by every modern UHD disc) and fall back to
|
||||
/// `0x05` for AACS 1.0 MKBs.
|
||||
///
|
||||
/// References:
|
||||
/// - libaacs `mkb_cvalues` (mkb.c:190-193) uses `0x05` exclusively.
|
||||
/// - sgx.fail Appendix D.5 walks an AACS 2.x MKB and confirms cvalues
|
||||
/// at `0x07`.
|
||||
/// - Empirically confirmed against our `aacs2-mkb-samples/`
|
||||
/// (Wicked / Civil War / Barbie v77 MKBs): cvalues at `0x07`.
|
||||
fn mkb_find_cvalues(mkb: &[u8]) -> Option<Vec<u8>> {
|
||||
if let Some(body) = find_record_body(mkb, 0x07) {
|
||||
return Some(body);
|
||||
}
|
||||
find_record_body(mkb, 0x05)
|
||||
}
|
||||
|
||||
/// Walk an MKB and return the payload (header stripped) of the first
|
||||
/// record matching `rec_type`. Returns `None` if no such record exists or
|
||||
/// the record is empty.
|
||||
fn find_record_body(mkb: &[u8], rec_type_wanted: u8) -> Option<Vec<u8>> {
|
||||
let mut pos = 0;
|
||||
while pos + 4 <= mkb.len() {
|
||||
let rec_type = mkb[pos];
|
||||
@@ -311,16 +344,19 @@ fn mkb_find_cvalues(mkb: &[u8]) -> Option<Vec<u8>> {
|
||||
if rec_len < 4 || pos + rec_len > mkb.len() {
|
||||
break;
|
||||
}
|
||||
|
||||
if rec_type == 0x07 && rec_len > 4 {
|
||||
if rec_type == rec_type_wanted && rec_len > 4 {
|
||||
return Some(mkb[pos + 4..pos + rec_len].to_vec());
|
||||
}
|
||||
if rec_len == 0 {
|
||||
break;
|
||||
}
|
||||
pos += rec_len;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Get MKB version from Type and Version Record (type 0x81).
|
||||
/// Get MKB version from Type and Version Record (type 0x10).
|
||||
/// Version is a BE u32 at offset 8 of the record body (offset 12 from `pos`).
|
||||
pub fn mkb_version(mkb: &[u8]) -> Option<u32> {
|
||||
let mut pos = 0;
|
||||
while pos + 4 <= mkb.len() {
|
||||
@@ -330,12 +366,12 @@ pub fn mkb_version(mkb: &[u8]) -> Option<u32> {
|
||||
break;
|
||||
}
|
||||
|
||||
if rec_type == 0x81 && rec_len >= 8 {
|
||||
if rec_type == 0x10 && rec_len >= 12 {
|
||||
return Some(u32::from_be_bytes([
|
||||
mkb[pos + 4],
|
||||
mkb[pos + 5],
|
||||
mkb[pos + 6],
|
||||
mkb[pos + 7],
|
||||
mkb[pos + 8],
|
||||
mkb[pos + 9],
|
||||
mkb[pos + 10],
|
||||
mkb[pos + 11],
|
||||
]));
|
||||
}
|
||||
pos += rec_len;
|
||||
@@ -668,6 +704,21 @@ pub fn resolve_keys(
|
||||
tracing::warn!(target: "freemkv::disc", phase = "resolve_keys_path1_miss", "disc hash NOT in keydb");
|
||||
}
|
||||
|
||||
// Paths 2-4 all consume the Volume ID. Without it (handshake
|
||||
// skipped, libredrive bypass failed, etc.) every downstream
|
||||
// derivation produces garbage. Caller stamps `[0u8; 16]` as the
|
||||
// sentinel "no VID" — short-circuit here so we don't surface a
|
||||
// misleading "all paths failed" log when really the math is
|
||||
// structurally impossible.
|
||||
if *volume_id == [0u8; 16] {
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "resolve_keys_no_vid",
|
||||
"VID unavailable; paths 2/3/4 require VID and are skipped"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
// Path 2: Find entry with matching VID → derive VUK from MK + VID
|
||||
let mut path2_mk_did_count = 0usize;
|
||||
for entry in keydb.disc_entries.values() {
|
||||
@@ -935,23 +986,137 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mkb_version_parse() {
|
||||
// Synthetic MKB with Type and Version record (0x81)
|
||||
let mut mkb = vec![0u8; 32];
|
||||
// Record: type=0x81, length=12 (BE24)
|
||||
mkb[0] = 0x81;
|
||||
mkb[1] = 0x00;
|
||||
mkb[2] = 0x00;
|
||||
mkb[3] = 0x0C;
|
||||
// Version = 77
|
||||
mkb[4] = 0x00;
|
||||
mkb[5] = 0x00;
|
||||
mkb[6] = 0x00;
|
||||
mkb[7] = 77;
|
||||
|
||||
fn mkb_version_recognizes_type_0x10() {
|
||||
// Type-and-Version record: type=0x10, rec_len=12 (BE24).
|
||||
// Body is 8 bytes; the version u32 sits at offset 8 of the record.
|
||||
let mkb = [
|
||||
0x10, 0x00, 0x00, 0x0C, 0x48, 0x14, 0x10, 0x03, 0x00, 0x00, 0x00, 0x4D,
|
||||
];
|
||||
assert_eq!(mkb_version(&mkb), Some(77));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mkb_version_returns_none_on_empty() {
|
||||
assert_eq!(mkb_version(&[]), None);
|
||||
assert_eq!(mkb_version(&[0x10, 0x00]), None);
|
||||
// Type 0x10 record but rec_len < 12 → no version available.
|
||||
let short = [0x10, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01];
|
||||
assert_eq!(mkb_version(&short), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mkb_find_mk_dv_recognizes_type_0x81() {
|
||||
// First: type-0x10 type/version record (12 bytes), then type-0x81 verify record.
|
||||
// Verify record carries a known 16-byte mk_dv at offset 4 of the record body.
|
||||
let expected: [u8; 16] = [
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
|
||||
0xFF, 0x00,
|
||||
];
|
||||
let mut mkb = vec![
|
||||
0x10, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
|
||||
];
|
||||
// type=0x81, rec_len=24 (4-byte header + 16-byte mk_dv + 4-byte trailing zeros)
|
||||
mkb.extend_from_slice(&[0x81, 0x00, 0x00, 0x18]);
|
||||
mkb.extend_from_slice(&expected);
|
||||
mkb.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
|
||||
|
||||
assert_eq!(mkb_find_mk_dv(&mkb), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_processing_key_round_trip_with_nonzero_uv() {
|
||||
// Synthesise a (pk, uv, mk, cvalue, mk_dv) tuple that satisfies the
|
||||
// libaacs _validate_pk relation, then confirm validate_processing_key
|
||||
// recovers mk. Catches the bugs that landed pre-fix:
|
||||
// * uv XOR step was missing → mk wrong whenever uv != 0
|
||||
// * AES-128E + 12-zero check instead of AES-128D + magic
|
||||
use super::super::decrypt::{aes_ecb_decrypt as dec, aes_ecb_encrypt as enc};
|
||||
|
||||
let pk: [u8; 16] = [
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
|
||||
0xFF, 0x00,
|
||||
];
|
||||
let mk: [u8; 16] = [
|
||||
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD,
|
||||
0xAE, 0xAF,
|
||||
];
|
||||
let uv: [u8; 4] = [0x00, 0x00, 0x04, 0x00];
|
||||
|
||||
// cvalue is what AES-128E(pk, mk') gives, where mk' = mk with the
|
||||
// last-4-bytes-uv XOR pre-undone:
|
||||
// mk_raw[12..16] = mk[12..16] XOR uv (so the validate step XORs
|
||||
// uv back in and recovers mk).
|
||||
let mut mk_raw = mk;
|
||||
for a in 0..4 {
|
||||
mk_raw[12 + a] ^= uv[a];
|
||||
}
|
||||
let cvalue = enc(&pk, &mk_raw);
|
||||
|
||||
// mk_dv is the encryption (under the correct mk) of the verify
|
||||
// magic, padded with arbitrary bytes — when decrypted with mk we
|
||||
// recover the magic.
|
||||
let mut plaintext_vd = [0u8; 16];
|
||||
plaintext_vd[..8].copy_from_slice(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]);
|
||||
// Trailing 8 bytes are don't-cares in the magic check.
|
||||
plaintext_vd[8..].copy_from_slice(&[0x11; 8]);
|
||||
let mk_dv = enc(&mk, &plaintext_vd);
|
||||
// Sanity: decrypting mk_dv with mk yields the magic.
|
||||
let _check = dec(&mk, &mk_dv);
|
||||
|
||||
let recovered = validate_processing_key(&pk, &cvalue, &uv, &mk_dv)
|
||||
.expect("validate_processing_key must accept a correct pk + uv pair");
|
||||
assert_eq!(recovered, mk, "recovered mk must match the planted mk");
|
||||
|
||||
// And a wrong pk must be rejected.
|
||||
let mut wrong_pk = pk;
|
||||
wrong_pk[0] ^= 0xFF;
|
||||
assert!(validate_processing_key(&wrong_pk, &cvalue, &uv, &mk_dv).is_none());
|
||||
|
||||
// And a uv mismatch must be rejected.
|
||||
let wrong_uv = [0x00u8, 0x00, 0x00, 0x00];
|
||||
assert!(validate_processing_key(&pk, &cvalue, &wrong_uv, &mk_dv).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mkb_find_cvalues_prefers_0x07_then_falls_back_to_0x05() {
|
||||
// AACS 2.x: type 0x07 carries cvalues; 0x05 is the host-revocation
|
||||
// signature. Mixed-record MKB → 0x07 wins.
|
||||
let mut mkb = vec![
|
||||
0x10, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D,
|
||||
];
|
||||
// type=0x05, body = [0xAA; 4]
|
||||
mkb.extend_from_slice(&[0x05, 0x00, 0x00, 0x08, 0xAA, 0xAA, 0xAA, 0xAA]);
|
||||
// type=0x07, body = [0xBB; 4]
|
||||
mkb.extend_from_slice(&[0x07, 0x00, 0x00, 0x08, 0xBB, 0xBB, 0xBB, 0xBB]);
|
||||
let body = mkb_find_cvalues(&mkb).expect("cvalues record must be found");
|
||||
assert_eq!(body, vec![0xBB, 0xBB, 0xBB, 0xBB], "0x07 must be preferred");
|
||||
|
||||
// AACS 1.0: only 0x05 present → fall back to it.
|
||||
let mut mkb1 = vec![
|
||||
0x10, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
|
||||
];
|
||||
mkb1.extend_from_slice(&[0x05, 0x00, 0x00, 0x08, 0xCC, 0xCC, 0xCC, 0xCC]);
|
||||
let body = mkb_find_cvalues(&mkb1).expect("0x05 fallback must work for AACS 1.0");
|
||||
assert_eq!(body, vec![0xCC, 0xCC, 0xCC, 0xCC]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mkb_find_mk_dv_recognizes_type_0x86() {
|
||||
// AACS 2.0 form uses type 0x86 for the verify record.
|
||||
let expected: [u8; 16] = [
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
|
||||
0x0B, 0x0C,
|
||||
];
|
||||
let mut mkb = vec![
|
||||
0x10, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D,
|
||||
];
|
||||
mkb.extend_from_slice(&[0x86, 0x00, 0x00, 0x18]);
|
||||
mkb.extend_from_slice(&expected);
|
||||
mkb.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
|
||||
|
||||
assert_eq!(mkb_find_mk_dv(&mkb), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_keys_vuk_path() {
|
||||
// Test the full resolve chain using VUK path
|
||||
@@ -987,6 +1152,90 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a minimal Unit_Key_RO.inf with `num_unit_keys = 1`. The
|
||||
/// disc hash won't be in any synthetic keydb so path 1 misses,
|
||||
/// which lets us isolate the path-2/3/4 short-circuit behavior.
|
||||
fn minimal_unit_key_ro() -> Vec<u8> {
|
||||
let mut data = vec![0u8; 256];
|
||||
// uk_pos = 0x60
|
||||
data[3] = 0x60;
|
||||
data[16] = 1; // app_type = BD-ROM
|
||||
data[17] = 1; // num_bdmv_dir
|
||||
let uk_pos = 0x60usize;
|
||||
data[uk_pos + 1] = 1; // 1 unit key
|
||||
// Key at uk_pos + 48 — value doesn't matter, just needs to fit.
|
||||
for i in 0..16 {
|
||||
data[uk_pos + 48 + i] = 0xCC;
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_keys_skips_paths_2_through_4_when_vid_is_zero() {
|
||||
// No VID -> paths 2/3/4 cannot succeed. The function must
|
||||
// return None WITHOUT touching the MKB / device keys, so we
|
||||
// can pass an MKB that would otherwise cause expensive
|
||||
// derivation work — it must not be consumed.
|
||||
let uk_ro = minimal_unit_key_ro();
|
||||
let zero_vid = [0u8; 16];
|
||||
|
||||
// Populate keydb with a non-matching VID entry (path 2 would
|
||||
// miss anyway) plus dummy processing/device keys (paths 3/4
|
||||
// would also miss, but the short-circuit means they're never
|
||||
// attempted).
|
||||
let mut keydb = KeyDb::empty();
|
||||
keydb.disc_entries.insert(
|
||||
"0xDEADBEEF".to_string(),
|
||||
DiscEntry {
|
||||
disc_hash: "0xDEADBEEF".to_string(),
|
||||
title: "fixture".to_string(),
|
||||
media_key: Some([0x11u8; 16]),
|
||||
disc_id: Some([0x22u8; 16]),
|
||||
vuk: None,
|
||||
unit_keys: Vec::new(),
|
||||
},
|
||||
);
|
||||
keydb.processing_keys.push([0u8; 16]);
|
||||
|
||||
let result = resolve_keys(&uk_ro, None, &zero_vid, &keydb, None);
|
||||
assert!(
|
||||
result.is_none(),
|
||||
"resolve_keys with VID=0 and no matching disc-hash entry must return None"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_keys_path1_still_runs_when_vid_is_zero() {
|
||||
// Path 1 (disc-hash → VUK) doesn't need VID. Confirm the
|
||||
// short-circuit doesn't block it: install a keydb entry whose
|
||||
// disc_hash matches the fixture's hash, with a known VUK, and
|
||||
// verify resolve_keys returns it with key_source = 1.
|
||||
let uk_ro = minimal_unit_key_ro();
|
||||
let hash = disc_hash(&uk_ro);
|
||||
// `find_disc` lowercases the incoming hash; the entry map is
|
||||
// keyed lowercase too, so we have to lowercase here.
|
||||
let hash_hex = disc_hash_hex(&hash).to_lowercase();
|
||||
|
||||
let mut keydb = KeyDb::empty();
|
||||
let known_vuk = [0xABu8; 16];
|
||||
keydb.disc_entries.insert(
|
||||
hash_hex.clone(),
|
||||
DiscEntry {
|
||||
disc_hash: hash_hex,
|
||||
title: "fixture".to_string(),
|
||||
media_key: None,
|
||||
disc_id: None,
|
||||
vuk: Some(known_vuk),
|
||||
unit_keys: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
let resolved = resolve_keys(&uk_ro, None, &[0u8; 16], &keydb, None)
|
||||
.expect("path 1 must run regardless of VID availability");
|
||||
assert_eq!(resolved.vuk, known_vuk);
|
||||
assert_eq!(resolved.key_source, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_cert_parse() {
|
||||
// AACS 1.0 cert
|
||||
|
||||
+4
-3
@@ -4,13 +4,14 @@
|
||||
//! 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
|
||||
//!
|
||||
//! Based on libdvdcss (VideoLAN) and Stevenson 1999 analysis.
|
||||
|
||||
use crate::drive::Drive;
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
// ── Player keys (from libdvdcss, Stevenson's PlayerKey cracker) ───────────
|
||||
// ── 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],
|
||||
|
||||
+196
-20
@@ -13,20 +13,126 @@ pub(super) struct HandshakeResult {
|
||||
pub read_data_key: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
/// Retrieve VID via the libredrive alternate read path. The drive's
|
||||
/// runtime firmware has cleared bus encryption AND no longer requires
|
||||
/// a cert-based AGID for protected-area queries — standard
|
||||
/// READ_DISC_STRUCTURE format 0x80 with AGID = 0 returns the raw VID.
|
||||
///
|
||||
/// Layout matches the spec response (4-byte header + 16-byte VID +
|
||||
/// 16-byte MAC), but MAC is meaningless without a bus key derivation;
|
||||
/// libredrive mode delivers `[0u8; 16]` (or stale bytes) in the MAC
|
||||
/// field. We extract the VID bytes only and skip MAC validation
|
||||
/// entirely — this is the documented behavior gap when bus encryption
|
||||
/// is off.
|
||||
fn read_volume_id_libredrive(session: &mut crate::drive::Drive) -> Result<[u8; 16]> {
|
||||
// CDB: READ_DISC_STRUCTURE (0xAD), media=Blu-ray (0x01), AGID=0,
|
||||
// format=0x80 (AACS Volume ID), allocation_length=36 (4-byte
|
||||
// header + 16-byte VID + 16-byte MAC).
|
||||
let mut cdb = [0u8; 12];
|
||||
cdb[0] = crate::scsi::SCSI_READ_DISC_STRUCTURE;
|
||||
cdb[1] = 0x01; // Blu-ray media type
|
||||
cdb[7] = 0x80; // format = Volume ID
|
||||
cdb[8] = 0x00;
|
||||
cdb[9] = 36;
|
||||
cdb[10] = 0; // AGID = 0 (no auth session)
|
||||
|
||||
let mut buf = [0u8; 36];
|
||||
let result = session.scsi_execute(
|
||||
&cdb,
|
||||
crate::scsi::DataDirection::FromDevice,
|
||||
&mut buf,
|
||||
5_000,
|
||||
)?;
|
||||
if result.bytes_transferred < 20 {
|
||||
return Err(Error::AacsVidRead);
|
||||
}
|
||||
let mut vid = [0u8; 16];
|
||||
vid.copy_from_slice(&buf[4..20]);
|
||||
Ok(vid)
|
||||
}
|
||||
|
||||
impl Disc {
|
||||
/// SCSI handshake result — volume ID and bus keys from ECDH authentication.
|
||||
/// Only available when scanning from a real drive (not ISO images).
|
||||
/// SCSI handshake — retrieve VID (and bus keys when applicable).
|
||||
///
|
||||
/// Branches on `Drive::is_libredrive_active()`:
|
||||
/// * libredrive raw-read mode active → skip cert auth, read VID
|
||||
/// directly via the alternate path (bus encryption is already
|
||||
/// off; the drive accepts standard READ_DISC_STRUCTURE format
|
||||
/// 0x80 without an AGID).
|
||||
/// * libredrive inactive → traditional AACS mutual auth using
|
||||
/// host certs from the keydb. Caps attempts at 3 with a 1 s
|
||||
/// backoff to avoid the firmware-wedge hammering we hit in
|
||||
/// v0.25.7.
|
||||
///
|
||||
/// Returns `(handshake, error)`:
|
||||
/// * `(Some(_), None)` — VID acquired
|
||||
/// * `(None, Some(_))` — specific failure mode (see new
|
||||
/// `AacsHostCertRejected` / `AacsLibredriveUnsupported` /
|
||||
/// `AacsVidUnavailable` variants in `error.rs`)
|
||||
/// * `(None, None)` — handshake not attempted (no keydb;
|
||||
/// resolution will proceed with built-in keys and VID=zero)
|
||||
pub(super) fn do_handshake(
|
||||
session: &mut crate::drive::Drive,
|
||||
opts: &ScanOptions,
|
||||
) -> Option<HandshakeResult> {
|
||||
use crate::aacs::{self, KeyDb};
|
||||
|
||||
) -> (Option<HandshakeResult>, Option<Error>) {
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "handshake_entry",
|
||||
libredrive_active = session.is_libredrive_active(),
|
||||
"do_handshake entered"
|
||||
);
|
||||
|
||||
// Libredrive mode: skip cert auth entirely. The drive returns
|
||||
// VID via READ_DISC_STRUCTURE format 0x80 with no AGID and no
|
||||
// bus encryption applied. This is what MakeMKV does on the
|
||||
// same drive + disc combination where libfreemkv used to fail
|
||||
// with E7000 — empirically confirmed 2026-05-21 on rip1
|
||||
// (BU40N + Barbie UHD, MKB v77, libaacs leaked cert revoked
|
||||
// by HRL but disc rips cleanly via libredrive).
|
||||
if session.is_libredrive_active() {
|
||||
return match read_volume_id_libredrive(session) {
|
||||
Ok(vid) => {
|
||||
tracing::debug!(
|
||||
target: "freemkv::disc",
|
||||
phase = "handshake_libredrive_ok",
|
||||
"libredrive VID acquired without cert auth"
|
||||
);
|
||||
(
|
||||
Some(HandshakeResult {
|
||||
volume_id: vid,
|
||||
// No bus key in libredrive mode -> no
|
||||
// encrypted-read-data-key to decrypt.
|
||||
// AACS 2.0 bus-encrypted sectors are
|
||||
// already plaintext when libredrive is
|
||||
// active, so consumers don't need RDK.
|
||||
read_data_key: None,
|
||||
}),
|
||||
None,
|
||||
)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "handshake_libredrive_vid_failed",
|
||||
error_code = e.code(),
|
||||
"libredrive VID read failed"
|
||||
);
|
||||
(None, Some(Error::AacsVidUnavailable))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Self::do_handshake_cert(session, opts)
|
||||
}
|
||||
|
||||
/// Cert-based AACS handshake. Only called when libredrive mode is
|
||||
/// NOT active — see `do_handshake` for the dispatch.
|
||||
fn do_handshake_cert(
|
||||
session: &mut crate::drive::Drive,
|
||||
opts: &ScanOptions,
|
||||
) -> (Option<HandshakeResult>, Option<Error>) {
|
||||
use crate::aacs::{self, KeyDb};
|
||||
|
||||
let keydb_path = match opts.resolve_keydb() {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
@@ -35,7 +141,7 @@ impl Disc {
|
||||
phase = "handshake_no_keydb",
|
||||
"no KEYDB found in search paths; handshake skipped"
|
||||
);
|
||||
return None;
|
||||
return (None, None);
|
||||
}
|
||||
};
|
||||
let keydb = match KeyDb::load(&keydb_path) {
|
||||
@@ -48,7 +154,12 @@ impl Disc {
|
||||
keydb = %keydb_path.display(),
|
||||
"KEYDB load failed; handshake skipped"
|
||||
);
|
||||
return None;
|
||||
return (
|
||||
None,
|
||||
Some(Error::KeydbLoad {
|
||||
path: keydb_path.display().to_string(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -61,9 +172,37 @@ impl Disc {
|
||||
"handshake starting"
|
||||
);
|
||||
|
||||
const MAX_CERT_ATTEMPTS: usize = 16;
|
||||
if host_cert_count == 0 {
|
||||
// Drive isn't in libredrive mode AND keydb has no host
|
||||
// certs -> cert auth cannot proceed. Surface as
|
||||
// LibredriveUnsupported so the caller knows neither path
|
||||
// is available on this configuration.
|
||||
return (None, Some(Error::AacsLibredriveUnsupported));
|
||||
}
|
||||
|
||||
// v0.25.7 wedge fix. Pre-0.25.7 this loop fired up to 16 AACS
|
||||
// authenticate attempts back-to-back with no pause. Each attempt
|
||||
// is 5-10 SCSI REPORT_KEY/SEND_KEY exchanges. On a disc whose
|
||||
// host cert isn't in our KEYDB (or one the drive rejects),
|
||||
// that's 80-160 SCSI commands hammered at the drive in a
|
||||
// few hundred milliseconds — and the BU40N (and most consumer
|
||||
// optical drives) responds by entering a fast-fail firmware
|
||||
// wedge state where every subsequent CDB returns
|
||||
// ILLEGAL_REQUEST/INVALID_FIELD_IN_CDB (sense 05/24) until
|
||||
// power-cycled. Hit live on rip1 2026-05-20 during a Barbie
|
||||
// UHD scan: KEYDB miss → 16 cert attempts in a tight loop →
|
||||
// wedge → forced host reboot + drive disconnect to recover.
|
||||
//
|
||||
// Defense-in-depth: cap attempts, sleep between, and bail
|
||||
// early on the drive's wedge sense so any later regression
|
||||
// can't undo the protection silently.
|
||||
const MAX_CERT_ATTEMPTS: usize = 3;
|
||||
const PER_CERT_BACKOFF_MS: u64 = 1000;
|
||||
let mut last_err_code: Option<u16> = None;
|
||||
for (idx, hc) in keydb.host_certs.iter().take(MAX_CERT_ATTEMPTS).enumerate() {
|
||||
if idx > 0 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(PER_CERT_BACKOFF_MS));
|
||||
}
|
||||
match aacs::handshake::aacs_authenticate(session, &hc.private_key, &hc.certificate) {
|
||||
Ok(mut auth) => {
|
||||
let volume_id = match aacs::handshake::read_volume_id(session, &mut auth) {
|
||||
@@ -76,7 +215,7 @@ impl Disc {
|
||||
error_code = e.code(),
|
||||
"auth ok but volume ID read failed"
|
||||
);
|
||||
return None;
|
||||
return (None, Some(Error::AacsVidUnavailable));
|
||||
}
|
||||
};
|
||||
let read_data_key = aacs::handshake::read_data_keys(session, &mut auth)
|
||||
@@ -88,13 +227,33 @@ impl Disc {
|
||||
cert_index = idx,
|
||||
has_read_data_key = read_data_key.is_some(),
|
||||
);
|
||||
return Some(HandshakeResult {
|
||||
volume_id,
|
||||
read_data_key,
|
||||
});
|
||||
return (
|
||||
Some(HandshakeResult {
|
||||
volume_id,
|
||||
read_data_key,
|
||||
}),
|
||||
None,
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
last_err_code = Some(e.code());
|
||||
let code = e.code();
|
||||
last_err_code = Some(code);
|
||||
// Drive wedge senses (any with high byte 0x05 =
|
||||
// ILLEGAL_REQUEST). The drive isn't merely
|
||||
// rejecting our cert — it's saying "I won't talk
|
||||
// to you anymore." Trying more certs makes the
|
||||
// wedge worse. Bail out immediately.
|
||||
let sense_key = ((code >> 8) & 0xFF) as u8;
|
||||
if sense_key == 0x05 {
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "handshake_wedge_detected",
|
||||
cert_index = idx,
|
||||
error_code = code,
|
||||
"drive returned ILLEGAL_REQUEST during auth; bailing out to avoid wedge"
|
||||
);
|
||||
return (None, Some(Error::AacsHostCertRejected));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -105,10 +264,10 @@ impl Disc {
|
||||
host_cert_count,
|
||||
tried = host_cert_count.min(MAX_CERT_ATTEMPTS),
|
||||
last_error_code = last_err_code,
|
||||
"all host certs in KEYDB rejected by drive"
|
||||
"all host certs in KEYDB rejected by drive (capped at {} attempts to prevent firmware wedge)",
|
||||
MAX_CERT_ATTEMPTS
|
||||
);
|
||||
// All host certs failed — return None, not a fake success
|
||||
None
|
||||
(None, Some(Error::AacsHostCertRejected))
|
||||
}
|
||||
|
||||
/// Resolve disc encryption — AACS 1.0, AACS 2.0, CSS, or none.
|
||||
@@ -181,11 +340,28 @@ impl Disc {
|
||||
);
|
||||
|
||||
// Use handshake volume ID if available, otherwise zeros
|
||||
// (KEYDB VUK lookup by disc hash works without volume ID)
|
||||
// (KEYDB VUK lookup by disc hash works without volume ID;
|
||||
// paths 2/3/4 in `resolve_keys` short-circuit on the zero
|
||||
// sentinel and don't waste cycles trying to derive against
|
||||
// garbage input).
|
||||
let volume_id = handshake.map(|h| h.volume_id).unwrap_or([0u8; 16]);
|
||||
let vid_available = volume_id != [0u8; 16];
|
||||
let read_data_key = handshake.and_then(|h| h.read_data_key);
|
||||
|
||||
// Resolve: tries all available paths — KEYDB VUK, media key, processing key, device key
|
||||
// Resolve: tries all available paths — KEYDB VUK, media key, processing key, device key.
|
||||
//
|
||||
// Distinguish "we had every input and still missed" from "we
|
||||
// never had VID so the derivation paths couldn't run." The
|
||||
// former points at a stale keydb / unsupported MKB; the
|
||||
// latter points at a failed handshake upstream. Path 1
|
||||
// (disc-hash lookup) ran without VID and missed -> disc isn't
|
||||
// in the keydb. If the caller has a handshake-failure reason
|
||||
// it overrides this in `scan_with`.
|
||||
let miss_error = if vid_available {
|
||||
Error::AacsMkUnavailable
|
||||
} else {
|
||||
Error::AacsVukNotInKeydb
|
||||
};
|
||||
let resolved = aacs::resolve_keys(
|
||||
&uk_ro_data,
|
||||
cc_data.as_deref(),
|
||||
@@ -193,7 +369,7 @@ impl Disc {
|
||||
&keydb,
|
||||
mkb_data.as_deref(),
|
||||
)
|
||||
.ok_or(Error::AacsNoKeys)?;
|
||||
.ok_or(miss_error)?;
|
||||
|
||||
Ok(AacsState {
|
||||
version: if resolved.aacs2 { 2 } else { 1 },
|
||||
|
||||
+43
-15
@@ -1043,8 +1043,11 @@ impl Disc {
|
||||
/// The session must be open and unlocked (Drive::open handles this).
|
||||
/// All disc reads use standard READ(10) via UDF -- no vendor SCSI commands.
|
||||
pub fn scan(session: &mut Drive, opts: &ScanOptions) -> Result<Self> {
|
||||
// AACS handshake (Blu-ray/UHD)
|
||||
let handshake = Self::do_handshake(session, opts);
|
||||
// AACS handshake (Blu-ray/UHD). Branches internally on
|
||||
// libredrive raw-read mode: when active the drive serves VID
|
||||
// without cert auth and no bus encryption is in play. When
|
||||
// inactive we fall back to the cert-based mutual auth.
|
||||
let (handshake, handshake_error) = Self::do_handshake(session, opts);
|
||||
|
||||
// Request max read speed — removes riplock on DVD
|
||||
// (BD/UHD speed is set by firmware init, but DVD needs explicit SET CD SPEED)
|
||||
@@ -1059,7 +1062,14 @@ impl Disc {
|
||||
buffered.prefetch_ranges(&ranges);
|
||||
}
|
||||
|
||||
let mut disc = Self::scan_with(&mut buffered, capacity, handshake, opts, udf_fs)?;
|
||||
let mut disc = Self::scan_with(
|
||||
&mut buffered,
|
||||
capacity,
|
||||
handshake,
|
||||
handshake_error,
|
||||
opts,
|
||||
udf_fs,
|
||||
)?;
|
||||
|
||||
// CSS key extraction for DVDs (bus auth → disc key → title key).
|
||||
// Must be a single auth session — can't call authenticate() separately.
|
||||
@@ -1100,14 +1110,21 @@ impl Disc {
|
||||
opts: &ScanOptions,
|
||||
) -> Result<Self> {
|
||||
let udf_fs = udf::read_filesystem(reader)?;
|
||||
Self::scan_with(reader, capacity, None, opts, udf_fs)
|
||||
Self::scan_with(reader, capacity, None, None, opts, udf_fs)
|
||||
}
|
||||
|
||||
/// Core scan pipeline — works with any SectorSource.
|
||||
///
|
||||
/// `handshake_error` is plumbed from `do_handshake` so failures
|
||||
/// (cert rejected, libredrive unsupported, VID read failed) are
|
||||
/// preserved as `disc.aacs_error` for callers to render. When key
|
||||
/// resolution succeeds despite the handshake failure (built-in
|
||||
/// keys + disc-hash lookup hit) the error is dropped.
|
||||
fn scan_with(
|
||||
reader: &mut dyn SectorSource,
|
||||
capacity: u32,
|
||||
handshake: Option<HandshakeResult>,
|
||||
handshake_error: Option<Error>,
|
||||
opts: &ScanOptions,
|
||||
udf_fs: udf::UdfFs,
|
||||
) -> Result<Self> {
|
||||
@@ -1122,15 +1139,28 @@ impl Disc {
|
||||
{
|
||||
Ok(state) => (Some(state), None),
|
||||
Err(e) => {
|
||||
// When the handshake itself failed AND resolution
|
||||
// bottomed out at "no keys", surface the upstream
|
||||
// handshake failure — it's more actionable than
|
||||
// the generic AacsNoKeys.
|
||||
let final_err = match (&e, handshake_error.as_ref()) {
|
||||
(
|
||||
Error::AacsNoKeys
|
||||
| Error::AacsVukNotInKeydb
|
||||
| Error::AacsVidUnavailable,
|
||||
Some(_),
|
||||
) => handshake_error.unwrap(),
|
||||
_ => e,
|
||||
};
|
||||
tracing::warn!(
|
||||
target: "freemkv::disc",
|
||||
phase = "scan_aacs_resolve_failed",
|
||||
error_code = e.code(),
|
||||
error_code = final_err.code(),
|
||||
keydb = %keydb_path.display(),
|
||||
handshake_ok = handshake.is_some(),
|
||||
"AACS key resolution failed"
|
||||
);
|
||||
(None, Some(e))
|
||||
(None, Some(final_err))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1140,16 +1170,14 @@ impl Disc {
|
||||
phase = "scan_aacs_no_keydb",
|
||||
"encrypted disc but no KEYDB found in search paths"
|
||||
);
|
||||
// Reuse KeydbLoad with sentinel path — adding a new Error
|
||||
// variant would be a breaking change for downstream
|
||||
// exhaustive matches. The path string makes the cause
|
||||
// unambiguous to autorip's message switch.
|
||||
(
|
||||
None,
|
||||
Some(crate::error::Error::KeydbLoad {
|
||||
// Sentinel path string lets autorip's message switch
|
||||
// distinguish "no keydb found anywhere" from "keydb at
|
||||
// <path> failed to parse".
|
||||
let final_err =
|
||||
handshake_error.unwrap_or_else(|| crate::error::Error::KeydbLoad {
|
||||
path: String::from("<no keydb in search paths>"),
|
||||
}),
|
||||
)
|
||||
});
|
||||
(None, Some(final_err))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -432,6 +432,27 @@ impl Drive {
|
||||
}
|
||||
}
|
||||
|
||||
/// True if the drive is currently in libredrive raw-read mode.
|
||||
///
|
||||
/// Detected by the platform driver during `init()` from the unlock
|
||||
/// response's mode markers. When true:
|
||||
/// - SCSI READ_10 returns plaintext sectors (no AACS bus
|
||||
/// encryption applied)
|
||||
/// - VID retrieval works without the cert-based AACS handshake
|
||||
/// - Disc-side Host Revocation List enforcement is effectively
|
||||
/// bypassed by the alternate data path
|
||||
///
|
||||
/// AACS layer code should branch on this: if true, skip
|
||||
/// `aacs::handshake::aacs_authenticate` (the cert dance) and read
|
||||
/// VID via the libredrive alternate path. If false, fall back to
|
||||
/// the standard cert-based handshake.
|
||||
pub fn is_libredrive_active(&self) -> bool {
|
||||
match self.driver {
|
||||
Some(ref d) => d.is_libredrive_active(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read sectors from the disc. Single-shot — no inline retries, no
|
||||
/// SCSI reset.
|
||||
///
|
||||
|
||||
@@ -71,6 +71,11 @@ pub const E_AACS_VID_MAC: u16 = 7010;
|
||||
pub const E_AACS_DATA_KEY: u16 = 7011;
|
||||
pub const E_DECRYPT_FAILED: u16 = 7013;
|
||||
pub const E_CSS_AUTH_FAILED: u16 = 7014;
|
||||
pub const E_AACS_HOST_CERT_REJECTED: u16 = 7015;
|
||||
pub const E_AACS_LIBREDRIVE_UNSUPPORTED: u16 = 7016;
|
||||
pub const E_AACS_VID_UNAVAILABLE: u16 = 7017;
|
||||
pub const E_AACS_MK_UNAVAILABLE: u16 = 7018;
|
||||
pub const E_AACS_VUK_NOT_IN_KEYDB: u16 = 7019;
|
||||
|
||||
// Keydb (8xxx)
|
||||
pub const E_KEYDB_CONNECT: u16 = 8000;
|
||||
@@ -222,6 +227,22 @@ pub enum Error {
|
||||
AacsDataKey,
|
||||
DecryptFailed,
|
||||
CssAuthFailed,
|
||||
/// Host certificate rejected by the drive's revocation list (HRL hit).
|
||||
/// All available host certs failed mutual auth on this drive.
|
||||
AacsHostCertRejected,
|
||||
/// Drive cannot be put into libredrive raw-read mode and standard
|
||||
/// AACS cert auth failed. No path to decryption remains.
|
||||
AacsLibredriveUnsupported,
|
||||
/// Volume ID could not be retrieved from the drive (neither via cert
|
||||
/// auth nor via the libredrive alternate path). Downstream of step 1
|
||||
/// of the AACS chain.
|
||||
AacsVidUnavailable,
|
||||
/// No available path produced a Media Key (no MK+VID in keydb, no
|
||||
/// PK match, no DK derivation).
|
||||
AacsMkUnavailable,
|
||||
/// Disc-hash lookup in the keydb missed and no other path is
|
||||
/// available (typically because VID is missing).
|
||||
AacsVukNotInKeydb,
|
||||
|
||||
// Keydb (8xxx)
|
||||
KeydbConnect {
|
||||
@@ -307,6 +328,11 @@ impl Error {
|
||||
Error::AacsDataKey => E_AACS_DATA_KEY,
|
||||
Error::DecryptFailed => E_DECRYPT_FAILED,
|
||||
Error::CssAuthFailed => E_CSS_AUTH_FAILED,
|
||||
Error::AacsHostCertRejected => E_AACS_HOST_CERT_REJECTED,
|
||||
Error::AacsLibredriveUnsupported => E_AACS_LIBREDRIVE_UNSUPPORTED,
|
||||
Error::AacsVidUnavailable => E_AACS_VID_UNAVAILABLE,
|
||||
Error::AacsMkUnavailable => E_AACS_MK_UNAVAILABLE,
|
||||
Error::AacsVukNotInKeydb => E_AACS_VUK_NOT_IN_KEYDB,
|
||||
Error::KeydbConnect { .. } => E_KEYDB_CONNECT,
|
||||
Error::KeydbHttp { .. } => E_KEYDB_HTTP,
|
||||
Error::KeydbInvalid => E_KEYDB_INVALID,
|
||||
|
||||
@@ -18,4 +18,18 @@ pub(crate) trait PlatformDriver: Send {
|
||||
|
||||
/// True after successful init().
|
||||
fn is_ready(&self) -> bool;
|
||||
|
||||
/// True if the drive is currently in libredrive raw-read mode (the
|
||||
/// per-drive runtime firmware has been uploaded AND the drive
|
||||
/// confirms active mode via the `MMkv` / `LbDr` markers in the
|
||||
/// unlock response). When true the host can read sectors without
|
||||
/// AACS bus encryption and retrieve VID without cert-based mutual
|
||||
/// auth — the cert/HRL gate on the drive's standard AACS path is
|
||||
/// effectively bypassed by the alternate data path.
|
||||
///
|
||||
/// Default `false` — platforms that don't implement this mode are
|
||||
/// always reported as inactive.
|
||||
fn is_libredrive_active(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ const UNLOCK_RESPONSE_SIZE: u8 = 64;
|
||||
const VALIDATE_RESPONSE_SIZE: u8 = 4;
|
||||
const FIRMWARE_ACTIVE_OFFSET: usize = 12;
|
||||
const FIRMWARE_ACTIVE_SIG: [u8; 4] = [0x4D, 0x4D, 0x6B, 0x76];
|
||||
/// Mode-identifier marker repeated through bytes 16..64 of the unlock
|
||||
/// response on a drive whose runtime firmware is uploaded and active.
|
||||
const FIRMWARE_MODE_OFFSET: usize = 16;
|
||||
const FIRMWARE_MODE_SIG: [u8; 4] = [0x4C, 0x62, 0x44, 0x72];
|
||||
|
||||
// ── Init address (per disc type) ──────────────────────────────────────
|
||||
const INIT_ADDR_BD: u16 = 0x0100;
|
||||
@@ -47,6 +51,11 @@ pub struct Mt1959 {
|
||||
pub(crate) mode: u8,
|
||||
pub(crate) buffer_id: u8,
|
||||
pub(crate) unlocked: bool,
|
||||
/// True when the unlock response carried both the per-drive
|
||||
/// signature AND the active-mode markers (`MMkv` at [12..16],
|
||||
/// `LbDr` at [16..20]). When true the drive will accept raw-read
|
||||
/// SCSI traffic without AACS bus encryption / cert auth.
|
||||
libredrive_active: bool,
|
||||
probed: bool,
|
||||
}
|
||||
|
||||
@@ -62,6 +71,7 @@ impl Mt1959 {
|
||||
mode,
|
||||
buffer_id,
|
||||
unlocked: false,
|
||||
libredrive_active: false,
|
||||
probed: false,
|
||||
}
|
||||
}
|
||||
@@ -141,6 +151,18 @@ impl Mt1959 {
|
||||
return Err(Error::UnlockFailed);
|
||||
}
|
||||
|
||||
// Raw-read mode is active when BOTH the per-drive signature
|
||||
// matched AND the response carries the secondary `LbDr` marker
|
||||
// repeated through bytes 16..64. The active-mode signature at
|
||||
// [12..16] checked above is the primary gate; the [16..20]
|
||||
// marker is the redundant confirmation Mt1959 firmware writes
|
||||
// through the rest of the response. Requiring both before we
|
||||
// tell the AACS layer "skip the cert dance" keeps any partial
|
||||
// / corrupted response from steering us into the bypass.
|
||||
self.libredrive_active = response.len() >= FIRMWARE_MODE_OFFSET + 4
|
||||
&& response[FIRMWARE_ACTIVE_OFFSET..FIRMWARE_ACTIVE_OFFSET + 4] == FIRMWARE_ACTIVE_SIG
|
||||
&& response[FIRMWARE_MODE_OFFSET..FIRMWARE_MODE_OFFSET + 4] == FIRMWARE_MODE_SIG;
|
||||
|
||||
self.unlocked = true;
|
||||
Ok(response)
|
||||
}
|
||||
@@ -334,4 +356,135 @@ impl PlatformDriver for Mt1959 {
|
||||
fn is_ready(&self) -> bool {
|
||||
self.unlocked
|
||||
}
|
||||
|
||||
fn is_libredrive_active(&self) -> bool {
|
||||
self.libredrive_active
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::profile::{DriveProfile, Identity};
|
||||
use crate::scsi::{DataDirection, ScsiResult, ScsiTransport};
|
||||
|
||||
/// Minimal mock transport that returns a scripted response to the
|
||||
/// next `execute()` call. Only used for verifying that `do_unlock`
|
||||
/// classifies the response correctly — no general SCSI coverage.
|
||||
struct ScriptedTransport {
|
||||
response: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ScsiTransport for ScriptedTransport {
|
||||
fn execute(
|
||||
&mut self,
|
||||
_cdb: &[u8],
|
||||
_dir: DataDirection,
|
||||
data: &mut [u8],
|
||||
_timeout_ms: u32,
|
||||
) -> Result<ScsiResult> {
|
||||
let n = self.response.len().min(data.len());
|
||||
data[..n].copy_from_slice(&self.response[..n]);
|
||||
Ok(ScsiResult {
|
||||
status: 0,
|
||||
bytes_transferred: n,
|
||||
sense: [0u8; 32],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_profile(signature: [u8; 4]) -> DriveProfile {
|
||||
DriveProfile {
|
||||
identity: Identity {
|
||||
vendor_id: "TEST".into(),
|
||||
product_revision: String::new(),
|
||||
vendor_specific: String::new(),
|
||||
firmware_date: String::new(),
|
||||
},
|
||||
signature,
|
||||
firmware: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a synthetic 64-byte unlock response.
|
||||
///
|
||||
/// `mode_marker`: bytes [12..16]. Pass `FIRMWARE_ACTIVE_SIG` for the
|
||||
/// active-mode primary marker.
|
||||
/// `id_marker`: bytes [16..20] (and repeated through [20..64] in
|
||||
/// real responses; only [16..20] is checked).
|
||||
fn build_response(signature: [u8; 4], mode_marker: [u8; 4], id_marker: [u8; 4]) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 64];
|
||||
r[0..4].copy_from_slice(&signature);
|
||||
// bytes [4..12] left as zeros (version + reserved per format)
|
||||
r[12..16].copy_from_slice(&mode_marker);
|
||||
// Real firmware repeats LbDr through [16..64]; the parser only
|
||||
// checks [16..20], so we just write the marker once.
|
||||
r[16..20].copy_from_slice(&id_marker);
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_unlock_sets_libredrive_active_when_both_markers_present() {
|
||||
let sig = [0x99, 0x9E, 0xC3, 0x75];
|
||||
let response = build_response(sig, FIRMWARE_ACTIVE_SIG, FIRMWARE_MODE_SIG);
|
||||
let mut transport = ScriptedTransport { response };
|
||||
let mut mt = Mt1959::new(fixture_profile(sig), false);
|
||||
|
||||
let raw = mt.do_unlock(&mut transport).expect("unlock should succeed");
|
||||
assert_eq!(raw.len(), 64);
|
||||
assert!(mt.unlocked, "unlocked flag set after success");
|
||||
assert!(
|
||||
mt.is_libredrive_active(),
|
||||
"both MMkv and LbDr present -> libredrive_active"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_unlock_unlocked_but_not_libredrive_when_id_marker_missing() {
|
||||
// Active-mode primary marker present (so unlock passes) but the
|
||||
// secondary LbDr marker is replaced with zeros — drive isn't
|
||||
// serving raw-read traffic on this path.
|
||||
let sig = [0x99, 0x9E, 0xC3, 0x75];
|
||||
let response = build_response(sig, FIRMWARE_ACTIVE_SIG, [0u8; 4]);
|
||||
let mut transport = ScriptedTransport { response };
|
||||
let mut mt = Mt1959::new(fixture_profile(sig), false);
|
||||
|
||||
mt.do_unlock(&mut transport).expect("unlock should succeed");
|
||||
assert!(mt.unlocked);
|
||||
assert!(
|
||||
!mt.is_libredrive_active(),
|
||||
"missing LbDr marker -> raw-read not active"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_unlock_rejects_signature_mismatch() {
|
||||
let response = build_response(
|
||||
[0xAA, 0xBB, 0xCC, 0xDD],
|
||||
FIRMWARE_ACTIVE_SIG,
|
||||
FIRMWARE_MODE_SIG,
|
||||
);
|
||||
let mut transport = ScriptedTransport { response };
|
||||
let mut mt = Mt1959::new(fixture_profile([0x99, 0x9E, 0xC3, 0x75]), false);
|
||||
|
||||
let err = mt.do_unlock(&mut transport).unwrap_err();
|
||||
assert!(matches!(err, Error::SignatureMismatch { .. }));
|
||||
assert!(!mt.unlocked);
|
||||
assert!(!mt.is_libredrive_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_unlock_rejects_inactive_mode_marker() {
|
||||
// Signature matches but [12..16] is NOT MMkv -> drive is not in
|
||||
// active mode; both unlock and libredrive flag must stay false.
|
||||
let sig = [0x99, 0x9E, 0xC3, 0x75];
|
||||
let response = build_response(sig, [0u8; 4], FIRMWARE_MODE_SIG);
|
||||
let mut transport = ScriptedTransport { response };
|
||||
let mut mt = Mt1959::new(fixture_profile(sig), false);
|
||||
|
||||
let err = mt.do_unlock(&mut transport).unwrap_err();
|
||||
assert!(matches!(err, Error::UnlockFailed));
|
||||
assert!(!mt.unlocked);
|
||||
assert!(!mt.is_libredrive_active());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user