fix(drm): stop a bridged FairPlay track whose server-CDM answer or licence key does not decrypt it

This commit is contained in:
imSp4rky
2026-12-01 21:07:27 -07:00
parent ed6ed02033
commit cefd5295ac
15 changed files with 350 additions and 25 deletions
+1
View File
@@ -1262,6 +1262,7 @@ A slow answer arrives as a [slow response](#slow-responses).
| `clear_tracks` (response) | Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. |
| `file_keys` (response) | Content keys of whole-file ciphers, by track id, for a single track and for a batch. Absent when no requested track holds such a cipher. |
| `vault_keys` (response) | KIDs whose content key came from a server vault, not the CDM. The client proves such a content key with a decode before it trusts it; the field is absent when every content key came from the CDM. |
| `bridge_kids` (response) | For a batch: the KIDs of the init segments of each FairPlay-only track that the server licensed through the FairPlay bridge, by track id. The client needs the content key of each of these KIDs, or the download of that track stops. Absent when the batch has no such track. |
| Status | Error code | Meaning |
| --- | --- | --- |
+3 -1
View File
@@ -550,7 +550,9 @@ The download reads the key ID from the init segment, builds a DRM object for tha
the service on the server has the hook. The server reads the same key ID at the licence step, accepts
the DRM object of the client and sends the challenge to the hook of its service. A server that cannot
read the key ID refuses the challenge. A licence that gives no content key stops the track before it
downloads a segment.
downloads a segment. With the server CDM, the batch licence names the key IDs that the server read, so an
answer without their content keys stops the track in the same way. A content key that does not decode
the downloaded track stops the track with an error, and unshackle keeps no output file.
unshackle reads one key ID from each init segment. So it licenses a playlist that changes its content key
correctly only when each content key has its own init segment with a real `tenc` key ID, after an
+2
View File
@@ -87,6 +87,8 @@ appropriate one for each track.
`Left out 1 FairPlay-only track: EXAMPLE has no FairPlay bridge hook`. When only FairPlay-only tracks
match your quality or range options, unshackle skips the title, unless you use `--best-available`.
`--list` still shows every track.
A licence without the content key of a key ID, or with a content key that does not decrypt the
track, stops the download of that track with an error, and unshackle keeps no output file.
When each `EXT-X-KEY` of an fMP4 playlist is sample encryption
for a DRM system that unshackle cannot license, such as FairPlay, unshackle reads the key ID from
+5
View File
@@ -298,6 +298,11 @@ Each command reports how many files it removed and how much space it freed, then
**Inspect:** while it decrypts a track whose content key came from a vault, unshackle keeps the ciphertext as a `.enc` sibling of the track file in the temp directory, and removes it afterwards; a leftover one is from a killed run and is safe to delete. Read the `bad_keys` table of your local SQLite vault to see which pairs are flagged and which vault each came from. See [Wrong keys from a poisoned vault](vaults.md#wrong-keys-from-a-poisoned-vault).
!!! example "A FairPlay-only track stops after its licence"
**Symptom:** the download of a FairPlay-only track stops with `No content key for KID <kid> of track <id>`, `No Content Key for KID <kid> was returned by the server CDM`, or `The licence content key of KID <kid> does not decrypt track <id>`, and unshackle keeps no output file.
**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 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.
+1 -1
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. 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, except those of a FairPlay-only track that the FairPlay bridge licensed. 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.
When the decode fails, unshackle:
@@ -0,0 +1,110 @@
"""The decode check of the content keys that a licence gives a bridged FairPlay-only track."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from uuid import UUID
import pytest
from tests.core.key_resolver import resolver, vaults_of
from tests.core.test_vault_bad_keys import BAD, GOOD, KID, FakeDRM, Remote
from unshackle.core.drm import key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.vaults import Vaults
from unshackle.vaults.SQLite import SQLite
pytestmark = pytest.mark.unit
TRACK = SimpleNamespace(id="vid")
class BridgedDRM(FakeDRM):
"""A DRM that names KID."""
def __init__(self, keys: dict[UUID, str], bridged: bool = True) -> None:
super().__init__(keys)
self.kids = [KID]
self.bridged = bridged
@pytest.fixture
def decodes(monkeypatch: pytest.MonkeyPatch) -> list[Path]:
"""Each file the decode check reads; only a file decrypted with GOOD decodes."""
checked: list[Path] = []
def ffmpeg_decodes(path: Path, start: float | None = None, seconds: float = 3, video: bool | None = None) -> bool:
checked.append(path)
return path.read_bytes() == b"plain:" + GOOD.encode()
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", ffmpeg_decodes)
return checked
def check(tmp_path: Path, drm: BridgedDRM, vaults: Vaults | None = None, decrypt: bool = True) -> Path:
"""Decrypt a file with ``drm`` through ``decrypt_verified``, with a licence that gives GOOD.
Without ``decrypt`` the file is already plain, as after per-segment decryption.
"""
path = tmp_path / "track.mp4"
path.write_bytes(b"cipher" if decrypt else b"plain:" + drm.content_keys[KID].encode())
keys = resolver(vaults, tag="SVC")
ContentKeyResolver.LICENSE_KEY_CACHE.update(drm.content_keys)
def licence(drm: BridgedDRM, track_kid: UUID | None = None) -> None:
drm.content_keys[KID] = GOOD
try:
keys.decrypt_verified(drm, path, licence, KID, decrypt, TRACK) # type: ignore[arg-type]
finally:
keys.wait_vault_writes()
return path
@pytest.mark.parametrize("decrypt", [True, False], ids=["decrypt", "segments-decrypted"])
def test_a_licence_key_of_a_bridged_track_that_does_not_decode_stops_the_track(
tmp_path: Path, decodes: list[Path], decrypt: bool
) -> None:
local = SQLite("local", tmp_path / "local.db")
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$"):
check(tmp_path, BridgedDRM({KID: BAD}), vaults, decrypt)
assert decodes and not (tmp_path / "track.mp4").exists()
assert local.is_bad_key(KID, BAD) and local.get_key(KID, "SVC") is None
assert KID not in ContentKeyResolver.LICENSE_KEY_CACHE
def test_a_licence_key_of_a_bridged_track_that_decodes_is_kept(tmp_path: Path, decodes: list[Path]) -> None:
local = SQLite("local", tmp_path / "local.db")
path = check(tmp_path, BridgedDRM({KID: GOOD}), vaults_of(local, service="SVC"))
assert decodes and path.read_bytes() == b"plain:" + GOOD.encode()
assert not local.is_bad_key(KID, GOOD)
def test_a_licence_key_of_a_track_that_is_not_bridged_is_not_decoded(tmp_path: Path, decodes: list[Path]) -> None:
path = check(tmp_path, BridgedDRM({KID: BAD}, bridged=False))
assert not decodes and path.read_bytes() == b"plain:" + BAD.encode()
def test_a_bad_vault_key_of_a_bridged_track_gives_way_to_the_licence_key_which_is_checked(
tmp_path: Path, decodes: list[Path]
) -> None:
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
poisoned.add_key("SVC", KID, BAD)
vaults = vaults_of(SQLite("local", tmp_path / "local.db"), poisoned, service="SVC")
drm = BridgedDRM({})
drm.content_keys[KID] = vaults.get_key(KID)[0] # type: ignore[assignment]
path = check(tmp_path, drm, vaults)
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert len(decodes) == 2 and vaults.vaults[0].is_bad_key(KID, BAD)
@@ -0,0 +1,166 @@
"""A FairPlay-only HLS track on the server CDM: the stub of the client names the key IDs that the server bridged."""
from __future__ import annotations
import dataclasses
from collections.abc import Callable, Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import UUID
import pytest
from tests.core.key_resolver import key_table, resolver
from tests.core.test_hls_service_drm_keys import (
KID,
OTHER_KID,
ROTATION,
SKD_KEY,
WIDEVINE_KEY,
InitServer,
download,
hls_video,
playlist,
rotation_server,
)
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core.api import server_keys
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import PlayReady, Widevine, cenc
from unshackle.core.tracks import Video
pytestmark = pytest.mark.unit
KEY = "ab" * 16
OTHER_KEY = "cd" * 16
FAIRPLAY_ONLY = playlist(SKD_KEY)
@pytest.fixture(autouse=True)
def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""No FFprobe, and a licence failure that cancels the run does not reach the next test."""
monkeypatch.setattr(cenc, "ffprobe", lambda data: {})
yield
DOWNLOAD_CANCELLED.clear()
def server_answer(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
text: str,
licence: dict[UUID, str],
system: str = "playready",
origin: Callable[[], InitServer] = InitServer,
) -> dict[str, Any]:
"""The batch answer of the server CDM for one HLS video of ``text``, whose licence holds ``licence``.
The server service has the FairPlay bridge hook and serves an init segment with an all-zero tenc KID and a pssh
box for KID. Each field of the batch goes into the answer when it is not empty, as the licence route sends it.
"""
monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: text)
monkeypatch.setattr(server_keys, "licence_candidates", lambda *args: [system])
monkeypatch.setattr(server_keys, "find_title_for_track", lambda *args: None)
monkeypatch.setattr(
server_keys, "handle_single_server_cdm", lambda *args, **kwargs: {k.hex: v for k, v in licence.items()}
)
service = SimpleNamespace(session=origin(), fairplay_bridge=lambda: print)
session = session_entry(service_instance=service, tracks={"vid": hls_video(tmp_path, text)})
batch = server_keys.resolve_batch(session, ["vid"], system, KeyPolicy())
return {name: value for name, value in dataclasses.asdict(batch).items() if value}
def licence_on_the_client(
tmp_path: Path,
text: str,
answer: dict[str, Any],
licence: dict[UUID, str],
origin: Callable[[], InitServer] = InitServer,
asked: list[UUID | None] | None = None,
) -> Video:
"""Take the server answer as dl does, then run the licence step of the download; return the track.
A single-track licence of the server CDM answers with ``licence`` and lands in ``asked``.
"""
def license_track(track: Video, drm: Any, kid: UUID | None = None) -> dict[UUID, str]:
if asked is not None:
asked.append(kid)
return dict(licence)
remote = remote_session(None, answer)
remote.license_track = license_track # type: ignore[method-assign,assignment]
track = hls_video(tmp_path, text)
track.id = "vid"
title = one_title(track)
remote.resolve_server_keys(title) # type: ignore[arg-type]
keys = resolver(cdm=cdm_type_stub("playready"))
keys.source = remote
download(track, None, keys.licence_for(track, title, key_table()), True, origin()) # type: ignore[arg-type]
return track
def test_an_answer_without_the_content_key_of_a_bridged_track_stops_it(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The licence holds a content key for another KID only; with the all-zero tenc KID it would decrypt the track."""
licence = {OTHER_KID: OTHER_KEY}
answer = server_answer(monkeypatch, tmp_path, FAIRPLAY_ONLY, licence)
with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=f"No Content Key for KID {KID.hex} "):
licence_on_the_client(tmp_path, FAIRPLAY_ONLY, answer, licence)
def test_the_stub_of_a_bridged_track_names_the_key_ids_of_the_server(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
licence = {OTHER_KID: OTHER_KEY, KID: KEY}
answer = server_answer(monkeypatch, tmp_path, FAIRPLAY_ONLY, licence)
track = licence_on_the_client(tmp_path, FAIRPLAY_ONLY, answer, licence)
assert answer["bridge_kids"] == {"vid": [KID.hex]}
[drm] = track.drm or []
assert isinstance(drm, PlayReady) and drm.bridged
assert drm.kids == [KID] and drm.content_keys == licence
def test_the_stub_of_a_track_the_server_did_not_bridge_is_unchanged(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, playlist(WIDEVINE_KEY), {KID: KEY}, "widevine")
remote = remote_session(None, answer)
track = hls_video(tmp_path, playlist(WIDEVINE_KEY))
track.id = "vid"
remote.resolve_server_keys(one_title(track)) # type: ignore[arg-type]
[drm] = track.drm or []
assert "bridge_kids" not in answer
assert isinstance(drm, Widevine) and not drm.bridged
def test_a_rotation_asks_the_server_cdm_for_a_key_id_its_answer_lacks(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, ROTATION, {KID: KEY}, origin=rotation_server)
asked: list[UUID | None] = []
track = licence_on_the_client(tmp_path, ROTATION, answer, {OTHER_KID: OTHER_KEY}, rotation_server, asked)
assert answer["bridge_kids"] == {"vid": [KID.hex, OTHER_KID.hex]}
assert asked == [OTHER_KID]
[drm] = track.drm or []
assert isinstance(drm, PlayReady) and drm.content_keys == {KID: KEY, OTHER_KID: OTHER_KEY}
def test_a_rotation_without_a_later_content_key_stops_before_a_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, ROTATION, {KID: KEY}, origin=rotation_server)
with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=f"No Content Key for KID {OTHER_KID.hex} "):
licence_on_the_client(tmp_path, ROTATION, answer, {}, rotation_server)
+5 -2
View File
@@ -81,7 +81,9 @@ def test_a_pair_the_server_accepted_is_not_posted_again() -> None:
assert [post["keys"] for post in posts] == [{LICENSED.hex: KEY}, {VAULTED.hex: KEY}]
def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monkeypatch) -> None:
@pytest.mark.parametrize("bridged", [False, True], ids=["licence", "bridged-licence"])
def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monkeypatch, bridged: bool) -> None:
"""A bridged licence key waits for the decode check in ``decrypt_verified``."""
licensed = {LICENSED: KEY, LATE: OTHER_KEY}
monkeypatch.setattr(Widevine, "get_content_keys", lambda self, **_: setattr(self, "content_keys", dict(licensed)))
pushed: list = []
@@ -89,12 +91,13 @@ def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monke
source.server_vault = SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track)))
keys = resolver(tag="EXAMPLE", source=source)
drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[LICENSED]))
drm.bridged = bridged
track = SimpleNamespace(id="v1", drm=[drm])
keys.licence_for(track, None, key_table())(drm, track_kid=LICENSED)
keys.wait_vault_writes()
assert pushed == [(licensed, track)]
assert pushed == ([] if bridged else [(licensed, track)])
def test_a_failed_post_is_dropped_and_logs_nothing(caplog: pytest.LogCaptureFixture) -> None:
+2
View File
@@ -3777,6 +3777,8 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
response["drm_types"] = batch.drm_types
if batch.capped_tracks:
response["capped_tracks"] = batch.capped_tracks
if batch.bridge_kids:
response["bridge_kids"] = batch.bridge_kids
return web.json_response(response)
if not track_id:
+3 -1
View File
@@ -2468,7 +2468,9 @@ async def session_license(request: web.Request) -> web.Response:
track id the server refused to license live to the refusal details (`reason` and
`max_height`); the client licenses those tracks with its own local CDM. A `reason` of
`server_device` means the remote session runs on the server's device: the client reads
only its own vaults for that track and makes no licence.
only its own vaults for that track and makes no licence. `bridge_kids`, absent when empty, maps
each FairPlay-only track id that the server licensed through the FairPlay bridge to the KID hex
strings of its init segments; the client gets the content key of each of these KIDs or stops the track.
After 30 s the route sends 200 and a newline every 30 s. A failure after that time
arrives as the error body with status 200.
'404':
+4
View File
@@ -620,6 +620,7 @@ class BatchKeys:
drm_types: dict[str, str] = field(default_factory=dict)
drm_type: str | None = None
capped_tracks: dict[str, dict[str, Any]] = field(default_factory=dict)
bridge_kids: dict[str, list[str]] = field(default_factory=dict)
def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy: KeyPolicy) -> BatchKeys:
@@ -653,6 +654,7 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
batch.clear_tracks.append(tid)
continue
bridge_kids = list(dict.fromkeys(kid.hex for d in track.drm if getattr(d, "bridged", False) for kid in d.kids))
title = find_title_for_track(tid, session)
candidates = licence_candidates(session, policy, drm_type, track, resolver.warn)
probed: uuid.UUID | None = None
@@ -668,6 +670,8 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
if result.keys:
batch.keys[tid] = result.keys
if bridge_kids:
batch.bridge_kids[tid] = bridge_kids
note_served_keys(session, result.keys, result.sources)
batch.vault_keys.extend(result.sources)
if result.drm_type:
+30 -8
View File
@@ -147,7 +147,8 @@ class ContentKeyResolver:
failure there flags each of those KIDs. On failure the pair is flagged in the local
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. A CDM
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
that returns the flagged key clears the flag and stores the content key again, because
then the decode check was wrong.
@@ -225,9 +226,10 @@ 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))
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() and decrypt and binaries.FFMPEG)
checking = bool((vault_kids() or bridged) and decrypt and binaries.FFMPEG)
if checking:
try:
os.link(path, backup)
@@ -247,14 +249,32 @@ class ContentKeyResolver:
def window_decodes(start: float, end: float) -> bool:
return ffmpeg_decodes(path, start=start, seconds=end - start if end > start else 0.5, video=video)
def judged_kids() -> dict[UUID, KeySource]:
"""The vault KIDs this file can judge. A map whose KIDs all have keys skips the KIDs it lacks."""
kids = vault_kids()
def judged_kids(kids: dict[UUID, Any] | None = None) -> dict[UUID, Any]:
"""The vault KIDs, or ``kids``, this file can judge. A map whose KIDs all have keys skips the KIDs it lacks."""
kids = vault_kids() if kids is None else kids
if kid_map is not None and all(kid in keys for kid in windows):
return {kid: vault for kid, vault in kids.items() if kid in windows}
return kids
def failed_kids(kids: dict[UUID, KeySource]) -> set[UUID]:
def refuse_bad_licence_keys() -> None:
"""Stop a bridged track whose licence content key does not decode, and 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.
The flag goes through the vault writer, after the licence's own write of the pair.
"""
if not (bridged and binaries.FFMPEG and path.exists()):
return
sourced = vault_kids()
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)}"
)
def failed_kids(kids: dict[UUID, Any]) -> set[UUID]:
"""The vault KIDs whose content key did not decode.
A KID in the KID map fails when one of its windows fails. The KIDs that are not in the
@@ -291,6 +311,7 @@ class ContentKeyResolver:
checked = bool(kids and binaries.FFMPEG and path.exists())
failed = failed_kids(kids) if checked else set()
if not failed:
refuse_bad_licence_keys()
passed = kids if checked else {}
self._flush_vault_writes([partial(self.vaults.proven, dict(keys), passed)])
server_vault = self.source.server_vault if self.source and track is not None else None
@@ -556,7 +577,8 @@ class ContentKeyResolver:
``decrypt_verified`` licenses any other KID the file turns out to use.
``force`` skips the run cache, so the licence runs again for each KID no vault answers.
A licence can answer a KID with a blank or null key; a vault key for that KID wins.
Every content key of the licence goes to the vaults and to the server key source's vault at once.
Every content key of the licence goes to the vaults and to the server key source's vault at once; for a
bridged DRM, the server key source's vault gets them only once ``decrypt_verified`` passes the track.
"""
pssh: str | None = None
if isinstance(drm, ClearKeyCENC):
@@ -679,7 +701,7 @@ class ContentKeyResolver:
licensed = {k: v for k, v in drm.content_keys.items() if k not in from_vaults}
pending_vault_writes.append(partial(self._cache_keys_to_vaults, licensed))
server_vault = self.source.server_vault if self.source else None
if server_vault is not None:
if server_vault is not None and not getattr(drm, "bridged", False):
pending_vault_writes.append(
partial(server_vault.add_keys, self.tag, cast(dict[UUID | str, str], licensed), track)
)
+5 -8
View File
@@ -713,7 +713,6 @@ class HLS:
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
session_drm = track.get_drm_for_cdm(cdm) if track.drm else None
bridge_drm = None
bridge_kids: list[UUID] = []
if (
session_drm is None
and ctx.fairplay_bridge
@@ -726,7 +725,7 @@ class HLS:
session_drm = bridge_drm
track.drm = [bridge_drm]
log.debug(
f"{track.id}: licensing key IDs {', '.join(kid.hex for kid in bridge_kids)} "
f"{track.id}: licensing key IDs {', '.join(kid.hex for kid in bridge_drm.kids)} "
f"of its init segments as {bridge_drm.NAME}"
)
elif isinstance(session_drm, (Widevine, PlayReady)) and HLS.drop_unsupported_keys(master):
@@ -774,8 +773,9 @@ class HLS:
initial_drm_key = media_playlist_key
initial_drm_licensed = True
bridged_drm = session_drm if isinstance(session_drm, (Widevine, PlayReady)) and session_drm.bridged else None
if not initial_drm_licensed:
for kid in bridge_kids or (None,):
for kid in bridged_drm.kids if bridged_drm else (None,):
license_drm(
track, session_drm, ctx, kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session)
)
@@ -793,11 +793,8 @@ class HLS:
progress(downloaded="[yellow]SKIPPED")
return
if bridge_drm:
content_keys = bridge_drm.content_keys
missing = [k for k in bridge_kids[1:] if k not in content_keys] if content_keys else bridge_kids[:1]
if missing:
raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {missing[0].hex} of track {track.id}")
if bridged_drm and (missing := [kid for kid in bridged_drm.kids if kid not in bridged_drm.content_keys]):
raise bridged_drm.Exceptions.CEKNotFound(f"No content key for KID {missing[0].hex} of track {track.id}")
# Downloaded segment files are named by post-filter index; map that back to the wanted
# segment so the IV uses the absolute media sequence number, not the download index.
+3
View File
@@ -314,11 +314,14 @@ class LicenseReply(TypedDict, total=False):
``keys`` maps KID to content key for one ``track_id``, and track id to that map for ``track_ids``. A capped
track gets no content keys: ``capped_tracks`` holds its refusal details, ``reason`` and ``max_height``.
``file_keys`` maps track id to the content key the server licensed for a track's whole-file cipher.
``bridge_kids`` maps the id of a FairPlay-only track that the server licensed through the bridge to the KIDs of
its init segments.
"""
license: str | None
keys: dict[str, Any]
file_keys: dict[str, str]
bridge_kids: dict[str, list[str]]
vault_keys: list[str]
clear_tracks: list[str]
drm_type: str
+9 -3
View File
@@ -49,6 +49,7 @@ from unshackle.core.drm import cbcs, 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
from unshackle.core.manifests import HLS
from unshackle.core.manifests.snapshot import match_track
from unshackle.core.proxies.resolve import is_loopback
from unshackle.core.remote_protocol import (
@@ -1527,8 +1528,9 @@ class RemoteService(TitleSource):
Called by dl.py between track selection and download. The server
decides which CDM device to use and tells the client through
server_cdm_type. We send track IDs and the server does the full
CDM flow, returning KID:KEY pairs. A capped track this machine's device cannot license
waits in ``deferred_refusals``, so dl reads the local vaults before ``license_track`` raises it.
CDM flow, returning KID:KEY pairs. The stub of a track the server bridged names the KIDs of its init
segments, so a licence without their content keys stops it. A capped track this machine's device cannot
license waits in ``deferred_refusals``, so dl reads the local vaults before ``license_track`` raises it.
"""
# track ids can repeat across titles, so a refusal for the last title must not carry over
self.client_licensed.clear()
@@ -1577,6 +1579,7 @@ class RemoteService(TitleSource):
server_drm_type = resp.get("drm_type", drm_type)
drm_types_by_track = resp.get("drm_types", {})
capped = resp.get("capped_tracks") or {}
bridge_kids = resp.get("bridge_kids", {})
self.server_cdm_type = server_drm_type
self.log.debug(f"Server responded with drm_type={server_drm_type}, keys for {len(keys_by_track)} track(s)")
@@ -1595,8 +1598,11 @@ class RemoteService(TitleSource):
self.log.warning(f"Server CDM returned no content keys for track {track_log_label(track)}")
continue
named = {kid.hex for drm in track.drm or [] for kid in real_kids(drm)} & track_keys.keys()
track_drm_type = drm_types_by_track.get(server_id, server_drm_type)
if bridged := bridge_kids.get(server_id):
drm_obj = HLS.bridge_stub(track_drm_type, [UUID(hex=kid) for kid in bridged])
else:
named = {kid.hex for drm in track.drm or [] for kid in real_kids(drm)} & track_keys.keys()
drm_obj = drm_stub(track_drm_type, sorted(named) or list(track_keys))
for kid_hex, key_hex in track_keys.items():
drm_obj.content_keys[UUID(hex=kid_hex)] = key_hex