fix(import): keep the FairPlay bridged mark and every KID of a DRM through an export

This commit is contained in:
imSp4rky
2026-12-01 21:46:44 -07:00
parent 1288a8e9b7
commit 992fff3626
5 changed files with 124 additions and 18 deletions
+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, 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.
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.
When the decode fails, unshackle:
+106
View File
@@ -0,0 +1,106 @@
"""A FairPlay-bridged DRM keeps its bridged mark and every KID through an export and an import."""
from __future__ import annotations
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from tests.core.key_resolver import resolver
from tests.core.test_export import make_writer, written
from tests.core.test_import_track_keys import AUDIO_KID, MPD, MPD_URL, VIDEO_KID, StubService, import_service
from tests.core.test_vault_bad_keys import BAD, GOOD
from unshackle.core.drm import key_resolution
from unshackle.core.manifests import DASH, HLS
from unshackle.core.titles import Movie
from unshackle.core.wire import drm_from_dict, drm_to_dict
@pytest.mark.parametrize("system", ["widevine", "playready"])
def test_the_export_form_keeps_the_bridged_mark_and_every_kid(system: str) -> None:
stub = HLS.bridge_stub(system, [VIDEO_KID, AUDIO_KID])
back: Any = drm_from_dict(json.loads(json.dumps(drm_to_dict(stub))))
assert back.bridged
assert back.kids == stub.kids == [VIDEO_KID, AUDIO_KID]
assert drm_to_dict(back) == drm_to_dict(stub)
def export_bridged(
tmp_path: Path, system: str = "widevine", row_kids: bool = True, mark: bool = True
) -> tuple[Path, str]:
"""Export a title whose video and audio each carry a bridged stub with a bad content key.
``row_kids=False`` drops the per-track KID lists, and ``mark=False`` the bridged mark, as in older exports.
"""
title = Movie(id_="movie-1", service=StubService, name="Example Movie", year=2024, language="en")
for track in DASH.from_text(MPD, MPD_URL).to_tracks(language="en"):
title.tracks.add(track)
writer = make_writer(tmp_path)
video = title.tracks.videos[0]
for track, kid in ((video, VIDEO_KID), (title.tracks.audio[0], AUDIO_KID)):
drm = HLS.bridge_stub(system, [kid])
drm.content_keys[kid] = BAD
writer.record(title, track, drm)
export = written(writer)
doc = json.loads(export.read_text(encoding="utf8"))
entry = doc["titles"][0]
if not row_kids:
for row in entry["tracks"]:
row.pop("kids", None)
if not mark:
for d in entry["x-unshackle"]["drm"]:
d.pop("bridged", None)
export.write_text(json.dumps(doc), encoding="utf8")
return export, str(video.id)
@pytest.mark.parametrize("system", ["widevine", "playready"])
@pytest.mark.parametrize("row_kids", [True, False], ids=["row-kids", "stub-fallback"])
def test_an_imported_bridged_track_stops_on_a_key_that_does_not_decrypt(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, system: str, row_kids: bool
) -> None:
export, video_id = export_bridged(tmp_path, system, row_kids)
drm: Any = import_service(export).rebuild_drm({"id": video_id, "type": "Video"}, "movie-1")[0] # type: ignore[index]
checked: list[Path] = []
def ffmpeg_decodes(path: Path, start: Any = None, seconds: int = 3, video: Any = None) -> bool:
checked.append(path)
return path.read_bytes() == b"plain:" + GOOD.encode()
def decrypt(path: Path) -> None:
path.write_bytes(b"plain:" + drm.content_keys[VIDEO_KID].encode())
def licence(d: Any, track_kid: Any = None) -> Any:
raise AssertionError("an import licenses nothing")
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", ffmpeg_decodes)
monkeypatch.setattr(drm, "decrypt", decrypt, raising=False)
path = tmp_path / "track.mp4"
path.write_bytes(b"cipher")
keys = resolver(None, tag="EXAMPLE")
with pytest.raises(ValueError, 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:
keys.wait_vault_writes()
assert drm.bridged
assert checked
assert "\n" not in str(e.value)
assert not path.exists()
def test_an_export_without_the_mark_imports_a_plain_stub(tmp_path: Path) -> None:
export, video_id = export_bridged(tmp_path, mark=False)
drm = import_service(export).rebuild_drm({"id": video_id, "type": "Video"}, "movie-1")[0] # type: ignore[index]
assert not drm.bridged
assert drm.kids == [VIDEO_KID]
-1
View File
@@ -379,7 +379,6 @@ def handle_single_server_cdm(
from unshackle.core.cdm import load_cdm
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
ensure_track_drm(track, getattr(service, "session", None))
shared = {} if shared is None else shared
service_name = service.__class__.__name__
+3 -2
View File
@@ -654,8 +654,8 @@ class ImportService(TitleSource):
carries its own is honoured first. The track's row in the export can list its KIDs;
then the track gets only their keys, and the DRM entry that names them. Without that
list, a title with more than one DRM entry does not say which entry is this track's,
so the track gets a stub that names every exported KID instead of a guess. A rebuilt
PSSH holds only the keys for the KIDs it names.
so the track gets a stub that names every exported KID instead of a guess, bridged when
any entry is. A rebuilt PSSH holds only the keys for the KIDs it names.
A track that declares no content key, DRM or KID of its own is clear if it is a subtitle,
or if the export lists the KIDs of its other tracks. Only a video or audio track in an
@@ -693,6 +693,7 @@ class ImportService(TitleSource):
if drm_obj is None and stub_kids:
drm_type = (drm_dicts[0].get("system", "Widevine").lower()) if drm_dicts else "widevine"
drm_obj = drm_stub(drm_type, stub_kids)
drm_obj.bridged = any(d.get("bridged") for d in drm_dicts)
if drm_obj is None:
return None
+14 -14
View File
@@ -31,6 +31,7 @@ from pywidevine.pssh import PSSH as WidevinePSSH
from unshackle.core.config import config
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
from unshackle.core.drm import WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.manifests import HLS
from unshackle.core.manifests.snapshot import restore
from unshackle.core.titles import Album, Episode, Movie, Music, Song, Title_T
from unshackle.core.titles.availability import availability_metadata
@@ -439,7 +440,7 @@ def pssh_drm(system: str, pssh_b64: str, kids: list[str] | None) -> Widevine | P
def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC) -> dict[str, Any]:
"""A DRM in the export form: its system, PSSH and KIDs.
"""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.
"""
@@ -452,24 +453,21 @@ def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC) -> dict[str, Any]:
data["laurl"] = drm.laurl
return data
if isinstance(drm, Widevine):
return {
"system": "Widevine",
"pssh_b64": drm.pssh.dumps(),
"kids": [kid.hex for kid in drm.kids],
}
return {
"system": "PlayReady",
"pssh_b64": drm.pssh_b64,
"kids": [kid.hex for kid in drm.kids],
}
data = {"system": "Widevine", "pssh_b64": drm.pssh.dumps()}
else:
data = {"system": "PlayReady", "pssh_b64": drm.pssh_b64}
data["kids"] = [kid.hex for kid in drm.kids]
if drm.bridged:
data["bridged"] = True
return data
def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC:
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its export form.
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH)
and re-injects any saved content keys so the resulting object can decrypt without
contacting a license server.
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has 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.
"""
system = data.get("system")
pssh_b64 = data.get("pssh_b64")
@@ -478,6 +476,8 @@ def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC:
if system == "ClearKeyCENC":
drm: Widevine | PlayReady | ClearKeyCENC = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
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:
raise ValueError("Cannot reconstruct DRM without a stored PSSH.")
elif system in ("PlayReady", "Widevine"):