diff --git a/tests/core/test_http_cdm.py b/tests/core/test_http_cdm.py new file mode 100644 index 00000000..c2e89a00 --- /dev/null +++ b/tests/core/test_http_cdm.py @@ -0,0 +1,142 @@ +"""The shared bookkeeping of the HTTP CDMs: sessions, vault and cached keys, and their merge with licence keys.""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from uuid import UUID + +import pytest +from pywidevine.pssh import PSSH + +from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM, CustomRemoteCDMExceptions +from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM, DecryptLabsRemoteCDMExceptions +from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions +from unshackle.core.drm import Widevine + +pytestmark = pytest.mark.unit + +KID_A = UUID("00112233445566778899aabbccddeeff") +KID_B = UUID("ffeeddccbbaa99887766554433221100") +KEY_A, KEY_B, KEY_X = "01" * 16, "02" * 16, "0f" * 16 + + +class FakeVaults: + def __init__(self, keys: Dict[UUID, str]) -> None: + self.keys = dict(keys) + self.added: Dict[Any, str] = {} + + def __len__(self) -> int: + return 1 + + def get_key(self, kid: UUID) -> tuple[Optional[str], None]: + return self.keys.get(kid), None + + def add_keys(self, keys: Dict[Any, str]) -> None: + self.added.update(keys) + + +class StubCdm(HttpCdm): + """An adapter whose API answers from fixed lists and records what it was asked.""" + + def __init__( + self, + cached: Optional[List[Dict[str, Any]]] = None, + licence: Optional[List[Dict[str, Any]]] = None, + vaults: Any = None, + ) -> None: + super().__init__("https://cdm.test/", "L3", None, "EXAMPLE", vaults, {}) + self.cached = cached + self.licence = licence or [] + self.challenges = 0 + self.required: List[Optional[List[str]]] = [] + self.bodies: List[Dict[str, Any]] = [] + + def _request_challenge( + self, + session: Dict[str, Any], + body: Dict[str, Any], + license_type: str, + privacy_mode: bool, + ) -> bytes: + self.challenges += 1 + self.required.append(session.get("required_kids")) + if self.cached is not None and self._take_cached_keys(session, self.cached): + return b"" + return self._keep_challenge(session, b"challenge", "remote-1") + + def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]: + self.bodies.append(body) + return self.licence + + +def key(kid: UUID, value: str) -> Dict[str, str]: + return {"kid": kid.hex, "key": value, "type": "CONTENT"} + + +def licensed(cdm: StubCdm, *kids: UUID) -> Dict[UUID, str]: + """Run one challenge and licence round and return the content keys of the session.""" + session_id = cdm.open() + cdm.set_required_kids(list(kids), session_id=session_id) + if cdm.get_license_challenge(session_id, PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids))): + cdm.parse_license(session_id, b"licence") + return {k.kid: k.key.hex() for k in cdm.get_keys(session_id, "CONTENT")} + + +def test_vaults_holding_every_kid_skip_the_api() -> None: + cdm = StubCdm(vaults=FakeVaults({KID_A: KEY_A, KID_B: KEY_B})) + assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B} + assert cdm.challenges == 0 + + +def test_a_vault_key_wins_over_the_licence_and_licence_keys_go_to_the_vaults() -> None: + vaults = FakeVaults({KID_A: KEY_A}) + cdm = StubCdm(licence=[key(KID_A, KEY_X), key(KID_B, KEY_B), key(KID_B, KEY_X)], vaults=vaults) + assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B} + assert vaults.added == {KID_A: KEY_A, KID_B: KEY_B} + + +def test_cached_keys_covering_every_kid_need_no_licence() -> None: + cdm = StubCdm(cached=[key(KID_A, KEY_A)]) + assert licensed(cdm, KID_A) == {KID_A: KEY_A} + assert cdm.bodies == [] + + +def test_partial_cached_keys_merge_with_the_licence() -> None: + cdm = StubCdm(cached=[key(KID_A, KEY_A)], licence=[key(KID_A, KEY_X), key(KID_B, KEY_B)]) + assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B} + assert cdm.bodies[0]["session_id"] == "remote-1" + + +def test_an_unknown_session_raises_the_shared_exception() -> None: + cdm = StubCdm() + session_id = cdm.open() + cdm.close(session_id) + with pytest.raises(CustomRemoteCDMExceptions.InvalidSession): + cdm.get_keys(session_id) + assert CustomRemoteCDMExceptions is DecryptLabsRemoteCDMExceptions is HttpCdmExceptions + + +def test_widevine_skips_the_licence_when_the_cdm_holds_cached_keys() -> None: + def licence(**_: Any) -> bytes: + raise AssertionError("no licence request when the cache holds every key") + + drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID_A]), kid=KID_A) + cdm = StubCdm(cached=[key(KID_A, KEY_A)]) + drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence) + assert drm.content_keys == {KID_A: KEY_A} + assert cdm.required == [[KID_A.hex]] + + +@pytest.mark.parametrize( + ("cdm", "privacy_cert"), + [ + (DecryptLabsRemoteCDM(secret="s", device_name="L2"), True), + (DecryptLabsRemoteCDM(secret="s", device_name="L3"), False), + (CustomRemoteCDM(host="https://cdm.test", device={"name": "L1"}), True), + (CustomRemoteCDM(host="https://cdm.test", device={"name": "L2"}), False), + ], +) +def test_only_the_listed_devices_get_the_common_privacy_certificate(cdm: HttpCdm, privacy_cert: bool) -> None: + session_id = cdm.open() + cdm.set_service_certificate(session_id, None) + assert (cdm.get_service_certificate(session_id) is not None) is privacy_cert diff --git a/tests/core/test_http_cdm_loopback.py b/tests/core/test_http_cdm_loopback.py new file mode 100644 index 00000000..937e33ef --- /dev/null +++ b/tests/core/test_http_cdm_loopback.py @@ -0,0 +1,238 @@ +"""Each HTTP CDM adapter licenses a title end to end against a loopback stub of its API. + +The stub answers the request shapes the adapter sends, so the test covers the wire form of each +adapter through ``Widevine.get_content_keys`` and ``PlayReady.get_content_keys``. +""" + +from __future__ import annotations + +import base64 +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Callable, Dict, Iterator, List +from uuid import UUID + +import pytest +from pyplayready.system.pssh import PSSH as PlayReadyPssh +from pywidevine.pssh import PSSH as WidevinePssh + +from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM +from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM +from unshackle.core.drm import PlayReady, Widevine + +pytestmark = pytest.mark.unit + +KID = UUID("00112233445566778899aabbccddeeff") +KEY = "0123456789abcdef0123456789abcdef" +CHALLENGE = b"loopback challenge" +LICENCE = b"loopback licence" +PR_LICENCE = "loopback" + +Answer = Callable[[Dict[str, Any]], Dict[str, Any]] + + +class Api: + """A loopback HTTP API: one answer per path, every request recorded.""" + + def __init__(self) -> None: + self.answers: Dict[str, Answer] = {} + self.requests: List[tuple[str, Dict[str, str], Dict[str, Any]]] = [] + api = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + api.requests.append((self.path, dict(self.headers), body)) + answer = json.dumps(api.answers[self.path](body)).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(answer))) + self.end_headers() + self.wfile.write(answer) + + def log_message(self, *_: Any) -> None: + pass + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.server.server_address[1]}" + + +@pytest.fixture +def api() -> Iterator[Api]: + stub = Api() + thread = threading.Thread(target=stub.server.serve_forever, daemon=True) + thread.start() + yield stub + stub.server.shutdown() + stub.server.server_close() + + +def b64(data: bytes) -> str: + return base64.b64encode(data).decode() + + +def widevine_drm() -> Widevine: + return Widevine(pssh=WidevinePssh.new(system_id=WidevinePssh.SystemId.Widevine, key_ids=[KID]), kid=KID) + + +def playready_drm() -> PlayReady: + kid_xml = f'' + header = ( + '' + f"{kid_xml}" + ).encode("utf-16-le") + pro = PlayReadyPssh.PlayreadyHeader.build( + {"length": 10 + len(header), "records": [{"type": 1, "length": len(header), "data": header}]} + ) + return PlayReady.from_pssh_b64(b64(pro)) + + +def licence_for(expected: Any) -> Callable[..., Any]: + def licence(*, challenge: Any, **_: Any) -> Any: + assert challenge == CHALLENGE + return expected + + return licence + + +def decrypt_labs_answers(api: Api, keys: Any) -> None: + api.answers["/get-request"] = lambda body: { + "message": "success", + "message_type": "license-request", + "challenge": b64(CHALLENGE), + "session_id": "remote-1", + } + api.answers["/decrypt-response"] = lambda body: {"message": "success", "keys": keys} + + +def test_decrypt_labs_widevine(api: Api) -> None: + decrypt_labs_answers(api, f"--key {KID.hex}:{KEY}\n") + drm = widevine_drm() + cdm = DecryptLabsRemoteCDM(secret="s3cret", host=api.url, device_name="L3", service_name="EXAMPLE") + + drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence_for(LICENCE)) + + assert drm.content_keys == {KID: KEY} + (path, headers, challenge_req), (_, _, keys_req) = api.requests + assert headers["decrypt-labs-api-key"] == "s3cret" + assert challenge_req == { + "scheme": "L3", + "init_data": drm.pssh.dumps(), + "get_cached_keys_if_exists": True, + "service": "EXAMPLE", + } + assert keys_req["session_id"] == "remote-1" + assert keys_req["license_request"] == b64(CHALLENGE) + assert keys_req["license_response"] == b64(LICENCE) + + +def test_decrypt_labs_playready(api: Api) -> None: + decrypt_labs_answers(api, [{"kid": KID.hex, "key": KEY, "type": "CONTENT"}]) + drm = playready_drm() + cdm = DecryptLabsRemoteCDM(secret="s3cret", host=api.url, device_name="SL3") + + drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence_for(PR_LICENCE)) + + assert drm.content_keys == {KID: KEY} + (_, _, challenge_req), (_, _, keys_req) = api.requests + assert challenge_req["init_data"] == drm.pssh_b64 + assert keys_req["init_data"] == drm.pssh_b64 + assert base64.b64decode(keys_req["license_response"]) == PR_LICENCE.encode() + + +def test_decrypt_labs_cached_keys_need_no_licence(api: Api) -> None: + api.answers["/get-request"] = lambda body: { + "message": "success", + "message_type": "cached-keys", + "cached_keys": [{"kid": KID.hex, "key": KEY}], + } + drm = widevine_drm() + cdm = DecryptLabsRemoteCDM(secret="s", host=api.url, device_name="L3") + + drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence_for(None)) + + assert drm.content_keys == {KID: KEY} + assert [path for path, _, _ in api.requests] == ["/get-request"] + + +KID_B = UUID("ffeeddccbbaa99887766554433221100") +KEY_B = "fedcba9876543210fedcba9876543210" + + +@pytest.mark.parametrize("second_answer", ["challenge", "refused"]) +def test_decrypt_labs_partial_cache_asks_for_a_licence(api: Api, second_answer: str) -> None: + """Cached keys that miss a KID make an L1 device ask again without the cache, then merge both sets.""" + answers = iter( + [ + {"message": "success", "message_type": "cached-keys", "cached_keys": [{"kid": KID.hex, "key": KEY}]}, + {"message": "success", "challenge": b64(CHALLENGE), "session_id": "remote-1"} + if second_answer == "challenge" + else {"message": "refused"}, + ] + ) + api.answers["/get-request"] = lambda body: next(answers) + api.answers["/decrypt-response"] = lambda body: {"message": "success", "keys": f"--key {KID_B.hex}:{KEY_B}"} + cdm = DecryptLabsRemoteCDM(secret="s", host=api.url, device_name="L1") + session_id = cdm.open() + cdm.set_required_kids([KID, KID_B], session_id=session_id) + + challenge = cdm.get_license_challenge(session_id, widevine_drm().pssh) + if challenge: + cdm.parse_license(session_id, LICENCE) + + keys = {k.kid: k.key.hex() for k in cdm.get_keys(session_id, "CONTENT")} + requests = [(path, body.get("get_cached_keys_if_exists")) for path, _, body in api.requests] + assert requests[:2] == [("/get-request", True), ("/get-request", False)] + if second_answer == "challenge": + assert challenge == CHALLENGE + assert keys == {KID: KEY, KID_B: KEY_B} + else: + assert challenge == b"" + assert keys == {KID: KEY} + + +CUSTOM_CONFIG: Dict[str, Any] = { + "auth": {"type": "header", "header_name": "x-api-key", "key": "s3cret"}, + "endpoints": {"get_request": "/challenge", "decrypt_response": {"path": "/keys"}}, + "request_mapping": {"get_request": {"param_names": {"init_data": "pssh"}}}, + "response_mapping": { + "get_request": { + "fields": {"challenge": "data.challenge", "session_id": "data.session", "status": "status"}, + "success_conditions": ["status == ok"], + }, + "decrypt_response": {"fields": {"keys": "data.keys"}, "key_fields": {"kid": "key_id", "key": "value"}}, + }, +} + + +def custom_answers(api: Api) -> None: + api.answers["/challenge"] = lambda body: { + "status": "ok", + "data": {"challenge": b64(CHALLENGE), "session": "remote-1"}, + } + api.answers["/keys"] = lambda body: {"data": {"keys": [{"key_id": KID.hex, "value": KEY}]}} + + +@pytest.mark.parametrize( + ("device", "drm_of", "licence"), + [ + ({"name": "L3", "type": "CHROME"}, widevine_drm, LICENCE), + ({"name": "SL3000", "type": "PLAYREADY"}, playready_drm, PR_LICENCE), + ], +) +def test_custom_api(api: Api, device: Dict[str, Any], drm_of: Callable[[], Any], licence: Any) -> None: + custom_answers(api) + drm = drm_of() + cdm = CustomRemoteCDM(host=api.url, device=device, **CUSTOM_CONFIG) + + drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence_for(licence)) + + assert drm.content_keys == {KID: KEY} + (path, headers, challenge_req), (keys_path, _, keys_req) = api.requests + assert (path, keys_path) == ("/challenge", "/keys") + assert headers["x-api-key"] == "s3cret" + assert challenge_req["scheme"] == device["name"] + assert "init_data" not in challenge_req and challenge_req["pssh"] + assert keys_req["session_id"] == "remote-1" + assert keys_req["license_request"] == b64(CHALLENGE) diff --git a/tests/core/test_playready_multi_header.py b/tests/core/test_playready_multi_header.py index 2985d1b2..246f87ef 100644 --- a/tests/core/test_playready_multi_header.py +++ b/tests/core/test_playready_multi_header.py @@ -10,6 +10,7 @@ from pyplayready.misc.exceptions import InvalidLicense, InvalidXmrLicense from pyplayready.system.pssh import PSSH from pyplayready.system.wrmheader import WRMHeader +from unshackle.core.cdm.http_cdm import HttpCdm from unshackle.core.drm import PlayReady KID_A = UUID("00112233-4455-6677-8899-aabbccddeeff") @@ -45,7 +46,7 @@ class FakeKey: self.key = bytes.fromhex(key) -class FakeCdm: +class FakeCdm(HttpCdm): """Answers each challenge with the keys mapped for the header's KIDs; records what it saw.""" def __init__(self, answers: dict[UUID, str], fail_on: set[UUID] | None = None) -> None: @@ -86,6 +87,12 @@ class FakeCdm: def get_keys(self, session_id: str) -> list[FakeKey]: return [FakeKey(kid, self.answers[kid]) for kid in self._by_session[session_id] if kid in self.answers] + def _request_challenge(self, *_: Any) -> bytes: + raise NotImplementedError + + def _request_keys(self, *_: Any) -> list[dict[str, Any]]: + raise NotImplementedError + def _licence(**_: Any) -> str: return "x" diff --git a/tests/core/test_remote_cdm_playready_licence.py b/tests/core/test_remote_cdm_playready_licence.py index b10e0765..fbc810ee 100644 --- a/tests/core/test_remote_cdm_playready_licence.py +++ b/tests/core/test_remote_cdm_playready_licence.py @@ -28,20 +28,20 @@ class Sent(Exception): """Stops ``parse_license`` after the request body has been captured.""" -def decrypt_labs_cdm() -> tuple[Any, str]: - return DecryptLabsRemoteCDM(secret="x", host="https://cdm.test", device_name="SL3"), "decrypt_labs_session_id" +def decrypt_labs_cdm() -> Any: + return DecryptLabsRemoteCDM(secret="x", host="https://cdm.test", device_name="SL3") -def custom_cdm() -> tuple[Any, str]: - cdm = CustomRemoteCDM(host="https://cdm.test", device={"name": "SL3000", "type": "PLAYREADY"}) - return cdm, "remote_session_id" +def custom_cdm() -> Any: + return CustomRemoteCDM(host="https://cdm.test", device={"name": "SL3000", "type": "PLAYREADY"}) -def licence_sent(cdm: Any, remote_id_key: str, licence: str) -> bytes: +def licence_sent(cdm: Any, licence: str) -> bytes: """Run ``parse_license`` on a session that has a challenge, and return the licence bytes it posts.""" session_id = cdm.open() - cdm.set_pssh_b64("UFNTSA==", session_id=session_id) - cdm._sessions[session_id].update({"challenge": b"challenge", remote_id_key: "remote", "pssh": object()}) + cdm._sessions[session_id].update( + {"challenge": b"challenge", "remote_session_id": "remote", "init_data": "UFNTSA=="} + ) body: dict[str, Any] = {} @@ -67,11 +67,9 @@ def licence_sent(cdm: Any, remote_id_key: str, licence: str) -> bytes: ], ) def test_a_playready_xml_licence_is_sent_as_it_is(make_cdm: Any, licence: str) -> None: - cdm, remote_id_key = make_cdm() - assert licence_sent(cdm, remote_id_key, licence) == licence.encode("utf-8") + assert licence_sent(make_cdm(), licence) == licence.encode("utf-8") @pytest.mark.parametrize("make_cdm", [decrypt_labs_cdm, custom_cdm]) def test_a_base64_licence_is_still_decoded(make_cdm: Any) -> None: - cdm, remote_id_key = make_cdm() - assert licence_sent(cdm, remote_id_key, base64.b64encode(b"binary licence").decode()) == b"binary licence" + assert licence_sent(make_cdm(), base64.b64encode(b"binary licence").decode()) == b"binary licence" diff --git a/tests/core/test_remote_cdm_pssh_reuse.py b/tests/core/test_remote_cdm_pssh_reuse.py index e25de0bb..9d559afc 100644 --- a/tests/core/test_remote_cdm_pssh_reuse.py +++ b/tests/core/test_remote_cdm_pssh_reuse.py @@ -1,21 +1,33 @@ -"""A reused CustomRemoteCDM must not carry one title's PlayReady PSSH into the next. +"""A reused HTTP CDM must not carry one title's PSSH or required KIDs into the next. -``dl.get_cdm`` builds each CDM once per run, so one instance serves every title. -``PlayReady.get_content_keys`` calls ``set_pssh_b64`` only when the DRM has a PSSH, so -an instance-level value left over from an earlier title would be sent as the init data -of a title that has none. +``dl.get_cdm`` builds each CDM once per run, so one instance serves every title, and tracks +decrypt in parallel on it. Each CDM session keeps its own PSSH and required KIDs. """ from __future__ import annotations import base64 +from typing import Any, Callable, List import pytest +from pyplayready.system.wrmheader import WRMHeader from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM +from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM +from unshackle.core.drm import PlayReady pytestmark = pytest.mark.unit +ADAPTERS: list[Callable[[], Any]] = [ + lambda: CustomRemoteCDM(host="https://cdm.test", device={"name": "SL3000", "type": "PLAYREADY"}), + lambda: DecryptLabsRemoteCDM(secret="x", host="https://cdm.test", device_name="SL3"), +] + +HEADER = ( + '' + "MzMzMzMzMzMzMzMzMzMzMw==" +) + class FakePssh: """A PSSH object shaped like the ones the manifests hand to the CDM.""" @@ -24,42 +36,58 @@ class FakePssh: self.raw = raw -def make_cdm() -> CustomRemoteCDM: - return CustomRemoteCDM(host="https://cdm.test", device={"name": "SL3000", "type": "PLAYREADY"}) +def recording(cdm: Any) -> List[tuple[str, Any]]: + """Make the adapter record the init data and required KIDs of each challenge instead of sending it.""" + sent: List[tuple[str, Any]] = [] + + def request_challenge(session: Any, body: Any, *_: Any) -> bytes: + sent.append((body["init_data"], session.get("required_kids"))) + return b"challenge" + + cdm._request_challenge = request_challenge + return sent -def set_pssh(cdm: CustomRemoteCDM, session_id: bytes, pssh_b64: str) -> None: - """Store a PSSH the way ``PlayReady.get_content_keys`` does.""" - try: - cdm.set_pssh_b64(pssh_b64, session_id=session_id) - except TypeError: # CDM predating the per-session signature - cdm.set_pssh_b64(pssh_b64) - - -def test_a_later_session_does_not_inherit_the_earlier_pssh() -> None: +@pytest.mark.parametrize("make_cdm", ADAPTERS) +def test_a_later_session_does_not_inherit_the_earlier_pssh_or_kids(make_cdm: Callable[[], Any]) -> None: cdm = make_cdm() assert cdm.is_playready + sent = recording(cdm) first = cdm.open() - set_pssh(cdm, first, "FIRST_TITLE_PSSH") - assert cdm.get_init_data_from_pssh(FakePssh(b"ignored")) == "FIRST_TITLE_PSSH" + cdm.set_pssh_b64("FIRST_TITLE_PSSH", session_id=first) + cdm.set_required_kids(["00" * 16], session_id=first) + cdm.get_license_challenge(first, FakePssh(b"ignored")) cdm.close(first) - # The second title has no PSSH of its own, so nothing calls set_pssh_b64. - cdm.open() - init_data = cdm.get_init_data_from_pssh(FakePssh(b"second")) + second = cdm.open() + cdm.get_license_challenge(second, FakePssh(b"second")) - assert init_data == base64.b64encode(b"second").decode("utf-8") + assert sent == [("FIRST_TITLE_PSSH", ["00" * 16]), (base64.b64encode(b"second").decode(), None)] -def test_two_open_sessions_keep_their_own_pssh() -> None: - """Tracks decrypt in parallel on the one shared instance, so the store is per session.""" +@pytest.mark.parametrize("make_cdm", ADAPTERS) +def test_two_open_sessions_keep_their_own_pssh(make_cdm: Callable[[], Any]) -> None: cdm = make_cdm() + sent = recording(cdm) one = cdm.open() two = cdm.open() - set_pssh(cdm, one, "PSSH_ONE") - set_pssh(cdm, two, "PSSH_TWO") + cdm.set_pssh_b64("PSSH_ONE", session_id=one) + cdm.set_pssh_b64("PSSH_TWO", session_id=two) + cdm.get_license_challenge(one, FakePssh(b"x")) + cdm.get_license_challenge(two, FakePssh(b"x")) - assert cdm.get_init_data_from_pssh(FakePssh(b"x"), cdm._sessions[one]["pssh_b64"]) == "PSSH_ONE" - assert cdm.get_init_data_from_pssh(FakePssh(b"x"), cdm._sessions[two]["pssh_b64"]) == "PSSH_TWO" + assert [init_data for init_data, _ in sent] == ["PSSH_ONE", "PSSH_TWO"] + + +@pytest.mark.parametrize("make_cdm", ADAPTERS) +@pytest.mark.parametrize("header", [WRMHeader(HEADER), HEADER]) +def test_a_bare_wrm_header_goes_out_as_a_playready_object(make_cdm: Callable[[], Any], header: Any) -> None: + """A service or the client relay may pass only a header; the API takes a PlayReady Object.""" + cdm = make_cdm() + sent = recording(cdm) + + cdm.get_license_challenge(cdm.open(), header) + + assert sent[0][0] == PlayReady.pro_b64_for(WRMHeader(HEADER)) diff --git a/tests/remote/unit/test_server_cdm_service_injected_keys.py b/tests/remote/unit/test_server_cdm_service_injected_keys.py index 83cc1f10..adbdbb31 100644 --- a/tests/remote/unit/test_server_cdm_service_injected_keys.py +++ b/tests/remote/unit/test_server_cdm_service_injected_keys.py @@ -37,9 +37,6 @@ class _BypassCdm: def close(self, session_id): pass - def set_pssh_b64(self, *a, **k): - pass - def get_license_challenge(self, session_id, pssh): return b"challenge" diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index d7acb745..59b5d1ef 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -37,7 +37,6 @@ from rich.spinner import Spinner from rich.table import Table from unshackle.core import __version__, binaries, providers -from unshackle.core.cdm import DecryptLabsRemoteCDM from unshackle.core.cdm.choice import choose_cdm from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm from unshackle.core.config import cdm_entry_names_device, config, load_yaml, resolve_cdm_name, resolve_decryption @@ -479,10 +478,8 @@ def cdm_summary(cdm: Any) -> dict[str, Any]: """The loaded CDM's DRM system, whether it is remote, its device and its security level, for the load log.""" drm_type = "PlayReady" if is_playready_cdm(cdm) else "Widevine" remote = is_remote_cdm(cdm) - if isinstance(cdm, DecryptLabsRemoteCDM): - device = "DecryptLabs" - elif remote: - device = cdm.device_name + if remote: + device = getattr(cdm, "label", None) or cdm.device_name elif drm_type == "Widevine": device = str(cdm.system_id) else: diff --git a/unshackle/core/cdm/custom_remote_cdm.py b/unshackle/core/cdm/custom_remote_cdm.py index c2d91f28..467cdc0c 100644 --- a/unshackle/core/cdm/custom_remote_cdm.py +++ b/unshackle/core/cdm/custom_remote_cdm.py @@ -1,85 +1,19 @@ from __future__ import annotations import base64 -import secrets -from typing import Any, Dict, List, Optional, Union -from uuid import UUID +from typing import Any, Dict, List, Optional import requests -from pywidevine.cdm import Cdm as WidevineCdm -from pywidevine.device import DeviceTypes from requests import Session from unshackle.core import __version__ -from unshackle.core.cdm.loader import system_of -from unshackle.core.vault import is_null_key +from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions, b64_or_utf8 from unshackle.core.vaults import Vaults - -class MockCertificateChain: - """Mock certificate chain for PlayReady compatibility.""" - - def __init__(self, name: str) -> None: - self._name = name - - def get_name(self) -> str: - return self._name +CustomRemoteCDMExceptions = HttpCdmExceptions -class Key: - """`Key` object compatible with pywidevine.""" - - def __init__( - self, - kid: Union[str, UUID], - key: Union[str, bytes], - type_: str = "CONTENT", - permissions: Optional[List[str]] = None, - ) -> None: - if isinstance(kid, str): - clean_kid = kid.replace("-", "") - if len(clean_kid) == 32: - self.kid = UUID(hex=clean_kid) - else: - self.kid = UUID(hex=clean_kid.ljust(32, "0")) - else: - self.kid = kid - - if isinstance(key, str): - self.key = bytes.fromhex(key) - else: - self.key = key - - self.type = type_ - self.permissions = permissions or [] - - -class CustomRemoteCDMExceptions: - """Exception classes for compatibility with pywidevine CDM.""" - - class InvalidSession(Exception): - """Raised when session ID is invalid.""" - - class TooManySessions(Exception): - """Raised when the CDM sessions reach the limit.""" - - class InvalidInitData(Exception): - """Raised when PSSH/init data is invalid.""" - - class InvalidLicenseType(Exception): - """Raised when license type is invalid.""" - - class InvalidLicenseMessage(Exception): - """Raised when license message is invalid.""" - - class InvalidContext(Exception): - """Raised when the CDM session has no context data.""" - - class SignatureMismatch(Exception): - """Raised when signature verification fails.""" - - -class CustomRemoteCDM: +class CustomRemoteCDM(HttpCdm): """ Highly Configurable Custom Remote CDM implementation. @@ -114,9 +48,7 @@ class CustomRemoteCDM: - Conditional parameters based on device type or other factors """ - service_certificate_challenge = b"\x08\x04" - - is_remote_cdm = True + chain_suffix = "Custom_Remote" def __init__( self, @@ -150,24 +82,21 @@ class CustomRemoteCDM: timeout: Default request timeout in seconds **kwargs: Additional configuration options for future extensibility """ - self.host = host.rstrip("/") - self.service_name = service_name or "" - self.vaults = vaults - self.timeout = timeout - device = device or {} - self.device_name = device.get("name", "ChromeCDM") self.device_type_str = device.get("type", "CHROME") + self.auth_config = auth or {"type": "header", "header_name": "Authorization", "key": ""} + super().__init__( + host, + device.get("name", "ChromeCDM"), + self.device_type_str, + service_name, + vaults, + {"User-Agent": f"unshackle-custom-cdm/{__version__}", **self.auth_config.get("custom_headers", {})}, + ) + self.timeout = timeout self.system_id = device.get("system_id", 26830) self.security_level = device.get("security_level", 3) - self._is_playready = system_of(self.device_type_str, self.device_name) == "playready" - - if self.device_type_str: - self.device_type = self.get_device_type_enum(self.device_type_str) - - self.auth_config = auth or {"type": "header", "header_name": "Authorization", "key": ""} - endpoints = endpoints or {} self.endpoints = { "get_request": { @@ -207,110 +136,8 @@ class CustomRemoteCDM: self.response_mapping = response_mapping or {} caching = caching or {} - self.caching_enabled = caching.get("enabled", True) self.use_vaults = caching.get("use_vaults", True) and self.vaults is not None - self.check_cached_first = caching.get("check_cached_first", True) - - self.legacy_config = legacy or {"enabled": False} - - self._sessions: Dict[bytes, Dict[str, Any]] = {} - self._pssh_b64: Optional[str] = None - self._required_kids: Optional[List[str]] = None - - self._http_session = Session() - self._http_session.headers.update( - {"Content-Type": "application/json", "User-Agent": f"unshackle-custom-cdm/{__version__}"} - ) - - custom_headers = self.auth_config.get("custom_headers", {}) - if custom_headers: - self._http_session.headers.update(custom_headers) - - def get_device_type_enum(self, device_type: str) -> DeviceTypes: - """Convert device type string to enum for compatibility.""" - device_type_upper = device_type.upper() - if device_type_upper == "ANDROID": - return DeviceTypes.ANDROID - elif device_type_upper == "CHROME": - return DeviceTypes.CHROME - else: - return DeviceTypes.CHROME - - @property - def is_playready(self) -> bool: - """Return True if this CDM is in PlayReady mode.""" - return self._is_playready - - @property - def certificate_chain(self) -> MockCertificateChain: - """Mock certificate chain for PlayReady compatibility.""" - return MockCertificateChain(f"{self.device_name}_Custom_Remote") - - def set_pssh_b64(self, pssh_b64: str, session_id: Optional[bytes] = None) -> None: - """Store base64-encoded PSSH data for PlayReady compatibility.""" - if session_id is not None and session_id in self._sessions: - self._sessions[session_id]["pssh_b64"] = pssh_b64 - self._pssh_b64 = pssh_b64 - - def set_required_kids(self, kids: List[Union[str, UUID]], session_id: Optional[bytes] = None) -> None: - """ - Set the required Key IDs for intelligent caching decisions. - - This method enables the CDM to make smart decisions about when to request - additional keys through license challenges. When cached keys are available, - the CDM will compare them against the required KIDs to determine if a - license request is still needed for missing keys. - - Args: - kids: List of required Key IDs as UUIDs or hex strings - - Note: - Call this method from the DRM classes (PlayReady/Widevine) before a - license challenge request, to enable optimal caching behaviour. - """ - required = [str(kid).replace("-", "").lower() for kid in kids] - if session_id is not None and session_id in self._sessions: - self._sessions[session_id]["required_kids"] = required - self._required_kids = required - - def generate_session_id(self) -> bytes: - """Make a unique session ID.""" - return secrets.token_bytes(16) - - def get_init_data_from_pssh(self, pssh: Any, pssh_b64: Optional[str] = None) -> str: - """Extract init data from various PSSH formats.""" - effective_pssh_b64 = pssh_b64 or self._pssh_b64 - if self.is_playready and effective_pssh_b64: - return effective_pssh_b64 - - if hasattr(pssh, "dumps"): - dumps_result = pssh.dumps() - - if isinstance(dumps_result, str): - try: - base64.b64decode(dumps_result) - return dumps_result - except ValueError: - return base64.b64encode(dumps_result.encode("utf-8")).decode("utf-8") - else: - return base64.b64encode(dumps_result).decode("utf-8") - elif hasattr(pssh, "raw"): - raw_data = pssh.raw - if isinstance(raw_data, str): - raw_data = raw_data.encode("utf-8") - return base64.b64encode(raw_data).decode("utf-8") - elif hasattr(pssh, "__class__") and "WrmHeader" in pssh.__class__.__name__: - if self.is_playready: - raise ValueError("PlayReady WRM header received but no PSSH B64 was set via set_pssh_b64()") - - if hasattr(pssh, "raw_bytes"): - return base64.b64encode(pssh.raw_bytes).decode("utf-8") - elif hasattr(pssh, "bytes"): - return base64.b64encode(pssh.bytes).decode("utf-8") - else: - raise ValueError(f"Cannot extract PSSH data from WRM header type: {type(pssh)}") - else: - raise ValueError(f"Unsupported PSSH type: {type(pssh)}") + self.apply_authentication(self._http_session) def get_nested_field(self, data: Dict[str, Any], field_path: str, default: Any = None) -> Any: """ @@ -664,233 +491,31 @@ class CustomRemoteCDM: return keys - def open(self) -> bytes: - """ - Open a new CDM session. + def _call(self, endpoint_name: str, params: Dict[str, Any], failure: str) -> Dict[str, Any]: + """POST to a configured endpoint and return its JSON body; raises on a status other than 200.""" + endpoint = self.endpoints[endpoint_name] + return self._post(endpoint["path"], params, failure, endpoint["timeout"]) - Returns: - Session identifier as bytes - """ - session_id = self.generate_session_id() - self._pssh_b64 = None - self._sessions[session_id] = { - "service_certificate": None, - "keys": [], - "pssh": None, - "pssh_b64": None, - "challenge": None, - "remote_session_id": None, - "tried_cache": False, - "cached_keys": None, - } - return session_id - - def close(self, session_id: bytes) -> None: - """ - Close a CDM session and do comprehensive cleanup. - - Args: - session_id: Session identifier - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - session.clear() - del self._sessions[session_id] - - def get_service_certificate(self, session_id: bytes) -> Optional[bytes]: - """ - Get the service certificate for a CDM session. - - Args: - session_id: Session identifier - - Returns: - Service certificate if set, None otherwise - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - return self._sessions[session_id]["service_certificate"] - - def set_service_certificate(self, session_id: bytes, certificate: Optional[Union[bytes, str]]) -> str: - """ - Set the service certificate for a CDM session. - - Args: - session_id: Session identifier - certificate: Service certificate (bytes or base64 string) - - Returns: - Certificate status message - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - if certificate is None: - if not self._is_playready and self.device_name == "L1": - certificate = WidevineCdm.common_privacy_cert - self._sessions[session_id]["service_certificate"] = base64.b64decode(certificate) - return "Using default Widevine common privacy certificate for L1" - else: - self._sessions[session_id]["service_certificate"] = None - return "No certificate set (not required for this device type)" - - if isinstance(certificate, str): - certificate = base64.b64decode(certificate) - - self._sessions[session_id]["service_certificate"] = certificate - return "Successfully set Service Certificate" - - def has_cached_keys(self, session_id: bytes) -> bool: - """ - Return True if cached keys are available for the CDM session. - - Args: - session_id: Session identifier - - Returns: - True if cached keys are available - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - session_keys = session.get("keys", []) - return len(session_keys) > 0 - - def get_license_challenge( - self, session_id: bytes, pssh_or_wrm: Any, license_type: str = "STREAMING", privacy_mode: bool = True + def _request_challenge( + self, + session: Dict[str, Any], + body: Dict[str, Any], + license_type: str, + privacy_mode: bool, ) -> bytes: - """ - Make a license challenge with the custom CDM API. - - This method implements intelligent caching logic that checks vaults first, - then attempts to retrieve cached keys from the API, and only makes a - license request if keys are missing. - - Args: - session_id: Session identifier - pssh_or_wrm: PSSH object or WRM header (for PlayReady compatibility) - license_type: Type of license (STREAMING, OFFLINE, AUTOMATIC) - for compatibility only - privacy_mode: Whether to use privacy mode - for compatibility only - - Returns: - License challenge as bytes, or empty bytes if available keys satisfy requirements - - Raises: - InvalidSession: If session ID is invalid - requests.RequestException: If API request fails - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - session["pssh"] = pssh_or_wrm - init_data = self.get_init_data_from_pssh(pssh_or_wrm, session.get("pssh_b64")) - - required_kids_list = session.get("required_kids") or self._required_kids - - if self.use_vaults and self.vaults is not None and required_kids_list: - vault_keys = [] - for kid_str in required_kids_list: - try: - clean_kid = kid_str.replace("-", "") - if len(clean_kid) == 32: - kid_uuid = UUID(hex=clean_kid) - else: - kid_uuid = UUID(hex=clean_kid.ljust(32, "0")) - key, _ = self.vaults.get_key(kid_uuid) - if not is_null_key(key): - vault_keys.append({"kid": kid_str, "key": key, "type": "CONTENT"}) - except (ValueError, TypeError): - continue - - if vault_keys: - vault_kids = set(k["kid"] for k in vault_keys) - required_kids = set(required_kids_list) - - if required_kids.issubset(vault_kids): - session["keys"] = vault_keys - return b"" - else: - session["vault_keys"] = vault_keys - - base_params = { - "scheme": self.device_name, - "init_data": init_data, - "license_type": license_type, - "privacy_mode": privacy_mode, - } - - if self.service_name: - base_params["service"] = self.service_name - - if session["service_certificate"]: - base_params["service_certificate"] = base64.b64encode(session["service_certificate"]).decode("utf-8") - + base_params = {**body, "license_type": license_type, "privacy_mode": privacy_mode} request_params = self.build_request_params("get_request", base_params, session) - - self.apply_authentication(self._http_session) - - endpoint_config = self.endpoints["get_request"] - url = f"{self.host}{endpoint_config['path']}" - timeout = endpoint_config["timeout"] - - response = self._http_session.post(url, json=request_params, timeout=timeout) - - if response.status_code != 200: - raise requests.RequestException(f"API request failed: {response.status_code} {response.text}") - - response_data = response.json() - parsed_response = self.parse_response_data("get_request", response_data) + parsed_response = self.parse_response_data( + "get_request", self._call("get_request", request_params, "API request failed") + ) if not parsed_response.get("_is_success", False): error_msg = parsed_response.get("_error_message", "Unknown error") raise requests.RequestException(f"API error: {error_msg}") - response_type = parsed_response.get("_response_type") - - if response_type == "cached_keys" or "cached_keys" in parsed_response: + if parsed_response.get("_response_type") == "cached_keys" or "cached_keys" in parsed_response: cached_keys = self.parse_keys_from_response("get_request", parsed_response) - - all_available_keys = list(cached_keys) - if "vault_keys" in session: - all_available_keys.extend(session["vault_keys"]) - - session["tried_cache"] = True - - if required_kids_list: - available_kids: set[str] = set() - for cached_key in all_available_keys: - if isinstance(cached_key, dict) and "kid" in cached_key: - available_kids.add(cached_key["kid"].replace("-", "").lower()) - - required_kids = set(required_kids_list) - missing_kids = required_kids - available_kids - - if missing_kids: - # Store cached keys separately - don't populate session["keys"] yet - # This allows parse_license() to properly combine cached + license keys - session["cached_keys"] = cached_keys - else: - session["keys"] = all_available_keys - return b"" - else: - session["keys"] = all_available_keys + if self._take_cached_keys(session, cached_keys): return b"" challenge = parsed_response.get("challenge") @@ -898,178 +523,24 @@ class CustomRemoteCDM: if challenge and remote_session_id: if isinstance(challenge, str): - challenge_text = challenge - try: - challenge = base64.b64decode(challenge_text) - except ValueError: - challenge = challenge_text.encode("utf-8") - - session["challenge"] = challenge - session["remote_session_id"] = remote_session_id - return challenge + challenge = b64_or_utf8(challenge) + return self._keep_challenge(session, challenge, remote_session_id) if session.get("keys"): return b"" raise requests.RequestException("API response did not contain challenge or cached keys") - def parse_license(self, session_id: bytes, license_message: Union[bytes, str]) -> None: - """ - Parse license response using the custom CDM API. - - The method collects vault keys and cached keys first, then appends any license key whose - key ID is not already present. It matches key IDs with dashes stripped and case ignored, so - an existing content key wins over a license key for the same ID. If the CDM session already - holds final keys and has no cached keys left to combine, the call is a no-op. - - Args: - session_id: Session identifier - license_message: License response from license server - - Raises: - ValueError: If session ID is invalid or no challenge available - requests.RequestException: If API request fails - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - - # If cached_keys exist (Widevine or PlayReady), we need to combine them with license keys - if session["keys"] and "cached_keys" not in session: - return - - if not session.get("challenge") or not session.get("remote_session_id"): - raise ValueError("No challenge available - call get_license_challenge first") - - if isinstance(license_message, str): - if self.is_playready and license_message.lstrip().startswith("<"): - license_message = license_message.encode("utf-8") - else: - license_text = license_message - try: - license_message = base64.b64decode(license_text) - except ValueError: - license_message = license_text.encode("utf-8") - - pssh = session["pssh"] - init_data = self.get_init_data_from_pssh(pssh, session.get("pssh_b64")) - license_request_b64 = base64.b64encode(session["challenge"]).decode("utf-8") - license_response_b64 = base64.b64encode(license_message).decode("utf-8") - - base_params = { - "scheme": self.device_name, - "session_id": session["remote_session_id"], - "init_data": init_data, - "license_request": license_request_b64, - "license_response": license_response_b64, - } - - request_params = self.build_request_params("decrypt_response", base_params, session) - - self.apply_authentication(self._http_session) - - endpoint_config = self.endpoints["decrypt_response"] - url = f"{self.host}{endpoint_config['path']}" - timeout = endpoint_config["timeout"] - - response = self._http_session.post(url, json=request_params, timeout=timeout) - - if response.status_code != 200: - raise requests.RequestException(f"License decrypt failed: {response.status_code} {response.text}") - - response_data = response.json() + def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]: + request_params = self.build_request_params("decrypt_response", body, session) + response_data = self._call("decrypt_response", request_params, "License decrypt failed") parsed_response = self.parse_response_data("decrypt_response", response_data) if not parsed_response.get("_is_success", False): error_msg = parsed_response.get("_error_message", "Unknown error") raise requests.RequestException(f"License decrypt error: {error_msg}") - license_keys = self.parse_keys_from_response("decrypt_response", parsed_response) - - all_keys = [] - - if "vault_keys" in session: - all_keys.extend(session["vault_keys"]) - - if session.get("cached_keys"): - all_keys.extend(session["cached_keys"]) - - for license_key in license_keys: - license_kid = license_key["kid"].replace("-", "").lower() - already_exists = False - - for existing_key in all_keys: - existing_kid = existing_key["kid"].replace("-", "").lower() - if existing_kid == license_kid: - already_exists = True - break - - if not already_exists: - all_keys.append(license_key) - - session["keys"] = all_keys - session.pop("cached_keys", None) - session.pop("vault_keys", None) - - if self.use_vaults and self.vaults is not None and session["keys"]: - key_dict: dict[UUID | str, str] = {} - for key in session["keys"]: - if key["type"] == "CONTENT": - try: - clean_kid = key["kid"].replace("-", "") - if len(clean_kid) == 32: - kid_uuid = UUID(hex=clean_kid) - else: - kid_uuid = UUID(hex=clean_kid.ljust(32, "0")) - key_dict[kid_uuid] = key["key"] - except (ValueError, TypeError): - continue - if key_dict: - self.vaults.add_keys(key_dict) - - def get_keys(self, session_id: bytes, type_: Optional[str] = None) -> List[Key]: - """ - Get keys from the CDM session. - - Args: - session_id: Session identifier - type_: Optional type filter (CONTENT, SIGNING, and the other types) - - Returns: - List of `Key` objects - - Raises: - InvalidSession: If session ID is invalid - """ - if session_id not in self._sessions: - raise CustomRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - key_dicts = self._sessions[session_id]["keys"] - keys = [] - for k in key_dicts: - kid_val = k["kid"] - if isinstance(kid_val, str): - clean_kid = kid_val.replace("-", "") - kid_obj = UUID(hex=clean_kid) if len(clean_kid) == 32 else UUID(hex=clean_kid.ljust(32, "0")) - else: - kid_obj = kid_val - - key_bytes = bytes.fromhex(k["key"].replace(":", "")) if isinstance(k["key"], str) else k["key"] - - keys.append( - Key( - type_=k.get("type", "CONTENT"), - kid=kid_obj, - key=key_bytes, - permissions=k.get("permissions", []), - ) - ) - - if type_: - keys = [key for key in keys if key.type == type_] - - return keys + return self.parse_keys_from_response("decrypt_response", parsed_response) -__all__ = ["CustomRemoteCDM"] +__all__ = ["CustomRemoteCDM", "CustomRemoteCDMExceptions"] diff --git a/unshackle/core/cdm/decrypt_labs_remote_cdm.py b/unshackle/core/cdm/decrypt_labs_remote_cdm.py index b237f496..01513022 100644 --- a/unshackle/core/cdm/decrypt_labs_remote_cdm.py +++ b/unshackle/core/cdm/decrypt_labs_remote_cdm.py @@ -1,104 +1,22 @@ from __future__ import annotations import base64 -import secrets -from typing import Any, Dict, List, Optional, Union -from uuid import UUID +from typing import Any, Dict, List, Optional import requests -from pywidevine.cdm import Cdm as WidevineCdm -from pywidevine.device import DeviceTypes -from requests import Session from unshackle.core import __version__ -from unshackle.core.cdm.loader import system_of -from unshackle.core.vault import is_null_key +from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions from unshackle.core.vaults import Vaults - -class MockCertificateChain: - """Mock certificate chain for PlayReady compatibility.""" - - def __init__(self, name: str) -> None: - self._name = name - - def get_name(self) -> str: - return self._name +DecryptLabsRemoteCDMExceptions = HttpCdmExceptions -class Key: - """`Key` object compatible with pywidevine.""" +class DecryptLabsRemoteCDM(HttpCdm): + """The ``HttpCdm`` adapter for the Decrypt Labs KeyXtractor API; L1 and L2 devices always ask for cached keys first.""" - def __init__(self, kid: str, key: str, type_: str = "CONTENT") -> None: - if isinstance(kid, str): - clean_kid = kid.replace("-", "") - if len(clean_kid) == 32: - self.kid = UUID(hex=clean_kid) - else: - self.kid = UUID(hex=clean_kid.ljust(32, "0")) - else: - self.kid = kid - - if isinstance(key, str): - self.key = bytes.fromhex(key) - else: - self.key = key - - self.type = type_ - - -class DecryptLabsRemoteCDMExceptions: - """Exception classes for compatibility with pywidevine CDM.""" - - class InvalidSession(Exception): - """Raised when session ID is invalid.""" - - class TooManySessions(Exception): - """Raised when the CDM sessions reach the limit.""" - - class InvalidInitData(Exception): - """Raised when PSSH/init data is invalid.""" - - class InvalidLicenseType(Exception): - """Raised when license type is invalid.""" - - class InvalidLicenseMessage(Exception): - """Raised when license message is invalid.""" - - class InvalidContext(Exception): - """Raised when the CDM session has no context data.""" - - class SignatureMismatch(Exception): - """Raised when signature verification fails.""" - - -class DecryptLabsRemoteCDM: - """ - Decrypt Labs Remote CDM implementation with intelligent caching system. - - This class provides a drop-in replacement for pywidevine's local CDM using - Decrypt Labs' KeyXtractor API service, enhanced with smart caching logic - that minimizes unnecessary license requests. - - Main Features: - - Compatible with both Widevine and PlayReady DRM schemes - - Intelligent caching that compares required vs. available keys - - Optimized caching for L1/L2 devices (uses API auto-optimization) - - Automatic content key combination for mixed cache/license scenarios - - Fallback to license requests when keys are missing - - Intelligent Caching System: - 1. DRM classes (PlayReady/Widevine) give the required KIDs through set_required_kids() - 2. get_license_challenge() first checks for cached keys - 3. For L1/L2 devices, always attempts cached keys first (API optimized) - 4. If cached keys satisfy requirements, returns empty challenge (no license needed) - 5. If keys are missing, makes targeted license request for remaining keys - 6. parse_license() combines cached and license keys intelligently - """ - - service_certificate_challenge = b"\x08\x04" - - is_remote_cdm = True + privacy_cert_devices = ("L1", "L2") + label = "DecryptLabs" def __init__( self, @@ -127,19 +45,14 @@ class DecryptLabsRemoteCDM: """ _ = kwargs - self.secret = secret - self.host = host.rstrip("/") - self.device_name = device_name - self.service_name = service_name or "" - self.vaults = vaults - self.uch = self.host != "https://keyxtractor.decryptlabs.com" - - self._device_type_str = device_type - if device_type: - self.device_type = self.get_device_type_enum(device_type) - - self._is_playready = system_of(device_type, device_name) == "playready" - + super().__init__( + host, + device_name, + device_type, + service_name, + vaults, + {"decrypt-labs-api-key": secret, "User-Agent": f"unshackle-decrypt-labs-cdm/{__version__}"}, + ) if self._is_playready: self.system_id = system_id or 0 self.security_level = security_level or (2000 if device_name == "SL2" else 3000) @@ -147,319 +60,28 @@ class DecryptLabsRemoteCDM: self.system_id = system_id or 26830 self.security_level = security_level or 3 - self._sessions: Dict[bytes, Dict[str, Any]] = {} - self._pssh_b64: Optional[str] = None - self._required_kids: Optional[List[str]] = None - self._http_session = Session() - self._http_session.headers.update( - { - "decrypt-labs-api-key": self.secret, - "Content-Type": "application/json", - "User-Agent": f"unshackle-decrypt-labs-cdm/{__version__}", - } - ) - - def get_device_type_enum(self, device_type: str) -> DeviceTypes: - """Convert device type string to enum for compatibility.""" - device_type_upper = device_type.upper() - if device_type_upper == "ANDROID": - return DeviceTypes.ANDROID - elif device_type_upper == "CHROME": - return DeviceTypes.CHROME - else: - return DeviceTypes.CHROME - - @property - def is_playready(self) -> bool: - """Return True if this CDM is in PlayReady mode.""" - return self._is_playready - - @property - def certificate_chain(self) -> MockCertificateChain: - """Mock certificate chain for PlayReady compatibility.""" - return MockCertificateChain(f"{self.device_name}_Remote") - - def set_pssh_b64(self, pssh_b64: str, session_id: Optional[bytes] = None) -> None: - """Store base64-encoded PSSH data for PlayReady compatibility.""" - if session_id is not None and session_id in self._sessions: - self._sessions[session_id]["pssh_b64"] = pssh_b64 - self._pssh_b64 = pssh_b64 - - def set_required_kids(self, kids: List[Union[str, UUID]], session_id: Optional[bytes] = None) -> None: - """ - Set the required Key IDs for intelligent caching decisions. - - This method enables the CDM to make smart decisions about when to request - additional keys through license challenges. When cached keys are available, - the CDM will compare them against the required KIDs to determine if a - license request is still needed for missing keys. - - Args: - kids: List of required Key IDs as UUIDs or hex strings - - Note: - Call this method from the DRM classes (PlayReady/Widevine) before a - license challenge request, to enable optimal caching behaviour. - """ - required = [str(kid).replace("-", "").lower() for kid in kids] - if session_id is not None and session_id in self._sessions: - self._sessions[session_id]["required_kids"] = required - self._required_kids = required - - def generate_session_id(self) -> bytes: - """Make a unique session ID.""" - return secrets.token_bytes(16) - - def get_init_data_from_pssh(self, pssh: Any, pssh_b64: Optional[str] = None) -> str: - """Extract init data from various PSSH formats.""" - effective_pssh_b64 = pssh_b64 or self._pssh_b64 - if self.is_playready and effective_pssh_b64: - return effective_pssh_b64 - - if hasattr(pssh, "dumps"): - dumps_result = pssh.dumps() - - if isinstance(dumps_result, str): - try: - base64.b64decode(dumps_result) - return dumps_result - except ValueError: - return base64.b64encode(dumps_result.encode("utf-8")).decode("utf-8") - else: - return base64.b64encode(dumps_result).decode("utf-8") - elif hasattr(pssh, "raw"): - raw_data = pssh.raw - if isinstance(raw_data, str): - raw_data = raw_data.encode("utf-8") - return base64.b64encode(raw_data).decode("utf-8") - elif hasattr(pssh, "__class__") and "WrmHeader" in pssh.__class__.__name__: - if self.is_playready: - raise ValueError("PlayReady WRM header received but no PSSH B64 was set via set_pssh_b64()") - - if hasattr(pssh, "raw_bytes"): - return base64.b64encode(pssh.raw_bytes).decode("utf-8") - elif hasattr(pssh, "bytes"): - return base64.b64encode(pssh.bytes).decode("utf-8") - else: - raise ValueError(f"Cannot extract PSSH data from WRM header type: {type(pssh)}") - else: - raise ValueError(f"Unsupported PSSH type: {type(pssh)}") - - def open(self) -> bytes: - """ - Open a new CDM session. - - Returns: - Session identifier as bytes - """ - session_id = self.generate_session_id() - self._sessions[session_id] = { - "service_certificate": None, - "keys": [], - "pssh": None, - "challenge": None, - "decrypt_labs_session_id": None, - "tried_cache": False, - "cached_keys": None, - "pssh_b64": None, - } - return session_id - - def close(self, session_id: bytes) -> None: - """ - Close a CDM session and do comprehensive cleanup. - - Args: - session_id: Session identifier - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - session.clear() - del self._sessions[session_id] - - def get_service_certificate(self, session_id: bytes) -> Optional[bytes]: - """ - Get the service certificate for a CDM session. - - Args: - session_id: Session identifier - - Returns: - Service certificate if set, None otherwise - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - return self._sessions[session_id]["service_certificate"] - - def set_service_certificate(self, session_id: bytes, certificate: Optional[Union[bytes, str]]) -> str: - """ - Set the service certificate for a CDM session. - - Args: - session_id: Session identifier - certificate: Service certificate (bytes or base64 string) - - Returns: - Certificate status message - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - if certificate is None: - if not self._is_playready and self.device_name in ("L1", "L2"): - certificate = WidevineCdm.common_privacy_cert - self._sessions[session_id]["service_certificate"] = base64.b64decode(certificate) - return f"Using default Widevine common privacy certificate for {self.device_name}" - else: - self._sessions[session_id]["service_certificate"] = None - return "No certificate set (not required for this device type)" - - if isinstance(certificate, str): - certificate = base64.b64decode(certificate) - - self._sessions[session_id]["service_certificate"] = certificate - return "Successfully set Service Certificate" - - def has_cached_keys(self, session_id: bytes) -> bool: - """ - Return True if cached keys are available for the CDM session. - - Args: - session_id: Session identifier - - Returns: - True if cached keys are available - - Raises: - ValueError: If session ID is invalid - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - session_keys = session.get("keys", []) - return len(session_keys) > 0 - - def get_license_challenge( - self, session_id: bytes, pssh_or_wrm: Any, license_type: str = "STREAMING", privacy_mode: bool = True + def _request_challenge( + self, + session: Dict[str, Any], + body: Dict[str, Any], + license_type: str, + privacy_mode: bool, ) -> bytes: + """Ask for cached keys first, and for a licence challenge when they miss a required KID. + + An L1 or L2 device always asks for cached keys, as the API optimises those; another device asks + only on the first try of the CDM session. """ - Make a license challenge with the Decrypt Labs API and intelligent caching. - - This method implements smart caching logic that: - 1. First checks local vaults for required keys - 2. Attempts to retrieve cached keys from the API - 3. If required KIDs are set, compares available keys (vault + cached) against requirements - 4. Only makes a license request if keys are missing - 5. Returns empty challenge if all required keys are available - - The intelligent caching works as follows: - - Local vaults: Always checked first if available - - For L1/L2 devices: Always prioritizes cached keys (API automatically optimizes) - - For other devices: Uses cache retry logic based on CDM session state - - With required KIDs set: Only requests license for missing keys - - Without required KIDs: Returns any available cached keys - - For PlayReady: Combines vault, cached, and license keys - - Args: - session_id: Session identifier - pssh_or_wrm: PSSH object or WRM header (for PlayReady compatibility) - license_type: Type of license (STREAMING, OFFLINE, AUTOMATIC) - for compatibility only - privacy_mode: Whether to use privacy mode - for compatibility only - - Returns: - License challenge as bytes, or empty bytes if available keys satisfy requirements - - Raises: - InvalidSession: If session ID is invalid - requests.RequestException: If API request fails - - Note: - Call set_required_kids() before this method for optimal caching behaviour. - L1/L2 devices automatically use cached keys when available per API design. - Local vault keys are always checked first when vaults are available. - """ - _ = license_type, privacy_mode - - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - - session["pssh"] = pssh_or_wrm - init_data = self.get_init_data_from_pssh(pssh_or_wrm, session.get("pssh_b64")) already_tried_cache = session.get("tried_cache", False) - - required_kids_list = session.get("required_kids") or self._required_kids - - if self.vaults and required_kids_list: - vault_keys = [] - for kid_str in required_kids_list: - try: - clean_kid = kid_str.replace("-", "") - if len(clean_kid) == 32: - kid_uuid = UUID(hex=clean_kid) - else: - kid_uuid = UUID(hex=clean_kid.ljust(32, "0")) - key, _ = self.vaults.get_key(kid_uuid) - if not is_null_key(key): - vault_keys.append({"kid": kid_str, "key": key, "type": "CONTENT"}) - except (ValueError, TypeError): - continue - - if vault_keys: - vault_kids = set(k["kid"] for k in vault_keys) - required_kids = set(required_kids_list) - - if required_kids.issubset(vault_kids): - session["keys"] = vault_keys - return b"" - else: - session["vault_keys"] = vault_keys - - if self.device_name in ["L1", "L2"]: - get_cached_keys = True - else: - get_cached_keys = not already_tried_cache - request_data = { - "scheme": self.device_name, - "init_data": init_data, - "get_cached_keys_if_exists": get_cached_keys, + **body, + "get_cached_keys_if_exists": self.device_name in ("L1", "L2") or not already_tried_cache, } - if self.service_name: - request_data["service"] = self.service_name - - if session["service_certificate"]: - request_data["service_certificate"] = base64.b64encode(session["service_certificate"]).decode("utf-8") - - response = self._http_session.post(f"{self.host}/get-request", json=request_data, timeout=30) - - if response.status_code != 200: - raise requests.RequestException(f"API request failed: {response.status_code} {response.text}") - - data = response.json() + data = self._post("/get-request", request_data, "API request failed") if data.get("message") != "success": - error_msg = data.get("message", "Unknown error") - if "details" in data: - error_msg += f" - Details: {data['details']}" - if "Error" in data: - error_msg += f" - Error: {data['Error']}" - + error_msg = self._api_error(data.get("message", "Unknown error"), data) if "service_certificate is required" in str(data) and not session["service_certificate"]: error_msg += " (No service certificate was provided to the CDM session)" @@ -468,247 +90,48 @@ class DecryptLabsRemoteCDM: message_type = data.get("message_type") if message_type == "cached-keys" or "cached_keys" in data: - """ - Handle cached keys response from API. - - When the API returns cached keys, we need to determine if they satisfy - our requirements or if we need to make an additional license request - for missing keys. - """ - cached_keys = data.get("cached_keys", []) - parsed_keys = self.parse_cached_keys(cached_keys) - - all_available_keys = list(parsed_keys) - if "vault_keys" in session: - all_available_keys.extend(session["vault_keys"]) - session["tried_cache"] = True - - if required_kids_list: - available_kids: set[str] = set() - for cached_key in all_available_keys: - if isinstance(cached_key, dict) and "kid" in cached_key: - available_kids.add(cached_key["kid"].replace("-", "").lower()) - - required_kids = set(required_kids_list) - missing_kids = required_kids - available_kids - - if missing_kids: - session["cached_keys"] = parsed_keys - - if self.device_name in ["L1", "L2"]: - license_request_data = { - "scheme": self.device_name, - "init_data": init_data, - "get_cached_keys_if_exists": False, - } - if self.service_name: - license_request_data["service"] = self.service_name - if session["service_certificate"]: - license_request_data["service_certificate"] = base64.b64encode( - session["service_certificate"] - ).decode("utf-8") - else: - license_request_data = request_data.copy() - license_request_data["get_cached_keys_if_exists"] = False - - response = self._http_session.post( - f"{self.host}/get-request", json=license_request_data, timeout=30 - ) - if response.status_code == 200: - data = response.json() - if data.get("message") == "success" and "challenge" in data: - challenge = base64.b64decode(data["challenge"]) - session["challenge"] = challenge - session["decrypt_labs_session_id"] = data["session_id"] - return challenge - - session["keys"] = all_available_keys - return b"" - else: - session["keys"] = all_available_keys - return b"" - else: - session["keys"] = all_available_keys + cached_keys = self.parse_cached_keys(data.get("cached_keys", [])) + if self._take_cached_keys(session, cached_keys): return b"" - if message_type == "license-request" or "challenge" in data: - challenge = base64.b64decode(data["challenge"]) - session["challenge"] = challenge - session["decrypt_labs_session_id"] = data["session_id"] - return challenge + response = self._http_session.post( + f"{self.host}/get-request", json={**request_data, "get_cached_keys_if_exists": False}, timeout=30 + ) + if response.status_code == 200: + data = response.json() + if data.get("message") == "success" and "challenge" in data: + return self._keep_challenge(session, base64.b64decode(data["challenge"]), data["session_id"]) - error_msg = f"Unexpected API response format: message_type={message_type}, available_fields={list(data.keys())}" - if data.get("message"): - error_msg = f"API response: {data['message']} - {error_msg}" - if "details" in data: - error_msg += f" - Details: {data['details']}" - if "Error" in data: - error_msg += f" - Error: {data['Error']}" - - if already_tried_cache and data.get("message") == "success": + session["keys"] = cached_keys + session.get("vault_keys", []) return b"" - raise requests.RequestException(error_msg) + if message_type == "license-request" or "challenge" in data: + return self._keep_challenge(session, base64.b64decode(data["challenge"]), data["session_id"]) - def parse_license(self, session_id: bytes, license_message: Union[bytes, str]) -> None: - """ - Parse license response with the Decrypt Labs API and intelligent content key combination. + if already_tried_cache: + return b"" - For PlayReady titles with partial cached keys, this method intelligently - combines the cached keys with newly obtained license keys, skipping a - license key whose KID is already present. + unexpected = f"Unexpected API response format: message_type={message_type}, available_fields={list(data)}" + raise requests.RequestException(self._api_error(f"API response: {data['message']} - {unexpected}", data)) - The content key combination process: - 1. Extracts keys from the license response - 2. If cached keys exist (PlayReady), combines them with license keys - 3. Removes duplicate keys by comparing normalized KIDs - 4. Updates the CDM session with the complete content key set - - Args: - session_id: Session identifier - license_message: License response from license server - - Raises: - ValueError: If session ID is invalid or no challenge available - requests.RequestException: If API request fails - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - session = self._sessions[session_id] - - # Skip parsing if we already have final keys (no cached keys to combine) - # If cached_keys exist (Widevine or PlayReady), we need to combine them with license keys - if session["keys"] and "cached_keys" not in session: - return - - if not session.get("challenge") or not session.get("decrypt_labs_session_id"): - raise ValueError("No challenge available - call get_license_challenge first") - - if isinstance(license_message, str): - if self.is_playready and license_message.lstrip().startswith("<"): - license_message = license_message.encode("utf-8") - else: - license_text = license_message - try: - license_message = base64.b64decode(license_text) - except ValueError: - license_message = license_text.encode("utf-8") - - pssh = session["pssh"] - init_data = self.get_init_data_from_pssh(pssh, session.get("pssh_b64")) - - license_request_b64 = base64.b64encode(session["challenge"]).decode("utf-8") - license_response_b64 = base64.b64encode(license_message).decode("utf-8") - - request_data = { - "scheme": self.device_name, - "session_id": session["decrypt_labs_session_id"], - "init_data": init_data, - "license_request": license_request_b64, - "license_response": license_response_b64, - } - - response = self._http_session.post(f"{self.host}/decrypt-response", json=request_data, timeout=30) - - if response.status_code != 200: - raise requests.RequestException(f"License decrypt failed: {response.status_code} {response.text}") - - data = response.json() + def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]: + data = self._post("/decrypt-response", body, "License decrypt failed") if data.get("message") != "success": - error_msg = data.get("message", "Unknown error") - if "Error" in data: - error_msg += f" - Error: {data['Error']}" - if "details" in data: - error_msg += f" - Details: {data['details']}" + error_msg = self._api_error(data.get("message", "Unknown error"), data) raise requests.RequestException(f"License decrypt error: {error_msg}") - license_keys = self.parse_keys_response(data) + return self.parse_keys_response(data) - all_keys = [] - - if "vault_keys" in session: - all_keys.extend(session["vault_keys"]) - - if "cached_keys" in session: - cached_keys = session.get("cached_keys", []) - if cached_keys: - for cached_key in cached_keys: - all_keys.append(cached_key) - - for license_key in license_keys: - already_exists = False - license_kid = None - if isinstance(license_key, dict) and "kid" in license_key: - license_kid = license_key["kid"].replace("-", "").lower() - elif hasattr(license_key, "kid"): - license_kid = str(license_key.kid).replace("-", "").lower() - elif hasattr(license_key, "key_id"): - license_kid = str(license_key.key_id).replace("-", "").lower() - - if license_kid: - for existing_key in all_keys: - existing_kid = None - if isinstance(existing_key, dict) and "kid" in existing_key: - existing_kid = existing_key["kid"].replace("-", "").lower() - elif hasattr(existing_key, "kid"): - existing_kid = str(existing_key.kid).replace("-", "").lower() - elif hasattr(existing_key, "key_id"): - existing_kid = str(existing_key.key_id).replace("-", "").lower() - - if existing_kid == license_kid: - already_exists = True - break - - if not already_exists: - all_keys.append(license_key) - - session["keys"] = all_keys - session.pop("cached_keys", None) - session.pop("vault_keys", None) - - if self.vaults and session["keys"]: - key_dict: dict[UUID | str, str] = {} - for key in session["keys"]: - if key["type"] == "CONTENT": - try: - clean_kid = key["kid"].replace("-", "") - if len(clean_kid) == 32: - kid_uuid = UUID(hex=clean_kid) - else: - kid_uuid = UUID(hex=clean_kid.ljust(32, "0")) - key_dict[kid_uuid] = key["key"] - except (ValueError, TypeError): - continue - if key_dict: - self.vaults.add_keys(key_dict) - - def get_keys(self, session_id: bytes, type_: Optional[str] = None) -> List[Key]: - """ - Get keys from the CDM session. - - Args: - session_id: Session identifier - type_: Optional type filter (CONTENT, SIGNING, and the other types) - - Returns: - List of `Key` objects - - Raises: - InvalidSession: If session ID is invalid - """ - if session_id not in self._sessions: - raise DecryptLabsRemoteCDMExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") - - key_dicts = self._sessions[session_id]["keys"] - keys = [Key(kid=k["kid"], key=k["key"], type_=k["type"]) for k in key_dicts] - - if type_: - keys = [key for key in keys if key.type == type_] - - return keys + @staticmethod + def _api_error(message: str, data: Dict[str, Any]) -> str: + """The message with the details and the error the API added to its answer.""" + if "details" in data: + message += f" - Details: {data['details']}" + if "Error" in data: + message += f" - Error: {data['Error']}" + return message def parse_cached_keys(self, cached_keys_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Parse cached keys from API response. @@ -754,4 +177,4 @@ class DecryptLabsRemoteCDM: return keys -__all__ = ["DecryptLabsRemoteCDM"] +__all__ = ["DecryptLabsRemoteCDM", "DecryptLabsRemoteCDMExceptions"] diff --git a/unshackle/core/cdm/http_cdm.py b/unshackle/core/cdm/http_cdm.py new file mode 100644 index 00000000..ad64b06e --- /dev/null +++ b/unshackle/core/cdm/http_cdm.py @@ -0,0 +1,381 @@ +"""The shared part of the CDMs that drive a device behind an HTTP API. + +``HttpCdm`` keeps the CDM sessions, the PSSH and required KIDs of each CDM session, the content keys from +the vaults and from the API cache, and the merge of those content keys with the licence keys. An adapter sends +its own API's requests in ``_request_challenge`` and ``_request_keys``. +""" + +from __future__ import annotations + +import base64 +import secrets +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union +from uuid import UUID + +from pyplayready.system.wrmheader import WRMHeader +from pywidevine.cdm import Cdm as WidevineCdm +from pywidevine.device import DeviceTypes +from pywidevine.key import Key +from requests import RequestException, Session + +from unshackle.core.cdm.loader import system_of +from unshackle.core.vault import is_null_key + +if TYPE_CHECKING: + from unshackle.core.vaults import Vaults + + +def kid_uuid(kid: Union[str, UUID]) -> UUID: + """A KID as a UUID; zeros on the right fill a short hex KID.""" + if isinstance(kid, UUID): + return kid + clean = kid.replace("-", "") + return UUID(hex=clean.ljust(32, "0")) + + +def kid_hex(kid: Union[str, UUID]) -> str: + """A KID as lower-case hex without dashes, the form the required KIDs use.""" + return str(kid).replace("-", "").lower() + + +def b64_or_utf8(text: str) -> bytes: + """Decode base64 text; text that is not base64 goes out as its UTF-8 bytes.""" + try: + return base64.b64decode(text) + except ValueError: + return text.encode("utf-8") + + +class MockCertificateChain: + """Mock certificate chain for PlayReady compatibility.""" + + def __init__(self, name: str) -> None: + self._name = name + + def get_name(self) -> str: + return self._name + + +class HttpCdmExceptions: + """Exception classes for compatibility with pywidevine CDM.""" + + class InvalidSession(Exception): + """Raised when session ID is invalid.""" + + class TooManySessions(Exception): + """Raised when the CDM sessions reach the limit.""" + + class InvalidInitData(Exception): + """Raised when PSSH/init data is invalid.""" + + class InvalidLicenseType(Exception): + """Raised when license type is invalid.""" + + class InvalidLicenseMessage(Exception): + """Raised when license message is invalid.""" + + class InvalidContext(Exception): + """Raised when the CDM session has no context data.""" + + class SignatureMismatch(Exception): + """Raised when signature verification fails.""" + + +class HttpCdm(ABC): + """A Widevine or PlayReady CDM whose device sits behind an HTTP API. + + The DRM classes give each CDM session its PSSH (``set_pssh_b64``) and the KIDs they need + (``set_required_kids``). A challenge is empty when the vaults or the API cache already hold + every required key, and ``has_cached_keys`` then says so. + """ + + service_certificate_challenge = b"\x08\x04" + is_remote_cdm = True + chain_suffix = "Remote" + privacy_cert_devices: tuple[str, ...] = ("L1",) + label: Optional[str] = None + + def __init__( + self, + host: str, + device_name: str, + device_type: Optional[str], + service_name: Optional[str], + vaults: Optional[Vaults], + headers: Dict[str, str], + ) -> None: + self.host = host.rstrip("/") + self.device_name = device_name + self.service_name = service_name or "" + self.vaults = vaults + self.use_vaults = True + self._is_playready = system_of(device_type, device_name) == "playready" + if device_type: + self.device_type = self.get_device_type_enum(device_type) + self._sessions: Dict[bytes, Dict[str, Any]] = {} + self._http_session = Session() + self._http_session.headers.update({"Content-Type": "application/json", **headers}) + + def get_device_type_enum(self, device_type: str) -> DeviceTypes: + """Convert device type string to enum for compatibility.""" + return DeviceTypes.ANDROID if device_type.upper() == "ANDROID" else DeviceTypes.CHROME + + @property + def is_playready(self) -> bool: + """Return True if this CDM is in PlayReady mode.""" + return self._is_playready + + @property + def certificate_chain(self) -> MockCertificateChain: + """Mock certificate chain for PlayReady compatibility.""" + return MockCertificateChain(f"{self.device_name}_{self.chain_suffix}") + + def set_pssh_b64(self, pssh_b64: str, session_id: bytes) -> None: + """Store the base64 PSSH that a PlayReady CDM session sends as its init data.""" + self._session(session_id)["pssh_b64"] = pssh_b64 + + def set_required_kids(self, kids: Sequence[Union[str, UUID]], session_id: bytes) -> None: + """Store the KIDs a CDM session needs, so that content keys from the vaults or the API cache can skip the licence.""" + self._session(session_id)["required_kids"] = [kid_hex(kid) for kid in kids] + + def generate_session_id(self) -> bytes: + """Make a unique session ID.""" + return secrets.token_bytes(16) + + def get_init_data_from_pssh(self, pssh: Any, pssh_b64: Optional[str] = None) -> str: + """Extract init data from various PSSH formats. + + PlayReady sends ``pssh_b64`` when it is set. Without it, a WRM header (object or XML text) goes + out as a one-record PlayReady Object, as the remote APIs take a PRO, not a bare header. + """ + if self.is_playready: + if pssh_b64: + return pssh_b64 + if isinstance(pssh, str) and pssh.lstrip().startswith("<"): + pssh = WRMHeader(pssh) + if isinstance(pssh, WRMHeader): + from unshackle.core.drm.playready import PlayReady + + return PlayReady.pro_b64_for(pssh) + if isinstance(pssh, str): + return pssh + + if hasattr(pssh, "dumps"): + dumps_result = pssh.dumps() + + if isinstance(dumps_result, str): + try: + base64.b64decode(dumps_result) + return dumps_result + except ValueError: + return base64.b64encode(dumps_result.encode("utf-8")).decode("utf-8") + else: + return base64.b64encode(dumps_result).decode("utf-8") + elif hasattr(pssh, "raw"): + raw_data = pssh.raw + if isinstance(raw_data, str): + raw_data = raw_data.encode("utf-8") + return base64.b64encode(raw_data).decode("utf-8") + else: + raise ValueError(f"Unsupported PSSH type: {type(pssh)}") + + def _session(self, session_id: bytes) -> Dict[str, Any]: + if session_id not in self._sessions: + raise HttpCdmExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}") + return self._sessions[session_id] + + def open(self) -> bytes: + """Open a new CDM session and return its ID.""" + session_id = self.generate_session_id() + self._sessions[session_id] = { + "service_certificate": None, + "keys": [], + "init_data": None, + "pssh_b64": None, + "challenge": None, + "remote_session_id": None, + "cached_keys": None, + } + return session_id + + def close(self, session_id: bytes) -> None: + """Close a CDM session; raises InvalidSession for an unknown ID.""" + self._session(session_id) + del self._sessions[session_id] + + def get_service_certificate(self, session_id: bytes) -> Optional[bytes]: + """The service certificate of a CDM session, or None.""" + return self._session(session_id)["service_certificate"] + + def set_service_certificate(self, session_id: bytes, certificate: Optional[Union[bytes, str]]) -> str: + """Set the service certificate (bytes or base64) of a CDM session and return a status message. + + With no certificate, a Widevine device in ``privacy_cert_devices`` gets the common privacy certificate. + """ + session = self._session(session_id) + if certificate is None: + if not self._is_playready and self.device_name in self.privacy_cert_devices: + session["service_certificate"] = base64.b64decode(WidevineCdm.common_privacy_cert) + return f"Using default Widevine common privacy certificate for {self.device_name}" + session["service_certificate"] = None + return "No certificate set (not required for this device type)" + + if isinstance(certificate, str): + certificate = base64.b64decode(certificate) + + session["service_certificate"] = certificate + return "Successfully set Service Certificate" + + def has_cached_keys(self, session_id: bytes) -> bool: + """True when the CDM session holds keys.""" + return bool(self._session(session_id).get("keys")) + + def get_license_challenge( + self, session_id: bytes, pssh_or_wrm: Any, license_type: str = "STREAMING", privacy_mode: bool = True + ) -> bytes: + """Make a licence challenge, or return empty bytes when the vaults or the API cache hold every required key. + + Raises InvalidSession for an unknown ID, and ``requests.RequestException`` when the API fails. + """ + session = self._session(session_id) + session["init_data"] = self.get_init_data_from_pssh(pssh_or_wrm, session.get("pssh_b64")) + required = session.get("required_kids") + if self._keys_from_vaults(session, required): + return b"" + body: Dict[str, Any] = {"scheme": self.device_name, "init_data": session["init_data"]} + if self.service_name: + body["service"] = self.service_name + if session["service_certificate"]: + body["service_certificate"] = base64.b64encode(session["service_certificate"]).decode("utf-8") + return self._request_challenge(session, body, license_type, privacy_mode) + + def _keys_from_vaults(self, session: Dict[str, Any], required: Optional[List[str]]) -> bool: + """Look up the required KIDs in the vaults; True when they hold every one.""" + if not (self.use_vaults and self.vaults and required): + return False + vault_keys = [] + for kid in required: + try: + key, _ = self.vaults.get_key(kid_uuid(kid)) + except (ValueError, TypeError): + continue + if not is_null_key(key): + vault_keys.append({"kid": kid, "key": key, "type": "CONTENT"}) + if not vault_keys: + return False + if set(required) <= {k["kid"] for k in vault_keys}: + session["keys"] = vault_keys + return True + session["vault_keys"] = vault_keys + return False + + def _take_cached_keys(self, session: Dict[str, Any], cached_keys: List[Dict[str, Any]]) -> bool: + """Keep the keys the API cache returned; True when they and the vault keys cover every required KID. + + Otherwise the cached keys wait in the CDM session for ``parse_license`` to merge with the licence keys. + """ + required = session.get("required_kids") + available = [*cached_keys, *session.get("vault_keys", [])] + have = {kid_hex(k["kid"]) for k in available} + if required and set(required) - have: + session["cached_keys"] = cached_keys + return False + session["keys"] = available + return True + + def _keep_challenge(self, session: Dict[str, Any], challenge: bytes, remote_session_id: Any) -> bytes: + session["challenge"] = challenge + session["remote_session_id"] = remote_session_id + return challenge + + def _post(self, path: str, body: Dict[str, Any], failure: str, timeout: float = 30) -> Dict[str, Any]: + """POST ``body`` to ``path`` on the host and return the JSON answer; raises on a status other than 200.""" + response = self._http_session.post(f"{self.host}{path}", json=body, timeout=timeout) + if response.status_code != 200: + raise RequestException(f"{failure}: {response.status_code} {response.text}") + return response.json() + + @abstractmethod + def _request_challenge( + self, + session: Dict[str, Any], + body: Dict[str, Any], + license_type: str, + privacy_mode: bool, + ) -> bytes: + """Ask the API for a challenge or cached keys; the adapter's wire form. + + ``body`` holds the scheme, the init data, and the service and service certificate when set. + """ + + @abstractmethod + def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]: + """Send the licence to the API and return the keys it holds; the adapter's wire form.""" + + def parse_license(self, session_id: bytes, license_message: Union[bytes, str]) -> None: + """Have the API read a licence, then merge its keys with the vault and cached keys of the CDM session. + + A content key from the vaults or the API cache wins over a licence key with the same KID. A CDM session + that already holds its final keys and has no cached keys left to merge makes this a no-op. + """ + session = self._session(session_id) + + if session["keys"] and "cached_keys" not in session: + return + + if not session.get("challenge") or not session.get("remote_session_id"): + raise ValueError("No challenge available - call get_license_challenge first") + + if isinstance(license_message, str): + if self.is_playready and license_message.lstrip().startswith("<"): + license_message = license_message.encode("utf-8") + else: + license_message = b64_or_utf8(license_message) + + license_keys = self._request_keys( + session, + { + "scheme": self.device_name, + "session_id": session["remote_session_id"], + "init_data": session["init_data"], + "license_request": base64.b64encode(session["challenge"]).decode("utf-8"), + "license_response": base64.b64encode(license_message).decode("utf-8"), + }, + ) + + all_keys = [*session.get("vault_keys", []), *(session.get("cached_keys") or [])] + have = {kid_hex(k["kid"]) for k in all_keys} + for key in license_keys: + kid = kid_hex(key["kid"]) + if kid not in have: + have.add(kid) + all_keys.append(key) + + session["keys"] = all_keys + session.pop("cached_keys", None) + session.pop("vault_keys", None) + + if self.use_vaults and self.vaults and all_keys: + key_dict: dict[UUID | str, str] = {} + for key in all_keys: + if key["type"] == "CONTENT": + try: + key_dict[kid_uuid(key["kid"])] = key["key"] + except (ValueError, TypeError): + continue + if key_dict: + self.vaults.add_keys(key_dict) + + def get_keys(self, session_id: bytes, type_: Optional[str] = None) -> List[Key]: + """The keys of a CDM session; only the keys of type ``type_`` when it is set.""" + keys = [ + Key( + k.get("type", "CONTENT"), + kid_uuid(k["kid"]), + bytes.fromhex(k["key"].replace(":", "")) if isinstance(k["key"], str) else k["key"], + k.get("permissions"), + ) + for k in self._session(session_id)["keys"] + ] + return [key for key in keys if key.type == type_] if type_ else keys diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py index 533cbc73..88de6c9d 100644 --- a/unshackle/core/drm/playready.py +++ b/unshackle/core/drm/playready.py @@ -16,6 +16,7 @@ from pyplayready.misc.exceptions import InvalidPssh from pyplayready.system.pssh import PSSH from pyplayready.system.wrmheader import WRMHeader +from unshackle.core.cdm.http_cdm import HttpCdm from unshackle.core.config import config from unshackle.core.constants import AnyTrack from unshackle.core.drm import key_args as drm_key_args @@ -455,17 +456,10 @@ class PlayReady: """Run one challenge/response round for a single header and return the keys it yielded.""" session_id = cdm.open() try: - if hasattr(cdm, "set_pssh_b64") and pssh_b64: - try: + if isinstance(cdm, HttpCdm): + if pssh_b64: cdm.set_pssh_b64(pssh_b64, session_id=session_id) - except TypeError: # CDM predating the per-session signature - cdm.set_pssh_b64(pssh_b64) - - if hasattr(cdm, "set_required_kids"): - try: - cdm.set_required_kids(required_kids, session_id=session_id) - except TypeError: # CDM predating the per-session signature - cdm.set_required_kids(required_kids) + cdm.set_required_kids(required_kids, session_id=session_id) challenge = cdm.get_license_challenge(session_id, header) diff --git a/unshackle/core/drm/widevine.py b/unshackle/core/drm/widevine.py index fb154292..faa4d9d2 100644 --- a/unshackle/core/drm/widevine.py +++ b/unshackle/core/drm/widevine.py @@ -12,6 +12,7 @@ from pymp4.parser import Box from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.pssh import PSSH +from unshackle.core.cdm.http_cdm import HttpCdm from unshackle.core.config import config from unshackle.core.constants import AnyTrack from unshackle.core.drm import key_args as drm_key_args @@ -223,15 +224,12 @@ class Widevine: if cert and hasattr(cdm, "set_service_certificate"): cdm.set_service_certificate(session_id, cert) - if hasattr(cdm, "set_required_kids"): - try: - cdm.set_required_kids(self.kids, session_id=session_id) - except TypeError: # CDM predating the per-session signature - cdm.set_required_kids(self.kids) + if isinstance(cdm, HttpCdm): + cdm.set_required_kids(self.kids, session_id=session_id) challenge = cdm.get_license_challenge(session_id, self.pssh) - if hasattr(cdm, "has_cached_keys") and cdm.has_cached_keys(session_id): + if isinstance(cdm, HttpCdm) and cdm.has_cached_keys(session_id): pass elif not challenge: raise Widevine.Exceptions.EmptyLicense(