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
+1 -1
View File
@@ -1260,7 +1260,7 @@ 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 licenses this PSSH. Proxy mode gives it to the service licence callback as `pssh` (Widevine) or `pssh_b64` (PlayReady), the PSSH of the header the challenge is for. A proxy-mode PSSH that names a KID the track does not carry goes to no callback. |
| `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. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. |
| `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. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. A MonaLisa track takes `monalisa` with no `pssh` and `mode` `server_cdm`: the server answers in `keys` with the content key that its service extracted, and only in a session that uses the server CDM. |
| `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. |
+1 -1
View File
@@ -446,7 +446,7 @@ service to talk to the platform's license server. unshackle recognizes seven DRM
| `PlayReady` | PlayReady | CDM challenge (WRM header) → license server → content keys (`.prd` device) |
| `ClearKeyCENC` | W3C `org.w3.clearkey` or W3C common PSSH over CENC | JSON KID request → JWK set; no CDM |
| `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. `command_builder` sets the command of the decryption backend, and `segment_decrypt=False` runs it once on the merged file |
| `MonaLisa` | Proprietary WASM DRM | keys extracted locally; no license server. Without `tool_path`, core uses `bbtsdecrypt` per segment, else its built-in decrypter (`core/drm/bbts.py`) per segment. `command_builder` sets the command of the decryption backend, and `segment_decrypt=False` runs it once on the merged file. Over `--remote` only the KID goes to the client, and the server sends the content key under the server CDM. An export also holds only the KID as its DRM, never the tool or the command. One process extracts the keys of one ticket at a time, because the wasmtime bindings are not thread-safe |
| `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 |
+1 -1
View File
@@ -283,7 +283,7 @@ Reconstruct a download (download → decrypt → mux) from an `--export` JSON fi
unshackle import EXPORT_FILE [DL_ARGS...]
```
unshackle forwards any `dl` options after the file verbatim, so you can override quality, range, proxy, and so on.
unshackle forwards any `dl` options after the file verbatim, so you can override quality, range, proxy, and so on. The import selects tracks with the `dl` defaults, not with the selection of the export. Give the selection options of the export again, for example `-r HYBRID` for an export of HDR tracks.
!!! example
```shell
+1 -1
View File
@@ -50,7 +50,7 @@ license-server handshake. The rest are special cases.
| **PlayReady** (Microsoft) | `.prd` | CDM challenge (WRM header) → license server → CDM parses → keys | shaka-packager / mp4decrypt |
| **ClearKey (CENC)**, W3C EME `org.w3.clearkey` or the W3C common PSSH | none | JSON `{"kids":[...],"type":"temporary"}` → license server returns a JWK Set. No CDM. | shaka-packager / mp4decrypt |
| **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. | External tool that the service names, per segment or on the whole track |
| **MonaLisa** (proprietary, WASM) | `.mld` | Ticket from the service API; keys extracted locally via WASM. No license server. Over `--remote` the server extracts the content key and sends it to the client, only when the remote session uses the server CDM. | The tool that the service names, else `bbtsdecrypt` per segment, else the built-in decrypter per segment, which needs no tool. Over `--remote` the client decrypts with its own tool or the built-in decrypter. An export holds the KID and the content key, and an import decrypts like a `--remote` client. After the merge FFmpeg decode-checks the video track; a content key that does not decode stops the track. |
| **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 |
+5
View File
@@ -303,6 +303,11 @@ Each command reports how many files it removed and how much space it freed, then
**Inspect:** the licence server gave no content key for a key ID of the init segments, or gave a PlayReady or Widevine content key that is not the FairPlay one. unshackle flags a content key that does not decode. The next licence of that key ID clears the flag, so each run licenses and checks the key again. Operate unshackle with `-d` and read the `Key check on` debug line for the result of each window. See [DRM & CDM](drm-and-cdm.md).
!!! example "A MonaLisa track stops after its decryption"
**Symptom:** the download of a MonaLisa video track stops with `The MonaLisa content key of KID <kid> does not decrypt track <id>`, and unshackle keeps no output file.
**Inspect:** FFmpeg could not decode the decrypted track, so the content key is wrong, or the platform changed its BBTS format and the decrypter no longer fits it. unshackle flags the pair in the local vaults and does not copy it to another vault. Run again with the other decrypter: hide `bbtsdecrypt` to use the built-in one, or install it. If both fail, the content key is wrong. See [DRM & CDM](drm-and-cdm.md).
!!! example "A network request fails at the connection or TLS layer"
**Symptom:** timeouts, connection resets, or handshake errors, and unshackle's own logs do not give the full cause.
+2 -2
View File
@@ -36,7 +36,7 @@ unshackle pushes keys from every source, not only a local CDM. A run against a r
### Wrong keys from a poisoned vault
A public vault can return the right KID with a wrong content key. The decrypters accept a wrong content key and write noise. unshackle therefore trusts a content key from a vault only after FFmpeg decodes the decrypted track with strict error detection. For a fragmented MP4, unshackle reads from the encrypted file which fragments each KID encrypts, and FFmpeg decodes up to three windows of each KID: from its first, middle and last fragment on through the next fragments of that KID, for up to 4 seconds. A window never runs into a fragment of another KID or a clear fragment. A clear lead or a lead under another KID therefore cannot hide a wrong content key, and only the KID that fails is flagged. When every KID in the map has a content key, the map is complete, and a KID that is not in it does not encrypt this file. This file does not judge that KID; the file of its own track judges it. A file with no encrypted sample entry and no encrypted fragment, for example a clear audio track, judges no KID, so it neither flags nor copies a content key. A KID that is not in an incomplete map, for example one with an all-zero KID, and every KID of any other file, gets one check of the whole file. FFmpeg decodes the first seconds and the last seconds. A failure there flags each of those KIDs. When a mapped KID fails, the KIDs that are not in the map get no verdict from that pass; the retry with the replaced key judges them. Content keys from a licence skip this check, except those of a FairPlay-only track that the FairPlay bridge licensed. An import also checks these content keys when it reads them from an export file. When one of these fails, unshackle flags the pair, stops the track and keeps no output file. A file this FFmpeg build cannot judge counts as a pass, never as a wrong content key: a codec it has no decoder for, or a header it cannot read. A pass is not proof. A wrong content key for HEVC video can decode without an error for some seconds, most often at a low resolution, and that content key passes the check. Without FFmpeg there is no check at all.
A public vault can return the right KID with a wrong content key. The decrypters accept a wrong content key and write noise. unshackle therefore trusts a content key from a vault only after FFmpeg decodes the decrypted track with strict error detection. For a fragmented MP4, unshackle reads from the encrypted file which fragments each KID encrypts, and FFmpeg decodes up to three windows of each KID: from its first, middle and last fragment on through the next fragments of that KID, for up to 4 seconds. A window never runs into a fragment of another KID or a clear fragment. A clear lead or a lead under another KID therefore cannot hide a wrong content key, and only the KID that fails is flagged. When every KID in the map has a content key, the map is complete, and a KID that is not in it does not encrypt this file. This file does not judge that KID; the file of its own track judges it. A file with no encrypted sample entry and no encrypted fragment, for example a clear audio track, judges no KID, so it neither flags nor copies a content key. A KID that is not in an incomplete map, for example one with an all-zero KID, and every KID of any other file, gets one check of the whole file. FFmpeg decodes the first seconds and the last seconds. A failure there flags each of those KIDs. When a mapped KID fails, the KIDs that are not in the map get no verdict from that pass; the retry with the replaced key judges them. Content keys from a licence skip this check, with two exceptions: a FairPlay-only track that the FairPlay bridge licensed, and a MonaLisa video track. A MonaLisa track is MPEG-TS, so it gets the check of the whole file after the merge of its decrypted segments. This applies to both decrypters. An import also checks these content keys when it reads them from an export file. When one of these fails, unshackle flags the pair, stops the track and keeps no output file. A file this FFmpeg build cannot judge counts as a pass, never as a wrong content key: a codec it has no decoder for, or a header it cannot read. A BBTS decrypter keeps the continuity counter of a TS packet that it empties, so unshackle corrects the counters of a MonaLisa track before the check. A pass is not proof. A wrong content key for HEVC video can decode without an error for some seconds, most often at a low resolution, and that content key passes the check. Damage to a small part of the slice data, such as one corrupt NAL unit, also often decodes without an error. Without FFmpeg there is no check at all.
When the decode fails, unshackle:
@@ -46,7 +46,7 @@ When the decode fails, unshackle:
The download stops with an error instead of writing noise when no ciphertext is left to retry with, or when every vault and the CDM are used up. Without a local SQLite vault nothing remembers a flag, so the same vault serves the same pair again and the download stops there.
Per-segment decryption gives up the retry. With `decrypt_segments` on, and always with a MonaLisa tool that decrypts segments, the plaintext replaces each segment as it arrives, so no ciphertext is left. A failed decode then flags the pair and stops the download. The next run skips the flagged pair.
Per-segment decryption gives up the retry. With `decrypt_segments` on, and always with a per-segment MonaLisa decrypter, the plaintext replaces each segment as it arrives, so no ciphertext is left. A failed decode then flags the pair and stops the download. The next run skips the flagged pair.
unshackle copies a content key from one vault to the others only after this check passes, so a content key that fails the check does not spread. Without FFmpeg, a content key from a vault is not copied at all. To see or clear the flags, open the SQLite file and read or delete rows in `bad_keys`.
+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"))
+2 -1
View File
@@ -2261,7 +2261,8 @@ class dl:
if self._remote_service.key_arrival is KeyArrival.EXPORT:
self.log.info("Using keys from the export; no CDM required")
elif (keyed := [*title.tracks.videos, *title.tracks.audio]) and all(
track.drm and all(isinstance(drm, WHOLE_FILE_DRM) for drm in track.drm) for track in keyed
track.drm and all(isinstance(drm, (*WHOLE_FILE_DRM, MonaLisa)) for drm in track.drm)
for track in keyed
):
self.log.info("Using keys from the server; no local CDM required")
else:
+9 -1
View File
@@ -55,7 +55,7 @@ from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.cdm.loader import device_system
from unshackle.core.config import config
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
from unshackle.core.drm import cbcs, monalisa_drm, real_kids, whole_file_cipher
from unshackle.core.drm.discovery import ensure_track_drm
from unshackle.core.launch import LaunchKeys, served_context
from unshackle.core.manifests.snapshot import capture
@@ -3793,6 +3793,14 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
title = server_keys.find_title_for_track(track_id, session)
service = session.service_instance
monalisa = monalisa_drm(track)
if monalisa is not None and mode == "server_cdm":
if vault_only:
raise APIError(
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
)
return web.json_response(LicenseReply(keys=server_keys.served_monalisa_keys(session, monalisa)))
cipher = whole_file_cipher(track)
if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
if vault_only and cipher.key is None:
+1 -1
View File
@@ -2449,7 +2449,7 @@ async def session_license(request: web.Request) -> web.Response:
description: Base64-encoded CDM challenge
drm_type:
type: string
enum: [widevine, playready]
enum: [widevine, playready, monalisa]
description: DRM type (default widevine)
is_certificate:
type: boolean
+16 -3
View File
@@ -17,7 +17,7 @@ from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.cdm.choice import SYSTEMS, choose_cdm
from unshackle.core.cdm.detect import cdm_system
from unshackle.core.cdm.loader import device_system
from unshackle.core.drm import WHOLE_FILE_DRM, is_null_key, whole_file_cipher
from unshackle.core.drm import WHOLE_FILE_DRM, MonaLisa, is_null_key, monalisa_drm, whole_file_cipher
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.title_source import service_licence
@@ -479,6 +479,13 @@ def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]
session.served_keys[kid] = (key, sources.get(kid, "cdm"))
def served_monalisa_keys(session: Any, drm: MonaLisa) -> dict[str, str]:
"""The content keys of a MonaLisa DRM the service built on the server, recorded as served by its device."""
keys = {kid.hex: key for kid, key in drm.content_keys.items()}
note_served_keys(session, keys, {})
return keys
def pssh_set(track: Any) -> tuple:
"""Every PSSH and KID the track carries, as the rest of the cache key.
@@ -625,8 +632,9 @@ class BatchKeys:
def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy: KeyPolicy) -> BatchKeys:
"""The server keys of each track in ``track_ids`` the remote session holds, with the client's ``drm_type``.
A whole-file cipher track gets its file key, a track without a licensed DRM is listed as clear, and a
track the server must not license live is listed as capped with its refusal details.
A whole-file cipher track gets its file key; a MonaLisa track gets the key of the DRM its service built, in a
server CDM session only. A track without a licensed DRM is listed as clear, and a track the server must not
license live is listed as capped with its refusal details.
``drm_type`` of the result is the system of the last keyed track.
"""
resolver = ServerKeys(session, policy)
@@ -636,6 +644,11 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
track = session.tracks.get(tid)
if not track:
continue
monalisa = monalisa_drm(track)
if monalisa is not None:
if session.licensing.server_cdm and monalisa.content_keys:
batch.keys[tid] = served_monalisa_keys(session, monalisa)
continue
svc_session = getattr(service, "session", None)
init_data = fetch_init_segment(track, svc_session)
@@ -25,6 +25,8 @@ class MonaLisaCDM:
"""
MonaLisa CDM wrapper for WASM-based content key extraction.
Not thread-safe: drive it through ``drm.MonaLisa``, which holds its ``CDM_LOCK`` for each licence.
This CDM differs from Widevine/PlayReady in that it does not use a
challenge/response flow with a license server. Instead, the service API
gives the license (ticket) directly, and the WASM module extracts the
+2 -1
View File
@@ -6,7 +6,7 @@ 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.monalisa import MonaLisa, monalisa_drm
from unshackle.core.drm.paged_aac import PAGED_AAC
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.widevine import Widevine
@@ -46,6 +46,7 @@ __all__ = (
"Widevine",
"PlayReady",
"MonaLisa",
"monalisa_drm",
"PAGED_AAC",
"DRM_T",
"WHOLE_FILE_DRM",
+349
View File
@@ -0,0 +1,349 @@
"""Decrypt a BBTS file: an MPEG-TS whose video NAL units a sparse AES-128-CTR cipher encrypts.
The cipher follows bbtsdecrypt (https://github.com/ReiDoBrega/bbtsdecrypt, MIT licence). The output matches the
bbtsdecrypt binary, which differs from that source: the IV field, no refill of the removed emulation-prevention
bytes, and dropped delimiters and cipher padding.
"""
from __future__ import annotations
import itertools
import re
import zlib
from collections.abc import Callable
from pathlib import Path
from Cryptodome.Cipher import AES
from Cryptodome.Util.strxor import strxor
PACKET = 188
SYNC = 0x47
PID_PAT = 0x0000
PID_SDT = 0x0011
PID_PMT = 0x1000
VIDEO_PID = 0x0100
AUDIO_PID = 0x0101
H264 = 0x1B
START_CODE = b"\x00\x00\x01"
START_CODES = re.compile(re.escape(START_CODE))
IV_FIELD = re.compile(rb"\|v([0-9A-Fa-f]{32})\|")
HEX_IV = re.compile(rb"([0-9A-Fa-f]{32})")
AUD = {True: 9, False: 35}
SEI = {True: (6,), False: (39, 40)}
DOVI_RPU = 62
BIT_REVERSED = bytes(int(f"{i:08b}"[::-1], 2) for i in range(256))
def decrypt_bbts(src: Path, dst: Path, key: bytes) -> None:
"""Write the clear MPEG-TS of the BBTS file ``src`` to ``dst``; only the video PES packets change."""
if len(key) != 16:
raise ValueError(f"BBTS needs a 16-byte key, got {len(key)}")
with src.open("rb") as reader, dst.open("wb") as writer:
_Decrypter(key, writer.write).run(reader.read)
def renumber_continuity(path: Path) -> None:
"""Give each TS packet of ``path`` the continuity counter that ISO/IEC 13818-1 expects, in place.
A BBTS decrypter keeps the counter of a packet that it empties, so the counter steps where it must not and FFmpeg
marks the next frame corrupt. A duplicate packet keeps its counter.
"""
last: dict[int, int] = {}
original: dict[int, int] = {}
with path.open("r+b") as f:
while chunk := bytearray(f.read(PACKET * 65536)):
changed = False
for i in range(0, len(chunk) - PACKET + 1, PACKET):
pid = (chunk[i + 1] & 0x1F) << 8 | chunk[i + 2]
header = chunk[i + 3]
cc = header & 0x0F
if pid == 0x1FFF:
continue
if pid in last:
payload = header & 0x10 and cc != original[pid]
original[pid] = cc
cc = (last[pid] + 1) & 0x0F if payload else last[pid]
if cc != header & 0x0F:
chunk[i + 3] = header & 0xF0 | cc
changed = True
else:
original[pid] = cc
last[pid] = cc
if changed:
f.seek(-len(chunk), 1)
f.write(chunk)
class _Keystream:
"""The keystream of one IV. Each NAL unit starts again at IV + 1, so one keystream serves every NAL unit of a PES.
Block 0, every tenth block and the last block XOR with AES-ECB of the counter; every other block XORs with the
counter bytes themselves.
"""
def __init__(self, key: bytes, iv: bytes) -> None:
self.key = key
self.counter = int.from_bytes(iv, "big") + 1
self.encrypted = b""
self.sparse = b""
def get(self, size: int) -> bytes:
"""The keystream of a NAL unit of ``size`` bytes."""
if size > len(self.encrypted):
self._grow(max(size, 2 * len(self.encrypted), 4096))
last = (size - 1) // 16 * 16
return self.sparse[:last] + self.encrypted[last:size]
def _grow(self, size: int) -> None:
size = -(-size // 160) * 160
encrypted = AES.new(self.key, AES.MODE_CTR, nonce=b"", initial_value=self.counter).encrypt(bytes(size))
# AES-ECB decryption of the CTR keystream gives back the counter blocks, all in C.
counters = int.from_bytes(AES.new(self.key, AES.MODE_ECB).decrypt(encrypted), "big")
every_tenth = int.from_bytes((b"\xff" * 16 + bytes(144)) * (size // 160), "big")
mixed = counters ^ ((counters ^ int.from_bytes(encrypted, "big")) & every_tenth)
self.encrypted, self.sparse = encrypted, mixed.to_bytes(size, "big")
def _decrypt_payload(data: bytes, keystream: _Keystream) -> bytes:
"""The clear bytes of a NAL payload: its emulation-prevention bytes removed, then the keystream XORed in."""
raw = data.replace(b"\x00\x00\x03", b"\x00\x00")
return strxor(raw, keystream.get(len(raw)))
def _sei_ends_at_stop_bit(rbsp: bytes) -> bool:
"""Whether the SEI messages of an RBSP end exactly on its final stop-bit byte."""
pos, last = 0, len(rbsp) - 1
while pos < last:
while pos < last and rbsp[pos] == 0xFF:
pos += 1
pos += 1
size = 0
while pos < last and rbsp[pos] == 0xFF:
size, pos = size + 255, pos + 1
if pos >= last:
return False
pos += 1 + size + rbsp[pos]
return pos == last and rbsp[last] == 0x80
def _padded(nal: bytes, kind: int, h264: bool) -> bool:
"""Whether a SEI or Dolby Vision RPU NAL unit is whole without its last 4 bytes, which the cipher appended."""
sei = kind in SEI[h264]
if not sei and (h264 or kind != DOVI_RPU):
return False
rbsp = nal[(1 if h264 else 2) : -4].replace(b"\x00\x00\x03", b"\x00\x00")
if len(rbsp) < 2:
return False
if sei:
return _sei_ends_at_stop_bit(rbsp)
# An RPU ends with a CRC-32/MPEG-2 of the bytes after its 0x19 prefix, then the stop-bit byte.
return rbsp[0] == 0x19 and rbsp[-1] == 0x80 and zlib.crc32(rbsp[1:-1].translate(BIT_REVERSED)) == 0xFFFFFFFF
def _decrypt_pes(pes: bytes, stream_type: int, keystream: _Keystream) -> bytes:
"""Decrypt each NAL unit of a video PES packet and drop what the cipher added.
Start codes, NAL headers and the last 2 bytes of a NAL unit stay clear. Access unit delimiters go, and so do the
4 bytes the cipher appends to a SEI message or a Dolby Vision RPU.
"""
header_end = 9 + pes[8]
if header_end > len(pes):
return pes
h264 = stream_type == H264
skip = 3 + (1 if h264 else 2)
end = len(pes)
bounds = [header_end, *(found.start() for found in START_CODES.finditer(pes, header_end + 1)), end]
out = [pes[:header_end]]
for start, stop in itertools.pairwise(bounds):
# A zero byte before the next start code belongs to that 4-byte start code.
nal_end = stop - 1 if stop < end and pes[stop - 1] == 0 else stop
if nal_end - start <= 3 or pes[start : start + 3] != START_CODE:
out.append(pes[start:stop])
continue
cut = nal_end - 2
if cut > start + skip:
nal = (
pes[start + 3 : start + skip] + _decrypt_payload(pes[start + skip : cut], keystream) + pes[cut:nal_end]
)
else:
nal = pes[start + 3 : nal_end]
kind = nal[0] & 0x1F if h264 else nal[0] >> 1 & 0x3F
if kind == AUD[h264]:
out.append(pes[nal_end:stop])
continue
if len(nal) > 4 and _padded(nal, kind, h264):
nal = nal[:-4]
out += [START_CODE, nal, pes[nal_end:stop]]
clear = b"".join(out)
if pes[4:6] != b"\x00\x00":
clear = clear[:4] + (len(clear) - 6).to_bytes(2, "big") + clear[6:]
return clear
def _payload_offset(packet: bytes) -> int:
"""Where the payload of a TS packet starts, or PACKET when it has none."""
control = (packet[3] >> 4) & 3
if control == 1:
return 4
if control == 3:
return 5 + packet[4]
return PACKET
def _stuffed(header: bytes, extra: int, empty: bool) -> bytes:
"""A TS packet header whose adaptation field grows by ``extra`` stuffing bytes; with no payload left, it says so."""
control = 0x20 if empty else 0x30
if header[3] & 0x20:
length = header[4]
stuffing = b"\xff" * extra if length else b"\x00" + b"\xff" * (extra - 1)
return header[:3] + bytes([header[3] & 0xCF | control, length + extra]) + header[5:] + stuffing
stuffing = b"\x00" + b"\xff" * (extra - 2) if extra > 1 else b""
return header[:3] + bytes([header[3] & 0xCF | control, extra - 1]) + stuffing
class _Section:
"""Reassembles the PSI sections of one PID."""
def __init__(self) -> None:
self.buffer: bytes | None = None
def push(self, packet: bytes) -> bytes | None:
"""Add a packet; return the section it completes."""
offset = _payload_offset(packet)
if offset >= PACKET:
return None
payload = packet[offset:]
if packet[1] & 0x40:
pointer = payload[0]
if pointer > len(payload) - 1:
return None
payload = payload[1 + pointer :]
self.buffer = b""
if self.buffer is None:
return None
self.buffer += payload
if len(self.buffer) >= 3 and len(self.buffer) >= (total := 3 + ((self.buffer[1] & 0x0F) << 8 | self.buffer[2])):
section, self.buffer = self.buffer[:total], None
return section
return None
def _sdt_iv(section: bytes) -> bytes | None:
"""The IV of a service-name descriptor (tag 0x48) that holds "mdcm|".
The IV is an inner "|" field of "v" and 32 hex digits, else a fourth "|" field of 32 hex digits.
"""
if len(section) < 16 or section[0] != 0x42:
return None
end = len(section)
pos = 11
while pos + 5 <= end - 4:
loop_end = pos + 5 + ((section[pos + 3] & 0x0F) << 8 | section[pos + 4])
at = pos + 5
while at + 2 <= loop_end and at + 2 <= end - 4:
tag, length = section[at], section[at + 1]
at += 2
if at + length > len(section):
break
body = section[at : at + length]
at += length
if tag != 0x48 or len(body) < 3 or 2 + body[1] >= len(body):
continue
name_at = 2 + body[1]
name = body[name_at + 1 : name_at + 1 + body[name_at]]
if b"mdcm|" not in name:
continue
fields = name.split(b"|")
if field := IV_FIELD.search(name) or (len(fields) > 3 and HEX_IV.fullmatch(fields[3])):
return bytes.fromhex(field[1].decode())[:12] + bytes(4)
pos = loop_end
return None
def _pmt_streams(section: bytes) -> list[tuple[int, int]]:
"""The PID and ``stream_type`` of each elementary stream of a PMT section."""
if len(section) < 12 or section[0] != 0x02:
return []
end = len(section)
pos = 12 + ((section[10] & 0x0F) << 8 | section[11])
streams = []
while pos + 5 <= end - 4:
streams.append((((section[pos + 1] & 0x1F) << 8) | section[pos + 2], section[pos]))
pos += 5 + ((section[pos + 3] & 0x0F) << 8 | section[pos + 4])
return streams
class _Decrypter:
"""One pass over a BBTS file. Each video PES packet decrypts with the IV of the last SDT before it starts."""
def __init__(self, key: bytes, write: Callable[[bytes], object]) -> None:
self.key = key
self.write = write
self.sdt, self.pmt = _Section(), _Section()
self.iv: bytes | None = None
self.keystream: _Keystream | None = None
self.streams: list[tuple[int, int]] = []
self.pes = bytearray()
self.headers: list[bytes] = []
self.pes_pid = 0
def flush(self) -> None:
"""Write the held PES packet back into the TS packets it came from; a shorter one ends in stuffing."""
if not self.headers:
return
pes = bytes(self.pes)
if len(pes) > 8 and pes[3] == 0xE0 and self.keystream:
stream_type = next((kind for pid, kind in self.streams if pid == self.pes_pid), 0)
pes = _decrypt_pes(pes, stream_type, self.keystream)
pos, out = 0, []
for header in self.headers:
size = PACKET - len(header)
payload = pes[pos : pos + size]
pos += size
if len(payload) < size:
header = _stuffed(header, size - len(payload), not payload)
out += [header, payload]
self.write(b"".join(out))
self.pes.clear()
self.headers.clear()
def run(self, read: Callable[[int], bytes]) -> None:
"""Decrypt every packet that ``read`` gives."""
while len(packet := read(PACKET)) == PACKET:
self.packet(packet)
self.flush()
def packet(self, packet: bytes) -> None:
"""Take one TS packet."""
if packet[0] != SYNC:
self.write(packet)
return
pid = (packet[1] & 0x1F) << 8 | packet[2]
if pid in (PID_PAT, PID_SDT, PID_PMT):
self.flush()
if pid == PID_SDT and (section := self.sdt.push(packet)) and (iv := _sdt_iv(section)):
if iv != self.iv:
self.iv, self.keystream = iv, _Keystream(self.key, iv)
elif pid == PID_PMT and (section := self.pmt.push(packet)):
self.streams = _pmt_streams(section)
self.write(packet)
return
if not self.keystream:
self.write(packet)
return
offset = _payload_offset(packet) if pid in (VIDEO_PID, AUDIO_PID) else PACKET
if offset >= PACKET:
self.flush()
self.write(packet)
return
starts = (
offset + 8 < PACKET and packet[offset : offset + 3] == START_CODE and packet[offset + 3] in (0xC0, 0xE0)
)
if starts:
self.flush()
elif not self.headers:
self.write(packet)
return
self.pes += packet[offset:]
self.headers.append(packet[:offset])
self.pes_pid = pid
+53 -16
View File
@@ -37,6 +37,7 @@ from unshackle.core.drm import (
real_kids,
verify,
)
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.title_source import TitleSource, service_licence
from unshackle.core.titles import Title_T
from unshackle.core.tracks import Video
@@ -148,12 +149,12 @@ class ContentKeyResolver:
vaults, the ciphertext is restored, and the licence runs again; ``Vaults`` tells the
vault that served it. Every vault skips a flagged pair, so each pass burns at most one
vault; when the vaults run out the CDM answers, and a CDM key is not checked, except that of a
bridged FairPlay-only track: one that does not decode stops the track. A CDM
bridged FairPlay-only track or a MonaLisa track: one that does not decode stops the track. A CDM
that returns the flagged key clears the flag and stores the content key again, because
then the decode check was wrong.
With ``decrypt=False`` the downloader already decrypted the segments in place, so a
failure can only flag and raise; the next run skips the flagged pair.
failure can only flag and raise; the next run skips the flagged pair. A MonaLisa track also loses its output.
After a decrypt that passes, the server key source's vault gets the proven content keys of
``track``: each licence key, and each vault key the decode check passed. A bridged track sends only
@@ -227,7 +228,8 @@ class ContentKeyResolver:
found = {kid: self.vaults.source_of(kid, key) for kid, key in keys.items()}
return {kid: source for kid, source in found.items() if source is not None}
bridged = bool(getattr(drm, "bridged", False))
monalisa = isinstance(drm, MonaLisa)
bridged = bool(getattr(drm, "bridged", False)) or monalisa
backup = path.with_name(path.name + ".enc")
backup.unlink(missing_ok=True) # a killed run leaves one behind; its bytes may not match
checking = bool((vault_kids() or bridged) and decrypt and binaries.FFMPEG)
@@ -262,12 +264,23 @@ class ContentKeyResolver:
return {kid: vault for kid, vault in kids.items() if kid in windows}
return kids
def refuse_bad_licence_keys() -> set[UUID]:
"""Stop a bridged track whose licence content key does not decode, and flag the pair like a bad vault key.
def refuse(kid: UUID) -> None:
"""Delete the output and stop the track for the content key of ``kid``."""
path.unlink(missing_ok=True)
name = "MonaLisa" if monalisa else "licence"
raise coded(
click.ClickException(
f"The {name} content key of KID {kid.hex} does not decrypt track {getattr(track, 'id', path.name)}"
),
APIErrorCode.DRM_ERROR,
)
A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one.
The flag goes through the vault writer, after the licence's own write of the pair. Returns the KIDs that
the check decoded.
def refuse_bad_licence_keys() -> set[UUID]:
"""Stop a bridged or MonaLisa track whose licence key does not decode; flag the pair like a bad vault key.
A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one,
and a BBTS decrypter reports no error for a wrong key. The flag goes through the vault writer, after the
licence's own write of the pair. Returns the KIDs that the check decoded.
"""
if not (bridged and binaries.FFMPEG and path.exists()):
return set()
@@ -275,11 +288,7 @@ class ContentKeyResolver:
licensed = judged_kids({kid: None for kid in real_kids(drm) if kid in keys and kid not in sourced})
if bad := failed_kids(licensed):
self._flush_vault_writes([partial(self.vaults.flag_bad_key, kid, drop(kid)) for kid in bad])
path.unlink()
kid = next(kid for kid in licensed if kid in bad)
raise ValueError(
f"The licence content key of KID {kid.hex} does not decrypt track {getattr(track, 'id', path.name)}"
)
refuse(next(kid for kid in licensed if kid in bad))
return set(licensed)
def failed_kids(kids: dict[UUID, Any]) -> set[UUID]:
@@ -327,12 +336,18 @@ class ContentKeyResolver:
self._flush_vault_writes([partial(server_vault.add_keys, self.tag, sent, track)])
return
bad = {kid: drop(kid) for kid in {*failed, *stale}}
retry = backup.exists() and licence
for kid, key in bad.items():
if kid not in kids:
continue
if retry:
self.log.warning(f"{key} from {kids[kid].name} was bad, trying other vaults")
else:
self.log.debug(f"{key} from {kids[kid].name} was bad")
self.vaults.flag_bad_key(kid, key)
if not backup.exists() or not licence:
if not retry:
if monalisa:
refuse(min(bad))
raise ValueError("The content key from the vault did not decrypt the track; run again")
path.unlink()
os.link(backup, path)
@@ -903,6 +918,11 @@ class ContentKeyResolver:
if server_cdm and not licensed_locally:
if not drm.content_keys:
if isinstance(drm, MonaLisa):
raise coded(
click.ClickException(f"The server sent no MonaLisa content key for track {track.id}"),
APIErrorCode.DRM_ERROR,
)
self.log.warning("Server CDM did not resolve any keys for this track")
return
if track_kid and track_kid not in drm.content_keys:
@@ -912,7 +932,11 @@ class ContentKeyResolver:
raise Widevine.Exceptions.CEKNotFound(msg)
assert remote is not None
server_drm_type = remote.server_cdm_type
drm_name = {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__)
drm_name = (
"MonaLisa"
if isinstance(drm, MonaLisa)
else {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__)
)
log_event(
"drm_content_keys",
level="INFO",
@@ -939,6 +963,10 @@ class ContentKeyResolver:
cek_tree = Tree(Text.assemble((drm_name, "cyan"), (f"({pssh_str})", "text"), overflow="fold"))
else:
cek_tree = Tree(Text.assemble((drm_name, "cyan"), overflow="fold"))
shown = next(
(x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None
)
cek_tree = shown or cek_tree
all_kids = self._with_track_kid(drm, track_kid)
for kid in all_kids:
if kid in drm.content_keys:
@@ -946,7 +974,7 @@ class ContentKeyResolver:
for kid, key in drm.content_keys.items():
if kid not in all_kids:
self._add_key_label(cek_tree, kid, key)
if not any(isinstance(x, Tree) and x.label == cek_tree.label for x in table.columns[0].cells):
if shown is None:
table.add_row(cek_tree)
if self.export:
self.export(title, track, drm)
@@ -1005,6 +1033,15 @@ class ContentKeyResolver:
self.export(title, track, drm)
elif isinstance(drm, MonaLisa):
if not drm.content_keys:
self._take_known_keys(drm, drm.kids, track, track_kid, None)
if not drm.content_keys:
raise coded(
click.ClickException(
f"No MonaLisa content key for track {track.id} from a vault or the server CDM"
),
APIErrorCode.DRM_ERROR,
)
with self.drm_lock(drm):
display_id = drm.content_id or drm.pssh
pssh_display = truncate_pssh_for_display(display_id, "MonaLisa")
+108 -49
View File
@@ -7,18 +7,43 @@ A WASM-based DRM system that uses local content key extraction from ticket data.
from __future__ import annotations
import base64
import functools
import gc
import logging
import threading
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import Any
from uuid import UUID
from unshackle.core import binaries
from unshackle.core.cdm.monalisa import MonaLisaCDM
from unshackle.core.drm.bbts import decrypt_bbts
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.utils.subprocess import run_step
log = logging.getLogger(__name__)
CommandBuilder = Callable[[Path, Path, Path, str, str], Sequence[str | Path]]
CDM_LOCK = threading.Lock()
def bbtsdecrypt_command(tool_path: Path, src: Path, dst: Path, kid: str, key: str) -> Sequence[str | Path]:
"""The bbtsdecrypt command that decrypts one file, a segment or a whole track."""
return [tool_path, "-i", src, "-o", dst, "-k", f"{kid}:{key}"]
@functools.cache
def local_tool() -> Path | None:
"""This machine's bbtsdecrypt, which decrypts each segment, or None for the built-in decrypter."""
return binaries.find("bbtsdecrypt", "bbtsdecryptor", "bbts-decrypt", "bbts-decryptor")
def monalisa_drm(track: Any) -> MonaLisa | None:
"""The MonaLisa DRM of a track, with or without a content key."""
return next((d for d in getattr(track, "drm", None) or [] if isinstance(d, MonaLisa)), None)
class MonaLisa:
"""
@@ -42,11 +67,13 @@ class MonaLisa:
def __init__(
self,
ticket: str | bytes,
device_path: Path,
ticket: str | bytes | None = None,
device_path: Path | None = None,
tool_path: Path | None = None,
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
segment_decrypt: bool = True,
command_builder: CommandBuilder | None = None,
segment_decrypt: bool | None = None,
*,
kid: UUID | str | None = None,
**kwargs: Any,
) -> None:
"""
@@ -55,48 +82,72 @@ class MonaLisa:
Args:
ticket: PSSH value from service API (base64 string or raw bytes).
device_path: Path to the CDM device file (.mld).
tool_path: Optional path to an external decryption binary.
tool_path: Optional path to an external decryption binary; without it, this machine's
tool (`local_tool`) decrypts, else the built-in BBTS decrypter.
command_builder: Optional callback `(tool_path, src, dst, kid_hex, key_hex) -> args`
that builds the decryption CLI invocation (default: `-i src -o dst -k kid:key`).
segment_decrypt: Whether the external tool supports per-segment decryption.
that builds the decryption CLI invocation (default: `bbtsdecrypt_command`).
segment_decrypt: Whether the decrypter supports per-segment decryption.
kid: The KID of a copy with no ticket, whose content key comes from elsewhere (a remote server).
**kwargs: Additional metadata stored in self.data.
Raises:
TicketNotFound: If ticket/PSSH is empty.
TicketNotFound: If ticket/PSSH is empty and the caller gives no kid.
KeyExtractionFailed: If content key extraction fails.
"""
if not ticket:
if not ticket and kid is None:
raise MonaLisa.Exceptions.TicketNotFound("No PSSH/ticket data provided.")
self._ticket = ticket
self._ticket = ticket or ""
self._device_path = device_path
self._tool_path = tool_path
self._command_builder = command_builder
self._command_builder = command_builder or bbtsdecrypt_command
self._segment_decrypt = segment_decrypt
self._decrypted_segments: int = 0
self._kid: UUID | None = None
self._key: str | None = None
self._kid: UUID | None = kid if kid is None or isinstance(kid, UUID) else UUID(hex=kid)
self.content_keys: dict[UUID, str] = {}
self.data: dict = kwargs or {}
if ticket:
self.extract_keys()
def extract_keys(self) -> None:
"""Extract keys from the ticket using the MonaLisa CDM."""
"""Extract keys from the ticket using the MonaLisa CDM.
One licence at a time per process (`CDM_LOCK`): concurrent wasmtime sessions corrupt its shared function table.
"""
if self._device_path is None:
raise MonaLisa.Exceptions.KeyExtractionFailed("Failed to extract keys: no MonaLisa device file")
with CDM_LOCK:
try:
cdm = MonaLisaCDM(device_path=self._device_path)
session_id = cdm.open()
try:
keys = cdm.extract_keys(self._ticket)
keys = self._cdm_keys(self._device_path)
if keys:
kid_hex = keys.get("kid")
if kid_hex:
self._kid = UUID(hex=kid_hex)
self._key = keys.get("key")
if self._kid and keys.get("key"):
self.content_keys[self._kid] = keys["key"]
return
except Exception as e:
error = str(e)
# the failed licence's traceback holds a wasmtime Store: free it while the lock is held
gc.collect()
raise MonaLisa.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {error}")
def _cdm_keys(self, device_path: Path) -> dict[str, Any]:
"""The KID and content key that one MonaLisa CDM session reads from the ticket."""
cdm = MonaLisaCDM(device_path=device_path)
session_id = cdm.open()
try:
return cdm.extract_keys(self._ticket)
finally:
cdm.close(session_id)
except Exception as e:
raise MonaLisa.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {e}") # noqa: B904
def to_dict(self) -> dict[str, Any]:
"""This DRM in the export form; see ``wire.drm_to_dict``."""
from unshackle.core.wire import drm_to_dict
return drm_to_dict(self)
@classmethod
def from_ticket(
@@ -104,8 +155,8 @@ class MonaLisa:
ticket: str | bytes,
device_path: Path,
tool_path: Path | None = None,
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
segment_decrypt: bool = True,
command_builder: CommandBuilder | None = None,
segment_decrypt: bool | None = None,
) -> MonaLisa:
"""
Make a MonaLisa DRM instance from a PSSH/ticket.
@@ -133,10 +184,15 @@ class MonaLisa:
"""Get the Key ID."""
return self._kid
@property
def kids(self) -> list[UUID]:
"""The KID of the track's content key, as a list like the other DRM systems give."""
return [self._kid] if self._kid else []
@property
def key(self) -> str | None:
"""Get the content key as hex string."""
return self._key
return self.content_keys.get(self._kid) if self._kid else None
@property
def pssh(self) -> str:
@@ -187,21 +243,16 @@ class MonaLisa:
return None
@property
def content_keys(self) -> dict[UUID, str]:
"""
Get content keys in the same format as Widevine/PlayReady.
Returns:
Dictionary mapping KID to the content key hex string.
"""
if self._kid and self._key:
return {self._kid: self._key}
return {}
def tool(self) -> Path | None:
"""The external decrypter: the service's, else this machine's (`local_tool`), else None."""
if self._tool_path is None:
self._tool_path = local_tool()
return self._tool_path
@property
def supports_segment_decrypt(self) -> bool:
"""Whether the configured external tool supports per-segment decryption."""
return self._segment_decrypt
"""Whether the decrypter supports per-segment decryption; the built-in one does."""
return self._segment_decrypt is not False
@property
def track_decrypted(self) -> bool:
@@ -209,18 +260,18 @@ class MonaLisa:
The service can keep its merged ciphertext beside that file, and the merge leaves it out.
"""
return not self._segment_decrypt and self._decrypted_segments > 0
return self._segment_decrypt is False and self._decrypted_segments > 0
@property
def key_pair(self) -> str:
"""The formatted ``KID:KEY`` for CLI decryptors (32hex:32hex)."""
if self._kid and self._key:
return f"{self._kid.hex}:{self._key}"
if self._kid and self.key:
return f"{self._kid.hex}:{self.key}"
return ""
def decrypt_segment(self, segment_path: Path, output_path: Path | None = None) -> None:
"""
Decrypt an individual segment file using the configured CLI tool via subprocess.
Decrypt an individual segment file with the external tool, else the built-in decrypter.
Args:
segment_path: Path to the segment file to decrypt.
@@ -231,7 +282,7 @@ class MonaLisa:
def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False) -> None:
"""
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
Decrypt a media file (segment or track) with the external tool, else the built-in decrypter.
A whole-track tool runs once on a service's own merged file, which the service gives an ``output_path``.
The in-place calls of core after it do nothing.
@@ -252,7 +303,7 @@ class MonaLisa:
return
self._execute_decrypt(path, output_path)
if output_path and not self._segment_decrypt:
if output_path and self._segment_decrypt is False:
self._decrypted_segments += 1
def _execute_decrypt(
@@ -262,25 +313,33 @@ class MonaLisa:
*,
timeout: float | None = None,
) -> None:
"""Run the external tool into a temporary file, which replaces the target only on success."""
"""Decrypt into a temporary file, which replaces the target only on success.
Without an external tool, the built-in BBTS decrypter does the work.
"""
if not path or not path.exists():
raise ValueError(f"Target file does not exist: {path}")
if not self._tool_path or not self._tool_path.exists():
raise RuntimeError(f"MonaLisa decryption tool missing: {self._tool_path or 'no tool_path given'}")
tool = self.tool
if tool and not tool.exists():
raise RuntimeError(f"MonaLisa decryption tool missing: {tool}")
if not self.key or not self.kid:
raise MonaLisa.Exceptions.KeyExtractionFailed("Missing content key for decryption.")
target_output = output_path or path
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
cmd: Sequence[str | Path] = [self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair]
if self._command_builder:
cmd = self._command_builder(self._tool_path, path, temp_out, self.kid.hex, self.key)
if tool:
run_step(
cmd,
self._command_builder(tool, path, temp_out, self.kid.hex, self.key),
output=temp_out,
label=f"MonaLisa decryption of {path.name}",
timeout=timeout,
)
else:
try:
decrypt_bbts(path, temp_out, bytes.fromhex(self.key))
except BaseException:
temp_out.unlink(missing_ok=True)
raise
temp_out.replace(target_output)
+4 -1
View File
@@ -102,7 +102,10 @@ class ExportWriter:
own.append(d)
system = str(d.get("system", "")).lower().replace("cenc", "")
pssh = str(d.get("pssh_b64") or "")
if system and all(x.pssh != pssh or x.system != system for x in entry.drm):
# the shared format names these systems only; MonaLisa stays under x-unshackle
if system in ("widevine", "playready", "clearkey") and all(
x.pssh != pssh or x.system != system for x in entry.drm
):
entry.drm.append(mediaexport.Drm(system, pssh))
content_keys = getattr(drm, "content_keys", None) or {}
pool = doc.key_pool()
+3 -3
View File
@@ -17,7 +17,7 @@ from langcodes import tag_is_valid
from unshackle.core.config import config
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.drm import ClearKey, MonaLisa, real_kids
from unshackle.core.drm import ClearKey, real_kids
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.drm.discovery import drm_from_init_segment
from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot
@@ -755,8 +755,8 @@ class ImportService(TitleSource):
keys = {kid: key for kid, key in pool.items() if kid in declared} if declared else pool
if track.drm:
drm_obj: Any = next(iter(track.drm))
# HLS AES-128 fetches its own key, and MonaLisa's content_keys is a read-only view.
if isinstance(drm_obj, (ClearKey, MonaLisa)):
# HLS AES-128 fetches its own key
if isinstance(drm_obj, ClearKey):
continue
else:
drm_obj = drm_stub(system, [kid.hex for kid in (declared or pool)])
+6 -2
View File
@@ -33,6 +33,7 @@ from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cd
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine
from unshackle.core.drm.bbts import renumber_continuity
from unshackle.core.drm.cenc import (
PLACEHOLDER_KIDS,
PLAYREADY_ID,
@@ -1011,7 +1012,7 @@ class HLS:
merged_path.rename(decrypted_path)
elif isinstance(drm, MonaLisa) and not drm.supports_segment_decrypt:
merge(to=merged_path, via=files, delete=True, include_map_data=not drm.track_decrypted)
decrypt_track(drm, merged_path, license_widevine, track=track)
decrypt_track(drm, merged_path, license_widevine, decrypt=not drm.track_decrypted, track=track)
merged_path.rename(decrypted_path)
else:
# AES segments must be decrypted individually before merging: each segment
@@ -1114,7 +1115,7 @@ class HLS:
decrypt(include_this_segment=False)
if key is None:
encryption_data = None
encryption_data = (None, session_drm) if isinstance(session_drm, MonaLisa) else None
elif not encryption_data or encryption_data[0] != key:
with licensing(ctx):
init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None
@@ -1210,6 +1211,9 @@ class HLS:
store.complete()
if isinstance(session_drm, MonaLisa) and session_drm.supports_segment_decrypt and isinstance(track, Video):
renumber_continuity(save_path)
decrypt_track(session_drm, save_path, decrypt=False, track=track)
if session_drm:
track.drm = None
complete_track(track, ctx, None)
+10 -2
View File
@@ -45,7 +45,7 @@ from unshackle.core.console import SyncLive, console
from unshackle.core.constants import AnyTrack, DownloadCancelled, RunCancel
from unshackle.core.credential import Credential
from unshackle.core.dl_options import remote_dl_params
from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
from unshackle.core.drm import MonaLisa, cbcs, monalisa_drm, real_kids, whole_file_cipher
from unshackle.core.drm.cenc import PLACEHOLDER_KIDS, drm_stub
from unshackle.core.drm.discovery import track_pssh
from unshackle.core.launch import launch_keys
@@ -1585,6 +1585,10 @@ class RemoteService(TitleSource):
for track in title.tracks:
server_id = self.server_track_id(track.id)
if (monalisa := monalisa_drm(track)) is not None:
for kid_hex, key_hex in keys_by_track.get(server_id, {}).items():
monalisa.content_keys[UUID(hex=kid_hex)] = key_hex
continue
cipher = whole_file_cipher(track)
if cipher is not None:
if server_id in file_keys:
@@ -1805,7 +1809,8 @@ class RemoteService(TitleSource):
"""The content keys the server CDM licenses for ``drm`` of ``track``, or None when the server hands it to this machine.
The request sends the header of ``drm`` when it is of a system the server licenses, as a playlist can name a
KID that ``track.drm`` does not hold. ``kid`` is the KID the server CDM must answer; a content key for it
KID that ``track.drm`` does not hold; a MonaLisa request sends no header, as the server holds the DRM its
service built. ``kid`` is the KID the server CDM must answer; a content key for it
from a server vault stands in for the licence. A failed request logs one warning and returns no keys.
"""
if self.local_vaults_only:
@@ -1813,6 +1818,9 @@ class RemoteService(TitleSource):
if deferred := self.deferred_refusals.get(str(track.id)):
raise click.ClickException(deferred)
server_type = self.server_cdm_type
if isinstance(drm, MonaLisa):
request = LicenseRequest(drm_type="monalisa", mode="server_cdm")
else:
other_type = "playready" if server_type == "widevine" else "widevine"
drm_type, pssh_b64 = server_type, track_pssh(track, server_type, drm)
if not pssh_b64:
+27 -9
View File
@@ -30,7 +30,15 @@ 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 WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.drm import (
WHOLE_FILE_DRM,
BlowfishStripe,
ClearKeyCENC,
ClearKeyCTR,
MonaLisa,
PlayReady,
Widevine,
)
from unshackle.core.manifests import HLS
from unshackle.core.manifests.snapshot import restore, restore_playlists, shared_url
from unshackle.core.titles import Album, Episode, Movie, Music, Song, Title_T
@@ -348,7 +356,7 @@ def build_music(songs: list[Title_T], info: Any) -> Album:
def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
"""Serialise DRM objects to JSON-serializable list."""
"""Serialise DRM objects to JSON-serializable list. A MonaLisa entry holds its KID only, never its content key or ticket."""
if not drm_list:
return None
@@ -357,6 +365,10 @@ def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
result = []
for drm in drm_list:
if isinstance(drm, MonaLisa):
if drm.kid:
result.append({"type": "monalisa", "kid": drm.kid.hex})
continue
drm_info = {}
drm_class = drm.__class__.__name__
drm_info["type"] = drm_class.lower()
@@ -408,7 +420,7 @@ 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 not in ("blowfishstripe", "clearkeyctr"):
if not pssh_str and drm_type not in ("blowfishstripe", "clearkeyctr", "monalisa"):
continue
try:
if drm_type == "blowfishstripe":
@@ -419,6 +431,8 @@ def reconstruct_drm(drm_list: list | None) -> list:
None, drm_info["iv"], drm_info["magic"], drm_info.get("skip", 0), key=drm_info.get("key")
)
)
elif drm_type == "monalisa":
result.append(MonaLisa(kid=drm_info["kid"]))
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
@@ -439,11 +453,13 @@ def pssh_drm(system: str, pssh_b64: str, kids: list[str] | None) -> Widevine | P
return Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None)
def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC) -> dict[str, Any]:
def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC | MonaLisa) -> dict[str, Any]:
"""A DRM in the export form: its system, PSSH, KIDs and the FairPlay bridged mark.
The export keeps the content keys once at title level, not here.
The export keeps the content keys once at title level, not here. A MonaLisa entry holds its KID only, as on the wire.
"""
if isinstance(drm, MonaLisa):
return {"system": "MonaLisa", "kids": [kid.hex for kid in drm.kids]}
if isinstance(drm, ClearKeyCENC):
data: dict[str, Any] = {
"system": "ClearKeyCENC",
@@ -462,10 +478,10 @@ def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC) -> dict[str, Any]:
return data
def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC:
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its export form.
def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC | MonaLisa:
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC/MonaLisa DRM instance from its export form.
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH, and for
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey and MonaLisa, which have no PSSH, and for
a bridged stub, whose PlayReady PSSH names only its first KID) and re-injects any saved
content keys so the resulting object can decrypt without contacting a license server.
"""
@@ -475,7 +491,9 @@ def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC:
content_keys = data.get("content_keys") or {}
if system == "ClearKeyCENC":
drm: Widevine | PlayReady | ClearKeyCENC = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
drm: Widevine | PlayReady | ClearKeyCENC | MonaLisa = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
elif system == "MonaLisa":
drm = MonaLisa(kid=kids[0] if kids else None)
elif data.get("bridged") and system in ("PlayReady", "Widevine"):
drm = HLS.bridge_stub(system.lower(), [UUID(hex=kid) for kid in kids])
elif not pssh_b64: