From c9cbd8c9fa2e5cc8378baba34084b638881c00c9 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sun, 29 Nov 2026 12:07:36 -0700 Subject: [PATCH] refactor(drm): read PlayReady KIDs from pyplayready WRM headers and drop the hand XML scan --- pyproject.toml | 1 - tests/core/test_playready_bare_header.py | 2 + tests/core/test_playready_multi_header.py | 47 +++++- .../unit/test_licence_declared_kwargs.py | 2 +- unshackle/core/drm/playready.py | 152 ++---------------- uv.lock | 11 -- 6 files changed, 60 insertions(+), 155 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 94be3cbcf..8ac4a0b70 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,6 @@ dependencies = [ "wasmtime>=41.0.0", "rnet>=2.4.2,<3", "mutagen>=1.47.0,<2", - "defusedxml>=0.7.1,<0.8", "rich-click>=1.9.8,<2", "mediaexport @ git+https://github.com/unshackle-dl/mediaexport@main", "segno>=1.6.6,<2", diff --git a/tests/core/test_playready_bare_header.py b/tests/core/test_playready_bare_header.py index db264e458..631b01702 100644 --- a/tests/core/test_playready_bare_header.py +++ b/tests/core/test_playready_bare_header.py @@ -32,6 +32,8 @@ def bare_header(version: str, kid: UUID = KID) -> str: kid_b64 = base64.b64encode(kid.bytes_le).decode() if version == "4.0.0.0": data = f"16AESCTR{kid_b64}" + elif version == "4.1.0.0": + data = f'' else: data = f'' xml = ( diff --git a/tests/core/test_playready_multi_header.py b/tests/core/test_playready_multi_header.py index 246f87ef6..b7f9a87df 100644 --- a/tests/core/test_playready_multi_header.py +++ b/tests/core/test_playready_multi_header.py @@ -1,6 +1,7 @@ from __future__ import annotations import base64 +from types import SimpleNamespace from typing import Any from uuid import UUID @@ -9,6 +10,7 @@ import pytest from pyplayready.misc.exceptions import InvalidLicense, InvalidXmrLicense from pyplayready.system.pssh import PSSH from pyplayready.system.wrmheader import WRMHeader +from pywidevine.key import Key as WidevineKey from unshackle.core.cdm.http_cdm import HttpCdm from unshackle.core.drm import PlayReady @@ -283,10 +285,6 @@ def test_a_track_carrying_playready_survives_deepcopy() -> None: assert len(clone.drm[0].distinct_headers()) == 2 -def _pro_b64(*headers: bytes) -> str: - return base64.b64encode(_pro(*headers)).decode() - - def _xml_header(version: str, body: str) -> bytes: return ( f'' @@ -313,11 +311,15 @@ def _b64le(kid: UUID) -> str: f'', [KID_A, KID_B], ), + ( + "4.3.0.0", + f'', + [KID_B], + ), ], ) def test_kids_are_read_from_every_header_version(version: str, body: str, expected: list[UUID]) -> None: - header = _xml_header(version, body) - assert PlayReady(pssh=PSSH(_pro(header)), pssh_b64=_pro_b64(header)).kids == expected + assert PlayReady(pssh=PSSH(_pro(_xml_header(version, body)))).kids == expected def test_customattributes_kids_follow_the_header_kids() -> None: @@ -328,13 +330,44 @@ def test_customattributes_kids_follow_the_header_kids() -> None: f'', ) - drm = PlayReady(pssh=PSSH(_pro(header)), pssh_b64=_pro_b64(header)) + drm = PlayReady(pssh=PSSH(_pro(header))) # the header KID leads (it is what the licence server acts on); CUSTOMATTRIBUTES KIDs stay reachable assert drm.kids == [KID_A, KID_B, kid_c] assert drm.kid == KID_A +def test_kids_of_every_header_lead_then_customattributes_then_the_given_kid() -> None: + kid_c = UUID("11111111-2222-3333-4444-555555555555") + kid_d = UUID("66666666-7777-8888-9999-000000000000") + custom = f'' + first = _xml_header( + "4.3.0.0", f'{custom}' + ) + + drm = PlayReady(pssh=PSSH(_pro(first, _wrm_header(KID_B))), kid=kid_d) + + assert drm.kids == [KID_A, KID_B, kid_c, kid_d] + + +def test_a_customattributes_value_that_is_not_a_kid_is_skipped() -> None: + header = _xml_header( + "4.3.0.0", + f'' + f'', + ) + + assert PlayReady(pssh=PSSH(_pro(header))).kids == [KID_A, KID_B] + + +def test_session_keys_of_both_key_shapes_map_kid_to_hex() -> None: + cdm = SimpleNamespace( + get_keys=lambda _: [FakeKey(KID_A, KEY_A), WidevineKey("CONTENT", KID_B, bytes.fromhex(KEY_B), [])] + ) + + assert _drm(_wrm_header(KID_A)).extract_keys_from_cdm(cdm, b"s") == {KID_A: KEY_A, KID_B: KEY_B} + + def test_device_revoked_on_the_first_header_is_not_swallowed() -> None: drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B)) cdm = FakeCdm({KID_A: KEY_A, KID_B: KEY_B}) diff --git a/tests/remote/unit/test_licence_declared_kwargs.py b/tests/remote/unit/test_licence_declared_kwargs.py index 4dcbc6b4b..dde86b325 100644 --- a/tests/remote/unit/test_licence_declared_kwargs.py +++ b/tests/remote/unit/test_licence_declared_kwargs.py @@ -105,7 +105,7 @@ class StubPlayReady(PlayReady): kids: Any = None def __init__(self, pssh: Any = None, pssh_b64: str | None = None, **kwargs: Any) -> None: - self.pssh = SimpleNamespace(wrm_headers=[SimpleNamespace(dumps=lambda: "")]) + self.pssh = SimpleNamespace(wrm_headers=[SimpleNamespace(dumps=lambda: "", key_ids=[])]) self.pssh_b64 = pssh_b64 self.kids = [KID] self._extra_headers: list[Any] = [] diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py index a7641f848..0ddf3af6a 100644 --- a/unshackle/core/drm/playready.py +++ b/unshackle/core/drm/playready.py @@ -41,22 +41,14 @@ class PlayReady(CencDrm): if not isinstance(pssh, PSSH): raise TypeError(f"Expected pssh to be a {PSSH}, not {pssh!r}") - kids: list[UUID] = [] - for header in pssh.wrm_headers: - for header_kid in self.header_kids(header): - if header_kid not in kids: - kids.append(header_kid) - if pssh_b64: - for extra_kid in self.extract_kids_from_pssh_b64(pssh_b64): - if extra_kid not in kids: - kids.append(extra_kid) - self._kid = as_kid(kid) - if self._kid and self._kid not in kids: + kids = [k for header in pssh.wrm_headers for k in self.header_kids(header)] + kids += [k for header in pssh.wrm_headers for k in self.custom_attribute_kids(header)] + if self._kid: kids.append(self._kid) self._pssh = pssh - self._kids = kids + self._kids = list(dict.fromkeys(kids)) self._extra_headers: list[WRMHeader] = [] self._refused_headers: set[str] = set() @@ -68,93 +60,6 @@ class PlayReady(CencDrm): if pssh_b64: self.data.setdefault("pssh_b64", pssh_b64) - def extract_kids_from_pssh_b64(self, pssh_b64: str) -> list[UUID]: - """Extract all KIDs from base64-encoded PSSH data.""" - try: - # PSSH XML comes from third-party manifests; defusedxml guards against entity expansion - import defusedxml.ElementTree as ET - - # Decode the PSSH - pssh_bytes = base64.b64decode(pssh_b64) - - # Try to find XML in the PSSH data - pssh_str = pssh_bytes.decode("utf-16le", errors="ignore") - - # Find WRMHEADER - xml_start = pssh_str.find("") + len("") - clean_xml = clean_xml[:xml_end] - - root = ET.fromstring(clean_xml) - ns = {"pr": "http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader"} - - kids = [] - - kid_elements = root.findall(".//pr:CUSTOMATTRIBUTES/pr:KIDS/pr:KID", ns) - for kid_elem in kid_elements: - value = kid_elem.get("VALUE") - if value: - try: - kid_bytes = base64.b64decode(value + "==") - kid_uuid = UUID(bytes_le=kid_bytes) - kids.append(kid_uuid) - except ValueError: - pass - - # v4.2/v4.3: DATA/PROTECTINFO/KIDS/KID - protectinfo_kids = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KIDS/pr:KID", ns) - for kid_elem in protectinfo_kids: - value = kid_elem.get("VALUE") - if value: - try: - kid_bytes = base64.b64decode(value + "==") - kid_uuid = UUID(bytes_le=kid_bytes) - if kid_uuid not in kids: - kids.append(kid_uuid) - except ValueError: - pass - - # v4.1: DATA/PROTECTINFO/KID - protectinfo_kid = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KID", ns) - for kid_elem in protectinfo_kid: - value = kid_elem.get("VALUE") - if value: - try: - kid_bytes = base64.b64decode(value + "==") - kid_uuid = UUID(bytes_le=kid_bytes) - if kid_uuid not in kids: - kids.append(kid_uuid) - except ValueError: - pass - - # v4.0: DATA/KID - individual_kids = root.findall(".//pr:DATA/pr:KID", ns) - for kid_elem in individual_kids: - if kid_elem.text: - try: - kid_bytes = base64.b64decode(kid_elem.text.strip() + "==") - kid_uuid = UUID(bytes_le=kid_bytes) - if kid_uuid not in kids: - kids.append(kid_uuid) - except ValueError: - pass - - return kids - - # covers bad base64 (binascii.Error), defusedxml rejections (both ValueError) and XML - # ParseError (SyntaxError) from arbitrary third-party PSSH data - except (ValueError, SyntaxError): - pass - - return [] - @classmethod def from_pssh_b64(cls, pssh_b64: str, kid: UUID | None = None) -> PlayReady: """Load a base64 PSSH box or PlayReady Object, or a bare UTF-16LE WRMHEADER that some packagers emit. @@ -196,14 +101,18 @@ class PlayReady(CencDrm): @staticmethod def header_kids(header: WRMHeader) -> list[UUID]: """Return the KIDs one WRM header names, in header order.""" + return [signed_key_id.value for signed_key_id in header.key_ids] + + @staticmethod + def custom_attribute_kids(header: WRMHeader) -> list[UUID]: + """Return the KIDs a WRM header lists under CUSTOMATTRIBUTES/KIDS, skipping a value that is not a KID.""" + if header.custom_attributes is None: + return [] kids: list[UUID] = [] - for signed_key_id in getattr(header, "key_ids", []): + for element in header.custom_attributes.findall("KIDS/KID"): try: - if isinstance(signed_key_id.value, UUID): - kids.append(signed_key_id.value) - else: - kids.append(UUID(bytes_le=base64.b64decode(signed_key_id.value))) - except (ValueError, TypeError): + kids.append(UUID(bytes_le=base64.b64decode(element.get("VALUE", "") + "=="))) + except ValueError: continue return kids @@ -259,36 +168,9 @@ class PlayReady(CencDrm): ) return base64.b64encode(pro).decode() - def extract_keys_from_cdm(self, cdm: PlayReadyCdm, session_id: bytes) -> dict: - """Extract keys from CDM session with cross-library compatibility. - - Args: - cdm: CDM instance - session_id: Session identifier - - Returns: - Dictionary mapping KID UUIDs to hex keys - """ - keys = {} - for key in cdm.get_keys(session_id): - if hasattr(key, "key_id"): - kid = key.key_id - elif hasattr(key, "kid"): - kid = key.kid - else: - continue - - if hasattr(key, "key") and hasattr(key.key, "hex"): - key_hex = key.key.hex() - elif hasattr(key, "key") and isinstance(key.key, bytes): - key_hex = key.key.hex() - elif hasattr(key, "key") and isinstance(key.key, str): - key_hex = key.key - else: - continue - - keys[kid] = key_hex - return keys + def extract_keys_from_cdm(self, cdm: PlayReadyCdm, session_id: bytes) -> dict[UUID, str]: + """Map each licence key to its hex content key: pyplayready names the KID key_id, pywidevine (HttpCdm) kid.""" + return {(key.key_id if hasattr(key, "key_id") else key.kid): key.key.hex() for key in cdm.get_keys(session_id)} def get_content_keys(self, cdm: PlayReadyCdm, certificate: Callable, licence: Callable) -> None: """License every distinct WRM header whose KIDs still lack a content key. diff --git a/uv.lock b/uv.lock index 97d57ddba..e2f966f40 100644 --- a/uv.lock +++ b/uv.lock @@ -601,15 +601,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/ec/bb273b7208c606890dc36540fe667d06ce840a6f62f9fae7e658fcdc90fb/cssutils-2.11.1-py3-none-any.whl", hash = "sha256:a67bfdfdff4f3867fab43698ec4897c1a828eca5973f4073321b3bccaf1199b1", size = 385747, upload-time = "2024-06-04T15:51:37.499Z" }, ] -[[package]] -name = "defusedxml" -version = "0.7.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, -] - [[package]] name = "distlib" version = "0.4.0" @@ -2259,7 +2250,6 @@ dependencies = [ { name = "click" }, { name = "construct" }, { name = "cryptography" }, - { name = "defusedxml" }, { name = "filelock" }, { name = "fonttools" }, { name = "jsonpickle" }, @@ -2328,7 +2318,6 @@ requires-dist = [ { name = "click", specifier = ">=8.2,<9" }, { name = "construct", specifier = ">=2.8.8,<3" }, { name = "cryptography", specifier = ">=45.0.0,<47" }, - { name = "defusedxml", specifier = ">=0.7.1,<0.8" }, { name = "filelock", specifier = ">=3.20.3,<4" }, { name = "fonttools", specifier = ">=4.60.2,<5" }, { name = "jsonpickle", specifier = ">=3.0.4,<5" },