forked from kenzuya/unshackle
fix(drm): keep the input when a cbcs, ClearKey, stripe or segment decrypt fails
This commit is contained in:
@@ -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",)
|
||||
|
||||
+26
-22
@@ -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(
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user