feat(drm): license MonaLisa over --remote on the server and decrypt it in core, with or without bbtsdecrypt

This commit is contained in:
imSp4rky
2026-12-02 15:23:58 -07:00
parent b1497c77a2
commit ac4425cdca
29 changed files with 1518 additions and 121 deletions
+187
View File
@@ -0,0 +1,187 @@
"""A synthetic BBTS file and its cipher, built from scratch so the tests need no real media.
The cipher here is a slow, plain reading of the format; the decrypter under test never builds its own input.
"""
from __future__ import annotations
import hashlib
import re
from Cryptodome.Cipher import AES
KEY = bytes.fromhex("00112233445566778899aabbccddeeff")
IVS = (bytes.fromhex("0123456789abcdef0123456789abcdef"), bytes.fromhex("fedcba9876543210fedcba9876543210"))
HEVC, H264, AAC = 0x24, 0x1B, 0x0F
SC3, SC4 = b"\x00\x00\x01", b"\x00\x00\x00\x01"
# SHA-256 of what the bbtsdecrypt binary wrote for bbts(video_type), so CI needs no binary.
GOLDEN = {
HEVC: "b2d70cf98ca9b08b94363c627266da9c31ed07f08acf2ac3d2645ca9cff0366a",
H264: "0f2bb9586781768f086d9a6d05ec09466453ee9e53557fa6ad6d09598be2e8b3",
}
def noise(seed: str, size: int) -> bytes:
"""Deterministic bytes with no zero byte."""
out = b"".join(hashlib.sha256(f"{seed}{i}".encode()).digest() for i in range(size // 32 + 1))[:size]
return out.replace(b"\x00", b"\x5a")
def crc32_mpeg(data: bytes) -> int:
crc = 0xFFFFFFFF
for byte in data:
crc ^= byte << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x104C11DB7) if crc & 0x80000000 else crc << 1
return crc & 0xFFFFFFFF
def encrypt(payload: bytes, iv: bytes) -> bytes:
"""Encrypt a NAL payload: all but its last 2 bytes, block by block, then escape the result for the byte stream."""
ecb = AES.new(KEY, AES.MODE_ECB)
counter = int.from_bytes(iv[:12] + bytes(4), "big")
body, out = payload[:-2], bytearray()
for n, at in enumerate(range(0, len(body), 16)):
counter += 1
block = counter.to_bytes(16, "big")
if n % 10 == 0 or len(body) - at <= 16:
block = ecb.encrypt(block)
out += bytes(a ^ b for a, b in zip(body[at : at + 16], block, strict=False))
return re.sub(b"\x00\x00(?=[\x00-\x03])", b"\x00\x00\x03", bytes(out) + payload[-2:])
def section(table_id: int, body: bytes) -> bytes:
"""A long-form PSI section with its CRC."""
data = bytes([table_id]) + (0xB000 | (len(body) + 9)).to_bytes(2, "big") + b"\x00\x01\xc1\x00\x00" + body
return data + crc32_mpeg(data).to_bytes(4, "big")
def psi_packet(pid: int, data: bytes) -> bytes:
payload = b"\x00" + data
return bytes([0x47, 0x40 | pid >> 8, pid & 0xFF, 0x10]) + payload + b"\xff" * (184 - len(payload))
def sdt(iv: bytes, name_format: str) -> bytes:
"""An SDT whose service name is ``name_format`` with the IV in it."""
name = name_format.format(iv=iv.hex()).encode()
descriptor = bytes([0x48, 3 + 7 + len(name), 0x01, 7]) + b"EXAMPLE" + bytes([len(name)]) + name
service = b"\x00\x01\xfc" + (0x8000 | len(descriptor)).to_bytes(2, "big") + descriptor
return psi_packet(0x11, section(0x42, b"\x00\x01\xff" + service))
def pmt(video_type: int) -> bytes:
"""A PMT with the video stream, an AAC stream and an H.264 stream on another PID."""
streams = bytes([video_type, 0xE1, 0x00, 0xF0, 0x00, AAC, 0xE1, 0x01, 0xF0, 0x00, H264, 0xE1, 0x02, 0xF0, 0x00])
return psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + streams))
PAT = psi_packet(0, section(0x00, b"\x00\x01\xf0\x00"))
def packets(pid: int, pes: bytes, counter: list[int], last: int) -> list[bytes]:
"""Cut a PES packet into TS packets, the last of which carries ``last`` bytes after adaptation-field stuffing."""
sizes = [184] * ((len(pes) - last) // 184) + [last]
assert sum(sizes) == len(pes), "the PES does not end on the asked size"
out, at = [], 0
for size in sizes:
chunk, at = pes[at : at + size], at + size
start = 0x40 if at == size else 0
head = bytes([0x47, start | pid >> 8, pid & 0xFF, (0x10 if size == 184 else 0x30) | counter[0] % 16])
counter[0] += 1
stuffing = 183 - size
field = b"" if size == 184 else bytes([stuffing]) + (b"\x00" + b"\xff" * (stuffing - 1) if stuffing else b"")
out.append(head + field + chunk)
return out
def pes(stream_id: int, es: bytes) -> bytes:
return SC3 + bytes([stream_id]) + b"\x00\x00\x80\x80\x05\x21\x00\x01\x00\x01" + es
def with_zero_runs(seed: str, size: int) -> bytes:
"""Bytes whose zero runs make the cipher hold emulation-prevention bytes."""
data = bytearray(noise(seed, size))
for at in range(20, size - 8, 37):
data[at : at + 5] = bytes(5)
return bytes(data)
def nal_units(seed: str, iv: bytes, h264: bool) -> bytes:
"""An access unit: a delimiter, a SEI and an RPU with the 4 bytes the cipher appends, slices, and a short NAL."""
aud, sei, slice_ = (b"\x09", b"\x06", b"\x65") if h264 else (b"\x46\x01", b"\x4e\x01", b"\x02\x01")
rpu = b"\x19" + noise(seed + "r", 40)
rpu += crc32_mpeg(rpu[1:]).to_bytes(4, "big") + b"\x80"
units = [
SC4 + aud + encrypt(b"\x50" + noise(seed + "a", 4), iv),
SC3 + sei + encrypt(b"\x05\x04\xaa\xbb\xcc\xdd\xff\x01\x02\x11\x22\x80" + noise(seed + "s", 4), iv),
SC3 + slice_ + encrypt(with_zero_runs(seed + "l", 300) + b"\x00", iv),
SC4 + slice_ + encrypt(noise(seed + "m", 2), iv),
SC3 + slice_ + encrypt(noise(seed + "n", 161), iv),
]
if not h264:
units.insert(2, SC3 + b"\x7c\x01" + encrypt(rpu + noise(seed + "p", 4), iv))
return b"".join(units)
def timestamp(ticks: int) -> bytes:
"""A PES PTS field of ``ticks`` at 90 kHz."""
return bytes(
[
0x21 | ticks >> 29 & 0x0E,
ticks >> 22 & 0xFF,
ticks >> 14 & 0xFE | 1,
ticks >> 7 & 0xFF,
ticks << 1 & 0xFE | 1,
]
)
def bbts_segments(es: bytes, iv: bytes, frames: int, fps: int) -> list[bytes]:
"""BBTS segments of ``frames`` pictures each, from an Annex B HEVC stream with a delimiter before each picture.
Each segment opens with its tables, and each picture is one video PES packet with only a PTS.
"""
pictures: list[list[bytes]] = []
for nal in es.split(SC3)[1:]:
if nal[0] >> 1 & 0x3F == 35:
pictures.append([])
pictures[-1].append(nal.rstrip(b"\x00"))
hevc_pmt = psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + bytes([HEVC, 0xE1, 0x00, 0xF0, 0x00])))
segments, counter = [], [0]
for first in range(0, len(pictures), frames):
out = [PAT, hevc_pmt, sdt(iv, "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q")]
for n, picture in enumerate(pictures[first : first + frames], first):
es_out = b"".join(SC4 + nal[:2] + (encrypt(nal[2:], iv) if len(nal) > 4 else nal[2:]) for nal in picture)
packet = SC3 + b"\xe0\x00\x00\x80\x80\x05" + timestamp(90000 * (n + 1) // fps) + es_out
out += packets(0x100, packet, counter, len(packet) % 184 or 184)
segments.append(b"".join(out))
return segments
def bbts(
video_type: int = HEVC, pmt_first: bool = False, name_format: str = "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q"
) -> bytes:
"""Two segments with their own IV, each with SDT, PMT, two video PES packets and an audio PES packet between them.
``pmt_first`` puts the PMT before the SDT; ``name_format`` is the service name that holds the IV.
The first video PES ends in a packet of 6 bytes, so the bytes the decrypter drops empty that packet; the second
ends in a packet whose adaptation field is only its length byte.
"""
counters: list[list[int]] = [[0], [0]]
out = []
for n, iv in enumerate(IVS):
tables = (
[PAT, pmt(video_type), sdt(iv, name_format)] if pmt_first else [PAT, sdt(iv, name_format), pmt(video_type)]
)
out += tables
for k, last in ((0, 6), (1, 183)):
es = nal_units(f"v{n}{k}", iv, video_type == H264)
head = b"\x01" if video_type == H264 else b"\x02\x01"
filler = (last - len(pes(0xE0, es)) - 3 - len(head)) % 184 + 184
es += SC3 + head + noise(f"f{n}{k}", filler)
out += packets(0x100, pes(0xE0, es), counters[0], last)
if k == 0:
audio = pes(0xC0, noise(f"a{n}", 400))
out += packets(0x101, audio, counters[1], len(audio) % 184)
return b"".join(out)
+108
View File
@@ -0,0 +1,108 @@
"""The built-in BBTS decrypter against output of the bbtsdecrypt binary, on a synthetic file built in the test."""
import hashlib
import subprocess
from pathlib import Path
import pytest
from tests.core import bbts_sample
from unshackle.core import binaries
from unshackle.core.drm.bbts import decrypt_bbts, renumber_continuity
from unshackle.core.utils.hdr10plus import ts_packets, ts_pid
pytestmark = pytest.mark.unit
def packets_of(data: bytes, pid: int) -> list[bytes]:
"""The TS packets of one PID, or of every PID for -1."""
return [packet for packet in ts_packets(data) if pid in (-1, ts_pid(packet))]
@pytest.fixture(params=[bbts_sample.HEVC, bbts_sample.H264], ids=["hevc", "h264"])
def sample(request: pytest.FixtureRequest, tmp_path: Path) -> tuple[int, Path]:
path = tmp_path / "segment.bbts"
path.write_bytes(bbts_sample.bbts(request.param))
return request.param, path
def test_the_clear_file_is_the_one_bbtsdecrypt_wrote(sample: tuple[int, Path], tmp_path: Path) -> None:
video_type, src = sample
decrypt_bbts(src, tmp_path / "clear.ts", bbts_sample.KEY)
assert hashlib.sha256((tmp_path / "clear.ts").read_bytes()).hexdigest() == bbts_sample.GOLDEN[video_type]
def test_only_the_video_pid_changes(sample: tuple[int, Path], tmp_path: Path) -> None:
_, src = sample
decrypt_bbts(src, tmp_path / "clear.ts", bbts_sample.KEY)
before, after = src.read_bytes(), (tmp_path / "clear.ts").read_bytes()
assert len(after) == len(before)
for pid in (0x0000, 0x0011, 0x1000, 0x0101):
assert packets_of(after, pid) == packets_of(before, pid)
assert packets_of(after, 0x0100) != packets_of(before, 0x0100)
def test_the_binary_writes_the_same_file(sample: tuple[int, Path], tmp_path: Path) -> None:
if not (tool := binaries.find("bbtsdecrypt")):
pytest.skip("no bbtsdecrypt binary on this machine")
_, src = sample
decrypt_bbts(src, tmp_path / "builtin.ts", bbts_sample.KEY)
subprocess.run(
[tool, "-i", src, "-o", tmp_path / "tool.ts", "-k", f"{'0' * 32}:{bbts_sample.KEY.hex()}"],
capture_output=True,
check=True,
)
assert (tmp_path / "builtin.ts").read_bytes() == (tmp_path / "tool.ts").read_bytes()
@pytest.mark.parametrize("video_type", [bbts_sample.HEVC, bbts_sample.H264], ids=["hevc", "h264"])
@pytest.mark.parametrize(
"layout",
[{"pmt_first": True}, {"name_format": "mdcm|a|b|{iv}|c"}],
ids=["pmt-before-sdt", "iv-in-fourth-field"],
)
def test_other_table_layouts_give_the_same_video(video_type: int, layout: dict, tmp_path: Path) -> None:
(tmp_path / "usual.bbts").write_bytes(bbts_sample.bbts(video_type))
(tmp_path / "other.bbts").write_bytes(bbts_sample.bbts(video_type, **layout))
for name in ("usual", "other"):
decrypt_bbts(tmp_path / f"{name}.bbts", tmp_path / f"{name}.ts", bbts_sample.KEY)
usual, other = ((tmp_path / f"{name}.ts").read_bytes() for name in ("usual", "other"))
assert hashlib.sha256(usual).hexdigest() == bbts_sample.GOLDEN[video_type]
assert packets_of(other, 0x0100) == packets_of(usual, 0x0100)
def test_a_file_with_no_iv_is_copied(tmp_path: Path) -> None:
data = b"".join(packet for packet in packets_of(bbts_sample.bbts(), -1) if packet[1:3] != b"\x40\x11")
(tmp_path / "in.ts").write_bytes(data)
decrypt_bbts(tmp_path / "in.ts", tmp_path / "out.ts", bbts_sample.KEY)
assert (tmp_path / "out.ts").read_bytes() == data
def test_a_key_of_another_length_is_refused(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="16-byte key"):
decrypt_bbts(tmp_path / "in.ts", tmp_path / "out.ts", b"short")
def test_the_counter_steps_only_on_a_packet_with_payload(tmp_path: Path) -> None:
def packet(pid: int, cc: int, payload: bool = True) -> bytes:
body = b"\x00" * 184 if payload else bytes([183, 0]) + b"\xff" * 182
return bytes([0x47, pid >> 8, pid & 0xFF, (0x10 if payload else 0x20) | cc]) + body
path = tmp_path / "clear.ts"
sent = [
(0x100, 5, True),
(0x100, 6, False),
(0x1FFF, 3, True),
(0x100, 7, True),
(0x100, 7, True),
(0x100, 8, True),
]
path.write_bytes(b"".join(packet(*p) for p in sent))
renumber_continuity(path)
assert [p[3] & 0x0F for p in packets_of(path.read_bytes(), -1)] == [5, 5, 3, 6, 6, 7]
+4 -1
View File
@@ -6,6 +6,7 @@ from pathlib import Path
from types import SimpleNamespace
from uuid import UUID
import click
import pytest
from tests.core.key_resolver import resolver, vaults_of
@@ -71,7 +72,9 @@ def test_a_licence_key_of_a_bridged_track_that_does_not_decode_stops_the_track(
local.add_key("SVC", KID, BAD)
vaults = vaults_of(local, service="SVC")
with pytest.raises(ValueError, match=f"^The licence content key of KID {KID.hex} does not decrypt track vid$"):
with pytest.raises(
click.ClickException, match=f"^The licence content key of KID {KID.hex} does not decrypt track vid$"
):
check(tmp_path, BridgedDRM({KID: BAD}), vaults, decrypt)
assert decodes and not (tmp_path / "track.mp4").exists()
+2 -1
View File
@@ -7,6 +7,7 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
import pytest
from tests.core.key_resolver import resolver
@@ -85,7 +86,7 @@ def test_an_imported_bridged_track_stops_on_a_key_that_does_not_decrypt(
path.write_bytes(b"cipher")
keys = resolver(None, tag="EXAMPLE")
with pytest.raises(ValueError, match="does not decrypt track vid") as e:
with pytest.raises(click.ClickException, match="does not decrypt track vid") as e:
try:
keys.decrypt_verified(drm, path, licence, VIDEO_KID, True, SimpleNamespace(id="vid")) # type: ignore[arg-type]
finally:
+119
View File
@@ -0,0 +1,119 @@
"""A MonaLisa track whose content key does not decode stops after the merge, through ``HLS.download_track``.
The segments are a real HEVC clip in the synthetic BBTS format, and the built-in decrypter decrypts them.
"""
from __future__ import annotations
import subprocess
import threading
from collections.abc import Iterator
from http.server import ThreadingHTTPServer
from pathlib import Path
from uuid import UUID
import click
import pytest
from tests.core import bbts_sample
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx
from unshackle.core import binaries
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import MonaLisa, monalisa, verify
from unshackle.core.manifests import HLS
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Video
from unshackle.core.tracks.track import DownloadContext
from unshackle.core.utils.subprocess import ffmpeg_decodes
pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg")
KID = UUID(hex="11111111111111111111111111111111")
WRONG = "5a" * 16
FPS = 25
@pytest.fixture(scope="module")
def segments(tmp_path_factory: pytest.TempPathFactory) -> list[bytes]:
"""Three 2 s BBTS segments of a 640x360 HEVC clip, encrypted with bbts_sample.KEY and a fixed IV."""
clip = tmp_path_factory.mktemp("bbts") / "clip.hevc"
x265 = "keyint=50:min-keyint=50:scenecut=0:bframes=0:aud=1:info=0:repeat-headers=1:log-level=none"
source = f"testsrc2=size=640x360:rate={FPS}:duration=6"
subprocess.run(
[str(binaries.FFMPEG), "-nostdin", "-v", "error", "-f", "lavfi", "-i", source, "-c:v", "libx265"]
+ ["-preset", "ultrafast", "-pix_fmt", "yuv420p", "-x265-params", x265, "-f", "hevc", str(clip)],
check=True,
)
return bbts_sample.bbts_segments(clip.read_bytes(), bbts_sample.IVS[0], 2 * FPS, FPS)
@pytest.fixture
def server(segments: list[bytes]) -> Iterator[ThreadingHTTPServer]:
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:2"]
srv.routes = {} # type: ignore[attr-defined]
for i, segment in enumerate(segments):
srv.routes[f"/{i}.ts"] = segment # type: ignore[attr-defined]
lines += ["#EXTINF:2.0,", f"{i}.ts"]
srv.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() # type: ignore[attr-defined]
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
DOWNLOAD_CANCELLED.clear()
def download(
server: ThreadingHTTPServer,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
key: str,
memory: MemoryVault,
vault: bool,
kind: type[Video] | type[Audio] = Video,
) -> tuple[Video | Audio, DownloadContext]:
"""Download the track with the built-in decrypter and the hook of dl; with ``vault``, ``memory`` is the key's source."""
monkeypatch.setattr(monalisa, "local_tool", lambda: None)
keys = resolver(vaults_of(memory, MemoryVault(name="other")))
monkeypatch.setattr(verify, "DECRYPT_HOOK", keys.decrypt_verified)
drm = MonaLisa(kid=KID)
drm.content_keys[KID] = key
if vault:
keys.vaults.supplied(KID, key, memory)
track = kind(url=f"{base(server)}v.m3u8", language="en", descriptor=kind.Descriptor.HLS)
track.drm = [drm]
ctx = make_ctx(tmp_path, "monalisa.ts")
ctx.license_widevine = lambda *a, **kw: None
try:
HLS.download_track(track, ctx)
finally:
keys.wait_vault_writes()
return track, ctx
@pytest.mark.parametrize("vault", [False, True], ids=["licence", "vault"])
def test_a_wrong_monalisa_key_stops_the_track_and_leaves_no_output(server, tmp_path, monkeypatch, vault: bool) -> None:
memory = MemoryVault({KID: WRONG} if vault else {})
refused = f"^The MonaLisa content key of KID {KID.hex} does not decrypt track "
with pytest.raises(click.ClickException, match=refused) as e:
download(server, tmp_path, monkeypatch, WRONG, memory, vault)
assert getattr(e.value, "error_code", None) == APIErrorCode.DRM_ERROR
assert not (tmp_path / "monalisa.ts").exists()
assert memory.told == [(KID, WRONG)] and not memory.added
def test_the_right_monalisa_key_keeps_a_track_that_decodes(server, tmp_path, monkeypatch) -> None:
track, ctx = download(server, tmp_path, monkeypatch, bbts_sample.KEY.hex(), MemoryVault(), vault=False)
assert track.path == ctx.save_path and ffmpeg_decodes(ctx.save_path)
def test_an_audio_track_judges_and_copies_no_vault_key(server, tmp_path, monkeypatch) -> None:
"""BBTS leaves audio clear, so a decode of an audio track proves no key."""
memory = MemoryVault({KID: WRONG})
download(server, tmp_path, monkeypatch, WRONG, memory, vault=True, kind=Audio)
assert (tmp_path / "monalisa.ts").exists() and not memory.told
+110 -4
View File
@@ -1,12 +1,16 @@
"""MonaLisa's external decrypt tool: a missing tool raises, and a failed run leaves the ciphertext untouched."""
"""MonaLisa's decrypt step: the external tool, or the built-in decrypter when this machine has none."""
import functools
import hashlib
import subprocess
from pathlib import Path
from uuid import UUID
import pytest
from unshackle.core.drm.monalisa import MonaLisa
from tests.core import bbts_sample
from unshackle.core.drm import monalisa
from unshackle.core.drm.monalisa import MonaLisa, bbtsdecrypt_command
from unshackle.core.utils import subprocess as tool_runner
pytestmark = pytest.mark.unit
@@ -27,7 +31,7 @@ def make_drm(monkeypatch: pytest.MonkeyPatch):
def build(tool: Path, **kwargs) -> MonaLisa:
drm = MonaLisa("ticket", Path("unused.mld"), tool, **kwargs)
drm._kid = UUID(int=1)
drm._key = "00" * 16
drm.content_keys[drm._kid] = "00" * 16
return drm
return build
@@ -114,7 +118,8 @@ def test_a_service_command_builder_replaces_the_default_command(
drm = make_drm(tool, command_builder=command, segment_decrypt=False)
else:
drm = MonaLisa.from_ticket("ticket", Path("unused.mld"), tool, command, False)
drm._kid, drm._key = UUID(int=1), "00" * 16
drm._kid = UUID(int=1)
drm.content_keys[drm._kid] = "00" * 16
assert not drm.supports_segment_decrypt
drm.decrypt(track)
output = track.with_name("track_decrypted.mp4")
@@ -157,3 +162,104 @@ def test_a_segment_tool_decrypts_every_file_it_gets_an_output_path_for(
for output in outputs:
drm.decrypt(track, output)
assert [output.read_bytes() for output in outputs] == [b"plain", b"plain"]
def local_tools(monkeypatch: pytest.MonkeyPatch, bbtsdecrypt: Path | None, shaka: Path | None) -> None:
"""Make `bbtsdecrypt` and `shaka` the binaries that this machine has."""
monkeypatch.setattr(monalisa, "local_tool", functools.cache(monalisa.local_tool.__wrapped__))
monkeypatch.setattr(
monalisa.binaries, "find", lambda *names, **kwargs: bbtsdecrypt if "bbtsdecrypt" in names else None
)
monkeypatch.setattr(monalisa.binaries, "ShakaPackager", shaka, raising=False)
def test_a_drm_without_a_tool_runs_the_bbtsdecrypt_of_this_machine_per_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, track: Path
) -> None:
tool = tmp_path / "bbtsdecrypt"
tool.write_bytes(b"")
local_tools(monkeypatch, tool, None)
commands = []
def run(cmd, **kwargs):
commands.append(cmd)
Path(cmd[cmd.index("-o") + 1]).write_bytes(b"plain")
return subprocess.CompletedProcess(cmd, 0, b"", b"")
monkeypatch.setattr(tool_runner.subprocess, "run", run)
drm = MonaLisa(kid=UUID(int=1))
drm.content_keys[UUID(int=1)] = "ab" * 16
assert drm.supports_segment_decrypt
drm.decrypt(track)
output = track.with_name("track_decrypted.mp4")
assert commands == [[str(arg) for arg in bbtsdecrypt_command(tool, track, output, UUID(int=1).hex, "ab" * 16)]]
assert track.read_bytes() == b"plain"
def built_in_drm(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MonaLisa:
"""A MonaLisa on a machine with no bbtsdecrypt but a shaka-packager built with BBTS, keyed for the synthetic file."""
shaka = tmp_path / "packager"
shaka.write_bytes(b"..bbts_decryptor.cc..")
local_tools(monkeypatch, None, shaka)
drm = MonaLisa(kid=UUID(int=1))
drm.content_keys[UUID(int=1)] = bbts_sample.KEY.hex()
return drm
def test_with_no_tool_the_built_in_decrypter_decrypts_each_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
drm = built_in_drm(monkeypatch, tmp_path)
segment = tmp_path / "0.ts"
segment.write_bytes(bbts_sample.bbts())
assert drm.tool is None and drm.supports_segment_decrypt
drm.decrypt_segment(segment)
assert hashlib.sha256(segment.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
assert [path.name for path in tmp_path.iterdir() if path.suffix == ".ts"] == ["0.ts"]
def test_with_no_tool_a_whole_track_drm_decrypts_the_merged_file_built_in(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
drm = built_in_drm(monkeypatch, tmp_path)
drm._segment_decrypt = False
merged = tmp_path / "merged.ts"
merged.write_bytes(bbts_sample.bbts())
assert not drm.supports_segment_decrypt
drm.decrypt(merged)
assert hashlib.sha256(merged.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
def test_a_failed_built_in_run_keeps_the_ciphertext(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, track: Path
) -> None:
def fail(src: Path, dst: Path, key: bytes) -> None:
dst.write_bytes(b"partial")
raise OSError("disk full")
drm = built_in_drm(monkeypatch, tmp_path)
monkeypatch.setattr(monalisa, "decrypt_bbts", fail)
with pytest.raises(OSError, match="disk full"):
drm.decrypt(track)
assert track.read_bytes() == b"cipher"
assert not track.with_name("track_decrypted.mp4").exists()
def test_a_copy_with_only_a_kid_holds_no_key_until_one_arrives() -> None:
drm = MonaLisa(kid=UUID(int=1).hex)
assert (drm.kid, drm.kids, drm.key, drm.content_keys) == (UUID(int=1), [UUID(int=1)], None, {})
drm.content_keys[UUID(int=1)] = "ab" * 16
assert drm.key_pair == f"{UUID(int=1).hex}:{'ab' * 16}"
def test_no_ticket_and_no_kid_is_refused() -> None:
with pytest.raises(MonaLisa.Exceptions.TicketNotFound):
MonaLisa()
+118
View File
@@ -0,0 +1,118 @@
"""A MonaLisa licence runs one CDM at a time per process, and a MonaLisa track survives an export and an import."""
from __future__ import annotations
import hashlib
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
from uuid import UUID
import pytest
from tests.core import bbts_sample
from tests.core.test_export import make_title, make_writer, written
from tests.core.test_import_track_keys import import_service
from tests.core.test_monalisa_decrypt import local_tools
from unshackle.core.drm import monalisa
from unshackle.core.drm.monalisa import MonaLisa
KID = UUID(int=1)
KEY = bbts_sample.KEY.hex()
def test_concurrent_licences_open_one_cdm_at_a_time(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
open_sessions = 0
peak = 0
guard = threading.Lock()
class OneSessionCDM:
def __init__(self, device_path: Path) -> None:
pass
def open(self) -> int:
nonlocal open_sessions, peak
with guard:
open_sessions += 1
peak = max(peak, open_sessions)
time.sleep(0.05)
return 1
def extract_keys(self, ticket: str) -> dict[str, str]:
return {"kid": KID.hex, "key": KEY}
def close(self, session_id: int) -> None:
nonlocal open_sessions
with guard:
open_sessions -= 1
monkeypatch.setattr(monalisa, "MonaLisaCDM", OneSessionCDM)
start = threading.Barrier(4)
def licence(_: int) -> MonaLisa:
start.wait()
return MonaLisa("EXAMPLE-TICKET", tmp_path / "device.mld")
with ThreadPoolExecutor(4) as pool:
drms = list(pool.map(licence, range(4)))
assert peak == 1
assert [drm.key_pair for drm in drms] == [f"{KID.hex}:{KEY}"] * 4
def test_a_failed_licence_raises_one_error_and_frees_the_lock(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
class TrappingCDM:
def __init__(self, device_path: Path) -> None:
pass
def open(self) -> int:
return 1
def extract_keys(self, ticket: str) -> dict[str, str]:
raise RuntimeError("wasm trap")
def close(self, session_id: int) -> None:
pass
monkeypatch.setattr(monalisa, "MonaLisaCDM", TrappingCDM)
with pytest.raises(MonaLisa.Exceptions.KeyExtractionFailed, match="^Failed to extract keys: wasm trap$"):
MonaLisa("EXAMPLE-TICKET", tmp_path / "device.mld")
assert not monalisa.CDM_LOCK.locked()
def export_monalisa(tmp_path: Path) -> Path:
"""Export a title whose video carries a licensed MonaLisa DRM with a service tool and whole-track mode."""
title = make_title()
drm = MonaLisa(kid=KID, tool_path=tmp_path / "service-tool", command_builder=lambda *a: [], segment_decrypt=False)
drm.content_keys[KID] = KEY
writer = make_writer(tmp_path)
writer.record(title, title.tracks.videos[0], drm)
return written(writer)
def test_the_export_holds_the_kid_and_no_tool_or_callable(tmp_path: Path) -> None:
entry = json.loads(export_monalisa(tmp_path).read_text(encoding="utf8"))["titles"][0]
assert entry["x-unshackle"]["drm"] == [{"system": "MonaLisa", "kids": [KID.hex]}]
assert entry.get("drm", []) == []
assert "service-tool" not in json.dumps(entry)
def test_an_imported_monalisa_track_decrypts_with_the_exported_key(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
export = export_monalisa(tmp_path)
local_tools(monkeypatch, None, None)
drm: Any = import_service(export).rebuild_drm({"id": "v1", "type": "Video"}, "movie-1")[0] # type: ignore[index]
segment = tmp_path / "0.ts"
segment.write_bytes(bbts_sample.bbts())
assert isinstance(drm, MonaLisa)
assert (drm.key_pair, drm.tool, drm.supports_segment_decrypt) == (f"{KID.hex}:{KEY}", None, True)
drm.decrypt_segment(segment)
assert hashlib.sha256(segment.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
+7 -3
View File
@@ -34,7 +34,7 @@ from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders import requests as requests_downloader
from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine
from unshackle.core.drm import cenc as cenc_module
from unshackle.core.drm import verify
from unshackle.core.drm import key_resolution, verify
from unshackle.core.events import events
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests import dash as dash_module
@@ -370,7 +370,7 @@ def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, monkeypa
@pytest.mark.parametrize("mode", ["segments", "core-whole", "service-whole", "service-whole-keeps-cipher"])
@pytest.mark.parametrize("playlist", ["plain", "discontinuity", "init"])
@pytest.mark.parametrize("playlist", ["plain", "discontinuity", "init", "method-none"])
@pytest.mark.parametrize("hooked", [False, True])
def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch, mode, playlist, hooked):
"""A segment tool runs per segment, a whole-track tool on each merged block or in the service's downloader.
@@ -395,10 +395,13 @@ def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch,
hook = resolver(vaults_of(MemoryVault())).decrypt_verified if hooked else None
monkeypatch.setattr(verify, "DECRYPT_HOOK", hook)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda *args, **kwargs: True)
parts = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))]
for i, part in enumerate(parts):
server.routes[f"/part{i}.m4s"] = part
lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:4"]
if playlist == "method-none":
lines.append("#EXT-X-KEY:METHOD=NONE")
server.routes["/init.mp4"] = b"INIT"
if playlist == "init":
lines.append('#EXT-X-MAP:URI="init.mp4"')
@@ -409,7 +412,8 @@ def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch,
server.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode()
track = Video(url=f"{base(server)}v.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS)
drm = MonaLisa("ticket", Path("unused.mld"), segment_decrypt=mode == "segments")
drm._kid, drm._key = KID, "00" * 16
drm._kid = KID
drm.content_keys[KID] = "00" * 16
track.drm = [drm]
if mode.startswith("service"):
+243
View File
@@ -0,0 +1,243 @@
"""A MonaLisa HLS track over --remote: the server licenses with the DRM its service built, the client decrypts it.
The service builds the DRM on the server with a device file there; only its KID crosses with the track list, and
the content key comes through the licence route. The client decrypts each segment with its own tool, or with the
built-in decrypter when it has none.
"""
from __future__ import annotations
import functools
import json
import sys
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import UUID
import click
import pytest
import requests
from tests.core import bbts_sample
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core import binaries
from unshackle.core.api import handlers, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import MonaLisa, monalisa
from unshackle.core.drm.bbts import decrypt_bbts, renumber_continuity
from unshackle.core.manifests.hls import HLS
from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.tracks import Video
from unshackle.core.tracks.track import DownloadContext, Track
from unshackle.core.wire import build_tracks, serialize_video_track
pytestmark = pytest.mark.unit
KID = UUID(hex="0123456789abcdef0123456789abcdef")
KEY = "5a" * 16
PLAIN = [b"EXAMPLE clear segment %d. " % i * 8 for i in range(3)]
PLAYLIST = (
"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:5\n#EXT-X-KEY:METHOD=NONE\n"
+ "".join(f"#EXTINF:5.0,\nhttps://example.test/seg{i}.ts\n" for i in range(len(PLAIN)))
+ "#EXT-X-ENDLIST\n"
)
TOOL = """import sys
args = dict(zip(sys.argv[1::2], sys.argv[2::2]))
key = bytes.fromhex(args["-k"].split(":")[1])
with open(args["-i"], "rb") as f:
data = f.read()
with open(args["-o"], "wb") as f:
f.write(bytes(b ^ key[0] for b in data))
"""
def encrypt(data: bytes) -> bytes:
return bytes(b ^ bytes.fromhex(KEY)[0] for b in data)
@pytest.fixture(autouse=True)
def tool(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
"""A bbtsdecrypt on this machine that XORs each byte with the first byte of the content key it gets."""
script = tmp_path / "bbtsdecrypt.py"
script.write_text(TOOL, encoding="utf-8")
if sys.platform == "win32":
path = tmp_path / "bbtsdecrypt.bat"
path.write_text(f'@"{sys.executable}" "{script}" %*\n', encoding="utf-8")
else:
path = tmp_path / "bbtsdecrypt"
path.write_text(f"#!{sys.executable}\n{TOOL}", encoding="utf-8")
path.chmod(0o755)
monkeypatch.setattr(monalisa, "local_tool", functools.cache(monalisa.local_tool.__wrapped__))
find = binaries.find
monkeypatch.setattr(binaries, "find", lambda *names, **kw: path if "bbtsdecrypt" in names else find(*names, **kw))
yield path
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def server_track(monkeypatch: pytest.MonkeyPatch) -> Video:
"""The track the service built on the server: its MonaLisa DRM read the content key from a ticket."""
def extract_keys(drm: MonaLisa) -> None:
drm._kid = KID
drm.content_keys[KID] = KEY
monkeypatch.setattr(MonaLisa, "extract_keys", extract_keys)
track = Video(
id_="vid",
url="https://example.test/seg0.ts",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
drm=[MonaLisa("EXAMPLE-TICKET", Path("server-only.mld"), segment_decrypt=False)],
)
track.data["hls"] = {"playlist_text": PLAYLIST}
return track
def server_of(track: Video, licensor: Licensor = Licensor.SERVER_CDM) -> Any:
"""A remote session on the server that holds the track."""
service = SimpleNamespace(fairplay_bridge=lambda: None, session=None)
return session_entry(service_instance=service, tracks={"vid": track}, licensing=LicensingMode(licensor))
def client_of(server: Any, posts: list[dict]) -> Any:
"""A client of the server session whose licence requests run the licence route of the server."""
remote = remote_session(None, {})
def post(endpoint: str, payload: dict, expect: Any = ()) -> dict:
posts.append(payload)
return json.loads(handlers.license_response(payload, server, "sess", None).text)
remote.client = SimpleNamespace(post=post)
return remote
def rebuilt(track: Video) -> Video:
"""The track as the client rebuilds it from the track list of the server, with the playlist its snapshot holds."""
payload = json.dumps(serialize_video_track(track, include_url=True))
assert KEY not in payload and "EXAMPLE-TICKET" not in payload and "server-only.mld" not in payload
track = build_tracks({"video": [json.loads(payload)]}).videos[0]
track.data["hls"] = {"playlist_text": PLAYLIST}
return track
def segments(urls: list[dict], output_dir: Path, filename: str, body: Any = None, **_: Any) -> Iterator[dict]:
"""The ciphertext of each segment, saved as the downloader of a track saves it; ``body`` gives other bytes."""
for i, url in enumerate(urls):
path = output_dir / filename.format(i=i, ext=".ts")
path.write_bytes(body() if body else encrypt(PLAIN[int(url["url"][-4])]))
yield {"file_downloaded": path}
def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segments) -> bytes:
"""Download the track through the licence step; return the output file."""
track.downloader = downloader
ctx = DownloadContext(
save_path=tmp_path / "video.ts",
save_dir=tmp_path / "video_segments",
progress=lambda **_: None,
license_widevine=licence,
cdm=None,
session=requests.Session(),
)
HLS.download_track(track=track, ctx=ctx)
return ctx.save_path.read_bytes()
def test_the_batch_licence_keys_the_client_copy_and_the_client_tool_decrypts(
server_track: Video, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
track = rebuilt(server_track)
drm = track.drm[0]
assert isinstance(drm, MonaLisa) and (drm.kid, drm.key) == (KID, None)
vault = MemoryVault()
keys = resolver(vaults_of(vault))
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
keys.wait_vault_writes()
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert [post.get("track_ids") for post in posts] == [["vid"]]
assert vault.added == {KID: KEY}
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_track: Video, tmp_path: Path) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
output = download(track, tmp_path, keys.licence_for(track, one_title(track), key_table()))
assert output == b"".join(PLAIN)
assert posts == [{"drm_type": "monalisa", "mode": "server_cdm", "track_id": "vid"}]
@pytest.mark.parametrize("licensor", [Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE])
def test_the_server_gives_no_key_outside_a_server_cdm_session(server_track: Video, licensor: Licensor) -> None:
server = server_of(server_track, licensor)
assert server_keys.resolve_batch(server, ["vid"], "widevine", KeyPolicy()).keys == {}
with pytest.raises(APIError, match="not enabled"):
handlers.license_response(
{"mode": "server_cdm", "drm_type": "monalisa", "track_id": "vid"}, server, "sess", None
)
assert not server.served_keys
def test_a_client_device_session_decrypts_with_the_key_of_a_client_vault(server_track: Video, tmp_path: Path) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver(vaults_of(MemoryVault({KID: KEY})))
keys.source = remote
assert download(track, tmp_path, keys.licence_for(track, one_title(track), key_table())) == b"".join(PLAIN)
def test_a_client_with_no_tool_decrypts_each_segment_with_the_built_in_decrypter(
server_track: Video, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(binaries, "find", lambda *_, **__: None)
monalisa.local_tool.cache_clear()
server_track.drm[0].content_keys[KID] = bbts_sample.KEY.hex()
remote = client_of(server_of(server_track), [])
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
output = download(
track,
tmp_path,
keys.licence_for(track, one_title(track), key_table()),
functools.partial(segments, body=bbts_sample.bbts),
)
(tmp_path / "sample.bbts").write_bytes(bbts_sample.bbts())
decrypt_bbts(tmp_path / "sample.bbts", tmp_path / "clear.ts", bbts_sample.KEY)
expected = tmp_path / "expected.ts"
expected.write_bytes((tmp_path / "clear.ts").read_bytes() * len(PLAIN))
renumber_continuity(expected)
assert output == expected.read_bytes()
def test_a_refused_licence_stops_the_track_before_its_segments(server_track: Video, tmp_path: Path) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
licence = keys.licence_for(track, one_title(track), key_table())
with pytest.raises(click.ClickException, match="no MonaLisa content key"):
download(track, tmp_path, licence, lambda **_: pytest.fail("a segment was requested"))