forked from kenzuya/unshackle
fix(vaults): stop false bad-key flags from a failed decode check
Judge a vault KID only on a file whose KID map holds it, tell remote vaults of a bad pair only once another key replaces it, and let the server CDM unflag a pair it returns; the server never flags a CDM-licensed pair. Log FFmpeg stderr on a failed check and name the missing CDM when none is set.
This commit is contained in:
@@ -4928,11 +4928,12 @@ CACHED_PAIRS: set[tuple[str, str, str]] = set()
|
||||
|
||||
|
||||
def cache_to_vaults(keys: Dict[str, str], service_name: str) -> None:
|
||||
"""Cache newly obtained keys to server vaults.
|
||||
"""Cache the content keys of a CDM licence to the server vaults.
|
||||
|
||||
A PlayReady licence always runs, and a Widevine licence runs when one PSSH KID has no content
|
||||
key in a vault, so the same content keys come back on every request for a title. This process
|
||||
does not send a pair again after every vault accepted it.
|
||||
does not send a pair again after every vault accepted it. A pair a client reported as bad
|
||||
leaves that set, and is unflagged when the CDM returns it.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
@@ -4945,6 +4946,8 @@ def cache_to_vaults(keys: Dict[str, str], service_name: str) -> None:
|
||||
return
|
||||
|
||||
key_map = {UUID(hex=kid): key for kid, key in new.items()}
|
||||
for kid in vaults.clear_licensed_flags(key_map):
|
||||
log.info(f"Unflagged {kid.hex}:{key_map[kid]}, the CDM returned it")
|
||||
cached = vaults.add_keys(key_map)
|
||||
if cached == len([vault for vault in vaults.vaults if not vault.no_push]):
|
||||
CACHED_PAIRS.update((service_name, kid, key) for kid, key in new.items())
|
||||
@@ -5617,7 +5620,8 @@ async def session_bad_key_handler(
|
||||
|
||||
The server never sees a segment, so the client is the only side that can test a content key.
|
||||
Only a pair this remote session served can be flagged, which keeps a client from
|
||||
poisoning the bad-key table for content keys it never received.
|
||||
poisoning the bad-key table for content keys it never received. A pair the CDM licensed is
|
||||
not flagged, because the CDM is the authority.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
@@ -5630,8 +5634,12 @@ async def session_bad_key_handler(
|
||||
if not key or served_key.lower() != key:
|
||||
log.warning(f"Session {sanitize_log(session_id[:12])} reported a bad content key it was never served: {kid}")
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "This session was not served that KID:KEY pair")
|
||||
if source == "cdm":
|
||||
log.warning(f"Session {sanitize_log(session_id[:12])} reported a CDM key as bad, not flagged: {kid}")
|
||||
return web.json_response({"flagged": False})
|
||||
|
||||
vaults = load_server_vaults(session.service_instance.__class__.__name__)
|
||||
service_name = session.service_instance.__class__.__name__
|
||||
vaults = load_server_vaults(service_name)
|
||||
|
||||
def flag() -> None:
|
||||
for vault in vaults.vaults:
|
||||
@@ -5644,6 +5652,7 @@ async def session_bad_key_handler(
|
||||
|
||||
await asyncio.to_thread(flag)
|
||||
session.served_keys.pop(kid, None)
|
||||
CACHED_PAIRS.discard((service_name, kid, served_key))
|
||||
log.warning(
|
||||
f"Client proved {kid}:{served_key} from vault {sanitize_log(source)} wrong, flagged in the server vaults"
|
||||
)
|
||||
|
||||
@@ -2421,7 +2421,7 @@ async def session_bad_key(request: web.Request) -> web.Response:
|
||||
description: Content key as hex
|
||||
responses:
|
||||
'200':
|
||||
description: The pair is flagged
|
||||
description: "flagged true when the pair is flagged; false when the CDM licensed it"
|
||||
'400':
|
||||
description: The remote session was not served that pair
|
||||
'404':
|
||||
|
||||
@@ -1045,9 +1045,11 @@ class ServerVault(Vault):
|
||||
``decrypt_verified`` needs a Vault to hold in ``Vaults.sources`` so a server-supplied
|
||||
content key gets the same decode check as a local vault key. The client never learns
|
||||
which server vault answered and can neither read nor write it, so every method returns
|
||||
nothing and a bad verdict goes to the server, which flags the row itself.
|
||||
nothing. A bad verdict goes to the server at once, so its next licence skips the pair.
|
||||
"""
|
||||
|
||||
report_now = True
|
||||
|
||||
def __init__(self, service: "RemoteService"):
|
||||
super().__init__("server_cdm", no_push=True)
|
||||
self.service = service
|
||||
@@ -1067,8 +1069,8 @@ class ServerVault(Vault):
|
||||
def get_services(self) -> Iterator[str]:
|
||||
return iter(())
|
||||
|
||||
def report_bad(self, kid: UUID, key: str) -> None:
|
||||
self.service.report_bad_key(kid, key)
|
||||
def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
|
||||
self.service.report_bad_key(UUID(str(kid)), key)
|
||||
|
||||
|
||||
class RemoteService:
|
||||
|
||||
@@ -131,6 +131,7 @@ def ffmpeg_decodes(path: Path, start: Optional[float] = None, seconds: float = 3
|
||||
return True
|
||||
if not keyframes and video is not False and any(m in err for m in FFMPEG_MISSING_REFERENCE):
|
||||
return decode(window, keyframes=True)
|
||||
log_tool_run("FFmpeg decode check", ffmpeg, ff.returncode, window=window, stderr=ff.stderr[-2000:])
|
||||
return False
|
||||
|
||||
tail = ["-sseof", f"-{FFMPEG_CHECK_TAIL}", "-t", str(FFMPEG_CHECK_TAIL)]
|
||||
|
||||
@@ -51,6 +51,7 @@ def vault_session(timeout: float) -> Session:
|
||||
class Vault(metaclass=ABCMeta):
|
||||
# a vault on this machine; Vaults.get_key tries these first, before the network ones
|
||||
local: bool = False
|
||||
report_now: bool = False
|
||||
|
||||
def __init__(self, name: str, no_push: bool = False):
|
||||
self.name = name
|
||||
|
||||
+34
-13
@@ -30,6 +30,7 @@ class Vaults:
|
||||
self.candidates: dict[Union[UUID, str], list[tuple[str, Vault]]] = {}
|
||||
self.warned: set[tuple[str, Union[UUID, str], str]] = set()
|
||||
self.unreachable: set[Vault] = set()
|
||||
self.unreported: dict[tuple[Union[UUID, str], str], Vault] = {}
|
||||
|
||||
def __iter__(self) -> Iterator[Vault]:
|
||||
return iter(self.vaults)
|
||||
@@ -153,22 +154,42 @@ 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, naming the Vault it came from.
|
||||
|
||||
Every local vault records it. A remote vault is told only when it served the pair,
|
||||
so it stops serving it too, and a vault that never held it is not bothered. A vault
|
||||
that cannot take the flag is skipped with a debug line: the local flag already
|
||||
protects this run, and a vault without the route is not a fault.
|
||||
"""
|
||||
"""Flag a KID:KEY in every local vault. A failed decode is no proof, so the remote vault that
|
||||
served it hears of it from ``report_replaced``, or at once when it sets ``report_now``."""
|
||||
self.flagged.add((kid, key))
|
||||
source = self.sources.pop(kid, None)
|
||||
name = source[1].name if source else "unknown"
|
||||
for vault in self.live():
|
||||
if not vault.local and (source is None or vault is not source[1]):
|
||||
continue
|
||||
try:
|
||||
vault.flag_bad_key(self.service, kid, key, source[1].name if source else "unknown")
|
||||
except Exception as e:
|
||||
log.debug(f"Could not flag {key} as bad in Vault '{vault.name}': {e!r}")
|
||||
if vault.local:
|
||||
self.tell(vault, kid, key, name)
|
||||
if source and not source[1].local:
|
||||
if source[1].report_now:
|
||||
self.tell(source[1], kid, key, name)
|
||||
else:
|
||||
self.unreported[kid, key] = source[1]
|
||||
|
||||
def report_replaced(self, content_keys: dict[Union[UUID, str], str]) -> None:
|
||||
"""Tell each remote vault about its flagged pair once ``content_keys`` holds another key for the KID."""
|
||||
live = self.live()
|
||||
for (kid, key), vault in list(self.unreported.items()):
|
||||
if content_keys.get(kid) not in (None, key):
|
||||
del self.unreported[kid, key]
|
||||
if vault in live:
|
||||
self.tell(vault, kid, key, vault.name)
|
||||
|
||||
def tell(self, vault: Vault, kid: Union[UUID, str], key: str, source: str) -> None:
|
||||
"""Flag one pair in one vault; a failure is only a debug line."""
|
||||
try:
|
||||
vault.flag_bad_key(self.service, kid, key, source)
|
||||
except Exception as e:
|
||||
log.debug(f"Could not flag {key} as bad in Vault '{vault.name}': {e!r}")
|
||||
|
||||
def clear_licensed_flags(self, content_keys: dict[UUID, str]) -> list[UUID]:
|
||||
"""Unflag each pair a licence returned, since the decode check was wrong. Returns their KIDs."""
|
||||
cleared = [kid for kid, key in content_keys.items() if self.is_flagged(kid, key)]
|
||||
for kid in cleared:
|
||||
self.unflag_bad_key(kid, content_keys[kid])
|
||||
return cleared
|
||||
|
||||
def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
|
||||
"""Remove a flag from every Vault."""
|
||||
|
||||
Reference in New Issue
Block a user