forked from kenzuya/unshackle
feat(vaults): flag and skip wrong content keys from poisoned vaults
Verify a vault-sourced key with an FFmpeg decode after decryption. On failure flag the KID:KEY locally with its source, restore the ciphertext, and retry through the remaining vaults and then the CDM.
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
from uuid import UUID
|
||||
|
||||
DECRYPT_HOOK: Optional[Callable[..., None]] = None
|
||||
|
||||
|
||||
def decrypt_track(
|
||||
drm: Any,
|
||||
path: Path,
|
||||
licence: Optional[Callable] = None,
|
||||
track_kid: Optional[UUID] = None,
|
||||
decrypt: bool = True,
|
||||
) -> None:
|
||||
"""Decrypt ``path`` with ``drm`` through the installed hook, or directly when there is none.
|
||||
|
||||
``decrypt=False`` means the downloader already decrypted the segments in place; the hook
|
||||
then only checks the result, because there is no ciphertext left to retry with.
|
||||
"""
|
||||
if DECRYPT_HOOK:
|
||||
DECRYPT_HOOK(drm, path, licence, track_kid, decrypt)
|
||||
elif decrypt:
|
||||
drm.decrypt(path)
|
||||
@@ -27,6 +27,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
|
||||
@@ -643,8 +644,7 @@ class DASH:
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
if not decrypter:
|
||||
drm.decrypt(save_path)
|
||||
decrypt_track(drm, save_path, license_widevine, decrypt=not decrypter)
|
||||
assert_fragments_decrypted(save_path)
|
||||
track.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
|
||||
|
||||
@@ -32,6 +32,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetResponse, RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
|
||||
@@ -965,8 +966,7 @@ class HLS:
|
||||
decrypted_init = segment_decrypter.finish()
|
||||
map_data = (map_data[0], decrypted_init)
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=True)
|
||||
if not segment_decrypter:
|
||||
drm.decrypt(merged_path)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter)
|
||||
assert_fragments_decrypted(merged_path)
|
||||
merged_path.rename(decrypted_path)
|
||||
else:
|
||||
|
||||
@@ -20,6 +20,7 @@ from requests import Session
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.manifests.ism_init import (
|
||||
build_init_segment,
|
||||
@@ -574,7 +575,7 @@ class ISM:
|
||||
|
||||
if session_drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
session_drm.decrypt(save_path)
|
||||
decrypt_track(session_drm, save_path, license_widevine)
|
||||
assert_fragments_decrypted(save_path)
|
||||
track.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=session_drm, segment=None)
|
||||
|
||||
@@ -24,6 +24,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
from unshackle.core.downloaders import requests
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import resume
|
||||
@@ -717,7 +718,7 @@ class Track:
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
drm.decrypt(save_path)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid)
|
||||
assert_fragments_decrypted(save_path)
|
||||
self.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None)
|
||||
|
||||
@@ -40,6 +40,42 @@ def log_tool_run(
|
||||
)
|
||||
|
||||
|
||||
def ffmpeg_decodes(path: Path, seconds: int = 3) -> bool:
|
||||
"""Return True when FFmpeg decodes the first seconds of the file without an error.
|
||||
|
||||
A wrong content key leaves the container intact and the samples as noise, which the
|
||||
decoders reject. ``-xerror`` stops at the first error so the check stays short.
|
||||
A file this FFmpeg build cannot judge counts as a pass, never as a wrong key.
|
||||
"""
|
||||
if not binaries.FFMPEG:
|
||||
raise EnvironmentError('FFmpeg executable "ffmpeg" not found but is required.')
|
||||
args: list[str] = [
|
||||
str(binaries.FFMPEG),
|
||||
"-nostdin",
|
||||
"-v",
|
||||
"error",
|
||||
"-err_detect",
|
||||
"explode",
|
||||
"-xerror",
|
||||
"-i",
|
||||
str(path),
|
||||
"-t",
|
||||
str(seconds),
|
||||
"-f",
|
||||
"null",
|
||||
"-",
|
||||
]
|
||||
ff = subprocess.run(args, capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
if ff.returncode == 0:
|
||||
return True
|
||||
err = ff.stderr.lower()
|
||||
if any(
|
||||
m in err for m in ("not found for", "no decoder found", "sub-sample encryption info", "error reading header")
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def ffprobe(uri: Union[bytes, Path]) -> dict:
|
||||
"""Use FFprobe on the provided data to get its track information (``-show_streams``)."""
|
||||
if not binaries.FFProbe:
|
||||
|
||||
@@ -53,5 +53,15 @@ class Vault(metaclass=ABCMeta):
|
||||
get_key/get_keys/add_key/add_keys reaches the namespace it came from.
|
||||
"""
|
||||
|
||||
def is_bad_key(self, kid: Union[UUID, str], key: str) -> bool:
|
||||
"""Return True if this Vault has flagged the KID:KEY as wrong."""
|
||||
return False
|
||||
|
||||
def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
|
||||
"""Remember a KID:KEY that failed decryption and where it came from."""
|
||||
|
||||
def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
|
||||
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
|
||||
|
||||
|
||||
__all__ = ("Vault",)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import inspect
|
||||
import logging
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
||||
from functools import partial
|
||||
from typing import Any, Iterator, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
@@ -24,6 +25,9 @@ class Vaults:
|
||||
def __init__(self, service: Optional[str] = None):
|
||||
self.service = service or ""
|
||||
self.vaults = []
|
||||
self.sources: dict[Union[UUID, str], tuple[str, Vault]] = {}
|
||||
self.flagged: set[tuple[Union[UUID, str], str]] = set()
|
||||
self.candidates: dict[Union[UUID, str], list[tuple[str, Vault]]] = {}
|
||||
|
||||
def __iter__(self) -> Iterator[Vault]:
|
||||
return iter(self.vaults)
|
||||
@@ -60,30 +64,56 @@ class Vaults:
|
||||
"""Get Key from the first Vault it can by KID (Key ID) and Service.
|
||||
|
||||
Local vaults go first, one at a time: a hit there costs nothing and skips the network.
|
||||
The remaining vaults run at the same time, and the first one with the content key wins.
|
||||
A remote answer kept from an earlier call comes next, so a retry after a flagged pair
|
||||
reuses it instead of querying again. The remaining vaults then run at the same time,
|
||||
and the first one with the content key wins.
|
||||
"""
|
||||
local = [v for v in self.vaults if v.local]
|
||||
remote = [v for v in self.vaults if not v.local]
|
||||
for vault in local:
|
||||
key = self.query_vault(vault, kid)
|
||||
if key:
|
||||
self.sources[kid] = (key, vault)
|
||||
return key, vault
|
||||
for key, vault in self.candidates.get(kid, []):
|
||||
if not self.is_flagged(kid, key):
|
||||
self.sources[kid] = (key, vault)
|
||||
return key, vault
|
||||
if not remote:
|
||||
return None, None
|
||||
pool = ThreadPoolExecutor(len(remote))
|
||||
try:
|
||||
futures = {pool.submit(self.query_vault, vault, kid): vault for vault in remote}
|
||||
for future, vault in futures.items():
|
||||
future.add_done_callback(partial(self.remember_candidate, kid, vault))
|
||||
for future in as_completed(futures):
|
||||
key = future.result()
|
||||
if key:
|
||||
self.sources[kid] = (key, futures[future])
|
||||
return key, futures[future]
|
||||
return None, None
|
||||
finally:
|
||||
# a slow vault must not hold up a content key another vault already returned
|
||||
# a slow vault must not hold up a content key another vault already returned; the
|
||||
# ones already running still finish and land in candidates through the callback
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
def remember_candidate(self, kid: Union[UUID, str], vault: Vault, future: Future) -> None:
|
||||
"""Keep a remote answer for a later retry. Cancelled or failed queries leave nothing."""
|
||||
if future.cancelled() or future.exception():
|
||||
return
|
||||
key = future.result()
|
||||
if key and (key, vault) not in self.candidates.setdefault(kid, []):
|
||||
self.candidates[kid].append((key, vault))
|
||||
|
||||
def is_flagged(self, kid: Union[UUID, str], key: str) -> bool:
|
||||
"""True when a local vault has flagged the KID:KEY as wrong."""
|
||||
return any(v.is_bad_key(kid, key) for v in self.vaults if v.local)
|
||||
|
||||
def query_vault(self, vault: Vault, kid: Union[UUID, str]) -> Optional[str]:
|
||||
"""Ask one vault for a content key. A failure logs a warning and returns None."""
|
||||
"""Ask one vault for a content key. A failure logs a warning and returns None.
|
||||
|
||||
A flagged pair counts as no content key, so no vault can serve one again.
|
||||
"""
|
||||
dl = get_debug_logger()
|
||||
start = time.monotonic()
|
||||
try:
|
||||
@@ -103,6 +133,9 @@ class Vaults:
|
||||
)
|
||||
return None
|
||||
found = bool(key and key.count("0") != len(key))
|
||||
if found and key and self.is_flagged(kid, key):
|
||||
log.warning(f"{key} from {vault.name} is flagged bad, skipping")
|
||||
found = False
|
||||
if dl:
|
||||
dl.log_vault_query(
|
||||
vault.name,
|
||||
@@ -114,6 +147,21 @@ class Vaults:
|
||||
)
|
||||
return key if found else None
|
||||
|
||||
def flag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
|
||||
"""Flag a KID:KEY that failed decryption in every local Vault, naming the Vault it came from."""
|
||||
self.flagged.add((kid, key))
|
||||
source = self.sources.pop(kid, None)
|
||||
for vault in self.vaults:
|
||||
if vault.local:
|
||||
vault.flag_bad_key(self.service, kid, key, source[1].name if source else "unknown")
|
||||
|
||||
def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
|
||||
"""Remove a flag from every local Vault."""
|
||||
self.flagged.discard((kid, key))
|
||||
for vault in self.vaults:
|
||||
if vault.local:
|
||||
vault.unflag_bad_key(kid, key)
|
||||
|
||||
def add_key(self, kid: Union[UUID, str], key: str, excluding: Optional[Vault] = None) -> int:
|
||||
"""Add a KID:KEY to all Vaults, optionally with an exclusion.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user