diff --git a/tests/core/test_blowfish_stripe.py b/tests/core/test_blowfish_stripe.py index 9e99c47a..e4a00658 100644 --- a/tests/core/test_blowfish_stripe.py +++ b/tests/core/test_blowfish_stripe.py @@ -45,6 +45,39 @@ def test_decrypt_round_trip(tmp_path: Path) -> None: 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: # the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear plain = os.urandom(CHUNK * 3 + 100) diff --git a/tests/core/test_cbcs_decrypt.py b/tests/core/test_cbcs_decrypt.py new file mode 100644 index 00000000..675818b8 --- /dev/null +++ b/tests/core/test_cbcs_decrypt.py @@ -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] diff --git a/tests/core/test_clearkey.py b/tests/core/test_clearkey.py index dab4bf4b..8f842462 100644 --- a/tests/core/test_clearkey.py +++ b/tests/core/test_clearkey.py @@ -13,6 +13,7 @@ Covers the correctness guards on the whole-segment AES-128-CBC path: from __future__ import annotations import base64 +from pathlib import Path import m3u8 import pytest @@ -48,6 +49,22 @@ def test_valid_encrypted_segment_decrypts(tmp_path) -> None: 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: data = clear_ts() seg = tmp_path / "0.ts" diff --git a/tests/core/test_mp4decrypt_track_key.py b/tests/core/test_mp4decrypt_track_key.py index 89de71ad..7889f0ba 100644 --- a/tests/core/test_mp4decrypt_track_key.py +++ b/tests/core/test_mp4decrypt_track_key.py @@ -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 +@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"]) def test_segment_decrypt_needs_a_key_for_a_kidless_track( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key_kid: UUID, usable: bool diff --git a/unshackle/core/drm/blowfish_stripe.py b/unshackle/core/drm/blowfish_stripe.py index 3c188564..1bfb343e 100644 --- a/unshackle/core/drm/blowfish_stripe.py +++ b/unshackle/core/drm/blowfish_stripe.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib from pathlib import Path 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 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(): raise ValueError("Tried to decrypt a file that does not exist.") log_event( @@ -35,12 +39,16 @@ class BlowfishStripe: file=path.name, ) decrypted_path = path.with_suffix(f".decrypted{path.suffix}") - with path.open("rb") as src, decrypted_path.open("wb") as dst: - while stripe := src.read(self.CHUNK * 3): - if len(stripe) >= self.CHUNK: - stripe = self.decrypt_chunk(stripe[: self.CHUNK]) + stripe[self.CHUNK :] - dst.write(stripe) - decrypted_path.replace(path) + try: + with path.open("rb") as src, decrypted_path.open("wb") as dst: + while stripe := src.read(self.CHUNK * 3): + if len(stripe) >= self.CHUNK: + stripe = self.decrypt_chunk(stripe[: self.CHUNK]) + stripe[self.CHUNK :] + dst.write(stripe) + decrypted_path.replace(path) + finally: + with contextlib.suppress(OSError): + decrypted_path.unlink(missing_ok=True) __all__ = ("BlowfishStripe",) diff --git a/unshackle/core/drm/cbcs.py b/unshackle/core/drm/cbcs.py index 997053f1..d83dc302 100644 --- a/unshackle/core/drm/cbcs.py +++ b/unshackle/core/drm/cbcs.py @@ -15,6 +15,7 @@ keys per sample group needs an external decrypter. from __future__ import annotations +import contextlib import shutil import struct 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 work_path = path.with_stem(f"{path.stem}_decrypted") - shutil.copyfile(path, work_path) - with work_path.open("r+b") as fh: - for box_type, _header, start, size in list(_top_level(fh)): - if box_type == b"moov": - fh.seek(start) - moov = bytearray(fh.read(size)) - strip_moov_protection(moov, parse_moov(moov)) - fh.seek(start) - fh.write(moov) - elif box_type == b"moof": - fh.seek(start) - moof = bytearray(fh.read(size)) - fragments = _parse_moof(moof, start, layout) - for fragment in fragments: - for offset in fragment.neutralise: - _rename_box(moof, offset, b"free") - fh.seek(start) - fh.write(moof) - for fragment in fragments: - _decrypt_fragment(fh, fragment, layout, keys) - path.unlink() - shutil.move(work_path, path) + try: + shutil.copyfile(path, work_path) + with work_path.open("r+b") as fh: + for box_type, _header, start, size in list(_top_level(fh)): + if box_type == b"moov": + fh.seek(start) + moov = bytearray(fh.read(size)) + strip_moov_protection(moov, parse_moov(moov)) + fh.seek(start) + fh.write(moov) + elif box_type == b"moof": + fh.seek(start) + moof = bytearray(fh.read(size)) + fragments = _parse_moof(moof, start, layout) + for fragment in fragments: + for offset in fragment.neutralise: + _rename_box(moof, offset, b"free") + fh.seek(start) + fh.write(moof) + for fragment in fragments: + _decrypt_fragment(fh, fragment, layout, keys) + work_path.replace(path) + finally: + with contextlib.suppress(OSError): + work_path.unlink(missing_ok=True) def _decrypt_fragment( diff --git a/unshackle/core/drm/clearkey.py b/unshackle/core/drm/clearkey.py index e366d86d..12cc2935 100644 --- a/unshackle/core/drm/clearkey.py +++ b/unshackle/core/drm/clearkey.py @@ -1,8 +1,8 @@ from __future__ import annotations import base64 +import contextlib import logging -import shutil from pathlib import Path from urllib.parse import urljoin @@ -104,10 +104,12 @@ class ClearKey: self._warned_unpad = True decrypted_path = path.with_suffix(f".decrypted{path.suffix}") - decrypted_path.write_bytes(decrypted) - - path.unlink() - shutil.move(decrypted_path, path) + try: + decrypted_path.write_bytes(decrypted) + decrypted_path.replace(path) + finally: + with contextlib.suppress(OSError): + decrypted_path.unlink(missing_ok=True) @classmethod def from_m3u_key(cls, m3u_key: Key, session: AnySession | None = None) -> ClearKey: diff --git a/unshackle/core/drm/segment_decrypt.py b/unshackle/core/drm/segment_decrypt.py index ff2109c1..0f5d7c61 100644 --- a/unshackle/core/drm/segment_decrypt.py +++ b/unshackle/core/drm/segment_decrypt.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import os import shutil 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.widevine import Widevine from unshackle.core.remote_protocol import APIErrorCode, coded +from unshackle.core.utils.subprocess import ToolFailed SEGMENT_DRM_T = Widevine | PlayReady | ClearKeyCENC @@ -71,11 +73,13 @@ class SegmentDecrypter: def decrypt_segment(self, segment: Path) -> None: output = segment.with_suffix(segment.suffix + ".dec") + output.unlink(missing_ok=True) try: self.run(["--fragments-info", str(self.init_path), str(segment), str(output)]) os.replace(output, segment) finally: - output.unlink(missing_ok=True) + with contextlib.suppress(OSError): + output.unlink(missing_ok=True) def init_bytes(self) -> 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) 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] try: - subprocess.run( + p = subprocess.run( cmd, check=True, capture_output=True, @@ -121,3 +129,8 @@ class SegmentDecrypter: raise RuntimeError( f"mp4decrypt failed on {args[-2]}: {e.stderr.strip() if e.stderr else f'exit code {e.returncode}'}" ) 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")