diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index a8bf3cfd..908bd012 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -474,7 +474,25 @@ that needs a process on the server also works for a remote client. A media playlist can name only a key system that unshackle does not read, such as an `skd://` key over cbcs media, while the licence server of the platform also issues the same content key over -PlayReady or Widevine. To license such a track through one of those systems: +PlayReady or Widevine. `HLS.download_track` licenses such a track with no service code when all of +these conditions are true: + +- The track has no DRM object. +- Every `EXT-X-KEY` of its media playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a DRM system + unshackle cannot license. +- The configured CDM is a PlayReady or Widevine CDM. +- The init segment (`EXT-X-MAP`) of the track names a key ID in its `tenc` box. When the `tenc` key ID is all + zeros, its `pssh` boxes must name exactly one key ID, and the encrypted segments must have one init + segment and the playlist one key URI. MPEG-TS media has no init segment. +- The init segment does not change without an `EXT-X-DISCONTINUITY`. + +The download reads the key ID from the init segment, builds a DRM object for the DRM system of the +CDM with `drm_stub`, and sends the challenge to the licence callback of the service. Over `--remote` +the server reads the same key ID at the licence step, so it accepts the DRM object of the client. A +licence that gives no content key stops the track before it downloads a segment. + +A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object +on the track: 1. Read the key ID from the init segment of the track. `HLS.get_track_kid_from_init` returns it. 2. Put a DRM object that names the key ID on the track: `drm_stub` from `unshackle.core.drm.cenc` @@ -488,8 +506,9 @@ content key of one package of a title and refuse another. When a track carries a object and every `EXT-X-KEY` of its playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a key system unshackle cannot license, `HLS.drop_unsupported_keys` removes the tags from the parsed playlist. The download then licenses and decrypts the track with the DRM object of the track. This works for -one content key per track: the key changes of the playlist go with the tags. A track with no such -DRM object stops with `None of the key systems are supported` before it downloads a segment. +one content key per track: the key changes of the playlist go with the tags. This limit also +applies to a DRM object that the download builds. Any other track stops with +`None of the key systems are supported` before it downloads a segment. ### How unshackle chooses a CDM and finds keys diff --git a/docs/guide/drm-and-cdm.md b/docs/guide/drm-and-cdm.md index 14f89896..429e1956 100644 --- a/docs/guide/drm-and-cdm.md +++ b/docs/guide/drm-and-cdm.md @@ -77,6 +77,12 @@ To download a Widevine-protected title you need a `.wvd` device. For PlayReady y need a `.prd` device. You can hold both, and unshackle automatically selects the appropriate one for each track. +!!! note "HLS tracks with only a FairPlay key tag" + unshackle has no FairPlay CDM. When each `EXT-X-KEY` of an fMP4 playlist is sample encryption + for a DRM system that unshackle cannot license, such as FairPlay, unshackle reads the key ID from + the init segment and asks for the licence with your PlayReady or Widevine device. This works + only when the licence server of the platform also issues that content key for that DRM system. MPEG-TS SAMPLE-AES stops with an error. + !!! info "Obtaining device files" A `.wvd` or `.prd` encodes the private keys of a real client device. unshackle does **not** ship with one and cannot make the underlying secret material for @@ -568,6 +574,8 @@ unshackle dl --skip-dl --all-drm --export EXAMPLE 81234567 system does not license, so the title fails unless you use `--best-available`. - An HLS playlist that changes its `EXT-X-KEY` entries part-way: only the first set licenses with the second system. + - An HLS playlist with only FairPlay key tags: the DRM system of the configured CDM + licenses it. - A remote session that the server CDM licenses, and `unshackle import`. unshackle shows a warning and ignores the flag. - A remote CDM that stores content keys can answer without a challenge to the service. diff --git a/tests/core/test_cenc.py b/tests/core/test_cenc.py index 54b5c5c0..1f1a30ff 100644 --- a/tests/core/test_cenc.py +++ b/tests/core/test_cenc.py @@ -18,6 +18,7 @@ from tests.core.test_kid_windows import box, encv from unshackle.core import binaries from unshackle.core.drm import PlayReady, Widevine, cenc from unshackle.core.drm.verify import PIFF_TENC +from unshackle.core.manifests import HLS from unshackle.core.tracks import Video from unshackle.core.utils import subprocess as subprocess_utils @@ -76,6 +77,38 @@ def test_init_kid_is_none_without_a_real_kid() -> None: assert cenc.init_kid(init(encv(UUID(int=0)))) is None +def common_box(kid: UUID) -> bytes: + body = {"type": b"pssh", "version": 1, "flags": 0, "system_ID": cenc.COMMON_ID, "key_IDs": [kid], "init_data": b""} + return Box.build(body) + + +def widevine_box(*kids: UUID) -> bytes: + return PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)).dump() + + +@pytest.mark.parametrize( + "boxes, kid", + [ + pytest.param([playready_box(TRACK_KID)], TRACK_KID, id="one-system"), + pytest.param([widevine_box(TRACK_KID), playready_box(TRACK_KID)], TRACK_KID, id="both-systems-agree"), + pytest.param([widevine_box(TRACK_KID, OTHER_KID)], None, id="several-kids"), + pytest.param([widevine_box(OTHER_KID), playready_box(TRACK_KID)], None, id="systems-disagree"), + pytest.param([widevine_box(TRACK_KID), widevine_box(OTHER_KID)], None, id="two-boxes-of-one-system"), + pytest.param([widevine_box(TRACK_KID), common_box(OTHER_KID)], None, id="common-box-disagrees"), + pytest.param([common_box(TRACK_KID)], TRACK_KID, id="common-box"), + pytest.param([PSSH(no_kid_pssh()).dump(), playready_box(TRACK_KID)], TRACK_KID, id="one-box-without-a-kid"), + pytest.param([widevine_box(UUID(int=0))], None, id="placeholder"), + pytest.param([], None, id="no-pssh"), + ], +) +def test_init_pssh_kid_is_the_one_real_kid_the_pssh_boxes_name(boxes: list[bytes], kid: UUID | None) -> None: + assert cenc.init_pssh_kid(init(*boxes, encv(UUID(int=0)))) == kid + + +def test_init_pssh_kid_needs_a_tenc() -> None: + assert cenc.init_pssh_kid(init(widevine_box(TRACK_KID))) is None + + def test_widevine_from_init_data_takes_the_piff_kid_when_the_pssh_names_none() -> None: pssh = PSSH(no_kid_pssh()).dump() drm = Widevine.from_init_data(init(pssh, encv(TRACK_KID, piff=True))) @@ -249,3 +282,15 @@ def test_from_track_reads_the_playlist_pssh_and_the_init_kid() -> None: assert drm.kids == [OTHER_KID, TRACK_KID] with pytest.raises(Widevine.Exceptions.PSSHNotFound): Widevine.from_track(track, track.session) + + +def test_the_hls_probe_reads_the_pssh_kid_only_when_asked() -> None: + manifest = cenc.m3u8.loads('#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:6.0,\nseg0.m4s\n#EXT-X-ENDLIST\n') + content = init(playready_box(TRACK_KID), encv(UUID(int=0))) + session: Any = SimpleNamespace(get=lambda url, headers=None: SimpleNamespace(ok=True, content=content)) + track = playlist_track("") + + track.get_key_id = lambda data: cenc.init_kid(data) # type: ignore[method-assign] + + assert HLS.get_track_kid_from_init(manifest, track, session) is None + assert HLS.get_track_kid_from_init(manifest, track, session, pssh=True) == TRACK_KID diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py index ed0db8b4..af0eab45 100644 --- a/tests/core/test_hls_service_drm_keys.py +++ b/tests/core/test_hls_service_drm_keys.py @@ -1,13 +1,14 @@ -"""A service can license a playlist whose key tags name key systems unshackle cannot license itself. +"""A playlist whose key tags name key systems unshackle cannot license is licensed with another DRM of the track. -Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts its own DRM on the track, and -``HLS.download_track`` then reads the playlist as one with no key tag. +Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts its own DRM on the track, or +``HLS.download_track`` builds one for the CDM, and the download then reads the playlist as one with no key tag. """ from __future__ import annotations from pathlib import Path from typing import Any +from unittest.mock import Mock from uuid import UUID import m3u8 @@ -16,7 +17,7 @@ from pywidevine.pssh import PSSH from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY -from unshackle.core.drm import ClearKey +from unshackle.core.drm import ClearKey, PlayReady from unshackle.core.drm.cenc import drm_stub from unshackle.core.manifests.hls import HLS from unshackle.core.tracks import Video @@ -43,6 +44,43 @@ def playlist(*key_tags: str) -> str: ) +def hls_video(tmp_path: Path, text: str) -> Video: + playlist_file = tmp_path / "media.m3u8" + playlist_file.write_text(text, encoding="utf-8") + track = Video( + url="https://example.test/media.m3u8", + language="en", + descriptor=Track.Descriptor.HLS, + codec=Video.Codec.HEVC, + ) + track.from_file = playlist_file + track.downloader = lambda **kwargs: pytest.fail("a segment was requested") + return track + + +def download(track: Video, cdm: Any, licence: Any = None, licence_only: bool = False) -> None: + ctx = DownloadContext( + save_path=Path(track.from_file).with_name("video.mp4"), + save_dir=Path(track.from_file).with_name("video_segments"), + progress=lambda **_: None, + license_widevine=licence or (lambda drm, track_kid=None: pytest.fail("a licence was requested")), + cdm=cdm, + ) + if licence_only: + DOWNLOAD_LICENCE_ONLY.set() + try: + HLS.download_track(track=track, ctx=ctx) + finally: + DOWNLOAD_LICENCE_ONLY.clear() + + +def init_kid_probe(monkeypatch: Any, kid: UUID | None) -> Mock: + """The KID normally comes from the init segment; these tests are offline.""" + probe = Mock(return_value=kid) + monkeypatch.setattr(HLS, "get_track_kid_from_init", probe) + return probe + + def test_key_tags_no_licence_route_can_use_are_dropped() -> None: manifest = m3u8.loads(playlist(SKD_KEY)) @@ -85,91 +123,187 @@ def test_a_playlist_with_no_key_tag_is_left_alone() -> None: def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path, monkeypatch: Any) -> None: - playlist_file = tmp_path / "media.m3u8" - playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8") - track = Video( - url="https://example.test/media.m3u8", - language="en", - descriptor=Track.Descriptor.HLS, - codec=Video.Codec.HEVC, - ) - track.from_file = playlist_file - drm = drm_stub("playready", [KID.hex]) - track.drm = [drm] - # the KID normally comes from the init segment; this test is offline - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: KID)) + track = hls_video(tmp_path, playlist(SKD_KEY)) + track.drm = [drm_stub("playready", [KID.hex])] + init_kid_probe(monkeypatch, KID) licensed: list[tuple[str, UUID | None]] = [] - ctx = DownloadContext( - save_path=tmp_path / "video.mp4", - save_dir=tmp_path / "video_segments", - progress=lambda **_: None, - license_widevine=lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)), - cdm=None, - ) - DOWNLOAD_LICENCE_ONLY.set() - try: - HLS.download_track(track=track, ctx=ctx) - finally: - DOWNLOAD_LICENCE_ONLY.clear() + download( + track, + None, + lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)), + licence_only=True, + ) assert licensed == [("PlayReady", KID)] -def test_a_track_without_drm_still_refuses_the_key_tag(tmp_path: Path, monkeypatch: Any) -> None: - playlist_file = tmp_path / "media.m3u8" - playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8") - track = Video( - url="https://example.test/media.m3u8", - language="en", - descriptor=Track.Descriptor.HLS, - codec=Video.Codec.HEVC, - ) - track.from_file = playlist_file - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) - ctx = DownloadContext( - save_path=tmp_path / "video.mp4", - save_dir=tmp_path / "video_segments", - progress=lambda **_: None, - license_widevine=lambda drm, track_kid=None: None, - cdm=None, - ) +@pytest.mark.parametrize("method", ["SAMPLE-AES", "SAMPLE-AES-CTR"]) +@pytest.mark.parametrize("system, drm_class", [("playready", "PlayReady"), ("widevine", "Widevine")]) +def test_a_track_with_no_drm_licenses_through_the_cdm( + tmp_path: Path, monkeypatch: Any, caplog: pytest.LogCaptureFixture, system: str, drm_class: str, method: str +) -> None: + track = hls_video(tmp_path, playlist(SKD_KEY.replace("SAMPLE-AES", method))) + probe = init_kid_probe(monkeypatch, KID) + licensed: list[tuple[str, list[UUID], UUID | None]] = [] - DOWNLOAD_LICENCE_ONLY.set() - try: - with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): - HLS.download_track(track=track, ctx=ctx) - finally: - DOWNLOAD_LICENCE_ONLY.clear() + with caplog.at_level("DEBUG", logger="HLS"): + download( + track, + cdm_type_stub(system), + lambda drm, track_kid=None: licensed.append((type(drm).__name__, drm.kids, track_kid)), + licence_only=True, + ) + + assert licensed == [(drm_class, [KID], KID)] + assert [type(drm).__name__ for drm in track.drm] == [drm_class] + assert probe.call_count == 1 + lines = [record.getMessage() for record in caplog.records if KID.hex in record.getMessage()] + assert len(lines) == 1 and track.id in lines[0] and drm_class in lines[0] + + +def two_inits(between: str, lead_key: str = "") -> str: + """A playlist with a lead under ``ad.mp4``, then the segments of ``init.mp4`` with the FairPlay key tag.""" + return playlist(SKD_KEY).replace( + '#EXT-X-MAP:URI="init.mp4",BYTERANGE="994@0"\n', + f'#EXT-X-MAP:URI="ad.mp4"\n{lead_key}#EXTINF:6.0,\nad.m4s\n{between}#EXT-X-MAP:URI="init.mp4"\n', + ) @pytest.mark.parametrize( - "drm", + "text, skip_lead", [ - pytest.param(None, id="no-drm"), - pytest.param(ClearKey(key=bytes(16)), id="aes-128-session-key"), + pytest.param(two_inits("#EXT-X-DISCONTINUITY\n", f"{SKD_KEY}\n"), True, id="filtered-encrypted-lead"), + pytest.param(two_inits("#EXT-X-DISCONTINUITY\n"), False, id="clear-lead"), ], ) -def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path, drm: Any) -> None: - """The refusal comes before a segment is requested: a ClearKey would otherwise write the ciphertext as the output.""" - playlist_file = tmp_path / "media.m3u8" - playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8") - track = Video( - url="https://example.test/media.m3u8", - language="en", - descriptor=Track.Descriptor.HLS, - codec=Video.Codec.HEVC, - ) - track.from_file = playlist_file - track.drm = [drm] if drm else None - track.downloader = lambda **kwargs: pytest.fail("a segment was requested") - ctx = DownloadContext( - save_path=tmp_path / "video.mp4", - save_dir=tmp_path / "video_segments", - progress=lambda **_: None, - license_widevine=lambda drm, track_kid=None: pytest.fail("a licence was requested"), - cdm=cdm_type_stub("playready"), +def test_the_key_id_comes_from_the_init_segment_of_the_encrypted_segments( + tmp_path: Path, monkeypatch: Any, text: str, skip_lead: bool +) -> None: + track = hls_video(tmp_path, text) + if skip_lead: + track.OnSegmentFilter = lambda segment: segment.uri.startswith("ad") + licensed: list[UUID | None] = [] + init_kid_probe(monkeypatch, None).side_effect = lambda master, track, session, init_section=None, pssh=False: { + "init.mp4": KID + }.get(init_section.uri) + + download( + track, + cdm_type_stub("playready"), + lambda drm, track_kid=None: licensed.append(track_kid), + licence_only=True, ) + assert licensed == [KID] + + +def filter_first_segment(track: Video) -> None: + track.OnSegmentFilter = lambda segment: segment.uri == "seg0.m4s" + + +@pytest.mark.parametrize( + "cdm", [pytest.param(cdm_type_stub("playready"), id="bridge"), pytest.param(None, id="refused")] +) +def test_a_key_tag_on_a_skipped_segment_stays_in_force(tmp_path: Path, monkeypatch: Any, cdm: Any) -> None: + """python-m3u8 puts a key tag on the next segment only, and ``--sample`` can skip that segment.""" + track = hls_video(tmp_path, playlist(SKD_KEY)) + filter_first_segment(track) + init_kid_probe(monkeypatch, KID) + licensed: list[UUID | None] = [] + + def run() -> None: + download(track, cdm, lambda drm, track_kid=None: licensed.append(track_kid), licence_only=True) + + if cdm: + run() + assert licensed == [KID] + else: + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + run() + + +TWO_KEYS = playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{SKD_KEY.replace('asset', 'other')}\n") + + +@pytest.mark.parametrize( + "text, skip_first, pssh", + [ + pytest.param(playlist(SKD_KEY), False, True, id="one-init-one-key"), + pytest.param(two_inits("#EXT-X-DISCONTINUITY\n"), False, True, id="clear-lead"), + pytest.param(two_inits("#EXT-X-DISCONTINUITY\n", f"{SKD_KEY}\n"), False, False, id="two-inits"), + pytest.param(TWO_KEYS, False, False, id="two-keys"), + pytest.param(TWO_KEYS, True, False, id="sample-of-the-second-key"), + ], +) +def test_the_pssh_names_the_key_id_only_of_one_init_segment_with_one_key( + tmp_path: Path, monkeypatch: Any, text: str, skip_first: bool, pssh: bool +) -> None: + """With an all-zero tenc, a decrypter gives the one content key to every segment, so a second key is garbage.""" + track = hls_video(tmp_path, text) + if skip_first: + filter_first_segment(track) + probe = init_kid_probe(monkeypatch, KID) + + download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None, licence_only=True) + + assert [call.kwargs["pssh"] for call in probe.call_args_list] == [pssh] + + +@pytest.mark.parametrize( + "text, kid, cdm", + [ + pytest.param(playlist(SKD_KEY), KID, None, id="no-cdm"), + pytest.param(playlist(SKD_KEY), KID, object(), id="cdm-of-neither-system"), + pytest.param( + playlist(SKD_KEY).replace('#EXT-X-MAP:URI="init.mp4",BYTERANGE="994@0"\n', ""), + KID, + cdm_type_stub("playready"), + id="no-init-segment", + ), + pytest.param(playlist(SKD_KEY), None, cdm_type_stub("playready"), id="no-key-id"), + pytest.param(playlist(SKD_KEY), UUID(int=0), cdm_type_stub("playready"), id="all-zero-key-id"), + pytest.param( + playlist(SKD_KEY), + UUID("00010203-0405-0607-0809-0a0b0c0d0e0f"), + cdm_type_stub("playready"), + id="placeholder-key-id", + ), + pytest.param(two_inits("", f"{SKD_KEY}\n"), KID, cdm_type_stub("playready"), id="init-changes-in-place"), + pytest.param( + playlist(SKD_KEY, '#EXT-X-KEY:METHOD=AES-256,URI="skd://keys.example/asset",KEYFORMAT="other"'), + KID, + cdm_type_stub("playready"), + id="not-sample-encryption", + ), + ], +) +def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_download( + tmp_path: Path, monkeypatch: Any, text: str, kid: UUID | None, cdm: Any +) -> None: + track = hls_video(tmp_path, text) + probe = init_kid_probe(monkeypatch, kid) + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): - HLS.download_track(track=track, ctx=ctx) + download(track, cdm) + + assert not track.drm + assert probe.called == (kid != KID) + + +def test_a_licence_with_no_content_key_stops_the_bridge_before_a_segment(tmp_path: Path, monkeypatch: Any) -> None: + track = hls_video(tmp_path, playlist(SKD_KEY)) + init_kid_probe(monkeypatch, KID) + + with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=KID.hex): + download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None) + + +def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path, monkeypatch: Any) -> None: + """The refusal comes before a segment is requested: a ClearKey would otherwise write the ciphertext as the output.""" + track = hls_video(tmp_path, playlist(SKD_KEY)) + track.drm = [ClearKey(key=bytes(16))] + init_kid_probe(monkeypatch, KID) + + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + download(track, cdm_type_stub("playready")) diff --git a/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py b/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py index b4dc3ee5..228e3a9d 100644 --- a/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py +++ b/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py @@ -13,8 +13,14 @@ from uuid import UUID import pytest from pywidevine.pssh import PSSH as WvPSSH +from tests.core.test_cenc import init, widevine_box from tests.core.test_hls_kid_from_init import NO_KID_PSSH +from tests.core.test_hls_service_drm_keys import SKD_KEY, playlist +from tests.core.test_kid_windows import encv +from unshackle.core.api.errors import APIError +from unshackle.core.api.server_keys import require_track_pssh from unshackle.core.drm import Widevine +from unshackle.core.drm.cenc import drm_stub from unshackle.core.drm.discovery import ensure_track_drm, track_pssh from unshackle.core.tracks import Track, Video @@ -82,3 +88,45 @@ def test_a_playlist_whose_keys_all_fail_leaves_the_track_without_drm(): ensure_track_drm(track, session) assert not track.drm + + +def skd_session(init_data: bytes = b"init") -> SimpleNamespace: + response = SimpleNamespace(text=playlist(SKD_KEY), ok=True, content=init_data) + return SimpleNamespace(get=lambda url, headers=None: response) + + +def skd_track() -> Video: + track = hls_track() + track.OnSegmentFilter = None + track.get_key_id = lambda init: KID # type: ignore[method-assign] + return track + + +def test_a_playlist_unshackle_cannot_license_gets_both_stubs_of_its_key_id(): + """The client sends the stub that it built, and the server must know the key id to accept it.""" + track = skd_track() + + ensure_track_drm(track, skd_session()) + + assert [type(drm).__name__ for drm in track.drm] == ["Widevine", "PlayReady"] + assert all(drm.kids == [KID] for drm in track.drm) + for system in ("widevine", "playready"): + require_track_pssh(track, track_pssh(SimpleNamespace(drm=[drm_stub(system, [KID.hex])]), system), system) + with pytest.raises(APIError, match="does not belong"): + require_track_pssh(track, drm_stub("playready", [UUID(int=5).hex]).pssh_b64, "playready") + + +def test_the_stubs_take_the_key_id_of_the_init_pssh_when_its_tenc_names_none(): + track = skd_track() + track.get_key_id = lambda init: None # type: ignore[method-assign] + + ensure_track_drm(track, skd_session(init(widevine_box(KID), encv(UUID(int=0))))) + + assert [drm.kids for drm in track.drm] == [[KID], [KID]] + + +def test_only_the_server_builds_the_stubs_before_the_download(): + track = skd_track() + + assert track.load_drm_from_playlist(skd_session()) is False + assert not track.drm diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py index 3bbf8ca6..5cf6366e 100644 --- a/unshackle/core/drm/cenc.py +++ b/unshackle/core/drm/cenc.py @@ -101,6 +101,26 @@ def init_kid(init_data: bytes) -> UUID | None: return None +def init_pssh_kid(init_data: bytes) -> UUID | None: + """The one real KID that every pssh box of an init segment with a tenc names, or None for none or several.""" + from unshackle.core.drm.playready import PlayReady + from unshackle.core.drm.widevine import Widevine + + if not any(get_boxes(init_data, b"tenc")): + return None + drm_classes: dict[UUID, type[CencDrm]] = {WIDEVINE_ID: Widevine, PLAYREADY_ID: PlayReady} + kids: set[UUID] = set() + for box in get_boxes(init_data, b"pssh"): + kids.update(box.key_IDs or []) + if drm_class := drm_classes.get(box.system_ID): + try: + kids.update(drm_class.from_pssh_box(box, None).kids) + except drm_class.Exceptions.KIDNotFound: + continue + kids -= PLACEHOLDER_KIDS + return kids.pop() if len(kids) == 1 else None + + def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | None: """The Widevine or PlayReady DRM of an EXT-X-KEY, or None for another KEYFORMAT. diff --git a/unshackle/core/drm/discovery.py b/unshackle/core/drm/discovery.py index 420d9e4c..7834ceaf 100644 --- a/unshackle/core/drm/discovery.py +++ b/unshackle/core/drm/discovery.py @@ -109,7 +109,7 @@ def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = if (track.data.get("hls") or getattr(track, "descriptor", None) is Track.Descriptor.HLS) and track.url: try: - if track.load_drm_from_playlist(session): + if track.load_drm_from_playlist(session, bridge=True): return except Exception as e: log.debug(f"HLS DRM prefetch failed for {track.id}: {e!r}") diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 8c814ce4..76200cef 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -12,7 +12,7 @@ import time from collections.abc import Callable from contextlib import suppress from functools import partial -from itertools import accumulate +from itertools import accumulate, pairwise from pathlib import Path from typing import Any, BinaryIO, cast from urllib.parse import urljoin, urlparse @@ -28,11 +28,21 @@ from pywidevine.pssh import PSSH as WV_PSSH from requests import Session from unshackle.core import binaries -from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm +from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine -from unshackle.core.drm.cenc import PLAYREADY_ID, WIDEVINE_ID, cenc_key, hls_key_drm, key_data, key_system +from unshackle.core.drm.cenc import ( + PLACEHOLDER_KIDS, + PLAYREADY_ID, + WIDEVINE_ID, + cenc_key, + drm_stub, + hls_key_drm, + init_pssh_kid, + key_data, + key_system, +) from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.verify import decrypt_track from unshackle.core.events import events @@ -711,10 +721,18 @@ class HLS: # Get session DRM as fallback but prefer media playlist keys for accurate KID matching session_drm = track.get_drm_for_cdm(cdm) if track.drm else None - if not isinstance(session_drm, (Widevine, PlayReady)): - for segment in wanted_segments: - if segment.keys: - HLS.resolve_segment_key(segment.keys, cdm, track.drm_preference) + bridge_drm = bridge_kid = None + if session_drm is None and (system := cdm_system(cdm)): + bridge_kid = HLS.get_bridge_kid(master, wanted_segments, track, session) + bridge_drm = drm_stub(system, [bridge_kid.hex]) if bridge_kid else None + if bridge_drm and bridge_kid: + HLS.drop_unsupported_keys(master) + session_drm = bridge_drm + track.drm = [bridge_drm] + log.debug(f"{track.id}: licensing key ID {bridge_kid.hex} of its init segment as {bridge_drm.NAME}") + elif not isinstance(session_drm, (Widevine, PlayReady)): + for keys in {id(keys): keys for _, keys in HLS.keys_in_force(master, wanted_segments)}.values(): + HLS.resolve_segment_key(keys, cdm, track.drm_preference) elif HLS.drop_unsupported_keys(master): log.debug(f"{track.id}: its key tags name key systems unshackle cannot license, using the DRM of the track") @@ -753,7 +771,9 @@ class HLS: initial_drm_licensed = True if not initial_drm_licensed: - license_drm(track, session_drm, ctx, probe=lambda: HLS.get_track_kid_from_init(master, track, session)) + license_drm( + track, session_drm, ctx, bridge_kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session) + ) if DOWNLOAD_LICENCE_ONLY.is_set(): # a playlist can change its key part-way, and only the download loop licenses the later keys @@ -770,6 +790,9 @@ class HLS: progress(downloaded="[yellow]SKIPPED") return + if bridge_drm and bridge_kid and not bridge_drm.content_keys: + raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {bridge_kid.hex} of track {track.id}") + # Downloaded segment files are named by post-filter index; map that back to the wanted # segment so the IV uses the absolute media sequence number, not the download index. single_init = HLS.single_init_no_rotation(wanted_segments, initial_drm_key, cdm, track.drm_preference) @@ -1410,10 +1433,12 @@ class HLS: track: Track, session: Session | RnetSession, init_section: m3u8.model.InitializationSection | None = None, + pssh: bool = False, ) -> UUID | None: """ Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist. + With `pssh`, an init segment with an all-zero tenc Key ID gives the one Key ID that its pssh boxes name. Returns None if no init segment exists or KID extraction fails. The caller should fall back to drm.kid from the PSSH if this returns None. """ @@ -1430,7 +1455,10 @@ class HLS: headers = {} map_res = unrecorded(session, "get", map_uri, headers=headers) if map_res.ok: - return track.get_key_id(map_res.content) + kid = track.get_key_id(map_res.content) + if pssh and (kid is None or kid.int == 0): + return init_pssh_kid(map_res.content) + return kid logging.getLogger("HLS").warning( f"Could not read the Key ID from the init segment {safe_display_url(map_uri)}: " f"HTTP {map_res.status_code}" @@ -1472,14 +1500,55 @@ class HLS: raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}") @staticmethod - def drop_unsupported_keys(manifest: M3U8) -> bool: - """Remove every EXT-X-KEY of `manifest` when each is sample encryption of a DRM system unshackle cannot license. + def get_bridge_kid( + manifest: M3U8, segments: list[Any], track: Track, session: Session | RnetSession + ) -> UUID | None: + """The real Key ID of the init segment of the first `segments` entry with an EXT-X-KEY unshackle cannot license. - Returns whether it did. The download then reads the playlist as one without an EXT-X-KEY and decrypts with the - one Widevine or PlayReady DRM of the track. Any other METHOD, such as AES-128 or AES-256, keeps every tag. + None when `only_unsupported_keys` is false of `manifest`, or when the init segment changes with no + EXT-X-DISCONTINUITY: the merge splits there only on a changed EXT-X-KEY, and the tags go. + The pssh boxes count only for one init segment in a one-key playlist: an all-zero tenc takes any content key. + """ + keyed = [(s, keys) for s, keys in HLS.keys_in_force(manifest, segments) if s.init_section and any(keys)] + if not keyed or not HLS.only_unsupported_keys(manifest): + return None + init_section = keyed[0][0].init_section + one_key = len({key.uri for key in manifest.keys if key}) == 1 + pssh = one_key and all(s.init_section == init_section for s, _ in keyed) + if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)): + return None + kid = HLS.get_track_kid_from_init(manifest, track, session, init_section, pssh=pssh) + return None if kid in PLACEHOLDER_KIDS else kid + + @staticmethod + def keys_in_force(manifest: M3U8, segments: list[Any]) -> list[tuple[Any, list[Any]]]: + """Each of `segments` that has an EXT-X-KEY in force, with its tags: python-m3u8 puts them on the first one only.""" + wanted = {id(segment) for segment in segments} + found: list[tuple[Any, list[Any]]] = [] + keys: list[Any] = [] + for segment in manifest.segments: + keys = segment.keys or keys + if keys and id(segment) in wanted: + found.append((segment, keys)) + return found + + @staticmethod + def only_unsupported_keys(manifest: M3U8) -> bool: + """Whether each EXT-X-KEY of `manifest`, at least one, is sample encryption of a DRM system unshackle cannot license. + + Any other METHOD, such as AES-128 or AES-256, makes it false. """ keys = [key for key in (manifest.keys or []) if key is not None] - if not keys or any(key.method not in ("SAMPLE-AES", "SAMPLE-AES-CTR") or cenc_key(key) for key in keys): + return bool(keys) and all(key.method in ("SAMPLE-AES", "SAMPLE-AES-CTR") and not cenc_key(key) for key in keys) + + @staticmethod + def drop_unsupported_keys(manifest: M3U8) -> bool: + """Remove every EXT-X-KEY of `manifest` when `only_unsupported_keys` is true of it. + + Returns whether it did. The download then reads the playlist as one without an EXT-X-KEY and decrypts with the + one Widevine or PlayReady DRM of the track. + """ + if not HLS.only_unsupported_keys(manifest): return False manifest.keys = [] for segment in manifest.segments: diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 64499b43..e7d673fb 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -22,13 +22,14 @@ from requests import Session from requests.adapters import HTTPAdapter, Retry from unshackle.core import binaries +from unshackle.core.cdm.choice import SYSTEMS from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.downloaders.requests import requests from unshackle.core.drm import DRM_T, PlayReady, Widevine from unshackle.core.drm.cbcs import SampleDecrypter -from unshackle.core.drm.cenc import cenc_key, init_kid +from unshackle.core.drm.cenc import cenc_key, drm_stub, init_kid from unshackle.core.drm.verify import ( children, find_child_box, @@ -993,10 +994,11 @@ class Track: return self.load_drm_from_playlist() - def load_drm_from_playlist(self, session: Any = None) -> bool: + def load_drm_from_playlist(self, session: Any = None, bridge: bool = False) -> bool: """Load the Widevine and PlayReady DRM of the EXT-X-KEY and EXT-X-SESSION-KEY tags of this track's playlist. It skips a tag that gives no DRM, and raises ValueError when the fetch fails or when every such tag fails. + With ``bridge`` it builds both stubs for the key ID that ``HLS.get_bridge_kid`` finds when no tag gives a DRM. """ if self.drm: self.needs_drm_loading = False @@ -1024,12 +1026,18 @@ class Track: except Exception as e: logging.getLogger("track").debug(f"Skipping HLS key {key} of track {self.id}: {e!r}") error = e + if error and not drm_list: + raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {error}") + if bridge and not drm_list: + segments = [ + s for s in playlist.segments if not (callable(self.OnSegmentFilter) and self.OnSegmentFilter(s)) + ] + if kid := HLS.get_bridge_kid(playlist, segments, self, session): + drm_list = [drm_stub(system, [kid.hex]) for system in SYSTEMS] if drm_list: self.drm = drm_list self.needs_drm_loading = False return True - if error: - raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {error}") return False def get_init_segment(