From 736f1cc73195b88bdaef913b3a25c3cf6bed73a1 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Fri, 27 Nov 2026 01:11:13 -0700 Subject: [PATCH] feat(drm): add the whole-file aes-ctr cipher and paged aac rewrite --- docs/dev/rest-api/endpoints.md | 3 +- docs/dev/service-architecture.md | 3 +- docs/getting-started/installation.md | 7 +- docs/guide/drm-and-cdm.md | 33 +- tests/core/test_clearkey_ctr.py | 376 ++++++++++++++++++ tests/core/test_paged_aac.py | 239 +++++++++++ tests/core/test_segment_pipeline.py | 10 +- tests/core/test_wire.py | 25 +- .../unit/test_server_cdm_key_verification.py | 165 +++++++- unshackle/core/api/handlers.py | 29 +- unshackle/core/drm/__init__.py | 10 +- unshackle/core/drm/clearkey_ctr.py | 144 +++++++ unshackle/core/drm/discovery.py | 13 +- unshackle/core/drm/key_resolution.py | 11 + unshackle/core/drm/paged_aac.py | 177 +++++++++ unshackle/core/import_service.py | 4 + unshackle/core/manifests/segment_pipeline.py | 4 +- unshackle/core/remote_protocol.py | 2 + unshackle/core/remote_service.py | 35 +- unshackle/core/title_source.py | 3 + unshackle/core/tracks/track.py | 7 +- unshackle/core/wire.py | 14 +- 22 files changed, 1269 insertions(+), 45 deletions(-) create mode 100644 tests/core/test_clearkey_ctr.py create mode 100644 tests/core/test_paged_aac.py create mode 100644 unshackle/core/drm/clearkey_ctr.py create mode 100644 unshackle/core/drm/paged_aac.py diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index f163fde8..31156957 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -1235,9 +1235,10 @@ A slow answer arrives as a [slow response](#slow-responses). | `track_id` / `track_ids` | Single track, or a batch of tracks. | | `challenge` | Base64 CDM challenge (proxy mode). | | `pssh` | Base64 PSSH (server-CDM mode). | -| `drm_type` | `widevine` (default) or `playready`. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. The client's value decides only when the server has no mapping for the service. | +| `drm_type` | `widevine` (default) or `playready`. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. The client's value decides only when the server has no mapping for the service. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. | | `mode` | `proxy` (default) or `server_cdm`. | | `clear_tracks` (response) | Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. | +| `file_keys` (response) | Content keys of whole-file ciphers, by track id, for a single track and for a batch. Absent when no requested track holds such a cipher. | | `vault_keys` (response) | KIDs whose content key came from a server vault, not the CDM. The client proves such a content key with a decode before it trusts it; the field is absent when every content key came from the CDM. | | Status | Error code | Meaning | diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 64772b6c..83f115b2 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -390,7 +390,7 @@ A typical `get_tracks` therefore looks like fetching the manifest text with ## DRM hooks If a track carries DRM, the framework licenses and decrypts it, but it needs your -service to talk to the platform's license server. unshackle recognizes six DRM systems: +service to talk to the platform's license server. unshackle recognizes seven DRM systems: | DRM class | System | License flow | |---|---|---| @@ -400,6 +400,7 @@ service to talk to the platform's license server. unshackle recognizes six DRM s | `ClearKey` | HLS AES-128 | content key fetched directly from a URI; no CDM, no challenge | | `MonaLisa` | Proprietary WASM DRM | keys extracted locally; no license server | | `BlowfishStripe` | Blowfish CBC stripe cipher | the service gives the per-track key; no CDM, no license server | +| `ClearKeyCTR` | AES-128-CTR over a whole file | the service gives the IV and licenses the content key at the licence step; no CDM, no license server | !!! warning "`ClearKey` vs `ClearKeyCENC`" Despite the shared prefix these are entirely different systems. `ClearKey` is HLS diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 5ee07b4c..bd9cf2d3 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -268,7 +268,7 @@ download. For example, `dovi_tool` only matters if you download Dolby Vision vid | Tool | Binary looked up | Why it is needed | | --- | --- | --- | | Bento4 (`mp4decrypt`) | `mp4decrypt` | Alternative DRM decryptor to shaka-packager | -| MP4Box (GPAC) | `MP4Box` | Muxing DTS:X Profile 2 (DTS-UHD) and MPEG-H audio, and 3D video; remuxing AC-4, MPEG-H and DTS-UHD music | +| MP4Box (GPAC) | `MP4Box` | Muxing DTS:X Profile 2 (DTS-UHD) and MPEG-H audio, and 3D video; remuxing AC-4, MPEG-H and DTS-UHD music; trimming the coder delay of AAC files in a paged container | | dovi_tool | `dovi_tool` | Dolby Vision metadata handling | | HDR10Plus_tool | `hdr10plus_tool` | HDR10+ metadata handling | | SubtitleEdit | `seconv`, `SubtitleEdit` | Subtitle conversion (the `SeConv` CLI from 5.x) | @@ -280,10 +280,13 @@ download. For example, `dovi_tool` only matters if you download Dolby Vision vid | Docker | `docker` | Gluetun VPN proxy support | | Git | `git` | Fetching and updating remote service repositories | -!!! info "MP4Box is only used for DTS:X Profile 2, MPEG-H, AC-4 music and 3D video" +!!! info "MP4Box is only used for DTS:X Profile 2, MPEG-H, AC-4 music, 3D video and paged AAC" Titles with DTS:X Profile 2 (DTS-UHD) or MPEG-H audio, or a stereoscopic 3D video track, mux to MP4; everything else muxes to MKV with `mkvmerge`. Install with `apt install gpac`. + AAC files that come in a paged container need MP4Box only to lose the coder delay of the encoder + and to declare HE-AACv2, see [DRM and CDM](../guide/drm-and-cdm.md). Without MP4Box they keep the delay. + !!! tip "SubtitleEdit specifics" unshackle looks for `seconv` first, the batch CLI shipped with SubtitleEdit 5.x, before falling back to a `SubtitleEdit` (4.x) binary. The diff --git a/docs/guide/drm-and-cdm.md b/docs/guide/drm-and-cdm.md index 6a52e29f..ed73526c 100644 --- a/docs/guide/drm-and-cdm.md +++ b/docs/guide/drm-and-cdm.md @@ -41,7 +41,7 @@ then decrypts the file with those keys. ## Supported DRM systems -unshackle implements six DRM systems. Only the first two need a device file and a +unshackle implements seven DRM systems. Only the first two need a device file and a license-server handshake. The rest are special cases. | System | Device file | License flow | Decryption | @@ -52,13 +52,15 @@ license-server handshake. The rest are special cases. | **ClearKey (HLS)**, AES-128 `EXT-X-KEY` | none | Key fetched directly from a URI or `data:` URL. No CDM, no challenge. | in-process AES-CBC | | **MonaLisa** (proprietary, WASM) | `.mld` | Ticket from the service API; keys extracted locally via WASM. No license server. | ML-Worker binary + AES-ECB, per segment | | **Blowfish stripe** | none | The service gives the per-track key. No CDM, no license server. | in-process Blowfish-CBC on every third 2048-byte chunk | +| **ClearKey (CTR)**, AES-128-CTR | none | The service gives the per-track key and IV. No CDM, no license server. | in-process AES-CTR over the whole file | -!!! warning "Two different ClearKeys" - "ClearKey (HLS)" and "ClearKey (CENC)" are entirely different systems that happen - to share a name. The HLS variant is the AES-128 content key that an `EXT-X-KEY` +!!! warning "Three different ClearKeys" + "ClearKey (HLS)", "ClearKey (CENC)" and "ClearKey (CTR)" are entirely different systems that + happen to share a name. The HLS variant is the AES-128 content key that an `EXT-X-KEY` tag references, and unshackle decrypts it in-process. The CENC variant is the W3C EME `org.w3.clearkey` scheme. It delivers keys as a JWK Set, and shaka-packager or - mp4decrypt decrypts it like Widevine. Neither involves a device file. + mp4decrypt decrypts it like Widevine. The CTR variant is one AES-CTR stream over a + whole file, with the content key and the IV that the service gives. None of them involves a device file. ### Widevine vs PlayReady @@ -472,6 +474,27 @@ license hook returns) and reads the JSON Web Key set back. You do not need a dev file. The decrypted file still goes through shaka-packager or mp4decrypt like any other CENC track, so the `decryption` setting applies. +### ClearKey over a whole file (AES-CTR) + +Some services encrypt one whole audio file with AES-128-CTR and give the content key and +the IV with the track. unshackle decrypts the file in-process after the download. There is +no device, no CDM and no license challenge. The licence step of a download or of a `--skip-dl` run licenses +the content key, so `--list` asks for none. The IV, the length of the header in front of the media and the +signature the file must start with travel with the track list. + +Over `--remote` the track list carries no content key. After the track selection the client asks the server +for the content key of each chosen track, and then it decrypts the file itself. The server licenses only for an +API key with the `server_cdm` grant for the service. Without it, or in a remote session on the server's device, the +track stops with one error before its download. A decrypted file with another +signature raises an error and stays encrypted. A decrypted file in a paged AAC container (`SpAC`) becomes an +`.m4a` file that declares HE-AACv2 and whose edit list removes the coder delay, so the file has the length of the +track. This needs [MP4Box](../getting-started/installation.md#recommended-and-optional-tools) on the machine that +decrypts, the client over `--remote`. Without it the file becomes one ADTS stream, which the mux step packs into +an `.m4a` file that keeps the coder delay. + +The client must know this cipher as well as the server: a client without it drops the DRM entry without a +log and saves the encrypted file. + ## Widevine and PlayReady on the same title A single manifest can advertise both Widevine and PlayReady. unshackle picks the CDM diff --git a/tests/core/test_clearkey_ctr.py b/tests/core/test_clearkey_ctr.py new file mode 100644 index 00000000..3949333b --- /dev/null +++ b/tests/core/test_clearkey_ctr.py @@ -0,0 +1,376 @@ +"""Tests for the AES-CTR whole-file cipher (``unshackle.core.drm.clearkey_ctr``).""" + +from __future__ import annotations + +import os +from collections.abc import Iterator +from functools import partial +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +import requests +from Cryptodome.Cipher import AES + +from tests.core.key_resolver import key_table, resolver +from tests.core.test_paged_aac import FIRST, config_record, file, header +from unshackle.core import binaries +from unshackle.core.config import config +from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED +from unshackle.core.drm import PAGED_AAC, ClearKeyCTR +from unshackle.core.drm.paged_aac import to_adts +from unshackle.core.tracks import Audio, Track +from unshackle.core.tracks import track as track_module +from unshackle.core.wire import build_tracks, reconstruct_drm, serialize_audio_track, serialize_drm + +KEY = bytes.fromhex("00112233445566778899aabbccddeeff") +IV = bytes.fromhex("72e067fbddcbcf77ebe8bc643f630d93") +MAGIC = b"OggS" + + +def ctr_encrypt(data: bytes) -> bytes: + """Reference encryption: one counter stream over the whole file.""" + return AES.new(KEY, AES.MODE_CTR, nonce=b"", initial_value=int.from_bytes(IV, "big")).encrypt(data) + + +def keyed(magic: bytes = MAGIC, skip: int = 0) -> ClearKeyCTR: + """A cipher that holds its content key from the start.""" + return ClearKeyCTR(None, IV, magic, skip, key=KEY) + + +def test_decrypt_round_trip(tmp_path: Path) -> None: + plain = MAGIC + os.urandom((1 << 20) * 3 + 123) + path = tmp_path / "track.ogg" + path.write_bytes(ctr_encrypt(plain)) + assert path.read_bytes() != plain + + ClearKeyCTR(lambda: KEY, IV, MAGIC).decrypt(path) + + assert path.read_bytes() == plain + assert list(tmp_path.iterdir()) == [path] + + +def test_hex_strings_build_the_same_cipher(tmp_path: Path) -> None: + plain = MAGIC + os.urandom(5000) + path = tmp_path / "track.ogg" + path.write_bytes(ctr_encrypt(plain)) + + ClearKeyCTR(lambda: KEY.hex(), IV.hex(), MAGIC.hex()).decrypt(path) + + assert path.read_bytes() == plain + + +def test_the_key_is_licensed_once_on_first_use(tmp_path: Path) -> None: + calls = [] + + def licence() -> bytes: + calls.append(1) + return KEY + + cipher = ClearKeyCTR(licence, IV, MAGIC) + assert cipher.key is None + + for name in ("a.ogg", "b.ogg"): + path = tmp_path / name + path.write_bytes(ctr_encrypt(MAGIC + os.urandom(100))) + cipher.decrypt(path) + + assert calls == [1] + assert cipher.key == KEY + + +def test_other_lengths_are_refused() -> None: + with pytest.raises(ValueError, match="16-byte IV"): + ClearKeyCTR(lambda: KEY, IV + IV, MAGIC) + with pytest.raises(ValueError, match="16-byte key"): + ClearKeyCTR(lambda: KEY[:15], IV, MAGIC).content_key() + + +def test_no_signature_is_refused() -> None: + with pytest.raises(ValueError, match="signature"): + ClearKeyCTR(lambda: KEY, IV, b"") + + +def test_negative_skip_is_refused() -> None: + with pytest.raises(ValueError, match="skip"): + keyed(skip=-1) + + +@pytest.mark.parametrize("header_size", [167, (1 << 20) + 167], ids=["short", "longer-than-one-chunk"]) +def test_skip_drops_a_header_in_front_of_the_media(tmp_path: Path, header_size: int) -> None: + header, plain = os.urandom(header_size), MAGIC + os.urandom((1 << 20) + 5) + path = tmp_path / "track.ogg" + path.write_bytes(ctr_encrypt(header + plain)) + + keyed(skip=header_size).decrypt(path) + + assert path.read_bytes() == plain + assert list(tmp_path.iterdir()) == [path] + + +def test_skip_past_the_end_raises_and_keeps_the_input(tmp_path: Path) -> None: + encrypted = ctr_encrypt(MAGIC + os.urandom(10)) + path = tmp_path / "track.ogg" + path.write_bytes(encrypted) + + with pytest.raises(ValueError, match="does not start with"): + keyed(skip=1 << 21).decrypt(path) + + assert path.read_bytes() == encrypted + + +def test_magic_accepts_the_expected_signature(tmp_path: Path) -> None: + path = tmp_path / "track.flac" + path.write_bytes(ctr_encrypt(b"fLaC" + os.urandom(5000))) + + keyed(magic=b"fLaC").decrypt(path) + + assert path.read_bytes().startswith(b"fLaC") + assert list(tmp_path.iterdir()) == [path] + + +TRIMMABLE = header(FIRST, total=7081, first_record=config_record(true=1000)) + FIRST + + +def test_a_paged_file_that_cannot_be_cut_becomes_one_adts_stream(tmp_path: Path) -> None: + paged = file(FIRST) + path = tmp_path / "track.m4a" + path.write_bytes(ctr_encrypt(paged)) + + keyed(PAGED_AAC).decrypt(path) + + assert path.read_bytes() == to_adts(paged) + assert path.read_bytes().startswith(b"\xff\xf1") + assert list(tmp_path.iterdir()) == [path] + + +def test_a_paged_file_without_mp4box_becomes_one_adts_stream(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(binaries, "MP4Box", None) + path = tmp_path / "track.m4a" + path.write_bytes(ctr_encrypt(TRIMMABLE)) + + keyed(PAGED_AAC).decrypt(path) + + assert path.read_bytes() == to_adts(TRIMMABLE) + assert list(tmp_path.iterdir()) == [path] + + +def test_a_paged_file_becomes_an_m4a_file_through_mp4box(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[list[str]] = [] + streams: list[bytes] = [] + + def step(args: list[str | Path], *, output: Path | None, label: str = "") -> bytes: + calls.append([str(arg) for arg in args]) + streams.append(Path(args[4][:-4]).read_bytes()) + output.write_bytes(b"M4A") + return b"" + + monkeypatch.setattr(binaries, "MP4Box", Path("MP4Box")) + monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.run_step", step) + path = tmp_path / "track.m4a" + path.write_bytes(ctr_encrypt(TRIMMABLE)) + + keyed(PAGED_AAC).decrypt(path) + + adts, output = Path(calls[0][4].removesuffix(":psx")), Path(calls[0][-1]) + assert path.read_bytes() == b"M4A" + assert streams == [to_adts(TRIMMABLE)] + assert calls == [ + [ + "MP4Box", + "-for-test", + "--moovts=-1", + "-add", + f"{adts}:psx", + "-edits", + "1=re0-1000/44100,6081/44100", + "-new", + str(output), + ] + ] + assert adts.parent == output.parent == tmp_path and adts.suffix == ".aac" and output.suffix == ".m4a" + assert list(tmp_path.iterdir()) == [path] + + +def test_a_failed_mp4box_step_leaves_one_adts_stream( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + def fail(args: list[str | Path], *, output: Path | None, label: str = "") -> bytes: + raise RuntimeError(f"{label} failed: unknown option") + + monkeypatch.setattr(binaries, "MP4Box", Path("MP4Box")) + monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.run_step", fail) + path = tmp_path / "track.m4a" + path.write_bytes(ctr_encrypt(TRIMMABLE)) + + with caplog.at_level("WARNING", logger="unshackle.core.drm.clearkey_ctr"): + keyed(PAGED_AAC).decrypt(path) + + assert path.read_bytes() == to_adts(TRIMMABLE) + assert list(tmp_path.iterdir()) == [path] + assert [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] == [ + "MP4Box failed on track.decrypted.m4a, wrote one ADTS stream" + ] + + +def test_any_failure_after_the_decrypt_keeps_only_the_input(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def full(path: Path) -> None: + raise OSError("No space left on device") + + monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.rewrite_paged", full) + encrypted = ctr_encrypt(TRIMMABLE) + path = tmp_path / "track.m4a" + path.write_bytes(encrypted) + + with pytest.raises(OSError, match="No space"): + keyed(PAGED_AAC).decrypt(path) + + assert list(tmp_path.iterdir()) == [path] and path.read_bytes() == encrypted + + +def test_a_broken_paged_file_raises_and_keeps_the_input(tmp_path: Path) -> None: + encrypted = ctr_encrypt(file(FIRST)[:-1]) + path = tmp_path / "track.m4a" + path.write_bytes(encrypted) + + with pytest.raises(ValueError, match="is truncated"): + keyed(PAGED_AAC).decrypt(path) + + assert path.read_bytes() == encrypted + assert list(tmp_path.iterdir()) == [path] + + +@pytest.mark.parametrize("start", [b"fLaX", b"XLaC", b"OggS"]) +def test_magic_mismatch_raises_and_keeps_the_input(tmp_path: Path, start: bytes) -> None: + encrypted = ctr_encrypt(start + os.urandom(5000)) + path = tmp_path / "track.flac" + path.write_bytes(encrypted) + + with pytest.raises(ValueError, match="does not start with"): + keyed(magic=b"fLaC").decrypt(path) + + assert path.read_bytes() == encrypted + assert list(tmp_path.iterdir()) == [path] + + +def test_serialize_carries_no_key_until_the_cipher_is_licensed() -> None: + cipher = ClearKeyCTR(lambda: KEY, IV, MAGIC) + + assert serialize_drm([cipher]) == [{"type": "clearkeyctr", "iv": IV.hex(), "magic": MAGIC.hex(), "skip": 0}] + assert cipher.key is None + + +def test_a_track_list_from_the_server_leaves_the_key_to_the_licence_step(tmp_path: Path) -> None: + plain = MAGIC + os.urandom(100) + rebuilt = reconstruct_drm([{"type": "clearkeyctr", "iv": IV.hex(), "magic": MAGIC.hex(), "skip": 167}]) + cipher = rebuilt[0] + assert isinstance(cipher, ClearKeyCTR) and (cipher.key, cipher.licence, cipher.skip) == (None, None, 167) + + path = tmp_path / "track.ogg" + path.write_bytes(ctr_encrypt(b"H" * 167 + plain)) + with pytest.raises(ValueError, match="no content key"): + cipher.decrypt(path) + assert path.read_bytes() != plain + + cipher.take_key(KEY) + cipher.decrypt(path) + + assert path.read_bytes() == plain + + +def test_remote_tracks_keep_the_cipher() -> None: + track = Audio( + id_="a1", + url="https://example.test/a1", + language="en", + codec=Audio.Codec.OGG, + drm=[keyed(skip=167)], + ) + + rebuilt = build_tracks({"audio": [serialize_audio_track(track, include_url=True)]}) + + drm = rebuilt.audio[0].drm[0] + assert isinstance(drm, ClearKeyCTR) + assert (drm.key, drm.iv, drm.skip, drm.magic) == (KEY, IV, 167, MAGIC) + + +@pytest.mark.parametrize("all_drm", [False, True], ids=["one-drm", "all-drm"]) +def test_url_download_decrypts_once_without_a_kid_probe( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, all_drm: bool +) -> None: + monkeypatch.setattr(config.directories, "temp", tmp_path) + monkeypatch.setattr(Track, "get_key_id", lambda *a, **k: pytest.fail("a counter-cipher file has no KID to probe")) + monkeypatch.setattr(Track, "get_init_segment", lambda *a, **k: pytest.fail("a counter-cipher file has no header")) + monkeypatch.setattr( + track_module, "assert_fragments_decrypted", lambda path: pytest.fail("a counter-cipher file has no fragments") + ) + plain = os.urandom(70000 + 5) + + def downloader(**kwargs: Any) -> Iterator[dict[str, Any]]: + (Path(kwargs["output_dir"]) / kwargs["filename"]).write_bytes(ctr_encrypt(b"H" * 167 + MAGIC + plain)) + yield {"file_downloaded": Path(kwargs["output_dir"]) / kwargs["filename"]} + + track = Audio( + id_="a1", + url="https://example.test/a1.ogg", + language="en", + codec=Audio.Codec.OGG, + drm=[ClearKeyCTR(lambda: KEY, IV, MAGIC, skip=167)], + downloader=downloader, + ) + if all_drm: + DOWNLOAD_ALL_DRM.set() + try: + track.download( + session=requests.Session(), prepare_drm=partial(lambda *a, **kw: None), progress=partial(lambda **kw: None) + ) + finally: + DOWNLOAD_CANCELLED.clear() + DOWNLOAD_ALL_DRM.clear() + + assert track.path is not None and track.path.read_bytes() == MAGIC + plain + assert track.drm is None + + +def test_the_resolver_licenses_a_lazy_cipher_at_the_licence_step() -> None: + calls = [] + + def licence() -> bytes: + calls.append(1) + return KEY + + cipher = ClearKeyCTR(licence, IV, MAGIC) + key_resolver = resolver() + track = SimpleNamespace(drm=[cipher]) + + key_resolver._prepare_drm(cipher, track, SimpleNamespace(), key_table()) + assert calls == [1] + key_resolver._prepare_drm(cipher, track, SimpleNamespace(), key_table()) + + assert calls == [1] + + +def test_the_resolver_asks_the_server_for_the_key_of_a_pending_cipher() -> None: + cipher = ClearKeyCTR(None, IV, MAGIC) + asked = [] + source = SimpleNamespace(license_file=lambda track: asked.append(track) or KEY.hex()) + + track = SimpleNamespace(drm=[cipher]) + + resolver(source=source)._prepare_drm(cipher, track, SimpleNamespace(), key_table()) + + assert asked == [track] + assert cipher.key == KEY + + +def test_a_cancelled_run_licenses_no_cipher() -> None: + from unshackle.core.constants import DownloadCancelled + + cipher = ClearKeyCTR(lambda: pytest.fail("licensed after a cancel"), IV, MAGIC) + DOWNLOAD_CANCELLED.set() + try: + with pytest.raises(DownloadCancelled): + resolver()._prepare_drm(cipher, SimpleNamespace(drm=[cipher]), SimpleNamespace(), key_table()) + finally: + DOWNLOAD_CANCELLED.clear() diff --git a/tests/core/test_paged_aac.py b/tests/core/test_paged_aac.py new file mode 100644 index 00000000..46645ea2 --- /dev/null +++ b/tests/core/test_paged_aac.py @@ -0,0 +1,239 @@ +"""Tests for the paged AAC container: its pages, the ADTS stream and the cut of an M4A file (``unshackle.core.drm.paged_aac``).""" + +from __future__ import annotations + +import struct + +import pytest + +from unshackle.core.drm.paged_aac import ( + PAGED_AAC, + adts_header, + audio_config, + checksum, + cut, + first_frame, + frame_sizes, + pages, + to_adts, +) + +HEADER_PAGE = bytes.fromhex( + "53704143800318700901006d7034614cd13b000244ac00ff1300080400eb8a08" + "00020000f47790698988807c798188788a6a9c6e8174947c7b897f778b7b7c88" + "7d7f807c8288777d7f79857789798177817c798479887a74857f837979828576" + "8076897a7d7c7e847a77916c8678867184818d72797792778c7c8277907f8479" + "7f758f67967c1d000000f03b0007200400030000000000000000c7b02a9d" +) +CONFIG = bytes.fromhex("eb8a0800") +HEADER, SHARED = 0x80, 0x01 + + +def page(flags: int, records: list[bytes], number: bytes = b"", shared: bytes = b"") -> bytes: + """One page of a paged file around ``records``: with ``shared``, each record is stored without its first byte.""" + stored = [record[len(shared) :] for record in records] + table = b"".join(bytes([255] * (len(record) // 255) + [len(record) % 255]) for record in stored) + body = PAGED_AAC + bytes([flags, len(table)]) + number + table + shared + b"".join(stored) + return body + struct.pack(" bytes: + """The first record of a header page, with the audio config at its end.""" + return ( + b"\x01\x00mp4a" + + struct.pack(" bytes: + """A header page for ``data``. + + Its records are the audio config, ``total`` samples with the byte length of ``data``, and one more that nothing reads. + """ + return page( + HEADER, + [ + config_record() if first_record is None else first_record, + b"\x02" + bytes(103) + struct.pack(" bytes: + """A paged file: a header page that declares the byte length of ``data``, then those pages.""" + return header(b"".join(data)) + b"".join(data) + + +def adts_frames(stream: bytes) -> list[bytes]: + """The frames of an ADTS stream, without their headers.""" + frames, pos = [], 0 + while pos < len(stream): + assert stream[pos : pos + 2] == b"\xff\xf1" + length = ((stream[pos + 3] & 3) << 11) | (stream[pos + 4] << 3) | (stream[pos + 5] >> 5) + frames.append(stream[pos + 7 : pos + length]) + pos += length + return frames + + +def fletcher_32(data: bytes) -> int: + """The page checksum by its definition, one word at a time.""" + total = running = 0xFFFF + for word in (int.from_bytes(data[pos : pos + 2], "little") for pos in range(0, len(data), 2)): + total = (total + word) % 0xFFFF or 0xFFFF + running = (running + total) % 0xFFFF or 0xFFFF + return running << 16 | total + + +FIRST = page(0, [b"\x01abc", b"\x00de"], number=b"\x00\x01") +LATER = page(0, [b"\x01xy"], number=b"\x00\x04") + + +def test_the_header_page_of_a_real_file_passes_its_checksum() -> None: + assert checksum(HEADER_PAGE[:-4]) == 0x9D2AB0C7 + assert checksum(b"") == 0xFFFFFFFF + + +@pytest.mark.parametrize("data", [b"\x01", b"\x01\x02\x03", bytes(6), b"\xff\xff" * 300, bytes(range(256))]) +def test_the_checksum_matches_its_definition(data: bytes) -> None: + assert checksum(data) == fletcher_32(data) + + +def test_the_header_page_of_a_real_file_names_the_rate_and_the_channels() -> None: + flags, number, records = next(pages(HEADER_PAGE)) + + assert (flags, number) == (HEADER, 0) + assert [len(record) for record in records] == [24, 112, 9] + assert audio_config(records) == (7, 1) + + +def test_the_header_page_of_a_real_file_declares_the_length_of_its_data_pages() -> None: + with pytest.raises(ValueError, match="truncated: 158 bytes of 270501"): + to_adts(HEADER_PAGE) + + +def test_the_header_page_of_a_real_file_gives_the_cut_of_its_m4a_file() -> None: + assert cut(HEADER_PAGE) == (6081, 3920204, 44100) + + +@pytest.mark.parametrize( + ("config", "true", "total", "expected"), + [ + pytest.param(CONFIG, 1000, 7081, (6081, 1000, 44100), id="fits"), + pytest.param(CONFIG, 1000, 7080, None, id="one-sample-short"), + pytest.param(CONFIG, 0, 7081, None, id="no-samples"), + pytest.param(bytes.fromhex("138800"), 1000, 7081, None, id="aac-lc"), + ], +) +def test_the_cut_needs_he_aacv2_and_a_sample_count_that_fits( + config: bytes, true: int, total: int, expected: tuple[int, int, int] | None +) -> None: + assert cut(header(FIRST, total=total, first_record=config_record(config, true=true)) + FIRST) == expected + + +def test_the_cut_reads_the_rate_of_the_header_page() -> None: + data = header(FIRST, total=7081, first_record=config_record(true=1000, rate=48000)) + FIRST + + assert cut(data) == (6081, 1000, 48000) + + +def test_no_cut_comes_from_a_header_page_without_the_sample_counts() -> None: + assert cut(page(HEADER, [config_record(), b"\x02" + bytes(7)]) + FIRST) is None + + +def test_each_frame_gets_the_adts_header_of_the_header_page() -> None: + long = b"\x01" + bytes(range(256)) * 2 + second = page(SHARED, [b"\x01xy", b"\x01z"], number=b"\x00\x03", shared=b"\x01") + + stream = to_adts(file(page(0, [b"\x01abc", long], number=b"\x00\x01"), second)) + + assert stream[:7] == bytes.fromhex("fff15c40017ffc") + assert adts_frames(stream) == [b"\x01abc", long, b"\x01xy", b"\x01z"] + + +def test_a_stored_frame_of_255_bytes_laces_as_255_then_0() -> None: + shared = page(SHARED, [b"\xff" + bytes(255)], number=b"\x00\x01", shared=b"\xff") + + assert shared[8:11] == bytes([255, 0, 255]) + assert adts_frames(to_adts(file(shared))) == [b"\xff" + bytes(255)] + + +def test_a_lacing_entry_of_255_continues_the_frame() -> None: + assert frame_sizes(bytes([255, 3, 7])) == [258, 7] + + +@pytest.mark.parametrize( + ("field", "expected"), + [ + (b"\x00\x01", (1, 2)), + (b"\x81\x00\x00", (0x10000, 3)), + (b"\xc1\x00\x00\x00", (0x1000000, 4)), + (b"\xe0\x12\x34\x56\x78", (0x12345678, 5)), + ], +) +def test_the_number_of_the_first_frame_grows_with_its_value(field: bytes, expected: tuple[int, int]) -> None: + assert first_frame(field, 0) == expected + + +def test_a_frame_too_long_for_adts_raises() -> None: + with pytest.raises(ValueError, match="too long for ADTS"): + adts_header(0x1FFF, 7, 1) + + +def test_an_empty_file_has_no_page() -> None: + assert list(pages(b"")) == [] + + +@pytest.mark.parametrize("padding", [1, 2, 3, 4, 4096]) +def test_zero_bytes_after_the_last_page_are_dropped(padding: int) -> None: + assert to_adts(file(FIRST) + bytes(padding)) == to_adts(file(FIRST)) + + +@pytest.mark.parametrize( + ("data", "reason"), + [ + pytest.param(file(FIRST, FIRST), "out of sequence", id="repeated-page"), + pytest.param(file(FIRST, LATER), "out of sequence", id="skipped-page"), + pytest.param(file(FIRST)[:-1], "is truncated", id="cut-inside-a-page"), + pytest.param(file(FIRST, LATER)[: -len(LATER)], "is truncated", id="cut-at-a-page-boundary"), + pytest.param(file(FIRST)[:-4] + bytes(4), "Checksum mismatch", id="wrong-checksum"), + pytest.param( + file(FIRST).replace(PAGED_AAC + b"\x00", PAGED_AAC + b"\x02", 1), "no valid page", id="unknown-flag" + ), + pytest.param( + file(page(HEADER, [bytes(10)], number=b"\x00\x01")), "no valid page", id="header-flag-on-a-data-page" + ), + pytest.param(FIRST + header(), "no valid page", id="no-header-on-the-first-page"), + pytest.param( + header(FIRST + bytes(20)) + FIRST + bytes(20), "no valid page", id="zeros-inside-the-declared-length" + ), + pytest.param( + file(PAGED_AAC + b"\x00\x01\x00\x01\xff" + bytes(255) + bytes(4)), + "continues past its page", + id="frame-past-the-page", + ), + pytest.param(header(FIRST, first_record=bytes(24)) + FIRST, "no AudioSpecificConfig", id="no-audio-config"), + pytest.param( + header(FIRST, first_record=config_record(bytes.fromhex("200800"))) + FIRST, + "cannot carry", + id="aac-that-adts-cannot-carry", + ), + pytest.param(header(), "no AAC frame", id="no-data-page"), + pytest.param( + file(page(0, [b"\x01" + bytes(0x1FFF)], number=b"\x00\x01")), "too long for ADTS", id="frame-too-long" + ), + pytest.param(b"OggS" + bytes(200), "no valid page", id="not-a-paged-file"), + pytest.param(header()[:-1], "runs past the end", id="truncated-header"), + pytest.param(file(FIRST) + LATER, "not zero after", id="page-after-the-declared-end"), + pytest.param(file(FIRST) + b"\x01", "not zero after", id="byte-after-the-declared-end"), + pytest.param(page(HEADER, [config_record()]) + FIRST, "declares no length", id="no-length-record"), + ], +) +def test_a_file_that_is_not_well_formed_raises(data: bytes, reason: str) -> None: + with pytest.raises(ValueError, match=reason): + to_adts(data) diff --git a/tests/core/test_segment_pipeline.py b/tests/core/test_segment_pipeline.py index 68dcd884..881a4b48 100644 --- a/tests/core/test_segment_pipeline.py +++ b/tests/core/test_segment_pipeline.py @@ -14,7 +14,7 @@ import pytest from tests.core.test_all_drm import playready, widevine from unshackle.core.constants import DOWNLOAD_CANCELLED -from unshackle.core.drm import ClearKey, ClearKeyCENC, MonaLisa, verify +from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, MonaLisa, verify from unshackle.core.events import events from unshackle.core.manifests.segment_pipeline import ( RollingMerge, @@ -199,7 +199,7 @@ def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path): check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type] -WV, PR, CKC, ML, AES = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey" +WV, PR, CKC, ML, AES, CTR = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey", "ClearKeyCTR" PSSH_KID = UUID(hex="22222222222222222222222222222222") PROBED_KID = UUID(hex="33333333333333333333333333333333") URL, DASH_, HLS_, ISM_ = (Track.Descriptor.URL, Track.Descriptor.DASH, Track.Descriptor.HLS, Track.Descriptor.ISM) @@ -216,6 +216,8 @@ def make_drm(system: str, monkeypatch: pytest.MonkeyPatch) -> Any: if system == ML: monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None) return MonaLisa("EXAMPLE", Path("unused.mld")) + if system == CTR: + return ClearKeyCTR(None, bytes(16), b"OggS") return ClearKey(key=bytes(16)) @@ -224,11 +226,11 @@ def licence_calls(tmp_path: Path) -> tuple[DownloadContext, list[tuple[Any, Any] return make_ctx(tmp_path, license_widevine=lambda drm, track_kid: calls.append((drm, track_kid))), calls -LICENSED = {URL: {WV, PR, CKC}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}} +LICENSED = {URL: {WV, PR, CKC, CTR}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}} @pytest.mark.parametrize("descriptor", list(LICENSED), ids=lambda d: d.name) -@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES]) +@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES, CTR]) def test_the_licence_step_licenses_the_systems_each_manifest_kind_licensed(tmp_path, monkeypatch, descriptor, system): ctx, calls = licence_calls(tmp_path) drm = make_drm(system, monkeypatch) diff --git a/tests/core/test_wire.py b/tests/core/test_wire.py index 2646adaf..8ec2d406 100644 --- a/tests/core/test_wire.py +++ b/tests/core/test_wire.py @@ -21,7 +21,7 @@ from tests.core.test_zero_kid_fallback import _playready_pssh from unshackle.commands.dl import dl from unshackle.core import wire from unshackle.core.config import config -from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine +from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine from unshackle.core.import_service import ImportService from unshackle.core.titles import Episode, Movie, Song from unshackle.core.titles.music import SONG_FIELDS @@ -58,6 +58,7 @@ VIDEO_KID = UUID("00112233-4455-6677-8899-aabbccddeeff") AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100") VIDEO_KEY = "0123456789abcdef0123456789abcdef" BLOWFISH_KEY = bytes(range(16)) +CTR_CIPHER = ClearKeyCTR(None, bytes(range(16, 32)), b"OggS", skip=7, key=bytes(range(16))) class EXAMPLE: @@ -995,11 +996,28 @@ def test_build_tracks_attaches_drm_preference_and_attachments() -> None: assert [(a.name, a.url) for a in tracks.attachments] == [("P", "https://img.example/p.jpg")] +def every_drm() -> list: + return [ + widevine(VIDEO_KID, keys=True), + playready(VIDEO_KID, AUDIO_KID), + BlowfishStripe(BLOWFISH_KEY), + CTR_CIPHER, + clearkey(), + ] + + def test_rest_drm_of_each_system() -> None: - drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()] + drm = every_drm() assert serialize_drm(drm) == [ *REST_VIDEO["drm"], {"type": "blowfishstripe", "key": "000102030405060708090a0b0c0d0e0f"}, + { + "type": "clearkeyctr", + "key": BLOWFISH_KEY.hex(), + "iv": bytes(range(16, 32)).hex(), + "magic": "4f676753", + "skip": 7, + }, {"type": "clearkeycenc", "kids": ["00112233-4455-6677-8899-aabbccddeeff"]}, ] @@ -1023,12 +1041,13 @@ def test_export_drm_of_each_system() -> None: def test_reconstruct_rest_drm() -> None: - drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()] + drm = every_drm() rebuilt = reconstruct_drm(json_copy(serialize_drm(drm))) assert [drm_fields(d) for d in rebuilt] == [ WIDEVINE_FIELDS, PLAYREADY_FIELDS, {"class": "BlowfishStripe", "kids": [], "content_keys": {}, "key": "000102030405060708090a0b0c0d0e0f"}, + {"class": "ClearKeyCTR", "kids": [], "content_keys": {}}, ] diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index 1343d217..de999b58 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -10,20 +10,22 @@ import json from types import SimpleNamespace from uuid import UUID +import click import pytest -from tests.remote.key_source import remote_keys +from tests.remote.key_source import one_title, remote_keys from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.drm import BlowfishStripe +from unshackle.core.drm import BlowfishStripe, ClearKeyCTR from unshackle.core.drm.cenc import drm_stub -from unshackle.core.remote_service import RemoteService +from unshackle.core.remote_service import RemoteError, RemoteService pytestmark = pytest.mark.unit KID = UUID("161219ec3df64e0eadbb3827c0ccc46d") CDM_KID = UUID("43de497c6d1945f49acc2951696ec628") +KEYED_CIPHER = ClearKeyCTR(None, bytes(range(16, 32)), b"OggS", key=bytes(16)) def remote_service() -> RemoteService: @@ -205,8 +207,12 @@ async def test_batch_asks_again_when_a_cached_vault_answer_lacks_the_track_kid(m assert payload["keys"]["c"] == {KID.hex: "v", CDM_KID.hex: "c"} -@pytest.mark.parametrize("drm", [["drm"], []], ids=["with-drm", "clear"]) -def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm): +@pytest.mark.parametrize( + ("drm", "head"), + [(["drm"], b"head"), ([], None), ([BlowfishStripe(bytes(16))], None), ([KEYED_CIPHER], None)], + ids=["with-drm", "clear", "stripe", "ctr"], +) +def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm, head): from unshackle.core.tracks import Video fetched: list = [] @@ -218,9 +224,9 @@ def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm): get_init_segment=lambda session: fetched.append(session) or b"head", ) - head = handlers.fetch_init_segment(track, "svc-session") - - assert (head, fetched) == ((b"head", ["svc-session"]) if drm else (None, [])) + assert (handlers.fetch_init_segment(track, "svc-session"), fetched) == ( + (head, ["svc-session"]) if head else (None, []) + ) async def test_server_tells_a_remote_vault_only_when_it_served_the_pair(monkeypatch, session): @@ -259,6 +265,67 @@ def test_resolve_server_keys_does_not_warn_for_clear_tracks(monkeypatch): assert warnings == ["Server CDM returned no content keys for track simplenamespace (v-1)"] +def test_resolve_server_keys_takes_the_key_of_a_whole_file_cipher(): + """The server licensed the track's whole-file cipher: the client takes its key and keeps the cipher.""" + svc = remote_service() + svc.log = SimpleNamespace(warning=lambda msg, *a, **k: pytest.fail(msg), debug=lambda *a, **k: None) + svc._server_cdm = True + svc.drain_server_logs = lambda: None + svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "file_keys": {"v-1": "aa" * 16}}) + cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS") + track = SimpleNamespace(id="v-1", drm=[cipher]) + + svc.resolve_server_keys(one_title(track)) + + assert track.drm == [cipher] and cipher.key == bytes.fromhex("aa" * 16) + + +def test_license_file_asks_the_server_for_the_key_of_a_whole_file_cipher(): + """A whole-file cipher can only be licensed by the service on the server.""" + svc = remote_service() + svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None) + svc._server_cdm = True + sent = [] + svc.client = SimpleNamespace(post=lambda ep, data, **kw: sent.append(data) or {"file_keys": {"v-1": "bb" * 16}}) + cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS") + track = SimpleNamespace(id="v-1", drm=[cipher]) + + assert svc.license_file(track) == "bb" * 16 + + assert sent == [{"mode": "server_cdm", "drm_type": "clearkeyctr", "track_id": "v-1"}] + + +@pytest.mark.parametrize( + ("grants", "answer", "message"), + [ + ({"_server_cdm": False}, None, "needs a server licence"), + ({"_local_vaults_only": True}, None, "needs a server licence"), + ({}, {"keys": {}}, "sent no content key"), + ({}, RemoteError("Content key tool not found: tool", "SERVICE_ERROR"), "Content key tool not found"), + ], + ids=["no-grant", "server-device", "no-key", "refused"], +) +def test_a_cipher_the_server_does_not_license_raises(grants, answer, message): + """A whole-file cipher the server gives no key for stops the track with one DRM error before its download.""" + svc = remote_service() + svc._server_cdm = True + for name, value in grants.items(): + setattr(svc, name, value) + + def post(ep, data, **kw): + if isinstance(answer, BaseException): + raise answer + return answer if answer is not None else pytest.fail("asked the server") + + svc.client = SimpleNamespace(post=post) + cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS") + + with pytest.raises(click.ClickException, match=message) as stopped: + svc.license_file(SimpleNamespace(id="v-1", drm=[cipher])) + + assert stopped.value.error_code == "DRM_ERROR" + + def resolve(manifest_drm, drm_type="widevine"): """Run resolve_server_keys for one track the server answers with its own key and a sibling.""" svc = remote_service() @@ -324,10 +391,11 @@ def test_a_cdm_licence_unflags_a_pair_a_client_reported(monkeypatch, tmp_path): assert local.get_key(KID, "SVC") == "ab" * 16 -async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch): - """A track whose only DRM needs no licence goes to clear_tracks and keeps its DRM for the client.""" - track = SimpleNamespace(id="aud", drm=[BlowfishStripe(bytes(16))]) +async def batch_answer(monkeypatch, track, vault_only=False, request=None, server_device=False): + """The server's licence answer for one track, with every CDM call stubbed out.""" session = session_entry(service_tag="SVC", tracks={"aud": track}) + session.server_cdm, session.server_vault = not vault_only, vault_only + session.server_device = server_device async def validated(sid, req): return session @@ -340,13 +408,80 @@ async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch): monkeypatch.setattr(handlers, "fetch_init_segment", lambda track, sess: None) monkeypatch.setattr(handlers, "handle_single_server_cdm", lambda *a, **k: pytest.fail("licensed a clear track")) monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False) - resp = await handlers.session_license_handler( - {"mode": "server_cdm", "track_ids": ["aud"], "drm_type": "widevine"}, "sess", None + request or {"mode": "server_cdm", "track_ids": ["aud"], "drm_type": "widevine"}, "sess", None ) + return json.loads(resp.body) - assert json.loads(resp.body)["clear_tracks"] == ["aud"] - assert isinstance(track.drm[0], BlowfishStripe) + +async def test_a_stripe_cipher_that_holds_its_key_is_never_licensed(monkeypatch): + """A track whose only DRM is a stripe cipher that holds its key is named as clear and licensed by nothing.""" + cipher = BlowfishStripe(bytes(16)) + track = SimpleNamespace(id="aud", drm=[cipher]) + + body = await batch_answer(monkeypatch, track) + + assert body == {"keys": {}, "clear_tracks": ["aud"]} + assert track.drm[0] is cipher + + +async def test_the_server_batch_licenses_a_cipher_that_holds_no_key(monkeypatch): + """A track whose whole-file cipher holds no key yet is licensed on the server and answered under file_keys.""" + cipher = ClearKeyCTR(lambda: "aa" * 16, bytes(range(16)), b"OggS") + track = SimpleNamespace(id="aud", drm=[cipher]) + + body = await batch_answer(monkeypatch, track) + + assert (body["keys"], body["file_keys"], "clear_tracks" in body) == ({}, {"aud": "aa" * 16}, False) + assert cipher.key == bytes.fromhex("aa" * 16) + + +async def test_the_server_batch_answers_a_cipher_that_already_holds_its_key(monkeypatch): + """A track the server licensed before answers its key again and licenses nothing.""" + cipher = ClearKeyCTR(lambda: pytest.fail("licensed a second time"), bytes(range(16)), b"OggS") + cipher.take_key("dd" * 16) + track = SimpleNamespace(id="aud", drm=[cipher]) + + body = await batch_answer(monkeypatch, track) + + assert (body["file_keys"], "clear_tracks" in body) == ({"aud": "dd" * 16}, False) + + +@pytest.mark.parametrize("refusal", ["vault_only", "server_device"]) +async def test_a_session_without_live_licences_licenses_no_cipher(monkeypatch, refusal): + """A session the server makes no live licence for gets no key of a whole-file cipher and no clear mark.""" + cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS") + track = SimpleNamespace(id="aud", drm=[cipher]) + + body = await batch_answer(monkeypatch, track, **{refusal: True}) + + assert body == {"keys": {}} + + +@pytest.mark.parametrize("refusal", ["vault_only", "server_device"]) +async def test_one_licence_request_refuses_a_cipher_without_live_licences(monkeypatch, refusal): + """The single-track route answers FORBIDDEN for a cipher with no key in a session without live licences.""" + cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS") + track = SimpleNamespace(id="aud", drm=[cipher]) + request = {"mode": "server_cdm", "track_id": "aud", "drm_type": "clearkeyctr"} + + with pytest.raises(APIError) as refused: + await batch_answer(monkeypatch, track, request=request, **{refusal: True}) + + assert refused.value.error_code == "FORBIDDEN" + + +@pytest.mark.parametrize("mode", ["server_cdm", "proxy"]) +async def test_one_licence_request_answers_the_key_of_a_cipher(monkeypatch, mode): + """The single-track licence route answers the key of a whole-file cipher, licensed or not, and calls no CDM.""" + cipher = ClearKeyCTR(lambda: "bb" * 16, bytes(range(16)), b"OggS") + if mode == "proxy": + cipher.take_key("cc" * 16) + track = SimpleNamespace(id="aud", drm=[cipher]) + + body = await batch_answer(monkeypatch, track, request={"mode": mode, "track_id": "aud", "drm_type": "clearkeyctr"}) + + assert body == {"file_keys": {"aud": ("cc" if mode == "proxy" else "bb") * 16}} def test_the_server_licence_drops_a_null_key(): diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index fd6a7047..213faca9 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -49,7 +49,7 @@ from unshackle.core.dl_options import ( DEFAULT_DOWNLOAD_PARAMS, forwarded_dl_params, ) -from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids +from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh from unshackle.core.launch import served_context from unshackle.core.manifests.snapshot import capture @@ -4210,6 +4210,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques all_keys: dict[str, dict[str, str]] = {} vault_keys: list[str] = [] clear_tracks: list[str] = [] + file_keys: dict[str, str] = {} drm_types: dict[str, str] = {} keys_by_pssh: dict[tuple, dict[str, str]] = {} shared: dict[str, Any] = {} @@ -4298,7 +4299,15 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques svc_session = getattr(service, "session", None) init_data = fetch_init_segment(track, svc_session) ensure_track_drm(track, svc_session, init_data) - if not track.drm or all(isinstance(d, BlowfishStripe) for d in track.drm): + cipher = whole_file_cipher(track) + if cipher is not None: + if not (vault_only or session.server_device): + try: + file_keys[tid] = cipher.content_key().hex() + except (Exception, SystemExit) as e: + warn(f"Failed to license track {track_log_label(track)}: {redact_all(str(e))}") + continue + if not track.drm or all(isinstance(d, WHOLE_FILE_DRM) for d in track.drm): log.info(f"Track {track_log_label(track)} needs no licence, so it has no keys to resolve") clear_tracks.append(tid) continue @@ -4356,6 +4365,8 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques response = LicenseReply(keys=all_keys) if clear_tracks: response["clear_tracks"] = clear_tracks + if file_keys: + response["file_keys"] = file_keys if vault_keys: response["vault_keys"] = vault_keys if actual_drm_type: @@ -4381,6 +4392,20 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques title = find_title_for_track(track_id, session) service = session.service_instance + cipher = whole_file_cipher(track) + if cipher is not None and (mode == "server_cdm" or cipher.key is not None): + if (vault_only or session.server_device) and cipher.key is None: + raise APIError( + APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service" + ) + try: + key = cipher.content_key().hex() + except Exception as e: + raise APIError( + APIErrorCode.SERVICE_ERROR, redact_all(str(e)) or "Could not license the track" + ) from None + return web.json_response(LicenseReply(file_keys={track_id: key})) + pssh_b64 = data.get("pssh") if pssh_b64 or mode == "server_cdm": ensure_track_drm(track, getattr(service, "session", None)) diff --git a/unshackle/core/drm/__init__.py b/unshackle/core/drm/__init__.py index 8b222083..74156304 100644 --- a/unshackle/core/drm/__init__.py +++ b/unshackle/core/drm/__init__.py @@ -5,13 +5,17 @@ from unshackle.core.drm.blowfish_stripe import BlowfishStripe from unshackle.core.drm.cenc import PLACEHOLDER_KIDS from unshackle.core.drm.clearkey import ClearKey from unshackle.core.drm.clearkey_cenc import ClearKeyCENC +from unshackle.core.drm.clearkey_ctr import ClearKeyCTR, whole_file_cipher from unshackle.core.drm.monalisa import MonaLisa +from unshackle.core.drm.paged_aac import PAGED_AAC from unshackle.core.drm.playready import PlayReady from unshackle.core.drm.widevine import Widevine from unshackle.core.vault import is_null_key -# BlowfishStripe stays out: the licensing paths typed on DRM_T never receive a DRM that needs no licence +# BlowfishStripe stays out: it holds its key from the start, so no licensing path receives it DRM_T = ClearKey | ClearKeyCENC | Widevine | PlayReady | MonaLisa +# A whole-file cipher has no KID to probe and no fragment to check +WHOLE_FILE_DRM = (BlowfishStripe, ClearKeyCTR) def drop_null_keys(drm: Any) -> None: @@ -38,10 +42,14 @@ __all__ = ( "BlowfishStripe", "ClearKey", "ClearKeyCENC", + "ClearKeyCTR", "Widevine", "PlayReady", "MonaLisa", + "PAGED_AAC", "DRM_T", + "WHOLE_FILE_DRM", + "whole_file_cipher", "drop_null_keys", "is_null_key", "real_kids", diff --git a/unshackle/core/drm/clearkey_ctr.py b/unshackle/core/drm/clearkey_ctr.py new file mode 100644 index 00000000..b11a9c6f --- /dev/null +++ b/unshackle/core/drm/clearkey_ctr.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import logging +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from Cryptodome.Cipher import AES + +from unshackle.core import binaries +from unshackle.core.drm.paged_aac import PAGED_AAC, cut, to_adts +from unshackle.core.utilities import log_event +from unshackle.core.utils.subprocess import run_step + +log = logging.getLogger(__name__) + + +class ClearKeyCTR: + """AES-128-CTR over a whole file: the service gives the IV and returns the content key through ``licence``. + + The key resolver asks ``licence`` at the licence step of a download or of a `--skip-dl` run, so listing tracks costs no request. + A cipher built with ``key`` holds its content key from the start. + ``magic`` is the signature the decrypted file must start with; a mismatch raises and keeps the input. + ``skip`` drops that many decrypted bytes from the start of the file: a header that sits in front of the media. + ``rewrite_paged`` rewrites a decrypted file in the paged AAC container (``PAGED_AAC``). + """ + + def __init__( + self, + licence: Callable[[], bytes | str] | None, + iv: bytes | str, + magic: bytes | str, + skip: int = 0, + key: bytes | str | None = None, + ) -> None: + self.iv: bytes = bytes.fromhex(iv) if isinstance(iv, str) else iv + self.magic: bytes = bytes.fromhex(magic) if isinstance(magic, str) else magic + if len(self.iv) != 16: + raise ValueError(f"ClearKeyCTR needs a 16-byte IV, got {len(self.iv)}") + if not self.magic: + raise ValueError("ClearKeyCTR needs the signature of the decrypted file") + if skip < 0: + raise ValueError(f"ClearKeyCTR needs a skip of 0 or more, got {skip}") + self.licence: Callable[[], bytes | str] | None = licence + self.skip: int = skip + self.key: bytes | None = None + if key is not None: + self.take_key(key) + + def take_key(self, key: bytes | str) -> bytes: + """Hold and return a content key: the one the licence callback returned, or one another source licensed.""" + key = bytes.fromhex(key) if isinstance(key, str) else key + if len(key) != 16: + raise ValueError(f"ClearKeyCTR needs a 16-byte key, got {len(key)}") + self.key = key + return key + + def content_key(self) -> bytes: + """The content key, licensed on first use.""" + if self.key is not None: + return self.key + if self.licence is None: + raise ValueError("ClearKeyCTR holds no content key: none was licensed") + return self.take_key(self.licence()) + + def decrypt(self, path: Path) -> None: + """Decrypt the file to a new file that then replaces it. + + The dropped header goes through the cipher too, so the keystream stays aligned with the file. + """ + if not path or not path.exists(): + raise ValueError("Tried to decrypt a file that does not exist.") + key = self.content_key() + log_event( + "drm_decrypt", + level="DEBUG", + message=f"Decrypting {path.name} with AES-CTR", + drm_type="ClearKeyCTR", + file=path.name, + ) + cipher = AES.new(key, AES.MODE_CTR, nonce=b"", initial_value=int.from_bytes(self.iv, "big")) + decrypted_path = path.with_suffix(f".decrypted{path.suffix}") + try: + with path.open("rb") as src, decrypted_path.open("wb") as dst: + cipher.decrypt(src.read(self.skip)) + while chunk := src.read(1 << 20): + dst.write(cipher.decrypt(chunk)) + with decrypted_path.open("rb") as decrypted: + start = decrypted.read(len(self.magic)) + if start != self.magic: + raise ValueError(f"Decrypted {path.name} does not start with {self.magic!r}") + if self.magic == PAGED_AAC: + rewrite_paged(decrypted_path) + except BaseException: + decrypted_path.unlink(missing_ok=True) + raise + decrypted_path.replace(path) + + +def rewrite_paged(path: Path) -> None: + """Replace a decrypted paged AAC file with the M4A file MP4Box makes of it, or with one ADTS stream. + + The M4A file declares HE-AACv2, and its edit list skips the coder delay and ends at the sample count of the header + page. Without MP4Box, or when its step fails, the file is one ADTS stream, which declares AAC-LC. + """ + data = path.read_bytes() + stream = to_adts(data) + tool, timing = binaries.MP4Box, cut(data) + if tool and timing: + delay, true, rate = timing + adts, output = path.with_suffix(".paged.aac"), path.with_suffix(".paged.m4a") + try: + adts.write_bytes(stream) + run_step( + [ + tool, + "-for-test", + "--moovts=-1", + "-add", + f"{adts}:psx", + "-edits", + f"1=re0-{true}/{rate},{delay}/{rate}", + "-new", + output, + ], + output=output, + label="paged AAC to M4A", + ) + output.replace(path) + return + except (OSError, RuntimeError) as error: + log.warning(f"MP4Box failed on {path.name}, wrote one ADTS stream") + log.debug(error) + finally: + adts.unlink(missing_ok=True) + output.unlink(missing_ok=True) + if not tool: + log.debug(f"MP4Box not found, {path.name} stays one ADTS stream") + path.write_bytes(stream) + + +def whole_file_cipher(track: Any) -> ClearKeyCTR | None: + """The whole-file cipher of a track, with or without a content key.""" + return next((d for d in getattr(track, "drm", None) or [] if isinstance(d, ClearKeyCTR)), None) diff --git a/unshackle/core/drm/discovery.py b/unshackle/core/drm/discovery.py index e97ad995..420d9e4c 100644 --- a/unshackle/core/drm/discovery.py +++ b/unshackle/core/drm/discovery.py @@ -5,6 +5,7 @@ from __future__ import annotations import logging from typing import Any +from unshackle.core.drm import WHOLE_FILE_DRM from unshackle.core.drm.playready import PlayReady from unshackle.core.drm.widevine import Widevine from unshackle.core.manifests import DASH, ISM @@ -28,14 +29,22 @@ def track_pssh(track: Any, drm_type: str, drm: Any = None) -> str | None: def fetch_init_segment(track: Any, session: Any = None) -> bytes | None: - """The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails.""" + """The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails. + + A track whose DRM is all whole-file ciphers has no KID to read, so its head is not fetched. + """ session = getattr(track, "session", None) or session if session is None: return None dash = (getattr(track, "data", None) or {}).get("dash") or {} if not all(dash.get(k) is not None for k in ("period", "adaptation_set", "representation", "manifest")): - if getattr(track, "descriptor", None) is not Track.Descriptor.URL or not getattr(track, "drm", None): + drm = getattr(track, "drm", None) + if ( + getattr(track, "descriptor", None) is not Track.Descriptor.URL + or not drm + or all(isinstance(d, WHOLE_FILE_DRM) for d in drm) + ): return None try: return track.get_init_segment(session=session) diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py index 3c411eca..a815ae8a 100644 --- a/unshackle/core/drm/key_resolution.py +++ b/unshackle/core/drm/key_resolution.py @@ -28,6 +28,7 @@ from unshackle.core.drm import ( DRM_T, ClearKey, ClearKeyCENC, + ClearKeyCTR, MonaLisa, PlayReady, Widevine, @@ -829,6 +830,16 @@ class ContentKeyResolver: ``force`` skips the content keys of earlier tracks in this run. The CDM then licenses again for each KID the DRM holds no content key for. """ + if isinstance(drm, ClearKeyCTR): + if drm.key is None: + with self.LICENCE_LOCK: + if DOWNLOAD_CANCELLED.is_set(): + raise DownloadCancelled() + if self.source is None: + drm.content_key() + else: + drm.take_key(self.source.license_file(track)) + return if not drm: return remote = self.source diff --git a/unshackle/core/drm/paged_aac.py b/unshackle/core/drm/paged_aac.py new file mode 100644 index 00000000..5746ffa0 --- /dev/null +++ b/unshackle/core/drm/paged_aac.py @@ -0,0 +1,177 @@ +"""A decrypted whole file in a paged AAC container: its pages, the ADTS stream that players and FFmpeg read, and the cut of an M4A file.""" + +from __future__ import annotations + +import struct +from collections.abc import Iterator +from itertools import accumulate + +PAGED_AAC = b"SpAC" +HEADER, SHARED = 0x80, 0x01 +CODER_DELAY = 6081 + + +def checksum(data: bytes) -> int: + """The Fletcher-32 of a page: the sum of its 16-bit little-endian words and of their running sums, both from 0xFFFF.""" + words = [word for (word,) in struct.iter_unpack(" tuple[int, int]: + """The number of the first frame of a page and the length of its field: big-endian, with the length in its first byte.""" + field = data[pos : pos + 5] + if len(field) < 2: + raise ValueError("The paged file ends inside the number of a page") + lead = field[0] + if lead < 0x80: + size, number = 2, lead + elif lead < 0xC0: + size, number = 3, lead & 0x3F + elif lead < 0xE0: + size, number = 4, lead & 0x1F + else: + size, number = 5, 0 + if len(field) < size: + raise ValueError("The paged file ends inside the number of a page") + return number << (8 * (size - 1)) | int.from_bytes(field[1:size], "big"), size + + +def frame_sizes(table: bytes) -> list[int]: + """The sizes that the lacing table of a page lists: an entry of 255 continues a frame, any other entry ends it.""" + sizes: list[int] = [] + pending = 0 + for entry in table: + pending += entry + if entry < 255: + sizes.append(pending) + pending = 0 + if pending: + raise ValueError("A frame of the paged file continues past its page") + return sizes + + +def pages_end(data: bytes, header_end: int, records: list[bytes]) -> int: + """Where the data pages end: the header page plus the byte length that its second record declares. + + The file must hold every page, and only zero bytes may follow the last one. + """ + record = records[1] if len(records) > 1 else b"" + if len(record) < 5 or record[0] != 2: + raise ValueError("The second record of the header page of the paged file declares no length") + end = header_end + struct.unpack(" len(data): + raise ValueError(f"The paged file is truncated: {len(data)} bytes of {end}") + if data[end:].strip(b"\0"): + raise ValueError( + f"The paged file holds {len(data) - end} bytes that are not zero after its last page at offset {end}" + ) + return end + + +def pages(data: bytes) -> Iterator[tuple[int, int, list[bytes]]]: + """Yield the flags, the number of the first frame (0 for the header page) and the frames of each page. + + The header page declares the byte length of the data pages: they must end exactly where ``pages_end`` says. + A page with unknown flags, a truncated page and a page that fails its checksum raise ``ValueError``. + """ + pos = 0 + stop = len(data) + while pos < stop: + head = data[pos : pos + 6] + flags = head[4] if len(head) == 6 else -1 + if len(head) < 6 or head[:4] != PAGED_AAC or flags & ~(HEADER | SHARED) or bool(flags & HEADER) != (pos == 0): + raise ValueError(f"The paged file holds no valid page at offset {pos}") + cursor = pos + 6 + number = 0 + if not flags & HEADER: + number, size = first_frame(data, cursor) + cursor += size + count = head[5] + sizes = frame_sizes(data[cursor : cursor + count]) + cursor += count + shared = data[cursor : cursor + 1] if flags & SHARED else b"" + cursor += len(shared) + end = cursor + sum(sizes) + 4 + if end > stop: + raise ValueError(f"The page at offset {pos} of the paged file runs past the end of the pages") + if checksum(data[pos : end - 4]) != int.from_bytes(data[end - 4 : end], "little"): + raise ValueError(f"Checksum mismatch on the page at offset {pos} of the paged file") + frames: list[bytes] = [] + for size in sizes: + frames.append(shared + data[cursor : cursor + size]) + cursor += size + yield flags, number, frames + pos = end + if flags & HEADER: + stop = pages_end(data, pos, frames) + + +def cut(data: bytes) -> tuple[int, int, int] | None: + """The cut of the M4A file made from a paged file: the coder delay, the sample count and the rate that its header page names. + + ``CODER_DELAY`` is the delay of the HE-AACv2 coder. None unless the audio is HE-AACv2 and the cut fits its samples. + """ + records = next(pages(data), (0, 0, []))[2] + first = records[0] if records else b"" + second = records[1] if len(records) > 1 else b"" + if len(first) < 21 or first[20] >> 3 != 29 or len(second) < 108: + return None + true, rate = struct.unpack_from(" tuple[int, int]: + """The sampling rate index and the channel configuration that the first record of the header page names.""" + record = records[0] if records else b"" + config = record[20:] + length = struct.unpack_from("= 20 else -1 + if record[:6] != b"\x01\x00mp4a" or length != len(config) or length < 3: + raise ValueError("The header page of the paged file holds no AudioSpecificConfig") + kind, rate, channels = config[0] >> 3, ((config[0] & 7) << 1) | (config[1] >> 7), (config[1] >> 3) & 0xF + if kind not in (2, 5, 29) or rate > 12 or not 1 <= channels <= 7: + raise ValueError( + f"The paged file holds AAC that ADTS cannot carry: object type {kind}, rate index {rate}, {channels} channels" + ) + return rate, channels + + +def adts_header(size: int, rate: int, channels: int) -> bytes: + """The 7-byte ADTS header of one AAC-LC frame: SBR and PS stay implicit, as ADTS cannot name them.""" + length = size + 7 + if length > 0x1FFF: + raise ValueError(f"An AAC frame of {size} bytes is too long for ADTS") + return bytes( + ( + 0xFF, + 0xF1, + 1 << 6 | rate << 2 | channels >> 2, + (channels & 3) << 6 | length >> 11, + length >> 3 & 0xFF, + (length & 7) << 5 | 0x1F, + 0xFC, + ) + ) + + +def to_adts(data: bytes) -> bytes: + """Return one ADTS stream: a 7-byte header before every AAC frame of the paged file.""" + out: list[bytes] = [] + rate = channels = 0 + expected = 1 + for flags, number, frames in pages(data): + if flags & HEADER: + rate, channels = audio_config(frames) + continue + if number != expected: + raise ValueError( + f"The page that starts at frame {number} of the paged file is out of sequence: frame {expected} is due" + ) + expected += len(frames) + out.extend(adts_header(len(frame), rate, channels) + frame for frame in frames) + if expected == 1: + raise ValueError("The paged file holds no AAC frame") + return b"".join(out) diff --git a/unshackle/core/import_service.py b/unshackle/core/import_service.py index f465d4cc..d74a09cc 100644 --- a/unshackle/core/import_service.py +++ b/unshackle/core/import_service.py @@ -704,6 +704,10 @@ class ImportService(TitleSource): """Raise the error that names the KIDs of ``track`` neither the export nor a vault holds.""" raise self.missing_key(track) + def license_file(self, track: AnyTrack) -> str: + """Raise the error that names the track: an export holds no content key of a whole-file cipher.""" + raise self.missing_key(track) + def vault_source(self, kid: UUID, key: str) -> None: """Always None: no server vault serves an import.""" return None diff --git a/unshackle/core/manifests/segment_pipeline.py b/unshackle/core/manifests/segment_pipeline.py index 36631943..c845333a 100644 --- a/unshackle/core/manifests/segment_pipeline.py +++ b/unshackle/core/manifests/segment_pipeline.py @@ -16,7 +16,7 @@ from typing import Any, BinaryIO from uuid import UUID from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack -from unshackle.core.drm import DRM_T, ClearKeyCENC, MonaLisa, PlayReady, Widevine +from unshackle.core.drm import DRM_T, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine from unshackle.core.drm.segment_decrypt import SegmentDecrypter from unshackle.core.drm.verify import decrypt_track from unshackle.core.events import events @@ -96,7 +96,7 @@ def licensing(ctx: DownloadContext) -> Iterator[None]: LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = { - Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC), + Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC, ClearKeyCTR), Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC), Track.Descriptor.HLS: (Widevine, PlayReady, MonaLisa), Track.Descriptor.ISM: (Widevine, PlayReady), diff --git a/unshackle/core/remote_protocol.py b/unshackle/core/remote_protocol.py index 45dde868..f1a20cd6 100644 --- a/unshackle/core/remote_protocol.py +++ b/unshackle/core/remote_protocol.py @@ -201,10 +201,12 @@ class LicenseReply(TypedDict, total=False): ``keys`` maps KID to content key for one ``track_id``, and track id to that map for ``track_ids``. A capped track gets no content keys: ``capped_tracks`` holds its refusal details, ``reason`` and ``max_height``. + ``file_keys`` maps track id to the content key the server licensed for a track's whole-file cipher. """ license: str | None keys: dict[str, Any] + file_keys: dict[str, str] vault_keys: list[str] clear_tracks: list[str] drm_type: str diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index d37d8301..70ef9782 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -44,7 +44,7 @@ from unshackle.core.console import SyncLive, console from unshackle.core.constants import AnyTrack from unshackle.core.credential import Credential from unshackle.core.dl_options import remote_dl_params -from unshackle.core.drm import cbcs, real_kids +from unshackle.core.drm import cbcs, real_kids, whole_file_cipher from unshackle.core.drm.cenc import drm_stub from unshackle.core.drm.discovery import track_pssh from unshackle.core.launch import launch_keys @@ -1543,6 +1543,7 @@ class RemoteService(TitleSource): track_ids = [self.server_track_id(t.id) for t in keyed] self.drain_server_logs() keys_by_track = resp.get("keys", {}) + file_keys = resp.get("file_keys", {}) clear_tracks = set(resp.get("clear_tracks", [])) vault_kids = set(resp.get("vault_keys", [])) for track_keys in keys_by_track.values(): @@ -1555,6 +1556,11 @@ class RemoteService(TitleSource): for track in title.tracks: server_id = self.server_track_id(track.id) + cipher = whole_file_cipher(track) + if cipher is not None: + if server_id in file_keys: + cipher.take_key(file_keys[server_id]) + continue track_keys = keys_by_track.get(server_id, {}) if not track_keys: if server_id in track_ids and server_id not in clear_tracks | set(capped): @@ -1761,6 +1767,33 @@ class RemoteService(TitleSource): self.license_locally(track, resp.get("details") or {}) return None + def license_file(self, track: AnyTrack) -> str: + """The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException.""" + if self.local_vaults_only or not self._server_cdm: + raise coded( + click.ClickException(f"Track {track.id} needs a server licence that this session does not allow"), + APIErrorCode.DRM_ERROR, + ) + try: + with quiet(): + resp = self.session_call( + lambda sid: self.client.post( + LICENSE_ROUTE.format(session_id=sid), + LicenseRequest( + mode="server_cdm", drm_type="clearkeyctr", track_id=self.server_track_id(track.id) + ), + ) + ) + except RemoteError as e: + raise coded(click.ClickException(e.message), APIErrorCode.DRM_ERROR) from None + finally: + self.drain_server_logs() + if not (key := (resp.get("file_keys") or {}).get(self.server_track_id(track.id))): + raise coded( + click.ClickException(f"The server sent no content key for track {track.id}"), APIErrorCode.DRM_ERROR + ) + return str(key) + def proxy_license(self, challenge: bytes | str, track: AnyTrack, drm_type: str) -> bytes: """Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it.""" if isinstance(challenge, str): diff --git a/unshackle/core/title_source.py b/unshackle/core/title_source.py index 6afe977d..10043ccf 100644 --- a/unshackle/core/title_source.py +++ b/unshackle/core/title_source.py @@ -83,6 +83,9 @@ class ServerKeySource(Protocol): raises ClickException. """ + def license_file(self, track: AnyTrack) -> str: + """The content key the server licenses for the whole-file cipher of ``track``; a refusal raises.""" + def vault_source(self, kid: UUID, key: str) -> Vault | None: """The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check.""" diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 593efd49..5dd5fa4c 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -27,7 +27,7 @@ from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.downloaders.requests import requests -from unshackle.core.drm import DRM_T, BlowfishStripe, PlayReady, Widevine +from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, PlayReady, Widevine from unshackle.core.drm.cenc import cenc_key, init_kid from unshackle.core.drm.verify import ( children, @@ -824,6 +824,7 @@ class Track: DOWNLOAD_ALL_DRM.is_set() and track_type in ("Video", "Audio") and not {Widevine, PlayReady} <= {type(d) for d in self.drm or []} + and all(type(d) in (Widevine, PlayReady) for d in self.drm or []) ): self.add_init_drm(self.get_init_segment(session=session), cdm) elif not self.drm and track_type in ("Video", "Audio"): @@ -831,7 +832,7 @@ class Track: if self.drm: drm = self.get_drm_for_cdm(cdm) - track_kid = None if isinstance(drm, BlowfishStripe) else self.get_key_id(session=session) + track_kid = None if isinstance(drm, WHOLE_FILE_DRM) else self.get_key_id(session=session) license_drm(self, drm, ctx, track_kid) else: drm = None @@ -882,7 +883,7 @@ class Track: if drm: progress(downloaded="Decrypting", completed=0, total=None) decrypt_track(drm, save_path, prepare_drm, track_kid, track=self) - if not isinstance(drm, BlowfishStripe): + if not isinstance(drm, WHOLE_FILE_DRM): assert_fragments_decrypted(save_path) self.drm = None events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None) diff --git a/unshackle/core/wire.py b/unshackle/core/wire.py index 455b2204..f5dcb4e4 100644 --- a/unshackle/core/wire.py +++ b/unshackle/core/wire.py @@ -28,7 +28,7 @@ from pywidevine.pssh import PSSH as WidevinePSSH from unshackle.core.config import config from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP -from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine +from unshackle.core.drm import WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine from unshackle.core.titles import Episode, Movie, Song, Title_T from unshackle.core.titles.availability import availability_metadata from unshackle.core.titles.music import MUSIC_DATA_KEYS, SONG_FIELDS, song_metadata @@ -309,8 +309,10 @@ def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None: drm_info = {} drm_class = drm.__class__.__name__ drm_info["type"] = drm_class.lower() - if isinstance(drm, BlowfishStripe): + if isinstance(drm, WHOLE_FILE_DRM) and drm.key is not None: drm_info["key"] = drm.key.hex() + if isinstance(drm, ClearKeyCTR): + drm_info.update(iv=drm.iv.hex(), magic=drm.magic.hex(), skip=drm.skip) # pywidevine exposes dumps(); pyplayready's PSSH does not, so PlayReady falls back # to the base64 it was built from. Without it the client drops every PlayReady @@ -355,11 +357,17 @@ def reconstruct_drm(drm_list: list | None) -> list: for drm_info in drm_list: drm_type = drm_info.get("type", "") pssh_str = drm_info.get("pssh") - if not pssh_str and drm_type != "blowfishstripe": + if not pssh_str and drm_type not in ("blowfishstripe", "clearkeyctr"): continue try: if drm_type == "blowfishstripe": result.append(BlowfishStripe(drm_info["key"])) + elif drm_type == "clearkeyctr": + result.append( + ClearKeyCTR( + None, drm_info["iv"], drm_info["magic"], drm_info.get("skip", 0), key=drm_info.get("key") + ) + ) elif drm_type in ("widevine", "playready"): result.append(pssh_drm(drm_type, pssh_str, drm_info.get("kids"))) # a dropped entry can leave the track with no DRM, so never skip silently