forked from kenzuya/unshackle
feat(drm): add the whole-file aes-ctr cipher and paged aac rewrite
This commit is contained in:
@@ -49,7 +49,7 @@ from unshackle.core.dl_options import (
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
forwarded_dl_params,
|
||||
)
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||
from unshackle.core.launch import served_context
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
@@ -4210,6 +4210,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
all_keys: dict[str, dict[str, str]] = {}
|
||||
vault_keys: list[str] = []
|
||||
clear_tracks: list[str] = []
|
||||
file_keys: dict[str, str] = {}
|
||||
drm_types: dict[str, str] = {}
|
||||
keys_by_pssh: dict[tuple, dict[str, str]] = {}
|
||||
shared: dict[str, Any] = {}
|
||||
@@ -4298,7 +4299,15 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
svc_session = getattr(service, "session", None)
|
||||
init_data = fetch_init_segment(track, svc_session)
|
||||
ensure_track_drm(track, svc_session, init_data)
|
||||
if not track.drm or all(isinstance(d, BlowfishStripe) for d in track.drm):
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if not (vault_only or session.server_device):
|
||||
try:
|
||||
file_keys[tid] = cipher.content_key().hex()
|
||||
except (Exception, SystemExit) as e:
|
||||
warn(f"Failed to license track {track_log_label(track)}: {redact_all(str(e))}")
|
||||
continue
|
||||
if not track.drm or all(isinstance(d, WHOLE_FILE_DRM) for d in track.drm):
|
||||
log.info(f"Track {track_log_label(track)} needs no licence, so it has no keys to resolve")
|
||||
clear_tracks.append(tid)
|
||||
continue
|
||||
@@ -4356,6 +4365,8 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
response = LicenseReply(keys=all_keys)
|
||||
if clear_tracks:
|
||||
response["clear_tracks"] = clear_tracks
|
||||
if file_keys:
|
||||
response["file_keys"] = file_keys
|
||||
if vault_keys:
|
||||
response["vault_keys"] = vault_keys
|
||||
if actual_drm_type:
|
||||
@@ -4381,6 +4392,20 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
title = find_title_for_track(track_id, session)
|
||||
service = session.service_instance
|
||||
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
|
||||
if (vault_only or session.server_device) and cipher.key is None:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
|
||||
)
|
||||
try:
|
||||
key = cipher.content_key().hex()
|
||||
except Exception as e:
|
||||
raise APIError(
|
||||
APIErrorCode.SERVICE_ERROR, redact_all(str(e)) or "Could not license the track"
|
||||
) from None
|
||||
return web.json_response(LicenseReply(file_keys={track_id: key}))
|
||||
|
||||
pssh_b64 = data.get("pssh")
|
||||
if pssh_b64 or mode == "server_cdm":
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
|
||||
@@ -5,13 +5,17 @@ from unshackle.core.drm.blowfish_stripe import BlowfishStripe
|
||||
from unshackle.core.drm.cenc import PLACEHOLDER_KIDS
|
||||
from unshackle.core.drm.clearkey import ClearKey
|
||||
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
|
||||
from unshackle.core.drm.clearkey_ctr import ClearKeyCTR, whole_file_cipher
|
||||
from unshackle.core.drm.monalisa import MonaLisa
|
||||
from unshackle.core.drm.paged_aac import PAGED_AAC
|
||||
from unshackle.core.drm.playready import PlayReady
|
||||
from unshackle.core.drm.widevine import Widevine
|
||||
from unshackle.core.vault import is_null_key
|
||||
|
||||
# BlowfishStripe stays out: the licensing paths typed on DRM_T never receive a DRM that needs no licence
|
||||
# BlowfishStripe stays out: it holds its key from the start, so no licensing path receives it
|
||||
DRM_T = ClearKey | ClearKeyCENC | Widevine | PlayReady | MonaLisa
|
||||
# A whole-file cipher has no KID to probe and no fragment to check
|
||||
WHOLE_FILE_DRM = (BlowfishStripe, ClearKeyCTR)
|
||||
|
||||
|
||||
def drop_null_keys(drm: Any) -> None:
|
||||
@@ -38,10 +42,14 @@ __all__ = (
|
||||
"BlowfishStripe",
|
||||
"ClearKey",
|
||||
"ClearKeyCENC",
|
||||
"ClearKeyCTR",
|
||||
"Widevine",
|
||||
"PlayReady",
|
||||
"MonaLisa",
|
||||
"PAGED_AAC",
|
||||
"DRM_T",
|
||||
"WHOLE_FILE_DRM",
|
||||
"whole_file_cipher",
|
||||
"drop_null_keys",
|
||||
"is_null_key",
|
||||
"real_kids",
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from Cryptodome.Cipher import AES
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.drm.paged_aac import PAGED_AAC, cut, to_adts
|
||||
from unshackle.core.utilities import log_event
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ClearKeyCTR:
|
||||
"""AES-128-CTR over a whole file: the service gives the IV and returns the content key through ``licence``.
|
||||
|
||||
The key resolver asks ``licence`` at the licence step of a download or of a `--skip-dl` run, so listing tracks costs no request.
|
||||
A cipher built with ``key`` holds its content key from the start.
|
||||
``magic`` is the signature the decrypted file must start with; a mismatch raises and keeps the input.
|
||||
``skip`` drops that many decrypted bytes from the start of the file: a header that sits in front of the media.
|
||||
``rewrite_paged`` rewrites a decrypted file in the paged AAC container (``PAGED_AAC``).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
licence: Callable[[], bytes | str] | None,
|
||||
iv: bytes | str,
|
||||
magic: bytes | str,
|
||||
skip: int = 0,
|
||||
key: bytes | str | None = None,
|
||||
) -> None:
|
||||
self.iv: bytes = bytes.fromhex(iv) if isinstance(iv, str) else iv
|
||||
self.magic: bytes = bytes.fromhex(magic) if isinstance(magic, str) else magic
|
||||
if len(self.iv) != 16:
|
||||
raise ValueError(f"ClearKeyCTR needs a 16-byte IV, got {len(self.iv)}")
|
||||
if not self.magic:
|
||||
raise ValueError("ClearKeyCTR needs the signature of the decrypted file")
|
||||
if skip < 0:
|
||||
raise ValueError(f"ClearKeyCTR needs a skip of 0 or more, got {skip}")
|
||||
self.licence: Callable[[], bytes | str] | None = licence
|
||||
self.skip: int = skip
|
||||
self.key: bytes | None = None
|
||||
if key is not None:
|
||||
self.take_key(key)
|
||||
|
||||
def take_key(self, key: bytes | str) -> bytes:
|
||||
"""Hold and return a content key: the one the licence callback returned, or one another source licensed."""
|
||||
key = bytes.fromhex(key) if isinstance(key, str) else key
|
||||
if len(key) != 16:
|
||||
raise ValueError(f"ClearKeyCTR needs a 16-byte key, got {len(key)}")
|
||||
self.key = key
|
||||
return key
|
||||
|
||||
def content_key(self) -> bytes:
|
||||
"""The content key, licensed on first use."""
|
||||
if self.key is not None:
|
||||
return self.key
|
||||
if self.licence is None:
|
||||
raise ValueError("ClearKeyCTR holds no content key: none was licensed")
|
||||
return self.take_key(self.licence())
|
||||
|
||||
def decrypt(self, path: Path) -> None:
|
||||
"""Decrypt the file to a new file that then replaces it.
|
||||
|
||||
The dropped header goes through the cipher too, so the keystream stays aligned with the file.
|
||||
"""
|
||||
if not path or not path.exists():
|
||||
raise ValueError("Tried to decrypt a file that does not exist.")
|
||||
key = self.content_key()
|
||||
log_event(
|
||||
"drm_decrypt",
|
||||
level="DEBUG",
|
||||
message=f"Decrypting {path.name} with AES-CTR",
|
||||
drm_type="ClearKeyCTR",
|
||||
file=path.name,
|
||||
)
|
||||
cipher = AES.new(key, AES.MODE_CTR, nonce=b"", initial_value=int.from_bytes(self.iv, "big"))
|
||||
decrypted_path = path.with_suffix(f".decrypted{path.suffix}")
|
||||
try:
|
||||
with path.open("rb") as src, decrypted_path.open("wb") as dst:
|
||||
cipher.decrypt(src.read(self.skip))
|
||||
while chunk := src.read(1 << 20):
|
||||
dst.write(cipher.decrypt(chunk))
|
||||
with decrypted_path.open("rb") as decrypted:
|
||||
start = decrypted.read(len(self.magic))
|
||||
if start != self.magic:
|
||||
raise ValueError(f"Decrypted {path.name} does not start with {self.magic!r}")
|
||||
if self.magic == PAGED_AAC:
|
||||
rewrite_paged(decrypted_path)
|
||||
except BaseException:
|
||||
decrypted_path.unlink(missing_ok=True)
|
||||
raise
|
||||
decrypted_path.replace(path)
|
||||
|
||||
|
||||
def rewrite_paged(path: Path) -> None:
|
||||
"""Replace a decrypted paged AAC file with the M4A file MP4Box makes of it, or with one ADTS stream.
|
||||
|
||||
The M4A file declares HE-AACv2, and its edit list skips the coder delay and ends at the sample count of the header
|
||||
page. Without MP4Box, or when its step fails, the file is one ADTS stream, which declares AAC-LC.
|
||||
"""
|
||||
data = path.read_bytes()
|
||||
stream = to_adts(data)
|
||||
tool, timing = binaries.MP4Box, cut(data)
|
||||
if tool and timing:
|
||||
delay, true, rate = timing
|
||||
adts, output = path.with_suffix(".paged.aac"), path.with_suffix(".paged.m4a")
|
||||
try:
|
||||
adts.write_bytes(stream)
|
||||
run_step(
|
||||
[
|
||||
tool,
|
||||
"-for-test",
|
||||
"--moovts=-1",
|
||||
"-add",
|
||||
f"{adts}:psx",
|
||||
"-edits",
|
||||
f"1=re0-{true}/{rate},{delay}/{rate}",
|
||||
"-new",
|
||||
output,
|
||||
],
|
||||
output=output,
|
||||
label="paged AAC to M4A",
|
||||
)
|
||||
output.replace(path)
|
||||
return
|
||||
except (OSError, RuntimeError) as error:
|
||||
log.warning(f"MP4Box failed on {path.name}, wrote one ADTS stream")
|
||||
log.debug(error)
|
||||
finally:
|
||||
adts.unlink(missing_ok=True)
|
||||
output.unlink(missing_ok=True)
|
||||
if not tool:
|
||||
log.debug(f"MP4Box not found, {path.name} stays one ADTS stream")
|
||||
path.write_bytes(stream)
|
||||
|
||||
|
||||
def whole_file_cipher(track: Any) -> ClearKeyCTR | None:
|
||||
"""The whole-file cipher of a track, with or without a content key."""
|
||||
return next((d for d in getattr(track, "drm", None) or [] if isinstance(d, ClearKeyCTR)), None)
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM
|
||||
from unshackle.core.drm.playready import PlayReady
|
||||
from unshackle.core.drm.widevine import Widevine
|
||||
from unshackle.core.manifests import DASH, ISM
|
||||
@@ -28,14 +29,22 @@ def track_pssh(track: Any, drm_type: str, drm: Any = None) -> str | None:
|
||||
|
||||
|
||||
def fetch_init_segment(track: Any, session: Any = None) -> bytes | None:
|
||||
"""The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails."""
|
||||
"""The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails.
|
||||
|
||||
A track whose DRM is all whole-file ciphers has no KID to read, so its head is not fetched.
|
||||
"""
|
||||
session = getattr(track, "session", None) or session
|
||||
if session is None:
|
||||
return None
|
||||
|
||||
dash = (getattr(track, "data", None) or {}).get("dash") or {}
|
||||
if not all(dash.get(k) is not None for k in ("period", "adaptation_set", "representation", "manifest")):
|
||||
if getattr(track, "descriptor", None) is not Track.Descriptor.URL or not getattr(track, "drm", None):
|
||||
drm = getattr(track, "drm", None)
|
||||
if (
|
||||
getattr(track, "descriptor", None) is not Track.Descriptor.URL
|
||||
or not drm
|
||||
or all(isinstance(d, WHOLE_FILE_DRM) for d in drm)
|
||||
):
|
||||
return None
|
||||
try:
|
||||
return track.get_init_segment(session=session)
|
||||
|
||||
@@ -28,6 +28,7 @@ from unshackle.core.drm import (
|
||||
DRM_T,
|
||||
ClearKey,
|
||||
ClearKeyCENC,
|
||||
ClearKeyCTR,
|
||||
MonaLisa,
|
||||
PlayReady,
|
||||
Widevine,
|
||||
@@ -829,6 +830,16 @@ class ContentKeyResolver:
|
||||
``force`` skips the content keys of earlier tracks in this run. The CDM then licenses
|
||||
again for each KID the DRM holds no content key for.
|
||||
"""
|
||||
if isinstance(drm, ClearKeyCTR):
|
||||
if drm.key is None:
|
||||
with self.LICENCE_LOCK:
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
raise DownloadCancelled()
|
||||
if self.source is None:
|
||||
drm.content_key()
|
||||
else:
|
||||
drm.take_key(self.source.license_file(track))
|
||||
return
|
||||
if not drm:
|
||||
return
|
||||
remote = self.source
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""A decrypted whole file in a paged AAC container: its pages, the ADTS stream that players and FFmpeg read, and the cut of an M4A file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from collections.abc import Iterator
|
||||
from itertools import accumulate
|
||||
|
||||
PAGED_AAC = b"SpAC"
|
||||
HEADER, SHARED = 0x80, 0x01
|
||||
CODER_DELAY = 6081
|
||||
|
||||
|
||||
def checksum(data: bytes) -> int:
|
||||
"""The Fletcher-32 of a page: the sum of its 16-bit little-endian words and of their running sums, both from 0xFFFF."""
|
||||
words = [word for (word,) in struct.iter_unpack("<H", data + b"\0" * (len(data) & 1))]
|
||||
total = (0xFFFF + sum(words)) % 0xFFFF or 0xFFFF
|
||||
running = (0xFFFF * (len(words) + 1) + sum(accumulate(words))) % 0xFFFF or 0xFFFF
|
||||
return running << 16 | total
|
||||
|
||||
|
||||
def first_frame(data: bytes, pos: int) -> tuple[int, int]:
|
||||
"""The number of the first frame of a page and the length of its field: big-endian, with the length in its first byte."""
|
||||
field = data[pos : pos + 5]
|
||||
if len(field) < 2:
|
||||
raise ValueError("The paged file ends inside the number of a page")
|
||||
lead = field[0]
|
||||
if lead < 0x80:
|
||||
size, number = 2, lead
|
||||
elif lead < 0xC0:
|
||||
size, number = 3, lead & 0x3F
|
||||
elif lead < 0xE0:
|
||||
size, number = 4, lead & 0x1F
|
||||
else:
|
||||
size, number = 5, 0
|
||||
if len(field) < size:
|
||||
raise ValueError("The paged file ends inside the number of a page")
|
||||
return number << (8 * (size - 1)) | int.from_bytes(field[1:size], "big"), size
|
||||
|
||||
|
||||
def frame_sizes(table: bytes) -> list[int]:
|
||||
"""The sizes that the lacing table of a page lists: an entry of 255 continues a frame, any other entry ends it."""
|
||||
sizes: list[int] = []
|
||||
pending = 0
|
||||
for entry in table:
|
||||
pending += entry
|
||||
if entry < 255:
|
||||
sizes.append(pending)
|
||||
pending = 0
|
||||
if pending:
|
||||
raise ValueError("A frame of the paged file continues past its page")
|
||||
return sizes
|
||||
|
||||
|
||||
def pages_end(data: bytes, header_end: int, records: list[bytes]) -> int:
|
||||
"""Where the data pages end: the header page plus the byte length that its second record declares.
|
||||
|
||||
The file must hold every page, and only zero bytes may follow the last one.
|
||||
"""
|
||||
record = records[1] if len(records) > 1 else b""
|
||||
if len(record) < 5 or record[0] != 2:
|
||||
raise ValueError("The second record of the header page of the paged file declares no length")
|
||||
end = header_end + struct.unpack("<I", record[-4:])[0]
|
||||
if end > len(data):
|
||||
raise ValueError(f"The paged file is truncated: {len(data)} bytes of {end}")
|
||||
if data[end:].strip(b"\0"):
|
||||
raise ValueError(
|
||||
f"The paged file holds {len(data) - end} bytes that are not zero after its last page at offset {end}"
|
||||
)
|
||||
return end
|
||||
|
||||
|
||||
def pages(data: bytes) -> Iterator[tuple[int, int, list[bytes]]]:
|
||||
"""Yield the flags, the number of the first frame (0 for the header page) and the frames of each page.
|
||||
|
||||
The header page declares the byte length of the data pages: they must end exactly where ``pages_end`` says.
|
||||
A page with unknown flags, a truncated page and a page that fails its checksum raise ``ValueError``.
|
||||
"""
|
||||
pos = 0
|
||||
stop = len(data)
|
||||
while pos < stop:
|
||||
head = data[pos : pos + 6]
|
||||
flags = head[4] if len(head) == 6 else -1
|
||||
if len(head) < 6 or head[:4] != PAGED_AAC or flags & ~(HEADER | SHARED) or bool(flags & HEADER) != (pos == 0):
|
||||
raise ValueError(f"The paged file holds no valid page at offset {pos}")
|
||||
cursor = pos + 6
|
||||
number = 0
|
||||
if not flags & HEADER:
|
||||
number, size = first_frame(data, cursor)
|
||||
cursor += size
|
||||
count = head[5]
|
||||
sizes = frame_sizes(data[cursor : cursor + count])
|
||||
cursor += count
|
||||
shared = data[cursor : cursor + 1] if flags & SHARED else b""
|
||||
cursor += len(shared)
|
||||
end = cursor + sum(sizes) + 4
|
||||
if end > stop:
|
||||
raise ValueError(f"The page at offset {pos} of the paged file runs past the end of the pages")
|
||||
if checksum(data[pos : end - 4]) != int.from_bytes(data[end - 4 : end], "little"):
|
||||
raise ValueError(f"Checksum mismatch on the page at offset {pos} of the paged file")
|
||||
frames: list[bytes] = []
|
||||
for size in sizes:
|
||||
frames.append(shared + data[cursor : cursor + size])
|
||||
cursor += size
|
||||
yield flags, number, frames
|
||||
pos = end
|
||||
if flags & HEADER:
|
||||
stop = pages_end(data, pos, frames)
|
||||
|
||||
|
||||
def cut(data: bytes) -> tuple[int, int, int] | None:
|
||||
"""The cut of the M4A file made from a paged file: the coder delay, the sample count and the rate that its header page names.
|
||||
|
||||
``CODER_DELAY`` is the delay of the HE-AACv2 coder. None unless the audio is HE-AACv2 and the cut fits its samples.
|
||||
"""
|
||||
records = next(pages(data), (0, 0, []))[2]
|
||||
first = records[0] if records else b""
|
||||
second = records[1] if len(records) > 1 else b""
|
||||
if len(first) < 21 or first[20] >> 3 != 29 or len(second) < 108:
|
||||
return None
|
||||
true, rate = struct.unpack_from("<I", first, 6)[0], struct.unpack_from("<H", first, 11)[0]
|
||||
if not 0 < true <= struct.unpack_from("<I", second, 104)[0] - CODER_DELAY or not rate:
|
||||
return None
|
||||
return CODER_DELAY, true, rate
|
||||
|
||||
|
||||
def audio_config(records: list[bytes]) -> tuple[int, int]:
|
||||
"""The sampling rate index and the channel configuration that the first record of the header page names."""
|
||||
record = records[0] if records else b""
|
||||
config = record[20:]
|
||||
length = struct.unpack_from("<H", record, 18)[0] if len(record) >= 20 else -1
|
||||
if record[:6] != b"\x01\x00mp4a" or length != len(config) or length < 3:
|
||||
raise ValueError("The header page of the paged file holds no AudioSpecificConfig")
|
||||
kind, rate, channels = config[0] >> 3, ((config[0] & 7) << 1) | (config[1] >> 7), (config[1] >> 3) & 0xF
|
||||
if kind not in (2, 5, 29) or rate > 12 or not 1 <= channels <= 7:
|
||||
raise ValueError(
|
||||
f"The paged file holds AAC that ADTS cannot carry: object type {kind}, rate index {rate}, {channels} channels"
|
||||
)
|
||||
return rate, channels
|
||||
|
||||
|
||||
def adts_header(size: int, rate: int, channels: int) -> bytes:
|
||||
"""The 7-byte ADTS header of one AAC-LC frame: SBR and PS stay implicit, as ADTS cannot name them."""
|
||||
length = size + 7
|
||||
if length > 0x1FFF:
|
||||
raise ValueError(f"An AAC frame of {size} bytes is too long for ADTS")
|
||||
return bytes(
|
||||
(
|
||||
0xFF,
|
||||
0xF1,
|
||||
1 << 6 | rate << 2 | channels >> 2,
|
||||
(channels & 3) << 6 | length >> 11,
|
||||
length >> 3 & 0xFF,
|
||||
(length & 7) << 5 | 0x1F,
|
||||
0xFC,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def to_adts(data: bytes) -> bytes:
|
||||
"""Return one ADTS stream: a 7-byte header before every AAC frame of the paged file."""
|
||||
out: list[bytes] = []
|
||||
rate = channels = 0
|
||||
expected = 1
|
||||
for flags, number, frames in pages(data):
|
||||
if flags & HEADER:
|
||||
rate, channels = audio_config(frames)
|
||||
continue
|
||||
if number != expected:
|
||||
raise ValueError(
|
||||
f"The page that starts at frame {number} of the paged file is out of sequence: frame {expected} is due"
|
||||
)
|
||||
expected += len(frames)
|
||||
out.extend(adts_header(len(frame), rate, channels) + frame for frame in frames)
|
||||
if expected == 1:
|
||||
raise ValueError("The paged file holds no AAC frame")
|
||||
return b"".join(out)
|
||||
@@ -704,6 +704,10 @@ class ImportService(TitleSource):
|
||||
"""Raise the error that names the KIDs of ``track`` neither the export nor a vault holds."""
|
||||
raise self.missing_key(track)
|
||||
|
||||
def license_file(self, track: AnyTrack) -> str:
|
||||
"""Raise the error that names the track: an export holds no content key of a whole-file cipher."""
|
||||
raise self.missing_key(track)
|
||||
|
||||
def vault_source(self, kid: UUID, key: str) -> None:
|
||||
"""Always None: no server vault serves an import."""
|
||||
return None
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any, BinaryIO
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
@@ -96,7 +96,7 @@ def licensing(ctx: DownloadContext) -> Iterator[None]:
|
||||
|
||||
|
||||
LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = {
|
||||
Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC),
|
||||
Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC, ClearKeyCTR),
|
||||
Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC),
|
||||
Track.Descriptor.HLS: (Widevine, PlayReady, MonaLisa),
|
||||
Track.Descriptor.ISM: (Widevine, PlayReady),
|
||||
|
||||
@@ -201,10 +201,12 @@ class LicenseReply(TypedDict, total=False):
|
||||
|
||||
``keys`` maps KID to content key for one ``track_id``, and track id to that map for ``track_ids``. A capped
|
||||
track gets no content keys: ``capped_tracks`` holds its refusal details, ``reason`` and ``max_height``.
|
||||
``file_keys`` maps track id to the content key the server licensed for a track's whole-file cipher.
|
||||
"""
|
||||
|
||||
license: str | None
|
||||
keys: dict[str, Any]
|
||||
file_keys: dict[str, str]
|
||||
vault_keys: list[str]
|
||||
clear_tracks: list[str]
|
||||
drm_type: str
|
||||
|
||||
@@ -44,7 +44,7 @@ from unshackle.core.console import SyncLive, console
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.dl_options import remote_dl_params
|
||||
from unshackle.core.drm import cbcs, real_kids
|
||||
from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.cenc import drm_stub
|
||||
from unshackle.core.drm.discovery import track_pssh
|
||||
from unshackle.core.launch import launch_keys
|
||||
@@ -1543,6 +1543,7 @@ class RemoteService(TitleSource):
|
||||
track_ids = [self.server_track_id(t.id) for t in keyed]
|
||||
self.drain_server_logs()
|
||||
keys_by_track = resp.get("keys", {})
|
||||
file_keys = resp.get("file_keys", {})
|
||||
clear_tracks = set(resp.get("clear_tracks", []))
|
||||
vault_kids = set(resp.get("vault_keys", []))
|
||||
for track_keys in keys_by_track.values():
|
||||
@@ -1555,6 +1556,11 @@ class RemoteService(TitleSource):
|
||||
|
||||
for track in title.tracks:
|
||||
server_id = self.server_track_id(track.id)
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if server_id in file_keys:
|
||||
cipher.take_key(file_keys[server_id])
|
||||
continue
|
||||
track_keys = keys_by_track.get(server_id, {})
|
||||
if not track_keys:
|
||||
if server_id in track_ids and server_id not in clear_tracks | set(capped):
|
||||
@@ -1761,6 +1767,33 @@ class RemoteService(TitleSource):
|
||||
self.license_locally(track, resp.get("details") or {})
|
||||
return None
|
||||
|
||||
def license_file(self, track: AnyTrack) -> str:
|
||||
"""The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException."""
|
||||
if self.local_vaults_only or not self._server_cdm:
|
||||
raise coded(
|
||||
click.ClickException(f"Track {track.id} needs a server licence that this session does not allow"),
|
||||
APIErrorCode.DRM_ERROR,
|
||||
)
|
||||
try:
|
||||
with quiet():
|
||||
resp = self.session_call(
|
||||
lambda sid: self.client.post(
|
||||
LICENSE_ROUTE.format(session_id=sid),
|
||||
LicenseRequest(
|
||||
mode="server_cdm", drm_type="clearkeyctr", track_id=self.server_track_id(track.id)
|
||||
),
|
||||
)
|
||||
)
|
||||
except RemoteError as e:
|
||||
raise coded(click.ClickException(e.message), APIErrorCode.DRM_ERROR) from None
|
||||
finally:
|
||||
self.drain_server_logs()
|
||||
if not (key := (resp.get("file_keys") or {}).get(self.server_track_id(track.id))):
|
||||
raise coded(
|
||||
click.ClickException(f"The server sent no content key for track {track.id}"), APIErrorCode.DRM_ERROR
|
||||
)
|
||||
return str(key)
|
||||
|
||||
def proxy_license(self, challenge: bytes | str, track: AnyTrack, drm_type: str) -> bytes:
|
||||
"""Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it."""
|
||||
if isinstance(challenge, str):
|
||||
|
||||
@@ -83,6 +83,9 @@ class ServerKeySource(Protocol):
|
||||
raises ClickException.
|
||||
"""
|
||||
|
||||
def license_file(self, track: AnyTrack) -> str:
|
||||
"""The content key the server licenses for the whole-file cipher of ``track``; a refusal raises."""
|
||||
|
||||
def vault_source(self, kid: UUID, key: str) -> Vault | None:
|
||||
"""The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check."""
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
from unshackle.core.downloaders.requests import requests
|
||||
from unshackle.core.drm import DRM_T, BlowfishStripe, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, PlayReady, Widevine
|
||||
from unshackle.core.drm.cenc import cenc_key, init_kid
|
||||
from unshackle.core.drm.verify import (
|
||||
children,
|
||||
@@ -824,6 +824,7 @@ class Track:
|
||||
DOWNLOAD_ALL_DRM.is_set()
|
||||
and track_type in ("Video", "Audio")
|
||||
and not {Widevine, PlayReady} <= {type(d) for d in self.drm or []}
|
||||
and all(type(d) in (Widevine, PlayReady) for d in self.drm or [])
|
||||
):
|
||||
self.add_init_drm(self.get_init_segment(session=session), cdm)
|
||||
elif not self.drm and track_type in ("Video", "Audio"):
|
||||
@@ -831,7 +832,7 @@ class Track:
|
||||
|
||||
if self.drm:
|
||||
drm = self.get_drm_for_cdm(cdm)
|
||||
track_kid = None if isinstance(drm, BlowfishStripe) else self.get_key_id(session=session)
|
||||
track_kid = None if isinstance(drm, WHOLE_FILE_DRM) else self.get_key_id(session=session)
|
||||
license_drm(self, drm, ctx, track_kid)
|
||||
else:
|
||||
drm = None
|
||||
@@ -882,7 +883,7 @@ class Track:
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid, track=self)
|
||||
if not isinstance(drm, BlowfishStripe):
|
||||
if not isinstance(drm, WHOLE_FILE_DRM):
|
||||
assert_fragments_decrypted(save_path)
|
||||
self.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None)
|
||||
|
||||
+11
-3
@@ -28,7 +28,7 @@ from pywidevine.pssh import PSSH as WidevinePSSH
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
|
||||
from unshackle.core.titles import Episode, Movie, Song, Title_T
|
||||
from unshackle.core.titles.availability import availability_metadata
|
||||
from unshackle.core.titles.music import MUSIC_DATA_KEYS, SONG_FIELDS, song_metadata
|
||||
@@ -309,8 +309,10 @@ def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
|
||||
drm_info = {}
|
||||
drm_class = drm.__class__.__name__
|
||||
drm_info["type"] = drm_class.lower()
|
||||
if isinstance(drm, BlowfishStripe):
|
||||
if isinstance(drm, WHOLE_FILE_DRM) and drm.key is not None:
|
||||
drm_info["key"] = drm.key.hex()
|
||||
if isinstance(drm, ClearKeyCTR):
|
||||
drm_info.update(iv=drm.iv.hex(), magic=drm.magic.hex(), skip=drm.skip)
|
||||
|
||||
# pywidevine exposes dumps(); pyplayready's PSSH does not, so PlayReady falls back
|
||||
# to the base64 it was built from. Without it the client drops every PlayReady
|
||||
@@ -355,11 +357,17 @@ def reconstruct_drm(drm_list: list | None) -> list:
|
||||
for drm_info in drm_list:
|
||||
drm_type = drm_info.get("type", "")
|
||||
pssh_str = drm_info.get("pssh")
|
||||
if not pssh_str and drm_type != "blowfishstripe":
|
||||
if not pssh_str and drm_type not in ("blowfishstripe", "clearkeyctr"):
|
||||
continue
|
||||
try:
|
||||
if drm_type == "blowfishstripe":
|
||||
result.append(BlowfishStripe(drm_info["key"]))
|
||||
elif drm_type == "clearkeyctr":
|
||||
result.append(
|
||||
ClearKeyCTR(
|
||||
None, drm_info["iv"], drm_info["magic"], drm_info.get("skip", 0), key=drm_info.get("key")
|
||||
)
|
||||
)
|
||||
elif drm_type in ("widevine", "playready"):
|
||||
result.append(pssh_drm(drm_type, pssh_str, drm_info.get("kids")))
|
||||
# a dropped entry can leave the track with no DRM, so never skip silently
|
||||
|
||||
Reference in New Issue
Block a user