fix(hls): refuse key tags the DRM of the track cannot decrypt

This commit is contained in:
imSp4rky
2026-11-29 22:07:43 -07:00
parent ba2911056d
commit f0163439d4
5 changed files with 123 additions and 26 deletions
+9 -6
View File
@@ -463,15 +463,18 @@ PlayReady or Widevine. To license such a track through one of those systems:
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`
with `"playready"` or `"widevine"` and the key ID.
with `"playready"` or `"widevine"` and the key ID. When only one of the two systems issues the
content key, also set `track.drm_preference` to it.
3. Let your licence callback send the challenge to the server that issues that key.
`drm_stub` builds the header from the key ID alone, so this works with a licence server that goes
by the key ID, not with one that checks a header a packager signed. When a track carries a DRM
object and every `EXT-X-KEY` of its playlist names 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. A track with no DRM object still stops
with `None of the key systems are supported`.
by the key ID, not with one that checks a header a packager signed. A platform can issue the
content key of one package of a title and refuse another. When a track carries a Widevine or PlayReady DRM
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.
### How unshackle chooses a CDM and finds keys
+51
View File
@@ -6,6 +6,8 @@ copy raised "Duplicate track ID" and failed the whole title.
from __future__ import annotations
import pytest
from unshackle.core.manifests.hls import HLS
URL = "https://example.test/master.m3u8"
@@ -39,3 +41,52 @@ def test_variants_with_the_same_attributes_and_other_links_stay_apart() -> None:
result = tracks(variant(5_000_000, "video/uhd.m3u8") + variant(5_000_000, "mirror/uhd.m3u8"))
assert len(result.videos) == 2
PLAIN = '#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153.B0",VIDEO-RANGE=PQ'
COMPOSITE = PLAIN + ',SUPPLEMENTAL-CODECS="dvh1.08.06/db1p"'
def test_variants_of_one_link_with_another_video_range_stay_apart() -> None:
result = tracks(f"{PLAIN}\nuhd.m3u8\n" + f"{PLAIN.replace('=PQ', '=SDR')}\nuhd.m3u8\n")
assert len(result.videos) == 2
def test_variants_with_other_supplemental_codecs_and_other_links_stay_apart() -> None:
result = tracks(f"{PLAIN}\nhdr10.m3u8\n{COMPOSITE}\ndv.m3u8\n")
flags = {str(video.url).rsplit("/", 1)[-1]: video.dv_compatible_bitstream for video in result.videos}
assert flags == {"hdr10.m3u8": False, "dv.m3u8": True}
@pytest.mark.parametrize("first, second", [(PLAIN, COMPOSITE), (COMPOSITE, PLAIN)], ids=["plain", "composite"])
def test_one_link_listed_with_and_without_supplemental_codecs_keeps_the_dv_flag(first: str, second: str) -> None:
"""python-m3u8 drops SUPPLEMENTAL-CODECS, so the two entries count as one; the flag goes by link, not by entry."""
result = tracks(f"{first}\nuhd.m3u8\n{second}\nuhd.m3u8\n")
assert [video.dv_compatible_bitstream for video in result.videos] == [True]
def test_a_media_entry_listed_twice_with_other_channel_counts_keeps_both() -> None:
result = tracks(
AUDIO.replace('CHANNELS="2"', 'CHANNELS="6"')
+ "\n"
+ AUDIO.replace('CHANNELS="2"', 'CHANNELS="5.1"')
+ "\n"
+ variant(5_000_000, "video/uhd.m3u8")
)
assert len(result.audio) == 2
CC = '#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID="cc",NAME="CC1",INSTREAM-ID="CC1"'
CC_VARIANT = variant(5_000_000, "video/uhd.m3u8").replace('AUDIO="en"', 'AUDIO="en",CLOSED-CAPTIONS="cc"')
def test_a_closed_caption_entry_listed_twice_is_carried_once() -> None:
result = tracks(CC + "\n" + CC + "\n" + CC_VARIANT)
assert result.videos[0].closed_captions == [
{"language": None, "name": "CC1", "instream_id": "CC1", "characteristics": None}
]
+42
View File
@@ -14,7 +14,9 @@ import m3u8
import pytest
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.cenc import drm_stub
from unshackle.core.manifests.hls import HLS
from unshackle.core.tracks import Video
@@ -57,6 +59,14 @@ def test_key_tags_no_licence_route_can_use_are_dropped() -> None:
pytest.param(WIDEVINE_KEY, id="widevine"),
pytest.param('#EXT-X-KEY:METHOD=AES-128,URI="key"', id="aes-128"),
pytest.param("#EXT-X-KEY:METHOD=NONE", id="none"),
pytest.param(
'#EXT-X-KEY:METHOD=AES-256,URI="skd://keys.example/asset",KEYFORMAT="com.apple.streamingkeydelivery"',
id="aes-256",
),
pytest.param(
'#EXT-X-KEY:METHOD=AES-256-GCM,URI="skd://keys.example/asset",KEYFORMAT="com.apple.streamingkeydelivery"',
id="aes-256-gcm",
),
],
)
def test_a_key_tag_unshackle_can_read_keeps_every_tag(key_tag: str) -> None:
@@ -131,3 +141,35 @@ def test_a_track_without_drm_still_refuses_the_key_tag(tmp_path: Path, monkeypat
HLS.download_track(track=track, ctx=ctx)
finally:
DOWNLOAD_LICENCE_ONLY.clear()
@pytest.mark.parametrize(
"drm",
[
pytest.param(None, id="no-drm"),
pytest.param(ClearKey(key=bytes(16)), id="aes-128-session-key"),
],
)
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"),
)
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
HLS.download_track(track=track, ctx=ctx)
+2 -2
View File
@@ -128,8 +128,8 @@ def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | Non
def drm_stub(drm_type: str, kid_hexes: list[str]) -> Widevine | PlayReady:
"""A PlayReady (``drm_type`` ``playready``) or else Widevine DRM that names ``kid_hexes``, for content keys got without a PSSH.
The header is built here and holds the key ids and nothing a packager signed. A licence server that goes by
the key ids answers its challenge, so a service can also license through it; one that checks the header does not.
The header is built here: a PlayReady one holds the first key id, a Widevine one every key id, and nothing a
packager signed. A licence server that goes by the key ids answers its challenge; one that checks the header does not.
"""
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.widevine import Widevine
+19 -18
View File
@@ -192,7 +192,7 @@ class HLS:
All Track objects' URL will be to another M3U(8) document. However, these documents
will be Invariant Playlists and contain the list of segments URIs among other metadata.
A variant or a media entry that the master lists twice gets one track.
A variant or a media entry that the master lists twice with the same attributes gets one track.
"""
session_keys = list(self.manifest.session_keys or [])
if not session_keys:
@@ -218,8 +218,10 @@ class HLS:
seen.add(mime)
cc_by_group_id: dict[str, list[dict[str, Any]]] = {}
cc_entries: set[str] = set()
for media in self.manifest.media:
if media.type == "CLOSED-CAPTIONS":
if media.type == "CLOSED-CAPTIONS" and str(media) not in cc_entries:
cc_entries.add(str(media))
cc_by_group_id.setdefault(media.group_id, []).append(
{
"language": media.language,
@@ -310,9 +312,10 @@ class HLS:
entries: set[str] = set()
for media in self.manifest.media:
if not media.uri or str(media) in entries:
entry = str(media)
if not media.uri or entry in entries:
continue
entries.add(str(media))
entries.add(entry)
joc = 0
track_type: type[Audio] | type[Subtitle]
@@ -345,7 +348,7 @@ class HLS:
tracks.add(
track_type(
id_=hex(crc32(str(media).encode()))[2:],
id_=hex(crc32(entry.encode()))[2:],
url=urljoin(media.base_uri, media.uri),
codec=codec,
language=track_lang, # HLS media may not have language info, fallback if needed
@@ -706,16 +709,14 @@ class HLS:
if ctx.on_segments:
ctx.on_segments(track, wanted_segments)
if track.drm and HLS.drop_unsupported_keys(master):
log.debug(
f"{track.id}: its key tags name key systems unshackle cannot license, using the DRM of the service"
)
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
if track.drm:
session_drm = track.get_drm_for_cdm(cdm)
else:
session_drm = None
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)
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")
initial_drm_licensed = False
initial_drm_key = None # Track the EXT-X-KEY used for initial licensing
@@ -1472,13 +1473,13 @@ class HLS:
@staticmethod
def drop_unsupported_keys(manifest: M3U8) -> bool:
"""Remove every EXT-X-KEY of `manifest` when each one names a DRM system unshackle cannot license; True when it did.
"""Remove every EXT-X-KEY of `manifest` when each is sample encryption of a DRM system unshackle cannot license.
A service can license such a playlist another way, with the DRM it puts on the track. The download then
reads the playlist as one without an EXT-X-KEY, and the track keeps that DRM.
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.
"""
keys = [key for key in (manifest.keys or []) if key is not None]
if not keys or any(key.method in ("NONE", "AES-128") or cenc_key(key) for key in keys):
if not keys or any(key.method not in ("SAMPLE-AES", "SAMPLE-AES-CTR") or cenc_key(key) for key in keys):
return False
manifest.keys = []
for segment in manifest.segments: