fix(drm): keep the input when a cbcs, ClearKey, stripe or segment decrypt fails

This commit is contained in:
imSp4rky
2026-11-28 18:27:40 -07:00
parent 79cc16d290
commit 5a2680d63d
8 changed files with 214 additions and 36 deletions
+33
View File
@@ -45,6 +45,39 @@ def test_decrypt_round_trip(tmp_path: Path) -> None:
assert list(tmp_path.iterdir()) == [path] assert list(tmp_path.iterdir()) == [path]
def refuse_replace(monkeypatch: pytest.MonkeyPatch) -> None:
def refuse(self: Path, target: Path) -> None:
raise PermissionError(target)
monkeypatch.setattr(Path, "replace", refuse)
def fail_chunk(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(self: BlowfishStripe, chunk: bytes) -> bytes:
raise ValueError("bad chunk")
monkeypatch.setattr(BlowfishStripe, "decrypt_chunk", fail)
@pytest.mark.parametrize(
("break_step", "raises"),
[pytest.param(fail_chunk, ValueError, id="decrypt"), pytest.param(refuse_replace, PermissionError, id="replace")],
)
def test_a_failed_decrypt_keeps_the_input(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, break_step: Any, raises: type[BaseException]
) -> None:
path = tmp_path / "track.flac"
path.write_bytes(stripe_encrypt(os.urandom(CHUNK * 4)))
original = path.read_bytes()
break_step(monkeypatch)
with pytest.raises(raises):
BlowfishStripe(KEY).decrypt(path)
assert path.read_bytes() == original
assert list(tmp_path.iterdir()) == [path]
def test_short_trailing_chunk_untouched(tmp_path: Path) -> None: def test_short_trailing_chunk_untouched(tmp_path: Path) -> None:
# the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear # the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear
plain = os.urandom(CHUNK * 3 + 100) plain = os.urandom(CHUNK * 3 + 100)
+64
View File
@@ -0,0 +1,64 @@
"""Tests for the in-process cbcs decrypt (``unshackle.core.drm.cbcs.decrypt_file``)."""
from __future__ import annotations
import struct
from pathlib import Path
from typing import Any
import pytest
from tests.core.test_kid_windows import A, box, full, movie
from unshackle.core.drm import cbcs
def cbcs_track(path: Path) -> bytes:
"""Write a cbcs track with one protected sample entry and no fragments, and return its bytes."""
tenc = full(b"tenc", b"\x00\x00\x01\x00" + A.bytes + b"\x10" + bytes(16), version=1)
schm = full(b"schm", b"cbcs" + struct.pack(">I", 0x10000))
entry = box(b"encv", bytes(78), box(b"sinf", box(b"frma", b"avc1"), schm, box(b"schi", tenc)))
data = movie(entry) + box(b"mdat", bytes(16))
path.write_bytes(data)
return data
def test_decrypt_replaces_the_input(tmp_path: Path) -> None:
path = tmp_path / "track.mp4"
cbcs_track(path)
cbcs.decrypt_file(path, lambda track, entry: bytes(16))
assert b"encv" not in path.read_bytes()
assert list(tmp_path.iterdir()) == [path]
def refuse_replace(monkeypatch: pytest.MonkeyPatch) -> None:
def refuse(self: Path, target: Path) -> None:
raise PermissionError(target)
monkeypatch.setattr(Path, "replace", refuse)
def fail_rewrite(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(*args: Any) -> None:
raise ValueError("bad moov")
monkeypatch.setattr(cbcs, "strip_moov_protection", fail)
@pytest.mark.parametrize(
("break_step", "raises"),
[pytest.param(fail_rewrite, ValueError, id="rewrite"), pytest.param(refuse_replace, PermissionError, id="replace")],
)
def test_a_failed_decrypt_keeps_the_input(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, break_step: Any, raises: type[BaseException]
) -> None:
path = tmp_path / "track.mp4"
original = cbcs_track(path)
break_step(monkeypatch)
with pytest.raises(raises):
cbcs.decrypt_file(path, lambda track, entry: bytes(16))
assert path.read_bytes() == original
assert list(tmp_path.iterdir()) == [path]
+17
View File
@@ -13,6 +13,7 @@ Covers the correctness guards on the whole-segment AES-128-CBC path:
from __future__ import annotations from __future__ import annotations
import base64 import base64
from pathlib import Path
import m3u8 import m3u8
import pytest import pytest
@@ -48,6 +49,22 @@ def test_valid_encrypted_segment_decrypts(tmp_path) -> None:
assert seg.read_bytes() == plaintext assert seg.read_bytes() == plaintext
def test_a_failed_swap_keeps_the_input(tmp_path, monkeypatch) -> None:
def refuse(self, target):
raise PermissionError(target)
seg = tmp_path / "0.ts"
seg.write_bytes(encrypt(b"the quick brown fox jumps over" * 4))
original = seg.read_bytes()
monkeypatch.setattr(Path, "replace", refuse)
with pytest.raises(PermissionError):
ClearKey(key=KEY, iv=IV).decrypt(seg)
assert seg.read_bytes() == original
assert list(tmp_path.iterdir()) == [seg]
def test_clear_ts_passes_through(tmp_path) -> None: def test_clear_ts_passes_through(tmp_path) -> None:
data = clear_ts() data = clear_ts()
seg = tmp_path / "0.ts" seg = tmp_path / "0.ts"
+37
View File
@@ -125,6 +125,43 @@ def test_segment_decrypter_keys_from_the_init_segment(tmp_path: Path, stub_mp4de
assert f"1:{KEY}" in decrypter.key_args assert f"1:{KEY}" in decrypter.key_args
@POSIX_STUBS
@pytest.mark.parametrize(
("output", "stderr", "raises"),
[
pytest.param(
b"partial", "ERROR: failed to process the file (-10)\n", subprocess.CalledProcessError, id="exit-0-error"
),
pytest.param(None, "", RuntimeError, id="exit-0-no-output"),
pytest.param(b"", "", RuntimeError, id="exit-0-empty-output"),
],
)
def test_a_failed_segment_decrypt_keeps_the_segment(
tmp_path: Path,
mp4decrypt_writes: Callable[[bytes | None, int, str], None],
output: bytes | None,
stderr: str,
raises: type[BaseException],
) -> None:
mp4decrypt_writes(output, 0, stderr)
drm = _widevine(A)
drm.content_keys[A] = KEY
segment_dir = tmp_path / "segments"
segment_dir.mkdir()
segment = segment_dir / "000.mp4"
segment.write_bytes(b"segment-0")
(segment_dir / "000.mp4.dec").write_bytes(b"stale")
decrypter = SegmentDecrypter(drm, movie(encv(A)), tmp_path / "work", workers=1)
decrypter.submit(segment)
with pytest.raises(raises) as caught:
decrypter.finish()
assert segment.read_bytes() == b"segment-0"
assert list(segment_dir.iterdir()) == [segment]
assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR
@pytest.mark.parametrize(("key_kid", "usable"), [(A, True), (B, False)], ids=["track-kid-keyed", "other-kid-only"]) @pytest.mark.parametrize(("key_kid", "usable"), [(A, True), (B, False)], ids=["track-kid-keyed", "other-kid-only"])
def test_segment_decrypt_needs_a_key_for_a_kidless_track( def test_segment_decrypt_needs_a_key_for_a_kidless_track(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key_kid: UUID, usable: bool tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key_kid: UUID, usable: bool
+15 -7
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import contextlib
from pathlib import Path from pathlib import Path
from Cryptodome.Cipher import Blowfish from Cryptodome.Cipher import Blowfish
@@ -24,7 +25,10 @@ class BlowfishStripe:
return Blowfish.new(self.key, Blowfish.MODE_CBC, iv=self.IV).decrypt(chunk) # nosec B304 return Blowfish.new(self.key, Blowfish.MODE_CBC, iv=self.IV).decrypt(chunk) # nosec B304
def decrypt(self, path: Path) -> None: def decrypt(self, path: Path) -> None:
"""Decrypt the file to a new file that then replaces it. A short trailing chunk stays clear.""" """Decrypt the file to a new file that then replaces it. A short trailing chunk stays clear.
A failure keeps ``path`` as it is and removes the new file.
"""
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.")
log_event( log_event(
@@ -35,12 +39,16 @@ class BlowfishStripe:
file=path.name, file=path.name,
) )
decrypted_path = path.with_suffix(f".decrypted{path.suffix}") decrypted_path = path.with_suffix(f".decrypted{path.suffix}")
with path.open("rb") as src, decrypted_path.open("wb") as dst: try:
while stripe := src.read(self.CHUNK * 3): with path.open("rb") as src, decrypted_path.open("wb") as dst:
if len(stripe) >= self.CHUNK: while stripe := src.read(self.CHUNK * 3):
stripe = self.decrypt_chunk(stripe[: self.CHUNK]) + stripe[self.CHUNK :] if len(stripe) >= self.CHUNK:
dst.write(stripe) stripe = self.decrypt_chunk(stripe[: self.CHUNK]) + stripe[self.CHUNK :]
decrypted_path.replace(path) dst.write(stripe)
decrypted_path.replace(path)
finally:
with contextlib.suppress(OSError):
decrypted_path.unlink(missing_ok=True)
__all__ = ("BlowfishStripe",) __all__ = ("BlowfishStripe",)
+26 -22
View File
@@ -15,6 +15,7 @@ keys per sample group needs an external decrypter.
from __future__ import annotations from __future__ import annotations
import contextlib
import shutil import shutil
import struct import struct
from collections.abc import Callable, Iterator from collections.abc import Callable, Iterator
@@ -484,28 +485,31 @@ def decrypt_file(path: Path, key_for: KeyResolver) -> None:
keys[(track.track_id, entry.index)] = resolved keys[(track.track_id, entry.index)] = resolved
work_path = path.with_stem(f"{path.stem}_decrypted") work_path = path.with_stem(f"{path.stem}_decrypted")
shutil.copyfile(path, work_path) try:
with work_path.open("r+b") as fh: shutil.copyfile(path, work_path)
for box_type, _header, start, size in list(_top_level(fh)): with work_path.open("r+b") as fh:
if box_type == b"moov": for box_type, _header, start, size in list(_top_level(fh)):
fh.seek(start) if box_type == b"moov":
moov = bytearray(fh.read(size)) fh.seek(start)
strip_moov_protection(moov, parse_moov(moov)) moov = bytearray(fh.read(size))
fh.seek(start) strip_moov_protection(moov, parse_moov(moov))
fh.write(moov) fh.seek(start)
elif box_type == b"moof": fh.write(moov)
fh.seek(start) elif box_type == b"moof":
moof = bytearray(fh.read(size)) fh.seek(start)
fragments = _parse_moof(moof, start, layout) moof = bytearray(fh.read(size))
for fragment in fragments: fragments = _parse_moof(moof, start, layout)
for offset in fragment.neutralise: for fragment in fragments:
_rename_box(moof, offset, b"free") for offset in fragment.neutralise:
fh.seek(start) _rename_box(moof, offset, b"free")
fh.write(moof) fh.seek(start)
for fragment in fragments: fh.write(moof)
_decrypt_fragment(fh, fragment, layout, keys) for fragment in fragments:
path.unlink() _decrypt_fragment(fh, fragment, layout, keys)
shutil.move(work_path, path) work_path.replace(path)
finally:
with contextlib.suppress(OSError):
work_path.unlink(missing_ok=True)
def _decrypt_fragment( def _decrypt_fragment(
+7 -5
View File
@@ -1,8 +1,8 @@
from __future__ import annotations from __future__ import annotations
import base64 import base64
import contextlib
import logging import logging
import shutil
from pathlib import Path from pathlib import Path
from urllib.parse import urljoin from urllib.parse import urljoin
@@ -104,10 +104,12 @@ class ClearKey:
self._warned_unpad = True 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) try:
decrypted_path.write_bytes(decrypted)
path.unlink() decrypted_path.replace(path)
shutil.move(decrypted_path, path) finally:
with contextlib.suppress(OSError):
decrypted_path.unlink(missing_ok=True)
@classmethod @classmethod
def from_m3u_key(cls, m3u_key: Key, session: AnySession | None = None) -> ClearKey: def from_m3u_key(cls, m3u_key: Key, session: AnySession | None = None) -> ClearKey:
+15 -2
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import contextlib
import os import os
import shutil import shutil
import subprocess import subprocess
@@ -15,6 +16,7 @@ from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.verify import kidless_track_kids from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.drm.widevine import Widevine from unshackle.core.drm.widevine import Widevine
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utils.subprocess import ToolFailed
SEGMENT_DRM_T = Widevine | PlayReady | ClearKeyCENC SEGMENT_DRM_T = Widevine | PlayReady | ClearKeyCENC
@@ -71,11 +73,13 @@ class SegmentDecrypter:
def decrypt_segment(self, segment: Path) -> None: def decrypt_segment(self, segment: Path) -> None:
output = segment.with_suffix(segment.suffix + ".dec") output = segment.with_suffix(segment.suffix + ".dec")
output.unlink(missing_ok=True)
try: try:
self.run(["--fragments-info", str(self.init_path), str(segment), str(output)]) self.run(["--fragments-info", str(self.init_path), str(segment), str(output)])
os.replace(output, segment) os.replace(output, segment)
finally: finally:
output.unlink(missing_ok=True) with contextlib.suppress(OSError):
output.unlink(missing_ok=True)
def init_bytes(self) -> bytes: def init_bytes(self) -> bytes:
"""Decrypt the init segment on first call and return its bytes. """Decrypt the init segment on first call and return its bytes.
@@ -107,9 +111,13 @@ class SegmentDecrypter:
shutil.rmtree(self.work_dir, ignore_errors=True) shutil.rmtree(self.work_dir, ignore_errors=True)
def run(self, args: list[str]) -> None: def run(self, args: list[str]) -> None:
"""Run mp4decrypt with the track keys and check its output.
mp4decrypt exits 0 after it fails to process a file, so this also reads its stderr.
"""
cmd = [str(binaries.Mp4decrypt), *self.key_args, *args] cmd = [str(binaries.Mp4decrypt), *self.key_args, *args]
try: try:
subprocess.run( p = subprocess.run(
cmd, cmd,
check=True, check=True,
capture_output=True, capture_output=True,
@@ -121,3 +129,8 @@ class SegmentDecrypter:
raise RuntimeError( raise RuntimeError(
f"mp4decrypt failed on {args[-2]}: {e.stderr.strip() if e.stderr else f'exit code {e.returncode}'}" f"mp4decrypt failed on {args[-2]}: {e.stderr.strip() if e.stderr else f'exit code {e.returncode}'}"
) from e ) from e
if "failed to process" in p.stderr:
raise coded(ToolFailed("mp4decrypt", p.returncode, cmd, p.stdout, p.stderr), APIErrorCode.DRM_ERROR)
output = Path(args[-1])
if not output.exists() or not output.stat().st_size:
raise RuntimeError(f"mp4decrypt failed on {args[-2]}: output file {output.name} is missing or empty")