fix: harden ClearKey/CENC decryption correctness

This commit is contained in:
imSp4rky
2026-07-19 10:49:45 -06:00
parent 446367f58d
commit 95a754fa6c
5 changed files with 255 additions and 16 deletions
+4 -1
View File
@@ -1851,6 +1851,7 @@ class dl:
cdm_only=cdm_only,
vaults_only=vaults_only,
export=export_path,
service_session=service.session,
),
cdm=self.cdm,
max_workers=workers,
@@ -2921,6 +2922,7 @@ class dl:
cdm_only=cdm_only,
vaults_only=vaults_only,
export=export_path,
service_session=service.session,
),
cdm=self.cdm,
max_workers=workers,
@@ -3645,6 +3647,7 @@ class dl:
cdm_only: bool = False,
vaults_only: bool = False,
export: Optional[Path] = None,
service_session: Optional[Any] = None,
) -> None:
"""
Prepare the DRM by getting decryption data like KIDs, Keys, and such.
@@ -4175,7 +4178,7 @@ class dl:
from_vaults = drm.content_keys.copy()
try:
drm.get_content_keys(licence=clearkey_licence or (lambda **_: None))
drm.get_content_keys(licence=clearkey_licence or (lambda **_: None), session=service_session)
except Exception as e:
if drm.content_keys:
self.log.debug(f"License call failed but keys already in content_keys: {e}")
+44 -12
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import base64
import logging
import shutil
from pathlib import Path
from typing import Optional, Union
@@ -14,6 +15,14 @@ from requests import Session
from unshackle.core.session import RnetSession
from unshackle.core.utilities import log_event
log = logging.getLogger(__name__)
# MPEG-TS: 188-byte packets, sync byte 0x47 at every packet boundary (shared with sample_aes).
SYNC_BYTE = 0x47
TS_PACKET_SIZE = 188
# Consecutive packet boundaries that must carry the sync byte to call a segment clear MPEG-TS.
TS_SYNC_CHECKS = 4
class ClearKey:
"""AES Clear Key DRM System."""
@@ -39,12 +48,38 @@ class ClearKey:
self.key: bytes = key
self.iv: bytes = iv
self._warned_clear: bool = False
def _warn_clear(self, reason: str) -> None:
"""Warn once per track that a segment was passed through undecrypted."""
if not self._warned_clear:
log.warning("ClearKey: manifest signaled AES-128 encryption but %s; passing segment through.", reason)
self._warned_clear = True
def decrypt(self, path: Path) -> None:
"""Decrypt a Track with AES Clear Key DRM."""
if not path or not path.exists():
raise ValueError("Tried to decrypt a file that does not exist.")
data = path.read_bytes()
# Mislabeled-clear guard: plaintext MPEG-TS the manifest wrongly tags AES-128. Require the
# 0x47 sync byte at 4 consecutive packet boundaries plus an exact packet-count length, so
# real CBC ciphertext matching all of these is negligible (~1/256^4).
if (
len(data) % TS_PACKET_SIZE == 0
and len(data) >= TS_PACKET_SIZE * TS_SYNC_CHECKS
and all(data[i * TS_PACKET_SIZE] == SYNC_BYTE for i in range(TS_SYNC_CHECKS))
):
self._warn_clear("the segment is clear MPEG-TS")
return
# Valid AES-128-CBC ciphertext is always a 16-byte multiple; anything else is not
# ciphertext (truncated/clear/SAMPLE-AES). Decrypting would raise, so pass it through.
if len(data) % AES.block_size != 0:
self._warn_clear(f"the segment length ({len(data)} bytes) is not a multiple of {AES.block_size}")
return
log_event(
"drm_decrypt",
level="DEBUG",
@@ -53,15 +88,6 @@ class ClearKey:
file=path.name,
)
data = path.read_bytes()
# Guard mislabeled-clear: EXT-X-KEY says AES-128 but the segment is plaintext MPEG-TS.
# CBC ciphertext is 16-aligned, but so are some clear TS runs (752 bytes = 4 packets),
# so also sniff the 0x47 sync byte at packet 0 and 1.
is_ts = data[:1] == b"\x47" and data[188:189] == b"\x47"
if len(data) % AES.block_size != 0 or is_ts:
return
decrypted = AES.new(self.key, AES.MODE_CBC, self.iv).decrypt(data)
try:
@@ -105,11 +131,17 @@ class ClearKey:
session.headers["User-Agent"] = "smartexoplayer/1.1.0 (Linux;Android 8.0.0) ExoPlayerLib/2.13.3"
if m3u_key.uri.startswith("data:"):
media_types, data = m3u_key.uri[5:].split(",")
media_types, payload = m3u_key.uri[5:].split(",", 1)
media_types = media_types.split(";")
# Materialise the key bytes here so the 16-byte check covers both encodings: base64
# decodes to bytes, a raw payload is latin-1 bytes. A raw str would otherwise reach
# __init__ and be reinterpreted through fromhex.
if "base64" in media_types:
data = base64.b64decode(data)
key = data
key = base64.b64decode(payload)
else:
key = payload.encode("latin-1")
if len(key) != 16:
raise ValueError(f"Unexpected Length of Key ({len(key)} bytes) in M3U data: URI.")
else:
url = urljoin(m3u_key.base_uri, m3u_key.uri)
log_event(
+21 -2
View File
@@ -132,14 +132,33 @@ class ClearKeyCENC:
raise ValueError(f"Expected the ClearKey license to be bytes, str, or dict, not {response!r}")
for jwk in document.get("keys") or []:
if jwk.get("kty") not in (None, "oct"):
kty = jwk.get("kty")
if kty not in (None, "oct"):
continue
if kty is None:
log_event(
"drm_license_warning",
level="WARNING",
message="ClearKey JWK is missing 'kty'; assuming 'oct' per W3C EME",
drm_type="ClearKeyCENC",
)
kid_b64 = jwk.get("kid")
key_b64 = jwk.get("k")
if not kid_b64 or not key_b64:
continue
kid = UUID(bytes=b64url_decode(kid_b64))
self.content_keys[kid] = b64url_decode(key_b64).hex()
key = b64url_decode(key_b64)
if len(key) != 16:
# A CENC content key is always 16 bytes; a wrong-length key would make the
# external tool fail opaquely. Skip it rather than pass it through.
log_event(
"drm_license_warning",
level="WARNING",
message=f"ClearKey JWK for KID {kid.hex} has a {len(key)}-byte key (expected 16); skipping",
drm_type="ClearKeyCENC",
)
continue
self.content_keys[kid] = key.hex()
if not self.content_keys:
raise ClearKeyCENC.Exceptions.EmptyLicense("No Content Keys were within the License")
+8 -1
View File
@@ -709,6 +709,9 @@ class HLS:
# First segment's Media Sequence Number - used as the AES-128 IV when EXT-X-KEY has
# no explicit IV (RFC 8216 §5.2), where each segment's IV is its sequence number.
media_sequence_start = getattr(master, "media_sequence", None) or 0
# 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.
wanted_segments = [seg for seg in master.segments if seg not in unwanted_segments]
map_data: Optional[tuple[m3u8.model.InitializationSection, bytes]] = None
if session_drm:
encryption_data: Optional[tuple[Optional[m3u8.Key], DRM_T]] = (initial_drm_key, session_drm)
@@ -802,7 +805,11 @@ class HLS:
seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
for file in files:
if seq_iv and file.stem.isdigit():
drm.iv = (media_sequence_start + int(file.stem)).to_bytes(16, "big")
download_i = int(file.stem)
seq = getattr(wanted_segments[download_i], "media_sequence", None)
if seq is None:
seq = media_sequence_start + download_i
drm.iv = int(seq).to_bytes(16, "big")
drm.decrypt(file)
merge(to=merged_path, via=files, delete=True, include_map_data=True)