fix(clearkey): warn when pkcs7 unpad fails and require a 16-byte key from the key uri

This commit is contained in:
imSp4rky
2026-11-26 13:40:06 -07:00
parent 625e632b53
commit 136e9fc84d
3 changed files with 67 additions and 8 deletions
+4
View File
@@ -453,6 +453,10 @@ decrypts each segment in-process with AES-CBC. There is no device, no CDM, and n
license challenge, so you do not set anything up. unshackle decrypts such tracks license challenge, so you do not set anything up. unshackle decrypts such tracks
automatically during download. automatically during download.
The `EXT-X-KEY` URI must return a content key of exactly 16 bytes, or the download stops with an error.
If a decrypted segment has no valid PKCS7 padding, unshackle keeps the output and
logs one warning for the track, because the content key is possibly wrong.
### ClearKey over CENC (W3C EME `org.w3.clearkey`) ### ClearKey over CENC (W3C EME `org.w3.clearkey`)
The CENC ClearKey scheme is a proper license flow, but the "license server" The CENC ClearKey scheme is a proper license flow, but the "license server"
+52 -2
View File
@@ -4,6 +4,8 @@ Covers the correctness guards on the whole-segment AES-128-CBC path:
- ``ClearKey.decrypt`` passing mislabeled-clear / non-block-aligned segments through - ``ClearKey.decrypt`` passing mislabeled-clear / non-block-aligned segments through
untouched instead of crashing or corrupting (WS1 / F1+F3) untouched instead of crashing or corrupting (WS1 / F1+F3)
- ``ClearKey.from_m3u_key`` ``data:`` URI parsing and 16-byte key validation (WS5 / F4) - ``ClearKey.from_m3u_key`` ``data:`` URI parsing and 16-byte key validation (WS5 / F4)
- ``ClearKey.decrypt`` warning once when the PKCS7 unpad fails, and keeping the output
- ``ClearKey.from_m3u_key`` rejecting a key URI body that is not exactly 16 bytes
- the RFC 8216 §5.2 sequence-number IV deriving from a segment's absolute media - the RFC 8216 §5.2 sequence-number IV deriving from a segment's absolute media
sequence number rather than the post-filter download index (WS2 / F2) sequence number rather than the post-filter download index (WS2 / F2)
""" """
@@ -14,6 +16,7 @@ import base64
import m3u8 import m3u8
import pytest import pytest
import requests
from Cryptodome.Cipher import AES from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad from Cryptodome.Util.Padding import pad
from m3u8.model import Key from m3u8.model import Key
@@ -66,11 +69,14 @@ def test_non_block_aligned_passes_through(tmp_path) -> None:
assert seg.read_bytes() == data assert seg.read_bytes() == data
def test_empty_segment_does_not_crash(tmp_path) -> None: def test_empty_segment_does_not_crash(tmp_path, caplog) -> None:
seg = tmp_path / "0.ts" seg = tmp_path / "0.ts"
seg.write_bytes(b"") seg.write_bytes(b"")
ClearKey(key=KEY, iv=IV).decrypt(seg) with caplog.at_level("WARNING"):
ClearKey(key=KEY, iv=IV).decrypt(seg)
assert not caplog.records
assert seg.exists() assert seg.exists()
assert seg.read_bytes() == b"" assert seg.read_bytes() == b""
@@ -88,6 +94,50 @@ def test_warns_once_per_instance(tmp_path, caplog) -> None:
assert len(warnings) == 1 assert len(warnings) == 1
def test_unpad_failure_warns_once_and_keeps_output(tmp_path, caplog) -> None:
plaintext = b"\x00" * 32
drm = ClearKey(key=KEY, iv=IV)
for name in ("0.ts", "1.ts"):
seg = tmp_path / name
seg.write_bytes(AES.new(KEY, AES.MODE_CBC, IV).encrypt(plaintext))
with caplog.at_level("WARNING"):
drm.decrypt(seg)
assert seg.read_bytes() == plaintext
warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"]
assert len(warnings) == 1
assert "PKCS7" in warnings[0] and "0.ts" in warnings[0]
def uri_key(monkeypatch, body: bytes) -> tuple[Key, requests.Session]:
response = requests.Response()
response.status_code = 200
response._content = body
session = requests.Session()
monkeypatch.setattr(session, "get", lambda url: response)
key = Key(
method="AES-128",
uri="key.bin",
base_uri="https://example.com/",
keyformat=None,
keyformatversions=None,
iv=None,
)
return key, session
def test_uri_key_of_16_bytes_loads(monkeypatch) -> None:
key, session = uri_key(monkeypatch, KEY)
assert ClearKey.from_m3u_key(key, session).key == KEY
@pytest.mark.parametrize("length", [0, 15, 17, 32])
def test_uri_key_wrong_length_rejected(monkeypatch, length) -> None:
key, session = uri_key(monkeypatch, b"\x01" * length)
with pytest.raises(EOFError, match=f"Unexpected Length of Key \\({length} bytes\\)"):
ClearKey.from_m3u_key(key, session)
def data_key(raw: bytes, base64_encoded: bool = True) -> Key: def data_key(raw: bytes, base64_encoded: bool = True) -> Key:
if base64_encoded: if base64_encoded:
uri = "data:text/plain;base64," + base64.b64encode(raw).decode("ascii") uri = "data:text/plain;base64," + base64.b64encode(raw).decode("ascii")
+11 -6
View File
@@ -49,6 +49,7 @@ class ClearKey:
self.key: bytes = key self.key: bytes = key
self.iv: bytes = iv self.iv: bytes = iv
self._warned_clear: bool = False self._warned_clear: bool = False
self._warned_unpad: bool = False
def warn_clear(self, reason: str) -> None: def warn_clear(self, reason: str) -> None:
"""Warn once per track that unshackle passed a segment through undecrypted.""" """Warn once per track that unshackle passed a segment through undecrypted."""
@@ -57,11 +58,16 @@ class ClearKey:
self._warned_clear = True self._warned_clear = True
def decrypt(self, path: Path) -> None: def decrypt(self, path: Path) -> None:
"""Decrypt a Track with AES-128 ClearKey (HLS) DRM.""" """Decrypt a Track with AES-128 ClearKey (HLS) DRM.
A segment that fails the PKCS7 unpad is kept as decrypted: some streams are block aligned with no padding.
"""
if not path or not path.exists(): if not path or not path.exists():
raise ValueError("Tried to decrypt a file that does not exist.") raise ValueError("Tried to decrypt a file that does not exist.")
data = path.read_bytes() data = path.read_bytes()
if not data:
return
# Mislabeled-clear guard: plaintext MPEG-TS the manifest wrongly tags AES-128. Require the # 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 # 0x47 sync byte at 4 consecutive packet boundaries plus an exact packet-count length, so
@@ -93,8 +99,9 @@ class ClearKey:
try: try:
decrypted = unpad(decrypted, AES.block_size) decrypted = unpad(decrypted, AES.block_size)
except ValueError: except ValueError:
# the decrypted data is likely already in the block size boundary if not self._warned_unpad:
pass log.warning("ClearKey: PKCS7 unpad failed for %s, the key may be wrong.", path.name)
self._warned_unpad = True
decrypted_path = path.with_suffix(f".decrypted{path.suffix}") decrypted_path = path.with_suffix(f".decrypted{path.suffix}")
decrypted_path.write_bytes(decrypted) decrypted_path.write_bytes(decrypted)
@@ -153,9 +160,7 @@ class ClearKey:
) )
res = session.get(url) res = session.get(url)
res.raise_for_status() res.raise_for_status()
if not res.content: if len(res.content) != 16:
raise EOFError("Unexpected Empty Response by M3U Key URI.")
if len(res.content) < 16:
raise EOFError(f"Unexpected Length of Key ({len(res.content)} bytes) in M3U Key.") raise EOFError(f"Unexpected Length of Key ({len(res.content)} bytes) in M3U Key.")
key = res.content key = res.content