mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
add(drm): Added Custom DRM Feature
- Added CDM Loader for Custom DRM - Added Service Unit API handling for custom DRM - Improvement of Versatility - Improved compatibility for remote services
This commit is contained in:
@@ -30,7 +30,7 @@ from rich.table import Table
|
||||
|
||||
from unshackle.core import binaries, login, process_exit
|
||||
from unshackle.core.cdm.choice import choose_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_custom_cdm, is_playready_cdm, is_remote_cdm
|
||||
from unshackle.core.config import (
|
||||
cdm_entry_names_device,
|
||||
check_filename_replacements,
|
||||
@@ -58,7 +58,7 @@ from unshackle.core.downloaders import (
|
||||
)
|
||||
from unshackle.core.drm import (
|
||||
WHOLE_FILE_DRM,
|
||||
MonaLisa,
|
||||
CustomDRM,
|
||||
verify,
|
||||
)
|
||||
from unshackle.core.drm.discovery import fairplay_only
|
||||
@@ -292,8 +292,15 @@ def take_unmuxable_audio(tracks: Tracks) -> list[Audio]:
|
||||
|
||||
def cdm_summary(cdm: Any) -> dict[str, Any]:
|
||||
"""The loaded CDM's DRM system, whether it is remote, its device and its security level, for the load log."""
|
||||
drm_type = "PlayReady" if is_playready_cdm(cdm) else "Widevine"
|
||||
remote = is_remote_cdm(cdm)
|
||||
if is_custom_cdm(cdm):
|
||||
return {
|
||||
"drm_type": getattr(cdm, "drm_type", "Custom"),
|
||||
"remote": remote,
|
||||
"device": getattr(cdm, "device", "None"),
|
||||
"security_level": getattr(cdm, "security_level", None),
|
||||
}
|
||||
drm_type = "PlayReady" if is_playready_cdm(cdm) else "Widevine"
|
||||
if remote:
|
||||
device = getattr(cdm, "label", None) or cdm.device_name
|
||||
elif drm_type == "Widevine":
|
||||
@@ -1350,6 +1357,8 @@ class dl:
|
||||
self.log.info(f"Using profile: '{self.profile}'")
|
||||
|
||||
self.is_remote = bool(ctx.params.get("remote"))
|
||||
self.remote_server = ctx.params.get("server")
|
||||
self.is_import = Services.is_import(ctx)
|
||||
|
||||
with console.status("Loading Service Config...", spinner="dots"):
|
||||
self.service_config = load_service_config(self.service, local=not self.is_remote)
|
||||
@@ -1435,9 +1444,8 @@ class dl:
|
||||
if self.cdm:
|
||||
cdm_info = cdm_summary(self.cdm)
|
||||
where = " Remote" if cdm_info["remote"] else ""
|
||||
self.log.info(
|
||||
f"Loaded {cdm_info['drm_type']}{where} CDM: {cdm_info['device']} (L{cdm_info['security_level']})"
|
||||
)
|
||||
level = f" (L{cdm_info['security_level']})" if cdm_info["security_level"] is not None else ""
|
||||
self.log.info(f"Loaded {cdm_info['drm_type']}{where} CDM: {cdm_info['device']}{level}")
|
||||
log_event("load_cdm", level="INFO", service=self.service, context={"cdm": cdm_info})
|
||||
|
||||
if ctx.params.get("local_proxy"):
|
||||
@@ -2271,11 +2279,12 @@ class dl:
|
||||
server_cdm_type = None
|
||||
if self._remote_service and self._remote_service.key_arrival.needs_no_cdm:
|
||||
server_cdm_type = self._remote_service.server_cdm_type
|
||||
if not is_custom_cdm(self.cdm):
|
||||
self.cdm = cdm_type_stub(server_cdm_type)
|
||||
if self._remote_service.key_arrival is KeyArrival.EXPORT:
|
||||
self.log.info("Using keys from the export; no CDM required")
|
||||
elif (keyed := [*title.tracks.videos, *title.tracks.audio]) and all(
|
||||
track.drm and all(isinstance(drm, (*WHOLE_FILE_DRM, MonaLisa)) for drm in track.drm)
|
||||
track.drm and all(isinstance(drm, (*WHOLE_FILE_DRM, CustomDRM)) for drm in track.drm)
|
||||
for track in keyed
|
||||
):
|
||||
self.log.info("Using keys from the server; no local CDM required")
|
||||
@@ -2543,8 +2552,8 @@ class dl:
|
||||
drm = track.get_drm_for_cdm(self.cdm)
|
||||
if drm and hasattr(drm, "decrypt"):
|
||||
self.keys.decrypt_verified(drm, track.path, prepare_drm_for(track), track=track)
|
||||
if not isinstance(drm, MonaLisa):
|
||||
# MonaLisa decrypts per segment; its decrypt() here is a no-op
|
||||
if not isinstance(drm, CustomDRM):
|
||||
# CustomDRM may decrypt per segment; its decrypt() here is a no-op
|
||||
assert_fragments_decrypted(track.path)
|
||||
has_decrypted = True
|
||||
events.emit(events.Types.TRACK_REPACKED, track=track)
|
||||
@@ -2947,9 +2956,39 @@ class dl:
|
||||
"""
|
||||
# A per-request override (set by the REST API per job) takes precedence over the
|
||||
# global config, so a job can select a specific CDM device without mutating shared state.
|
||||
if not drm and not quality:
|
||||
if getattr(self, "is_remote", False):
|
||||
from unshackle.core.cdm.loader import CustomCDM
|
||||
from unshackle.core.remote_service import find_remote_service, remote_service_list
|
||||
|
||||
remote_services = remote_service_list(getattr(self, "remote_server", None))
|
||||
if remote_services:
|
||||
svc_info = find_remote_service(remote_services, service)
|
||||
custom_info = svc_info.get("custom_cdm") if isinstance(svc_info, dict) else None
|
||||
if isinstance(custom_info, dict):
|
||||
return CustomCDM(
|
||||
drm_type=str(custom_info.get("drm_type") or "Custom"),
|
||||
device=str(custom_info.get("device") or "None"),
|
||||
is_remote_cdm=True,
|
||||
)
|
||||
elif not getattr(self, "is_import", False):
|
||||
from unshackle.core.cdm.loader import load_custom_cdm
|
||||
from unshackle.core.services import ensure_loaded
|
||||
|
||||
service_cls = ensure_loaded(service)
|
||||
if service_cls is not None:
|
||||
custom_cdm = load_custom_cdm(service_cls, service, getattr(self, "cdm_override", None))
|
||||
if custom_cdm is not None:
|
||||
return custom_cdm
|
||||
|
||||
cdm_name = resolve_cdm_name(config.cdm, service, getattr(self, "cdm_override", None))
|
||||
if not cdm_name:
|
||||
return None
|
||||
if isinstance(cdm_name, str):
|
||||
from unshackle.core.cdm.loader import find_device
|
||||
|
||||
if find_device(cdm_name) is None and Path(cdm_name).is_file():
|
||||
return None
|
||||
|
||||
if isinstance(cdm_name, dict):
|
||||
if quality:
|
||||
|
||||
@@ -55,7 +55,7 @@ from unshackle.core.cdm.detect import cdm_type_stub
|
||||
from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.drm import cbcs, monalisa_drm, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm import cbcs, custom_drm, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import ensure_track_drm
|
||||
from unshackle.core.launch import LaunchKeys, served_context
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
@@ -147,10 +147,17 @@ def load_full_cdm(service: str, profile: str | None, cdm_type: str | None = None
|
||||
view from :meth:`KeyPolicy.cdm_config`; None reads the server's own ``cdm``.
|
||||
"""
|
||||
from unshackle.core.cdm import load_cdm
|
||||
from unshackle.core.cdm.loader import load_custom_cdm
|
||||
from unshackle.core.services import ensure_loaded
|
||||
|
||||
app_config = app_config or config
|
||||
if not isinstance(cdm_type, str):
|
||||
cdm_type = None
|
||||
service_cls = ensure_loaded(service)
|
||||
if service_cls is not None:
|
||||
custom_cdm = load_custom_cdm(service_cls, service, app_config=app_config)
|
||||
if custom_cdm is not None:
|
||||
return custom_cdm
|
||||
cdm_name = choose_cdm(app_config.cdm, service, profile, cdm_type).name
|
||||
|
||||
if not cdm_name:
|
||||
@@ -3793,13 +3800,13 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
title = server_keys.find_title_for_track(track_id, session)
|
||||
service = session.service_instance
|
||||
|
||||
monalisa = monalisa_drm(track)
|
||||
if monalisa is not None and mode == "server_cdm":
|
||||
custom = custom_drm(track)
|
||||
if custom is not None and mode == "server_cdm":
|
||||
if vault_only:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
|
||||
)
|
||||
return web.json_response(LicenseReply(keys=server_keys.served_monalisa_keys(session, monalisa)))
|
||||
return web.json_response(LicenseReply(keys=server_keys.served_custom_keys(session, custom)))
|
||||
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
|
||||
|
||||
@@ -439,9 +439,20 @@ def service_details(tag: str) -> dict[str, Any]:
|
||||
service_data["has_drm"] = (
|
||||
getattr(service_module, "get_widevine_license", None) is not _BaseService.get_widevine_license
|
||||
or getattr(service_module, "get_playready_license", None) is not _BaseService.get_playready_license
|
||||
or getattr(service_module, "get_custom_drm_license", None) is not _BaseService.get_custom_drm_license
|
||||
or hasattr(service_module, "get_fairplay_bridge_license")
|
||||
)
|
||||
|
||||
from unshackle.core.cdm.loader import get_service_custom_cdm
|
||||
|
||||
custom_cdm_spec = get_service_custom_cdm(service_module)
|
||||
if custom_cdm_spec:
|
||||
default_path = custom_cdm_spec.get("default_path")
|
||||
service_data["custom_cdm"] = {
|
||||
"drm_type": str(custom_cdm_spec.get("drm_type") or "Custom"),
|
||||
"device": default_path.name if default_path else "None",
|
||||
}
|
||||
|
||||
# Prefer the service's explicit AUTH_METHODS; otherwise infer from authenticate().
|
||||
methods = []
|
||||
if service_data["needs_auth"]:
|
||||
@@ -2450,7 +2461,7 @@ async def session_license(request: web.Request) -> web.Response:
|
||||
description: Base64-encoded CDM challenge
|
||||
drm_type:
|
||||
type: string
|
||||
enum: [widevine, playready, monalisa]
|
||||
enum: [widevine, playready, custom]
|
||||
description: DRM type (default widevine)
|
||||
is_certificate:
|
||||
type: boolean
|
||||
|
||||
@@ -17,7 +17,7 @@ from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.cdm.choice import SYSTEMS, choose_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system
|
||||
from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, MonaLisa, is_null_key, monalisa_drm, whole_file_cipher
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, CustomDRM, custom_drm, is_null_key, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.title_source import service_licence
|
||||
@@ -479,8 +479,8 @@ def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]
|
||||
session.served_keys[kid] = (key, sources.get(kid, "cdm"))
|
||||
|
||||
|
||||
def served_monalisa_keys(session: Any, drm: MonaLisa) -> dict[str, str]:
|
||||
"""The content keys of a MonaLisa DRM the service built on the server, recorded as served by its device."""
|
||||
def served_custom_keys(session: Any, drm: CustomDRM) -> dict[str, str]:
|
||||
"""The content keys of a CustomDRM the service built on the server, recorded as served by its device."""
|
||||
keys = {kid.hex: key for kid, key in drm.content_keys.items()}
|
||||
note_served_keys(session, keys, {})
|
||||
return keys
|
||||
@@ -644,10 +644,10 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
|
||||
track = session.tracks.get(tid)
|
||||
if not track:
|
||||
continue
|
||||
monalisa = monalisa_drm(track)
|
||||
if monalisa is not None:
|
||||
if session.licensing.server_cdm and monalisa.content_keys:
|
||||
batch.keys[tid] = served_monalisa_keys(session, monalisa)
|
||||
custom = custom_drm(track)
|
||||
if custom is not None:
|
||||
if session.licensing.server_cdm and custom.content_keys:
|
||||
batch.keys[tid] = served_custom_keys(session, custom)
|
||||
continue
|
||||
|
||||
svc_session = getattr(service, "session", None)
|
||||
|
||||
@@ -11,13 +11,15 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .detect import is_playready_cdm, is_remote_cdm, is_widevine_cdm
|
||||
from .detect import is_custom_cdm, is_playready_cdm, is_remote_cdm, is_widevine_cdm
|
||||
|
||||
__all__ = [
|
||||
"DecryptLabsRemoteCDM",
|
||||
"CustomRemoteCDM",
|
||||
"MonaLisaCDM",
|
||||
"load_cdm",
|
||||
"load_custom_cdm",
|
||||
"resolve_custom_device_path",
|
||||
"is_custom_cdm",
|
||||
"is_remote_cdm",
|
||||
"is_playready_cdm",
|
||||
"is_widevine_cdm",
|
||||
@@ -33,13 +35,17 @@ def __getattr__(name: str) -> Any:
|
||||
from .custom_remote_cdm import CustomRemoteCDM
|
||||
|
||||
return CustomRemoteCDM
|
||||
if name == "MonaLisaCDM":
|
||||
from .monalisa import MonaLisaCDM
|
||||
|
||||
return MonaLisaCDM
|
||||
if name == "load_cdm":
|
||||
from .loader import load_cdm
|
||||
|
||||
return load_cdm
|
||||
if name == "load_custom_cdm":
|
||||
from .loader import load_custom_cdm
|
||||
|
||||
return load_custom_cdm
|
||||
if name == "resolve_custom_device_path":
|
||||
from .loader import resolve_custom_device_path
|
||||
|
||||
return resolve_custom_device_path
|
||||
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
@@ -151,3 +151,121 @@ def load_local_cdm(name: str, system: str, path: Path) -> Any:
|
||||
raise ValueError(f"{name}.wvd is an invalid or corrupt Widevine Device file, {e}") from e
|
||||
|
||||
return WidevineCdm.from_device(wvd)
|
||||
|
||||
|
||||
def resolve_custom_device_path(
|
||||
service: str,
|
||||
cdm_override: str | None = None,
|
||||
*,
|
||||
default_path: Path | None = None,
|
||||
extension: str | None = None,
|
||||
app_config: Any = None,
|
||||
) -> Path | None:
|
||||
"""Resolve a user-configured or overridden custom CDM device file, falling back to `default_path`."""
|
||||
if app_config is None:
|
||||
from unshackle.core.config import config
|
||||
|
||||
app_config = config
|
||||
|
||||
from unshackle.core.config import resolve_cdm_name
|
||||
|
||||
entry = resolve_cdm_name(getattr(app_config, "cdm", None) or {}, service, cdm_override)
|
||||
if isinstance(entry, str) and entry:
|
||||
explicit = Path(entry)
|
||||
if explicit.is_file():
|
||||
return explicit
|
||||
if extension and not entry.endswith(extension):
|
||||
explicit_ext = Path(f"{entry}{extension}")
|
||||
if explicit_ext.is_file():
|
||||
return explicit_ext
|
||||
|
||||
directories = getattr(app_config, "directories", None)
|
||||
if directories is not None:
|
||||
filename = f"{entry}{extension}" if (extension and not entry.endswith(extension)) else entry
|
||||
for attr in ("cdms", "wvds", "prds"):
|
||||
base_dir = getattr(directories, attr, None)
|
||||
if isinstance(base_dir, Path):
|
||||
candidate = base_dir / filename
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
|
||||
return default_path
|
||||
|
||||
|
||||
@dataclass
|
||||
class CustomCDM:
|
||||
"""Loaded service-defined custom CDM or stub."""
|
||||
|
||||
drm_type: str
|
||||
device: str
|
||||
device_path: Path | None = None
|
||||
instance: Any = None
|
||||
security_level: int | None = None
|
||||
is_custom_cdm: bool = True
|
||||
is_remote_cdm: bool = False
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
if self.instance is not None:
|
||||
return getattr(self.instance, name)
|
||||
raise AttributeError(f"{type(self).__name__!r} object has no attribute {name!r}")
|
||||
|
||||
|
||||
def get_service_custom_cdm(service_cls: Any) -> dict[str, Any] | None:
|
||||
"""Return the custom CDM specification declared on ``service_cls``, or None."""
|
||||
if service_cls is None:
|
||||
return None
|
||||
getter = getattr(service_cls, "get_custom_cdm", None)
|
||||
if callable(getter):
|
||||
spec = getter()
|
||||
if isinstance(spec, dict):
|
||||
return spec
|
||||
spec = getattr(service_cls, "CUSTOM_CDM", None)
|
||||
return spec if isinstance(spec, dict) else None
|
||||
|
||||
|
||||
def load_custom_cdm(
|
||||
service_cls: Any,
|
||||
service_name: str,
|
||||
cdm_override: str | None = None,
|
||||
*,
|
||||
app_config: Any = None,
|
||||
) -> CustomCDM | None:
|
||||
"""Load a service-declared custom CDM using ``resolve_custom_device_path`` and its loader."""
|
||||
spec = get_service_custom_cdm(service_cls)
|
||||
if not spec:
|
||||
return None
|
||||
|
||||
drm_type = str(spec.get("drm_type") or "Custom")
|
||||
extension = spec.get("extension")
|
||||
default_path = spec.get("default_path")
|
||||
required = bool(spec.get("required", False))
|
||||
loader_fn = spec.get("loader")
|
||||
|
||||
device_path = resolve_custom_device_path(
|
||||
service_name,
|
||||
cdm_override,
|
||||
default_path=default_path,
|
||||
extension=extension,
|
||||
app_config=app_config,
|
||||
)
|
||||
if device_path is None or not Path(device_path).is_file():
|
||||
if required:
|
||||
raise ValueError(f"Custom CDM device for {service_name} not found")
|
||||
return CustomCDM(
|
||||
drm_type=drm_type,
|
||||
device="None",
|
||||
device_path=None,
|
||||
security_level=spec.get("security_level"),
|
||||
)
|
||||
|
||||
resolved_path = Path(device_path)
|
||||
instance = loader_fn(resolved_path) if callable(loader_fn) else None
|
||||
device_name = str(getattr(instance, "device", None) or resolved_path.name)
|
||||
security_level = getattr(instance, "security_level", spec.get("security_level"))
|
||||
return CustomCDM(
|
||||
drm_type=drm_type,
|
||||
device=device_name,
|
||||
device_path=resolved_path,
|
||||
instance=instance,
|
||||
security_level=security_level,
|
||||
)
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from .monalisa_cdm import MonaLisaCDM
|
||||
|
||||
__all__ = ["MonaLisaCDM"]
|
||||
@@ -1,416 +0,0 @@
|
||||
"""
|
||||
MonaLisa CDM - WASM-based Content Decryption Module wrapper.
|
||||
|
||||
This module extracts content keys from MonaLisa-protected titles. It uses a
|
||||
WebAssembly module that runs locally with wasmtime.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import wasmtime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MonaLisaCDM:
|
||||
"""
|
||||
MonaLisa CDM wrapper for WASM-based content key extraction.
|
||||
|
||||
Not thread-safe: drive it through ``drm.MonaLisa``, which holds its ``CDM_LOCK`` for each licence.
|
||||
|
||||
This CDM differs from Widevine/PlayReady in that it does not use a
|
||||
challenge/response flow with a license server. Instead, the service API
|
||||
gives the license (ticket) directly, and the WASM module extracts the
|
||||
content keys locally.
|
||||
"""
|
||||
|
||||
DYNAMIC_BASE = 6065008
|
||||
DYNAMICTOP_PTR = 821968
|
||||
LICENSE_KEY_OFFSET = 0x5C8C0C
|
||||
LICENSE_KEY_LENGTH = 16
|
||||
|
||||
ENV_STRINGS = (
|
||||
"USER=web_user",
|
||||
"LOGNAME=web_user",
|
||||
"PATH=/",
|
||||
"PWD=/",
|
||||
"HOME=/home/web_user",
|
||||
"LANG=zh_CN.UTF-8",
|
||||
"_=./this.program",
|
||||
)
|
||||
|
||||
def __init__(self, device_path: Path) -> None:
|
||||
"""
|
||||
Initialise the MonaLisa CDM.
|
||||
|
||||
Args:
|
||||
device_path: Path to the device file (.mld).
|
||||
"""
|
||||
device_path = Path(device_path)
|
||||
|
||||
self.device_path = device_path
|
||||
self.base_dir = device_path.parent
|
||||
|
||||
if not self.device_path.is_file():
|
||||
raise FileNotFoundError(f"Device file not found at: {self.device_path}")
|
||||
|
||||
try:
|
||||
data = json.loads(self.device_path.read_text(encoding="utf-8", errors="replace"))
|
||||
except Exception as e:
|
||||
raise ValueError(f"Invalid device file (JSON): {e}") from e
|
||||
|
||||
wasm_path_str = data.get("wasm_path")
|
||||
if not wasm_path_str:
|
||||
raise ValueError("Device file missing 'wasm_path'")
|
||||
|
||||
wasm_filename = Path(wasm_path_str).name
|
||||
wasm_path = self.base_dir / wasm_filename
|
||||
|
||||
if not wasm_path.exists():
|
||||
raise FileNotFoundError(f"WASM file not found at: {wasm_path}")
|
||||
|
||||
try:
|
||||
self.engine = wasmtime.Engine()
|
||||
if wasm_path.suffix.lower() == ".wat":
|
||||
self.module = wasmtime.Module.from_file(self.engine, str(wasm_path))
|
||||
else:
|
||||
self.module = wasmtime.Module(self.engine, wasm_path.read_bytes())
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to load WASM module: {e}") # noqa: B904
|
||||
|
||||
self.store: wasmtime.Store | None = None
|
||||
self.memory: wasmtime.Memory | None = None
|
||||
self.instance: wasmtime.Instance | None = None
|
||||
self.exports: dict[str, Any] = {}
|
||||
self.ctx = None
|
||||
|
||||
def open(self) -> int:
|
||||
"""
|
||||
Open a CDM session.
|
||||
|
||||
Returns:
|
||||
Session ID (always 1 for MonaLisa).
|
||||
|
||||
Raises:
|
||||
RuntimeError: If CDM session initialization fails.
|
||||
"""
|
||||
try:
|
||||
self.store = wasmtime.Store(self.engine)
|
||||
memory_type = wasmtime.MemoryType(wasmtime.Limits(256, 256))
|
||||
self.memory = wasmtime.Memory(self.store, memory_type)
|
||||
|
||||
self.write_i32(self.DYNAMICTOP_PTR, self.DYNAMIC_BASE)
|
||||
imports = self.build_imports()
|
||||
self.instance = wasmtime.Instance(self.store, self.module, imports)
|
||||
|
||||
ex = self.instance.exports(self.store)
|
||||
self.exports = {
|
||||
"___wasm_call_ctors": ex["s"],
|
||||
"_monalisa_context_alloc": ex["D"],
|
||||
"monalisa_set_license": ex["F"],
|
||||
"_monalisa_set_canvas_id": ex["t"],
|
||||
"_monalisa_version_get": ex["A"],
|
||||
"monalisa_get_line_number": ex["v"],
|
||||
"stackAlloc": ex["N"],
|
||||
"stackSave": ex["L"],
|
||||
"stackRestore": ex["M"],
|
||||
}
|
||||
|
||||
self.exports["___wasm_call_ctors"](self.store)
|
||||
ctx = self.exports["_monalisa_context_alloc"](self.store)
|
||||
self.ctx = ctx
|
||||
|
||||
# _monalisa_context_alloc is expected to return a positive pointer/handle.
|
||||
# Treat 0/negative/non-int-like values as allocation failure.
|
||||
try:
|
||||
ctx_int = int(ctx)
|
||||
except (TypeError, ValueError):
|
||||
ctx_int = None
|
||||
|
||||
if ctx_int is None or ctx_int <= 0:
|
||||
# Ensure we don't leave a partially-initialized instance around.
|
||||
self.close()
|
||||
raise RuntimeError(f"Failed to allocate MonaLisa context (ctx={ctx!r})")
|
||||
return 1
|
||||
except Exception as e:
|
||||
# Clean up partial state (e.g., store/memory/instance) before propagating failure.
|
||||
self.close()
|
||||
if isinstance(e, RuntimeError):
|
||||
raise
|
||||
raise RuntimeError(f"Failed to initialize session: {e}") from e
|
||||
|
||||
def close(self, session_id: int = 1) -> None:
|
||||
"""
|
||||
Close the CDM session and release resources.
|
||||
|
||||
Args:
|
||||
session_id: The session ID to close (unused, for API compatibility).
|
||||
"""
|
||||
self.store = None
|
||||
self.memory = None
|
||||
self.instance = None
|
||||
self.exports = {}
|
||||
self.ctx = None
|
||||
|
||||
def extract_keys(self, license_data: str | bytes) -> dict:
|
||||
"""
|
||||
Extract decryption keys from license/ticket data.
|
||||
|
||||
Args:
|
||||
license_data: The license ticket, either as base64 string or raw bytes.
|
||||
|
||||
Returns:
|
||||
Dictionary with keys: kid (hex), key (hex), type ("CONTENT").
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the CDM session is not open, or license validation fails.
|
||||
ValueError: If license_data is empty.
|
||||
"""
|
||||
if not self.instance or not self.memory or self.ctx is None:
|
||||
raise RuntimeError("Session not open. Call open() first.")
|
||||
|
||||
if not license_data:
|
||||
raise ValueError("license_data is empty")
|
||||
|
||||
if isinstance(license_data, bytes):
|
||||
license_b64 = base64.b64encode(license_data).decode("utf-8")
|
||||
else:
|
||||
license_b64 = license_data
|
||||
|
||||
ret = self.ccall(
|
||||
"monalisa_set_license",
|
||||
int,
|
||||
self.ctx,
|
||||
license_b64,
|
||||
len(license_b64),
|
||||
"0",
|
||||
)
|
||||
|
||||
if ret != 0:
|
||||
raise RuntimeError(f"License validation failed with code: {ret}")
|
||||
|
||||
key_bytes = self.extract_license_key_bytes()
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(license_b64).decode("ascii", errors="ignore")
|
||||
except Exception as e:
|
||||
# Avoid logging raw license content; log only safe metadata.
|
||||
logger.exception("Failed to base64-decode MonaLisa license (len=%s): %s", len(license_b64), e)
|
||||
decoded = ""
|
||||
|
||||
m = re.search(
|
||||
r"DCID-[A-Z0-9]+-[A-Z0-9]+-\d{8}-\d{6}-[A-Z0-9]+-\d{10}-[A-Z0-9]+",
|
||||
decoded,
|
||||
)
|
||||
if m:
|
||||
kid_bytes = uuid.uuid5(uuid.NAMESPACE_DNS, m.group()).bytes
|
||||
else:
|
||||
# No DCID in the license: derive a deterministic per-license KID to avoid collisions.
|
||||
try:
|
||||
license_raw = base64.b64decode(license_b64)
|
||||
except ValueError:
|
||||
license_raw = license_b64.encode("utf-8", errors="replace")
|
||||
|
||||
license_hash = hashlib.sha256(license_raw).hexdigest()
|
||||
kid_bytes = uuid.uuid5(uuid.NAMESPACE_DNS, f"monalisa:license:{license_hash}").bytes
|
||||
|
||||
return {"kid": kid_bytes.hex(), "key": key_bytes.hex(), "type": "CONTENT"}
|
||||
|
||||
def extract_license_key_bytes(self) -> bytes:
|
||||
"""Extract the 16-byte content key from WASM memory."""
|
||||
assert self.memory is not None and self.store is not None
|
||||
data_ptr = self.memory.data_ptr(self.store)
|
||||
data_len = self.memory.data_len(self.store)
|
||||
|
||||
if self.LICENSE_KEY_OFFSET + self.LICENSE_KEY_LENGTH > data_len:
|
||||
raise RuntimeError("License key offset beyond memory bounds")
|
||||
|
||||
mem_ptr = ctypes.cast(data_ptr, ctypes.POINTER(ctypes.c_ubyte * data_len))
|
||||
start = self.LICENSE_KEY_OFFSET
|
||||
end = self.LICENSE_KEY_OFFSET + self.LICENSE_KEY_LENGTH
|
||||
|
||||
return bytes(mem_ptr.contents[start:end])
|
||||
|
||||
def ccall(self, func_name: str, return_type: type, *args: Any) -> Any:
|
||||
"""Call a WASM function with automatic string conversion."""
|
||||
stack = 0
|
||||
converted_args = []
|
||||
|
||||
try:
|
||||
for arg in args:
|
||||
if isinstance(arg, str):
|
||||
if stack == 0:
|
||||
stack = self.exports["stackSave"](self.store)
|
||||
max_length = (len(arg) << 2) + 1
|
||||
ptr = self.exports["stackAlloc"](self.store, max_length)
|
||||
self.string_to_utf8(arg, ptr, max_length)
|
||||
converted_args.append(ptr)
|
||||
else:
|
||||
converted_args.append(arg)
|
||||
|
||||
result = self.exports[func_name](self.store, *converted_args)
|
||||
finally:
|
||||
# stackAlloc pointers live on the WASM stack; always restore even if the call throws.
|
||||
if stack != 0:
|
||||
exc = sys.exc_info()[1]
|
||||
try:
|
||||
self.exports["stackRestore"](self.store, stack)
|
||||
except Exception:
|
||||
# If we're already failing, don't mask the original exception.
|
||||
if exc is None:
|
||||
raise
|
||||
|
||||
if return_type is bool:
|
||||
return bool(result)
|
||||
return result
|
||||
|
||||
def write_i32(self, addr: int, value: int) -> None:
|
||||
"""Write a 32-bit integer to WASM memory."""
|
||||
if addr % 4 != 0:
|
||||
raise ValueError(f"Unaligned i32 write: addr={addr} (must be 4-byte aligned)")
|
||||
assert self.memory is not None and self.store is not None
|
||||
|
||||
data_len = self.memory.data_len(self.store)
|
||||
if addr < 0 or addr + 4 > data_len:
|
||||
raise IndexError(f"i32 write out of bounds: addr={addr}, mem_len={data_len}")
|
||||
|
||||
data = self.memory.data_ptr(self.store)
|
||||
mem_ptr = ctypes.cast(data, ctypes.POINTER(ctypes.c_int32))
|
||||
mem_ptr[addr >> 2] = value
|
||||
|
||||
def string_to_utf8(self, data: str, ptr: int, max_length: int) -> int:
|
||||
"""Convert string to UTF-8 and write to WASM memory."""
|
||||
encoded = data.encode("utf-8")
|
||||
write_length = min(len(encoded), max_length - 1)
|
||||
assert self.memory is not None and self.store is not None
|
||||
|
||||
mem_data = self.memory.data_ptr(self.store)
|
||||
mem_ptr = ctypes.cast(mem_data, ctypes.POINTER(ctypes.c_ubyte))
|
||||
|
||||
for i in range(write_length):
|
||||
mem_ptr[ptr + i] = encoded[i]
|
||||
mem_ptr[ptr + write_length] = 0
|
||||
return write_length
|
||||
|
||||
def write_ascii_to_memory(self, string: str, buffer: int, dont_add_null: int = 0) -> None:
|
||||
"""Write ASCII string to WASM memory."""
|
||||
assert self.memory is not None and self.store is not None
|
||||
mem_data = self.memory.data_ptr(self.store)
|
||||
mem_ptr = ctypes.cast(mem_data, ctypes.POINTER(ctypes.c_ubyte))
|
||||
|
||||
encoded = string.encode("utf-8")
|
||||
for i, byte_val in enumerate(encoded):
|
||||
mem_ptr[buffer + i] = byte_val
|
||||
|
||||
if dont_add_null == 0:
|
||||
mem_ptr[buffer + len(encoded)] = 0
|
||||
|
||||
def build_imports(self) -> list[wasmtime.Func | wasmtime.Memory]:
|
||||
"""Assemble the WASM import stubs the MonaLisa module needs."""
|
||||
assert self.memory is not None and self.store is not None
|
||||
store, memory = self.store, self.memory
|
||||
|
||||
def sys_fcntl64(a: int, b: int, c: int) -> int:
|
||||
return 0
|
||||
|
||||
def fd_write(a: int, b: int, c: int, d: int) -> int:
|
||||
return 0
|
||||
|
||||
def fd_close(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def sys_ioctl(a: int, b: int, c: int) -> int:
|
||||
return 0
|
||||
|
||||
def sys_open(a: int, b: int, c: int) -> int:
|
||||
return 0
|
||||
|
||||
def sys_rmdir(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def sys_unlink(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def clock() -> int:
|
||||
return 0
|
||||
|
||||
def time(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def emscripten_run_script(a: int) -> None:
|
||||
return None
|
||||
|
||||
def fd_seek(a: int, b: int, c: int, d: int, e: int) -> int:
|
||||
return 0
|
||||
|
||||
def emscripten_resize_heap(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def fd_read(a: int, b: int, c: int, d: int) -> int:
|
||||
return 0
|
||||
|
||||
def emscripten_run_script_string(a: int) -> int:
|
||||
return 0
|
||||
|
||||
def emscripten_run_script_int(a: int) -> int:
|
||||
return 1
|
||||
|
||||
def emscripten_memcpy_big(dest: int, src: int, num: int | None) -> int:
|
||||
assert self.memory is not None and self.store is not None
|
||||
mem_data = self.memory.data_ptr(self.store)
|
||||
data_len = self.memory.data_len(self.store)
|
||||
if num is None:
|
||||
num = data_len - 1
|
||||
mem_ptr = ctypes.cast(mem_data, ctypes.POINTER(ctypes.c_ubyte))
|
||||
for i in range(num):
|
||||
if dest + i < data_len and src + i < data_len:
|
||||
mem_ptr[dest + i] = mem_ptr[src + i]
|
||||
return dest
|
||||
|
||||
def environ_get(environ_ptr: int, environ_buf: int) -> int:
|
||||
buf_size = 0
|
||||
for index, string in enumerate(self.ENV_STRINGS):
|
||||
ptr = environ_buf + buf_size
|
||||
self.write_i32(environ_ptr + index * 4, ptr)
|
||||
self.write_ascii_to_memory(string, ptr)
|
||||
buf_size += len(string) + 1
|
||||
return 0
|
||||
|
||||
def environ_sizes_get(penviron_count: int, penviron_buf_size: int) -> int:
|
||||
self.write_i32(penviron_count, len(self.ENV_STRINGS))
|
||||
buf_size = sum(len(s) + 1 for s in self.ENV_STRINGS)
|
||||
self.write_i32(penviron_buf_size, buf_size)
|
||||
return 0
|
||||
|
||||
i32 = wasmtime.ValType.i32()
|
||||
|
||||
return [
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32], [i32]), sys_fcntl64),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32, i32], [i32]), fd_write),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), fd_close),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32], [i32]), sys_ioctl),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32], [i32]), sys_open),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), sys_rmdir),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), sys_unlink),
|
||||
wasmtime.Func(store, wasmtime.FuncType([], [i32]), clock),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), time),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], []), emscripten_run_script),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32, i32, i32], [i32]), fd_seek),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32], [i32]), emscripten_memcpy_big),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), emscripten_resize_heap),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32], [i32]), environ_get),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32], [i32]), environ_sizes_get),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32, i32, i32, i32], [i32]), fd_read),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), emscripten_run_script_string),
|
||||
wasmtime.Func(store, wasmtime.FuncType([i32], [i32]), emscripten_run_script_int),
|
||||
memory,
|
||||
]
|
||||
@@ -0,0 +1,473 @@
|
||||
"""
|
||||
Custom DRM System.
|
||||
|
||||
A generic extensible DRM abstraction supporting local key extraction,
|
||||
certificate + challenge/response flows, multi-key/IV rotation,
|
||||
declarative CLI templates, built-in decryptor registry, and Remote compatibility.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import functools
|
||||
import logging
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util import Counter
|
||||
from Crypto.Util.Padding import unpad
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.drm.bbts import decrypt_bbts
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CommandBuilder = Callable[[Path, Path, Path, str, str], Sequence[str | Path]]
|
||||
KeyResolver = Callable[["CustomDRM"], dict[UUID, str] | tuple[UUID | None, str] | None]
|
||||
DecryptFn = Callable[..., None]
|
||||
|
||||
|
||||
def default_command_builder(tool_path: Path, src: Path, dst: Path, kid: str, key: str) -> Sequence[str | Path]:
|
||||
"""Default CLI command builder: `<tool> -i <src> -o <dst> -k <kid>:<key>`."""
|
||||
return [tool_path, "-i", src, "-o", dst, "-k", f"{kid}:{key}"]
|
||||
|
||||
|
||||
def _decrypt_builtin_bbts(src: Path, dst: Path, drm: CustomDRM, **_ctx: Any) -> None:
|
||||
if not drm.key:
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed("Missing content key for BBTS decryption.")
|
||||
decrypt_bbts(src, dst, bytes.fromhex(drm.key))
|
||||
|
||||
|
||||
def _decrypt_builtin_aes_cbc(src: Path, dst: Path, drm: CustomDRM, **ctx: Any) -> None:
|
||||
key_hex = ctx.get("key") or drm.key
|
||||
iv_hex = ctx.get("iv") or drm.iv_hex
|
||||
if not key_hex or not iv_hex:
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed("AES-128-CBC requires both key and IV.")
|
||||
cipher = AES.new(bytes.fromhex(key_hex), AES.MODE_CBC, iv=bytes.fromhex(iv_hex))
|
||||
dst.write_bytes(unpad(cipher.decrypt(src.read_bytes()), AES.block_size))
|
||||
|
||||
|
||||
def _decrypt_builtin_aes_ctr(src: Path, dst: Path, drm: CustomDRM, **ctx: Any) -> None:
|
||||
key_hex = ctx.get("key") or drm.key
|
||||
iv_hex = ctx.get("iv") or drm.iv_hex
|
||||
if not key_hex or not iv_hex:
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed("AES-128-CTR requires both key and IV.")
|
||||
iv_int = int.from_bytes(bytes.fromhex(iv_hex), "big")
|
||||
ctr = Counter.new(128, initial_value=iv_int)
|
||||
cipher = AES.new(bytes.fromhex(key_hex), AES.MODE_CTR, counter=ctr)
|
||||
dst.write_bytes(cipher.decrypt(src.read_bytes()))
|
||||
|
||||
|
||||
_BUILTIN_DECRYPTORS: dict[str, Callable[..., None]] = {
|
||||
"bbts": _decrypt_builtin_bbts,
|
||||
"aes-128-cbc": _decrypt_builtin_aes_cbc,
|
||||
"aes-128-ctr": _decrypt_builtin_aes_ctr,
|
||||
}
|
||||
|
||||
|
||||
@functools.cache
|
||||
def find_tool(*candidates: str) -> Path | None:
|
||||
"""Locate an external decryption binary from candidate names."""
|
||||
if not candidates:
|
||||
return None
|
||||
return binaries.find(*candidates)
|
||||
|
||||
|
||||
def custom_drm(track: Any) -> CustomDRM | None:
|
||||
"""Return the first CustomDRM attached to `track`, if any."""
|
||||
return next((d for d in getattr(track, "drm", None) or [] if isinstance(d, CustomDRM)), None)
|
||||
|
||||
|
||||
class CustomDRM:
|
||||
"""
|
||||
Generic Custom DRM system for service-specific or non-standard protections.
|
||||
|
||||
Supports:
|
||||
- Local key extraction via `key_resolver` and optional `session_initializer`.
|
||||
- Certificate + challenge/response flows via `certificate_resolver`,
|
||||
`challenge_builder`, `license_requester`, and `license_parser`.
|
||||
- Multi-key (`kids`), per-key/static IVs (`ivs`, `iv`), and `probe_kid`.
|
||||
- Built-in `decryptor` registry (`"bbts"`, `"aes-128-cbc"`, `"aes-128-ctr"`),
|
||||
declarative `command_template` / `tool_names`, `command_builder`, or `decrypt_fn`.
|
||||
"""
|
||||
|
||||
class Exceptions:
|
||||
class TicketNotFound(Exception):
|
||||
"""Raised when neither ticket/PSSH nor KID/resolver is provided."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class KeyExtractionFailed(Exception):
|
||||
"""Raised when content key extraction or resolution fails."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class CertificateError(Exception):
|
||||
"""Raised when service certificate acquisition or setup fails."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class LicenseError(Exception):
|
||||
"""Raised when license challenge or parsing fails."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
label: str = "Custom",
|
||||
pssh_or_ticket: str | bytes | None = None,
|
||||
*,
|
||||
display_id: str | None = None,
|
||||
kid: UUID | str | None = None,
|
||||
kids: Sequence[UUID | str] | None = None,
|
||||
content_keys: dict[UUID, str] | None = None,
|
||||
ivs: dict[UUID, str] | None = None,
|
||||
iv: str | bytes | None = None,
|
||||
probe_kid: bool = False,
|
||||
session_initializer: Callable[[CustomDRM], Any] | None = None,
|
||||
key_resolver: KeyResolver | None = None,
|
||||
certificate_resolver: Callable[..., bytes | str | None] | None = None,
|
||||
challenge_builder: Callable[..., bytes | str] | None = None,
|
||||
license_requester: Callable[..., bytes | str] | None = None,
|
||||
license_parser: Callable[..., dict[UUID, str]] | None = None,
|
||||
decryptor: str | None = None,
|
||||
tool_names: Sequence[str] | None = None,
|
||||
tool_path: Path | None = None,
|
||||
command_template: Sequence[str] | None = None,
|
||||
command_builder: CommandBuilder | None = None,
|
||||
decrypt_fn: DecryptFn | None = None,
|
||||
segment_decrypt: bool | None = None,
|
||||
decrypt_mode: Literal["segment", "track", "auto"] = "auto",
|
||||
resolve_immediately: bool = True,
|
||||
extra: dict[str, Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
has_resolver = bool(key_resolver or (challenge_builder and license_parser))
|
||||
if not pssh_or_ticket and kid is None and not kids and not content_keys and not has_resolver:
|
||||
raise CustomDRM.Exceptions.TicketNotFound("No PSSH/ticket, KID, or resolver provided.")
|
||||
|
||||
self.label = label
|
||||
self._pssh_or_ticket = pssh_or_ticket or ""
|
||||
self._display_id = display_id
|
||||
self.probe_kid = probe_kid
|
||||
self._session_initializer = session_initializer
|
||||
self._session_initialized = False
|
||||
self._key_resolver = key_resolver
|
||||
self._certificate_resolver = certificate_resolver
|
||||
self._challenge_builder = challenge_builder
|
||||
self._license_requester = license_requester
|
||||
self._license_parser = license_parser
|
||||
self._decryptor = decryptor
|
||||
self._tool_names: tuple[str, ...] = tuple(tool_names) if tool_names else (
|
||||
("bbtsdecrypt", "bbtsdecryptor", "bbts-decrypt", "bbts-decryptor") if decryptor == "bbts" else ()
|
||||
)
|
||||
self._tool_path = tool_path
|
||||
self._command_template: tuple[str, ...] | None = tuple(command_template) if command_template else None
|
||||
self._command_builder = command_builder or default_command_builder
|
||||
self._decrypt_fn = decrypt_fn
|
||||
if decrypt_mode == "segment":
|
||||
self._segment_decrypt: bool | None = True
|
||||
elif decrypt_mode == "track":
|
||||
self._segment_decrypt = False
|
||||
else:
|
||||
self._segment_decrypt = segment_decrypt
|
||||
self._decrypted_segments: int = 0
|
||||
|
||||
parsed_kids: list[UUID] = []
|
||||
if kids:
|
||||
for item in kids:
|
||||
parsed_kid = item if isinstance(item, UUID) else UUID(hex=item)
|
||||
if parsed_kid not in parsed_kids:
|
||||
parsed_kids.append(parsed_kid)
|
||||
if kid is not None:
|
||||
parsed_kid = kid if isinstance(kid, UUID) else UUID(hex=kid)
|
||||
if parsed_kid not in parsed_kids:
|
||||
parsed_kids.insert(0, parsed_kid)
|
||||
|
||||
self._kid: UUID | None = parsed_kids[0] if parsed_kids else None
|
||||
self._extra_kids: list[UUID] = parsed_kids
|
||||
self.content_keys: dict[UUID, str] = dict(content_keys or {})
|
||||
self.ivs: dict[UUID, str] = dict(ivs or {})
|
||||
if isinstance(iv, bytes):
|
||||
self._iv_hex: str | None = iv.hex()
|
||||
else:
|
||||
self._iv_hex = iv
|
||||
if self._kid is None and self.content_keys:
|
||||
self._kid = next(iter(self.content_keys))
|
||||
self.extra: dict[str, Any] = dict(extra or {})
|
||||
self.data: dict[str, Any] = dict(kwargs)
|
||||
|
||||
if resolve_immediately and key_resolver and not self.content_keys:
|
||||
self.extract_keys()
|
||||
|
||||
def _ensure_session_initialized(self) -> None:
|
||||
if self._session_initializer and not self._session_initialized:
|
||||
self._session_initializer(self)
|
||||
self._session_initialized = True
|
||||
|
||||
def extract_keys(self) -> dict[UUID, str]:
|
||||
"""Run `session_initializer` (if any) and `key_resolver` to populate `self.content_keys`."""
|
||||
if not self._key_resolver:
|
||||
return self.content_keys
|
||||
try:
|
||||
self._ensure_session_initialized()
|
||||
result = self._key_resolver(self)
|
||||
if isinstance(result, dict):
|
||||
self.content_keys.update(result)
|
||||
if self._kid is None and self.content_keys:
|
||||
self._kid = next(iter(self.content_keys))
|
||||
elif isinstance(result, tuple) and len(result) == 2:
|
||||
resolved_kid, resolved_key = result
|
||||
if resolved_kid is not None:
|
||||
self._kid = resolved_kid if isinstance(resolved_kid, UUID) else UUID(hex=resolved_kid)
|
||||
if self._kid and resolved_key:
|
||||
self.content_keys[self._kid] = resolved_key
|
||||
return self.content_keys
|
||||
except CustomDRM.Exceptions.KeyExtractionFailed:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {e}") from e
|
||||
|
||||
def get_content_keys(
|
||||
self,
|
||||
*,
|
||||
certificate: Callable[..., Any] | bytes | str | None = None,
|
||||
licence: Callable[..., Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> dict[UUID, str]:
|
||||
"""Resolve content keys via `key_resolver` or certificate/challenge/license pipeline."""
|
||||
if self.content_keys:
|
||||
return self.content_keys
|
||||
|
||||
if self._key_resolver:
|
||||
return self.extract_keys()
|
||||
|
||||
if self._challenge_builder and self._license_parser:
|
||||
self._ensure_session_initialized()
|
||||
|
||||
cert_data: Any = None
|
||||
if self._certificate_resolver:
|
||||
try:
|
||||
cert_data = self._certificate_resolver(self, **kwargs)
|
||||
except Exception as e:
|
||||
raise CustomDRM.Exceptions.CertificateError(f"Failed to resolve certificate: {e}") from e
|
||||
elif callable(certificate):
|
||||
try:
|
||||
cert_data = certificate(challenge=b"")
|
||||
except TypeError:
|
||||
cert_data = certificate()
|
||||
except Exception as e:
|
||||
raise CustomDRM.Exceptions.CertificateError(f"Failed to fetch certificate: {e}") from e
|
||||
else:
|
||||
cert_data = certificate
|
||||
|
||||
try:
|
||||
challenge = self._challenge_builder(self, cert_data, **kwargs)
|
||||
except Exception as e:
|
||||
raise CustomDRM.Exceptions.LicenseError(f"Failed to build license challenge: {e}") from e
|
||||
|
||||
requester = self._license_requester or licence
|
||||
if not requester:
|
||||
raise CustomDRM.Exceptions.LicenseError("No license requester provided for CustomDRM.")
|
||||
|
||||
try:
|
||||
license_response = requester(challenge=challenge, **kwargs) if self._license_requester else requester(
|
||||
challenge=challenge
|
||||
)
|
||||
keys = self._license_parser(self, license_response, **kwargs)
|
||||
except CustomDRM.Exceptions.LicenseError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise CustomDRM.Exceptions.LicenseError(f"Failed to license CustomDRM: {e}") from e
|
||||
|
||||
if keys:
|
||||
self.content_keys.update(keys)
|
||||
if self._kid is None:
|
||||
self._kid = next(iter(self.content_keys))
|
||||
return self.content_keys
|
||||
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed("No key resolver or challenge/license pipeline configured.")
|
||||
|
||||
@property
|
||||
def needs_licensing(self) -> bool:
|
||||
"""Whether this DRM still needs `get_content_keys` called during key resolution."""
|
||||
return not self.content_keys and bool(self._key_resolver or (self._challenge_builder and self._license_parser))
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""This DRM in the export form; see `wire.drm_to_dict`."""
|
||||
from unshackle.core.wire import drm_to_dict
|
||||
|
||||
return drm_to_dict(self)
|
||||
|
||||
@property
|
||||
def kid(self) -> UUID | None:
|
||||
return self._kid
|
||||
|
||||
@property
|
||||
def kids(self) -> list[UUID]:
|
||||
merged = list(self._extra_kids)
|
||||
for k in self.content_keys:
|
||||
if k not in merged:
|
||||
merged.append(k)
|
||||
return merged
|
||||
|
||||
@property
|
||||
def key(self) -> str | None:
|
||||
if self._kid and self._kid in self.content_keys:
|
||||
return self.content_keys[self._kid]
|
||||
if self.content_keys:
|
||||
return next(iter(self.content_keys.values()))
|
||||
return None
|
||||
|
||||
@property
|
||||
def iv_hex(self) -> str | None:
|
||||
if self._kid and self._kid in self.ivs:
|
||||
return self.ivs[self._kid]
|
||||
if self._iv_hex:
|
||||
return self._iv_hex
|
||||
if self.ivs:
|
||||
return next(iter(self.ivs.values()))
|
||||
return None
|
||||
|
||||
@property
|
||||
def pssh(self) -> str:
|
||||
if isinstance(self._pssh_or_ticket, bytes):
|
||||
try:
|
||||
return self._pssh_or_ticket.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
try:
|
||||
return self._pssh_or_ticket.decode("ascii")
|
||||
except UnicodeDecodeError:
|
||||
return base64.b64encode(self._pssh_or_ticket).decode("ascii")
|
||||
return self._pssh_or_ticket
|
||||
|
||||
@property
|
||||
def display_id(self) -> str:
|
||||
return self._display_id or self.pssh
|
||||
|
||||
@property
|
||||
def decryptor(self) -> str | None:
|
||||
return self._decryptor
|
||||
|
||||
@property
|
||||
def tool_names(self) -> tuple[str, ...]:
|
||||
return self._tool_names
|
||||
|
||||
@property
|
||||
def command_template(self) -> tuple[str, ...] | None:
|
||||
return self._command_template
|
||||
|
||||
@property
|
||||
def tool(self) -> Path | None:
|
||||
if self._tool_path is None and self._tool_names:
|
||||
self._tool_path = find_tool(*self._tool_names)
|
||||
return self._tool_path
|
||||
|
||||
@property
|
||||
def supports_segment_decrypt(self) -> bool:
|
||||
return self._segment_decrypt is not False
|
||||
|
||||
@property
|
||||
def track_decrypted(self) -> bool:
|
||||
return self._segment_decrypt is False and self._decrypted_segments > 0
|
||||
|
||||
@property
|
||||
def key_pair(self) -> str:
|
||||
if self._kid and self.key:
|
||||
return f"{self._kid.hex}:{self.key}"
|
||||
return ""
|
||||
|
||||
def decrypt_segment(self, segment_path: Path, output_path: Path | None = None, **context: Any) -> None:
|
||||
self._execute_decrypt(segment_path, output_path, timeout=60, **context)
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False, **context: Any) -> None:
|
||||
if is_segment:
|
||||
return self.decrypt_segment(path, output_path, **context)
|
||||
|
||||
if self._decrypted_segments > 0:
|
||||
log.debug(
|
||||
"%s: Track already decrypted during segment downloads (%s segments)",
|
||||
self.label,
|
||||
self._decrypted_segments,
|
||||
)
|
||||
return
|
||||
|
||||
self._execute_decrypt(path, output_path, **context)
|
||||
if output_path and self._segment_decrypt is False:
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def _build_cli_command(self, tool: Path, src: Path, dst: Path, kid_hex: str, key_hex: str) -> Sequence[str | Path]:
|
||||
if self._command_template:
|
||||
mapping = {
|
||||
"tool": str(tool),
|
||||
"src": str(src),
|
||||
"dst": str(dst),
|
||||
"kid": kid_hex,
|
||||
"key": key_hex,
|
||||
"iv": self.iv_hex or "",
|
||||
}
|
||||
return [tool, *(part.format(**mapping) for part in self._command_template)]
|
||||
return self._command_builder(tool, src, dst, kid_hex, key_hex)
|
||||
|
||||
def _execute_decrypt(
|
||||
self,
|
||||
path: Path,
|
||||
output_path: Path | None = None,
|
||||
*,
|
||||
timeout: float | None = None,
|
||||
**context: Any,
|
||||
) -> None:
|
||||
if not path or not path.exists():
|
||||
raise ValueError(f"Target file does not exist: {path}")
|
||||
|
||||
if not self.content_keys and not self.key:
|
||||
raise CustomDRM.Exceptions.KeyExtractionFailed("Missing content key for decryption.")
|
||||
|
||||
target_output = output_path or path
|
||||
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
|
||||
|
||||
if self._decrypt_fn:
|
||||
try:
|
||||
try:
|
||||
self._decrypt_fn(path, temp_out, self.content_keys, **context)
|
||||
except TypeError:
|
||||
self._decrypt_fn(path, temp_out, self.content_keys)
|
||||
except BaseException:
|
||||
temp_out.unlink(missing_ok=True)
|
||||
raise
|
||||
temp_out.replace(target_output)
|
||||
return
|
||||
|
||||
tool = self.tool
|
||||
if tool and not tool.exists():
|
||||
raise RuntimeError(f"{self.label} decryption tool missing: {tool}")
|
||||
|
||||
if tool:
|
||||
kid_hex = self._kid.hex if self._kid else "0" * 32
|
||||
key_hex = self.key or ""
|
||||
run_step(
|
||||
self._build_cli_command(tool, path, temp_out, kid_hex, key_hex),
|
||||
output=temp_out,
|
||||
label=f"{self.label} decryption of {path.name}",
|
||||
timeout=timeout,
|
||||
)
|
||||
temp_out.replace(target_output)
|
||||
return
|
||||
|
||||
builtin = _BUILTIN_DECRYPTORS.get(self._decryptor or "")
|
||||
if builtin:
|
||||
try:
|
||||
builtin(path, temp_out, self, **context)
|
||||
except BaseException:
|
||||
temp_out.unlink(missing_ok=True)
|
||||
raise
|
||||
temp_out.replace(target_output)
|
||||
return
|
||||
|
||||
raise RuntimeError(f"No decryptor or external tool configured for {self.label} DRM.")
|
||||
@@ -29,7 +29,7 @@ from unshackle.core.drm import (
|
||||
ClearKey,
|
||||
ClearKeyCENC,
|
||||
ClearKeyCTR,
|
||||
MonaLisa,
|
||||
CustomDRM,
|
||||
PlayReady,
|
||||
Widevine,
|
||||
drop_null_keys,
|
||||
@@ -228,8 +228,8 @@ class ContentKeyResolver:
|
||||
found = {kid: self.vaults.source_of(kid, key) for kid, key in keys.items()}
|
||||
return {kid: source for kid, source in found.items() if source is not None}
|
||||
|
||||
monalisa = isinstance(drm, MonaLisa)
|
||||
bridged = bool(getattr(drm, "bridged", False)) or monalisa
|
||||
custom = isinstance(drm, CustomDRM)
|
||||
bridged = bool(getattr(drm, "bridged", False)) or custom
|
||||
backup = path.with_name(path.name + ".enc")
|
||||
backup.unlink(missing_ok=True) # a killed run leaves one behind; its bytes may not match
|
||||
checking = bool((vault_kids() or bridged) and decrypt and binaries.FFMPEG)
|
||||
@@ -267,7 +267,7 @@ class ContentKeyResolver:
|
||||
def refuse(kid: UUID) -> None:
|
||||
"""Delete the output and stop the track for the content key of ``kid``."""
|
||||
path.unlink(missing_ok=True)
|
||||
name = "MonaLisa" if monalisa else "licence"
|
||||
name = drm.label if custom else "licence"
|
||||
raise coded(
|
||||
click.ClickException(
|
||||
f"The {name} content key of KID {kid.hex} does not decrypt track {getattr(track, 'id', path.name)}"
|
||||
@@ -346,7 +346,7 @@ class ContentKeyResolver:
|
||||
self.log.debug(f"{key} from {kids[kid].name} was bad")
|
||||
self.vaults.flag_bad_key(kid, key)
|
||||
if not retry:
|
||||
if monalisa:
|
||||
if custom:
|
||||
refuse(min(bad))
|
||||
raise ValueError("The content key from the vault did not decrypt the track; run again")
|
||||
path.unlink()
|
||||
@@ -467,14 +467,14 @@ class ContentKeyResolver:
|
||||
different siblings would get different locks.
|
||||
"""
|
||||
kids = getattr(drm, "kids", None) or []
|
||||
key = ",".join(sorted(getattr(k, "hex", str(k)) for k in kids)) or getattr(drm, "content_id", None)
|
||||
key = ",".join(sorted(getattr(k, "hex", str(k)) for k in kids)) or getattr(drm, "display_id", None)
|
||||
with cls.DRM_LOCKS_GUARD:
|
||||
return cls.DRM_LOCKS.setdefault(key or type(drm).__name__, Lock())
|
||||
|
||||
def _take_licence_turn(
|
||||
self,
|
||||
turn: ExitStack,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
|
||||
kids: list[UUID],
|
||||
track: AnyTrack,
|
||||
track_kid: UUID | None,
|
||||
@@ -494,7 +494,7 @@ class ContentKeyResolver:
|
||||
|
||||
def _take_cached_key(
|
||||
self,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
|
||||
kid: UUID,
|
||||
track: AnyTrack,
|
||||
track_kid: UUID | None,
|
||||
@@ -517,7 +517,7 @@ class ContentKeyResolver:
|
||||
|
||||
def _take_vault_key(
|
||||
self,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
|
||||
kid: UUID,
|
||||
track: AnyTrack,
|
||||
track_kid: UUID | None,
|
||||
@@ -556,7 +556,7 @@ class ContentKeyResolver:
|
||||
|
||||
def _take_known_keys(
|
||||
self,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
|
||||
kids: list[UUID],
|
||||
track: AnyTrack,
|
||||
track_kid: UUID | None,
|
||||
@@ -852,7 +852,7 @@ class ContentKeyResolver:
|
||||
|
||||
def _prepare_drm(
|
||||
self,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
|
||||
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
|
||||
track: AnyTrack,
|
||||
title: Title_T,
|
||||
table: Table,
|
||||
@@ -918,9 +918,9 @@ class ContentKeyResolver:
|
||||
|
||||
if server_cdm and not licensed_locally:
|
||||
if not drm.content_keys:
|
||||
if isinstance(drm, MonaLisa):
|
||||
if isinstance(drm, CustomDRM):
|
||||
raise coded(
|
||||
click.ClickException(f"The server sent no MonaLisa content key for track {track.id}"),
|
||||
click.ClickException(f"The server sent no {drm.label} content key for track {track.id}"),
|
||||
APIErrorCode.DRM_ERROR,
|
||||
)
|
||||
self.log.warning("Server CDM did not resolve any keys for this track")
|
||||
@@ -933,8 +933,8 @@ class ContentKeyResolver:
|
||||
assert remote is not None
|
||||
server_drm_type = remote.server_cdm_type
|
||||
drm_name = (
|
||||
"MonaLisa"
|
||||
if isinstance(drm, MonaLisa)
|
||||
drm.label
|
||||
if isinstance(drm, CustomDRM)
|
||||
else {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__)
|
||||
)
|
||||
log_event(
|
||||
@@ -1032,20 +1032,28 @@ class ContentKeyResolver:
|
||||
if self.export:
|
||||
self.export(title, track, drm)
|
||||
|
||||
elif isinstance(drm, MonaLisa):
|
||||
elif isinstance(drm, CustomDRM):
|
||||
if drm.needs_licensing:
|
||||
certificate = partial(self.service.get_custom_drm_service_certificate, title=title, track=track)
|
||||
custom_licence = partial(service_licence, self.service, "custom", title=title, track=track)
|
||||
get_keys = partial(drm.get_content_keys, certificate=certificate, licence=custom_licence)
|
||||
self._license_drm(drm, get_keys, track, title, track_kid, table, cdm_only, force)
|
||||
else:
|
||||
if not drm.content_keys:
|
||||
self._take_known_keys(drm, drm.kids, track, track_kid, None)
|
||||
if not drm.content_keys:
|
||||
raise coded(
|
||||
click.ClickException(
|
||||
f"No MonaLisa content key for track {track.id} from a vault or the server CDM"
|
||||
f"No {drm.label} content key for track {track.id} from a vault or the server CDM"
|
||||
),
|
||||
APIErrorCode.DRM_ERROR,
|
||||
)
|
||||
with self.drm_lock(drm):
|
||||
display_id = drm.content_id or drm.pssh
|
||||
pssh_display = truncate_pssh_for_display(display_id, "MonaLisa")
|
||||
cek_tree = Tree(Text.assemble(("MonaLisa", "cyan"), (f"({pssh_display})", "text"), overflow="fold"))
|
||||
display_id = drm.display_id
|
||||
pssh_display = truncate_pssh_for_display(display_id, drm.label)
|
||||
cek_tree = Tree(
|
||||
Text.assemble((drm.label, "cyan"), (f"({pssh_display})", "text"), overflow="fold")
|
||||
)
|
||||
pre_existing_tree = next(
|
||||
(x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None
|
||||
)
|
||||
@@ -1053,7 +1061,7 @@ class ContentKeyResolver:
|
||||
cek_tree = pre_existing_tree
|
||||
|
||||
for kid_, key in drm.content_keys.items():
|
||||
self._add_key_label(cek_tree, kid_, key, track_kid=kid_) # every MonaLisa key is the track's own
|
||||
self._add_key_label(cek_tree, kid_, key, track_kid=kid_)
|
||||
|
||||
if cek_tree.children and not pre_existing_tree:
|
||||
table.add_row()
|
||||
|
||||
@@ -1,345 +0,0 @@
|
||||
"""
|
||||
MonaLisa DRM System.
|
||||
|
||||
A WASM-based DRM system that uses local content key extraction from ticket data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import functools
|
||||
import gc
|
||||
import logging
|
||||
import threading
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.cdm.monalisa import MonaLisaCDM
|
||||
from unshackle.core.drm.bbts import decrypt_bbts
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CommandBuilder = Callable[[Path, Path, Path, str, str], Sequence[str | Path]]
|
||||
|
||||
CDM_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def bbtsdecrypt_command(tool_path: Path, src: Path, dst: Path, kid: str, key: str) -> Sequence[str | Path]:
|
||||
"""The bbtsdecrypt command that decrypts one file, a segment or a whole track."""
|
||||
return [tool_path, "-i", src, "-o", dst, "-k", f"{kid}:{key}"]
|
||||
|
||||
|
||||
@functools.cache
|
||||
def local_tool() -> Path | None:
|
||||
"""This machine's bbtsdecrypt, which decrypts each segment, or None for the built-in decrypter."""
|
||||
return binaries.find("bbtsdecrypt", "bbtsdecryptor", "bbts-decrypt", "bbts-decryptor")
|
||||
|
||||
|
||||
def monalisa_drm(track: Any) -> MonaLisa | None:
|
||||
"""The MonaLisa DRM of a track, with or without a content key."""
|
||||
return next((d for d in getattr(track, "drm", None) or [] if isinstance(d, MonaLisa)), None)
|
||||
|
||||
|
||||
class MonaLisa:
|
||||
"""
|
||||
MonaLisa DRM System.
|
||||
|
||||
Unlike Widevine/PlayReady, MonaLisa does not use a challenge/response flow
|
||||
with a license server. Instead, the service API gives the PSSH value (ticket)
|
||||
directly, and a WASM module extracts the content keys locally.
|
||||
"""
|
||||
|
||||
class Exceptions:
|
||||
class TicketNotFound(Exception):
|
||||
"""Raised when the caller gives no PSSH/ticket data."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class KeyExtractionFailed(Exception):
|
||||
"""Raised when content key extraction from the ticket fails."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ticket: str | bytes | None = None,
|
||||
device_path: Path | None = None,
|
||||
tool_path: Path | None = None,
|
||||
command_builder: CommandBuilder | None = None,
|
||||
segment_decrypt: bool | None = None,
|
||||
*,
|
||||
kid: UUID | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""
|
||||
Initialise MonaLisa DRM.
|
||||
|
||||
Args:
|
||||
ticket: PSSH value from service API (base64 string or raw bytes).
|
||||
device_path: Path to the CDM device file (.mld).
|
||||
tool_path: Optional path to an external decryption binary; without it, this machine's
|
||||
tool (`local_tool`) decrypts, else the built-in BBTS decrypter.
|
||||
command_builder: Optional callback `(tool_path, src, dst, kid_hex, key_hex) -> args`
|
||||
that builds the decryption CLI invocation (default: `bbtsdecrypt_command`).
|
||||
segment_decrypt: Whether the decrypter supports per-segment decryption.
|
||||
kid: The KID of a copy with no ticket, whose content key comes from elsewhere (a remote server).
|
||||
**kwargs: Additional metadata stored in self.data.
|
||||
|
||||
Raises:
|
||||
TicketNotFound: If ticket/PSSH is empty and the caller gives no kid.
|
||||
KeyExtractionFailed: If content key extraction fails.
|
||||
"""
|
||||
if not ticket and kid is None:
|
||||
raise MonaLisa.Exceptions.TicketNotFound("No PSSH/ticket data provided.")
|
||||
|
||||
self._ticket = ticket or ""
|
||||
self._device_path = device_path
|
||||
self._tool_path = tool_path
|
||||
self._command_builder = command_builder or bbtsdecrypt_command
|
||||
self._segment_decrypt = segment_decrypt
|
||||
self._decrypted_segments: int = 0
|
||||
self._kid: UUID | None = kid if kid is None or isinstance(kid, UUID) else UUID(hex=kid)
|
||||
self.content_keys: dict[UUID, str] = {}
|
||||
self.data: dict = kwargs or {}
|
||||
|
||||
if ticket:
|
||||
self.extract_keys()
|
||||
|
||||
def extract_keys(self) -> None:
|
||||
"""Extract keys from the ticket using the MonaLisa CDM.
|
||||
|
||||
One licence at a time per process (`CDM_LOCK`): concurrent wasmtime sessions corrupt its shared function table.
|
||||
"""
|
||||
|
||||
if self._device_path is None:
|
||||
raise MonaLisa.Exceptions.KeyExtractionFailed("Failed to extract keys: no MonaLisa device file")
|
||||
with CDM_LOCK:
|
||||
try:
|
||||
keys = self._cdm_keys(self._device_path)
|
||||
if keys:
|
||||
kid_hex = keys.get("kid")
|
||||
if kid_hex:
|
||||
self._kid = UUID(hex=kid_hex)
|
||||
if self._kid and keys.get("key"):
|
||||
self.content_keys[self._kid] = keys["key"]
|
||||
return
|
||||
except Exception as e:
|
||||
error = str(e)
|
||||
# the failed licence's traceback holds a wasmtime Store: free it while the lock is held
|
||||
gc.collect()
|
||||
raise MonaLisa.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {error}")
|
||||
|
||||
def _cdm_keys(self, device_path: Path) -> dict[str, Any]:
|
||||
"""The KID and content key that one MonaLisa CDM session reads from the ticket."""
|
||||
cdm = MonaLisaCDM(device_path=device_path)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
return cdm.extract_keys(self._ticket)
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""This DRM in the export form; see ``wire.drm_to_dict``."""
|
||||
from unshackle.core.wire import drm_to_dict
|
||||
|
||||
return drm_to_dict(self)
|
||||
|
||||
@classmethod
|
||||
def from_ticket(
|
||||
cls,
|
||||
ticket: str | bytes,
|
||||
device_path: Path,
|
||||
tool_path: Path | None = None,
|
||||
command_builder: CommandBuilder | None = None,
|
||||
segment_decrypt: bool | None = None,
|
||||
) -> MonaLisa:
|
||||
"""
|
||||
Make a MonaLisa DRM instance from a PSSH/ticket.
|
||||
|
||||
Args:
|
||||
ticket: PSSH value from service API.
|
||||
device_path: Path to the CDM device file (.mld).
|
||||
tool_path: Optional path to an external decryption binary.
|
||||
command_builder: Optional callback that builds the decryption CLI invocation.
|
||||
segment_decrypt: Whether the external tool supports per-segment decryption.
|
||||
|
||||
Returns:
|
||||
MonaLisa DRM instance with extracted keys.
|
||||
"""
|
||||
return cls(
|
||||
ticket=ticket,
|
||||
device_path=device_path,
|
||||
tool_path=tool_path,
|
||||
command_builder=command_builder,
|
||||
segment_decrypt=segment_decrypt,
|
||||
)
|
||||
|
||||
@property
|
||||
def kid(self) -> UUID | None:
|
||||
"""Get the Key ID."""
|
||||
return self._kid
|
||||
|
||||
@property
|
||||
def kids(self) -> list[UUID]:
|
||||
"""The KID of the track's content key, as a list like the other DRM systems give."""
|
||||
return [self._kid] if self._kid else []
|
||||
|
||||
@property
|
||||
def key(self) -> str | None:
|
||||
"""Get the content key as hex string."""
|
||||
return self.content_keys.get(self._kid) if self._kid else None
|
||||
|
||||
@property
|
||||
def pssh(self) -> str:
|
||||
"""
|
||||
Get the raw PSSH/ticket value as a string.
|
||||
|
||||
Returns:
|
||||
The raw PSSH value as a base64 string.
|
||||
"""
|
||||
if isinstance(self._ticket, bytes):
|
||||
try:
|
||||
return self._ticket.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
# Tickets are typically base64, so ASCII is a reasonable fallback.
|
||||
try:
|
||||
return self._ticket.decode("ascii")
|
||||
except UnicodeDecodeError as e:
|
||||
raise ValueError(
|
||||
f"Ticket bytes must be UTF-8 text or ASCII base64; got undecodable bytes (len={len(self._ticket)})"
|
||||
) from e
|
||||
return self._ticket
|
||||
|
||||
@property
|
||||
def content_id(self) -> str | None:
|
||||
"""
|
||||
Extract the Content ID from the PSSH for display.
|
||||
|
||||
The PSSH contains an embedded Content ID at bytes 21-75 with format:
|
||||
H5DCID-V3-P1-YYYYMMDD-HHMMSS-MEDIAID-TIMESTAMP-SUFFIX
|
||||
|
||||
Returns:
|
||||
The Content ID string if extractable, None otherwise.
|
||||
"""
|
||||
try:
|
||||
if isinstance(self._ticket, bytes):
|
||||
data = self._ticket
|
||||
else:
|
||||
data = base64.b64decode(self._ticket)
|
||||
|
||||
# Content ID is at bytes 21-75 (55 bytes)
|
||||
if len(data) >= 76:
|
||||
content_id = data[21:76].decode("ascii")
|
||||
if content_id.startswith("H5DCID-"):
|
||||
return content_id
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
@property
|
||||
def tool(self) -> Path | None:
|
||||
"""The external decrypter: the service's, else this machine's (`local_tool`), else None."""
|
||||
if self._tool_path is None:
|
||||
self._tool_path = local_tool()
|
||||
return self._tool_path
|
||||
|
||||
@property
|
||||
def supports_segment_decrypt(self) -> bool:
|
||||
"""Whether the decrypter supports per-segment decryption; the built-in one does."""
|
||||
return self._segment_decrypt is not False
|
||||
|
||||
@property
|
||||
def track_decrypted(self) -> bool:
|
||||
"""Whether the service already decrypted the whole track into one clear segment file.
|
||||
|
||||
The service can keep its merged ciphertext beside that file, and the merge leaves it out.
|
||||
"""
|
||||
return self._segment_decrypt is False and self._decrypted_segments > 0
|
||||
|
||||
@property
|
||||
def key_pair(self) -> str:
|
||||
"""The formatted ``KID:KEY`` for CLI decryptors (32hex:32hex)."""
|
||||
if self._kid and self.key:
|
||||
return f"{self._kid.hex}:{self.key}"
|
||||
return ""
|
||||
|
||||
def decrypt_segment(self, segment_path: Path, output_path: Path | None = None) -> None:
|
||||
"""
|
||||
Decrypt an individual segment file with the external tool, else the built-in decrypter.
|
||||
|
||||
Args:
|
||||
segment_path: Path to the segment file to decrypt.
|
||||
output_path: Optional path for the decrypted output segment.
|
||||
"""
|
||||
self._execute_decrypt(segment_path, output_path, timeout=60)
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False) -> None:
|
||||
"""
|
||||
Decrypt a media file (segment or track) with the external tool, else the built-in decrypter.
|
||||
|
||||
A whole-track tool runs once on a service's own merged file, which the service gives an ``output_path``.
|
||||
The in-place calls of core after it do nothing.
|
||||
|
||||
Args:
|
||||
path: Path to the target file to decrypt.
|
||||
output_path: Optional path for the decrypted output file.
|
||||
is_segment: Set True if this is an individual segment rather than a full track.
|
||||
"""
|
||||
if is_segment:
|
||||
return self.decrypt_segment(path, output_path)
|
||||
|
||||
# If segments were already decrypted during chunk downloads, skip reprocessing on final track.
|
||||
if self._decrypted_segments > 0:
|
||||
log.debug(
|
||||
"MonaLisa: Track already decrypted during segment downloads (%s segments)", self._decrypted_segments
|
||||
)
|
||||
return
|
||||
|
||||
self._execute_decrypt(path, output_path)
|
||||
if output_path and self._segment_decrypt is False:
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def _execute_decrypt(
|
||||
self,
|
||||
path: Path,
|
||||
output_path: Path | None = None,
|
||||
*,
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
"""Decrypt into a temporary file, which replaces the target only on success.
|
||||
|
||||
Without an external tool, the built-in BBTS decrypter does the work.
|
||||
"""
|
||||
if not path or not path.exists():
|
||||
raise ValueError(f"Target file does not exist: {path}")
|
||||
|
||||
tool = self.tool
|
||||
if tool and not tool.exists():
|
||||
raise RuntimeError(f"MonaLisa decryption tool missing: {tool}")
|
||||
|
||||
if not self.key or not self.kid:
|
||||
raise MonaLisa.Exceptions.KeyExtractionFailed("Missing content key for decryption.")
|
||||
|
||||
target_output = output_path or path
|
||||
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
|
||||
if tool:
|
||||
run_step(
|
||||
self._command_builder(tool, path, temp_out, self.kid.hex, self.key),
|
||||
output=temp_out,
|
||||
label=f"MonaLisa decryption of {path.name}",
|
||||
timeout=timeout,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
decrypt_bbts(path, temp_out, bytes.fromhex(self.key))
|
||||
except BaseException:
|
||||
temp_out.unlink(missing_ok=True)
|
||||
raise
|
||||
temp_out.replace(target_output)
|
||||
@@ -30,7 +30,7 @@ from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.downloaders.requests import parse_content_range, range_answers, request_range
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, CustomDRM, PlayReady, Widevine
|
||||
from unshackle.core.drm.cenc import COMMON_ID, PLACEHOLDER_KIDS, PLAYREADY_ID, common_pssh_kids
|
||||
from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import has_encrypted_entry, has_encrypted_sample_entry, walk
|
||||
@@ -530,7 +530,11 @@ class DASH:
|
||||
and manifest_drm
|
||||
and any(isinstance(existing, type(manifest)) for existing in existing_drm for manifest in manifest_drm)
|
||||
)
|
||||
or (existing_drm and manifest_drm and not any(isinstance(drm, Widevine) for drm in existing_drm))
|
||||
or (
|
||||
existing_drm
|
||||
and manifest_drm
|
||||
and not any(isinstance(drm, (Widevine, CustomDRM)) for drm in existing_drm)
|
||||
)
|
||||
)
|
||||
|
||||
pre_existing_keys: dict[UUID, str] = {}
|
||||
|
||||
@@ -32,7 +32,7 @@ from unshackle.core.cdm.choice import drm_system
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, CustomDRM, PlayReady, Widevine
|
||||
from unshackle.core.drm.bbts import renumber_continuity
|
||||
from unshackle.core.drm.cenc import (
|
||||
PLACEHOLDER_KIDS,
|
||||
@@ -1007,7 +1007,7 @@ class HLS:
|
||||
]
|
||||
if not files:
|
||||
raise ValueError(f"None of the segment files for {segment_range} exist...")
|
||||
elif len(files) != range_len and not (isinstance(drm, MonaLisa) and drm.track_decrypted):
|
||||
elif len(files) != range_len and not (isinstance(drm, CustomDRM) and drm.track_decrypted):
|
||||
raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
|
||||
|
||||
if isinstance(drm, (Widevine, PlayReady)):
|
||||
@@ -1020,7 +1020,7 @@ class HLS:
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
|
||||
check_decrypted(track, merged_path, drm)
|
||||
merged_path.rename(decrypted_path)
|
||||
elif isinstance(drm, MonaLisa) and not drm.supports_segment_decrypt:
|
||||
elif isinstance(drm, CustomDRM) and not drm.supports_segment_decrypt:
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=not drm.track_decrypted)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not drm.track_decrypted, track=track)
|
||||
merged_path.rename(decrypted_path)
|
||||
@@ -1125,7 +1125,7 @@ class HLS:
|
||||
decrypt(include_this_segment=False)
|
||||
|
||||
if key is None:
|
||||
encryption_data = (None, session_drm) if isinstance(session_drm, MonaLisa) else None
|
||||
encryption_data = (None, session_drm) if isinstance(session_drm, CustomDRM) else None
|
||||
elif not encryption_data or encryption_data[0] != key:
|
||||
with licensing(ctx):
|
||||
init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None
|
||||
@@ -1167,7 +1167,7 @@ class HLS:
|
||||
return sorted(segments)
|
||||
|
||||
segments_to_merge = find_segments_recursively(save_dir)
|
||||
if isinstance(session_drm, MonaLisa) and session_drm.track_decrypted:
|
||||
if isinstance(session_drm, CustomDRM) and session_drm.track_decrypted:
|
||||
segments_to_merge = [file for file in segments_to_merge if file.stem.isdigit()]
|
||||
|
||||
log_event(
|
||||
@@ -1221,7 +1221,7 @@ class HLS:
|
||||
|
||||
store.complete()
|
||||
|
||||
if isinstance(session_drm, MonaLisa) and session_drm.supports_segment_decrypt and isinstance(track, Video):
|
||||
if isinstance(session_drm, CustomDRM) and session_drm.supports_segment_decrypt and isinstance(track, Video):
|
||||
renumber_continuity(save_path)
|
||||
decrypt_track(session_drm, save_path, decrypt=False, track=track)
|
||||
if session_drm:
|
||||
|
||||
@@ -17,7 +17,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, WHOLE_FILE_DRM, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine, cbcs
|
||||
from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, ClearKeyCENC, ClearKeyCTR, CustomDRM, PlayReady, Widevine, cbcs
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
|
||||
from unshackle.core.drm.verify import decrypt_track, has_encrypted_sample_entry
|
||||
@@ -111,10 +111,10 @@ def licensing(ctx: DownloadContext) -> Iterator[None]:
|
||||
|
||||
|
||||
LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = {
|
||||
Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC, ClearKeyCTR),
|
||||
Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC),
|
||||
Track.Descriptor.HLS: (Widevine, PlayReady, MonaLisa),
|
||||
Track.Descriptor.ISM: (Widevine, PlayReady),
|
||||
Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC, ClearKeyCTR, CustomDRM),
|
||||
Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC, CustomDRM),
|
||||
Track.Descriptor.HLS: (Widevine, PlayReady, CustomDRM),
|
||||
Track.Descriptor.ISM: (Widevine, PlayReady, CustomDRM),
|
||||
}
|
||||
"""The DRM systems the licence step licenses, by the kind of manifest the track comes from."""
|
||||
|
||||
@@ -160,7 +160,7 @@ def license_drm(
|
||||
if not isinstance(drm, LICENSABLE[track.descriptor]):
|
||||
return
|
||||
track_kid = None
|
||||
if not isinstance(drm, MonaLisa):
|
||||
if not isinstance(drm, CustomDRM) or drm.probe_kid:
|
||||
track_kid = kid or (probe() if probe else None)
|
||||
if not track_kid and track.descriptor in (Track.Descriptor.HLS, Track.Descriptor.ISM):
|
||||
track_kid = getattr(drm, "kid", None)
|
||||
|
||||
@@ -157,6 +157,8 @@ class Service(TitleSource):
|
||||
# Cache key prefixes that hold state built from the device identity (a device ID, device session keys), never
|
||||
# login state. A remote session on the server's device keeps them on the server, per API key.
|
||||
IDENTITY_CACHE: tuple[str, ...] = ()
|
||||
# Optional custom CDM specification for services that do not use standard Widevine/PlayReady CDMs.
|
||||
CUSTOM_CDM: dict[str, Any] | None = None
|
||||
|
||||
def __init__(self, ctx: click.Context) -> None:
|
||||
console.print(Padding(Rule(f"[rule.text]Service: {self.__class__.__name__}"), (1, 2)))
|
||||
@@ -419,6 +421,15 @@ class Service(TitleSource):
|
||||
"""
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def get_custom_cdm() -> dict[str, Any] | None:
|
||||
"""
|
||||
Declare a custom CDM specification for services using CustomDRM.
|
||||
:returns: Dict with ``drm_type``, optional ``extension``, ``default_path``, ``loader``, ``required``,
|
||||
``security_level``; or None when the service uses standard Widevine/PlayReady CDMs.
|
||||
"""
|
||||
return None
|
||||
|
||||
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
|
||||
"""
|
||||
Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).
|
||||
|
||||
@@ -223,6 +223,16 @@ class TitleSource(metaclass=ABCMeta):
|
||||
Services with no license server can instead pre-populate the DRM object's
|
||||
`signatures` in get_tracks.
|
||||
"""
|
||||
|
||||
def get_custom_drm_service_certificate(
|
||||
self, *, challenge: bytes | str | None = None, title: Title_T, track: AnyTrack
|
||||
) -> bytes | str | None:
|
||||
"""Get a service certificate for a CustomDRM system, if required."""
|
||||
|
||||
def get_custom_drm_license(
|
||||
self, *, challenge: bytes | str, title: Title_T, track: AnyTrack
|
||||
) -> bytes | str | dict | None:
|
||||
"""Get a license response for a CustomDRM challenge."""
|
||||
return None
|
||||
|
||||
def fairplay_bridge(self) -> Callable[..., Any] | None:
|
||||
@@ -330,7 +340,11 @@ def service_licence(source: TitleSource, drm_system: str, **kwargs: Any) -> Any:
|
||||
"""
|
||||
bridged = any(getattr(drm, "bridged", False) for drm in getattr(kwargs.get("track"), "drm", None) or [])
|
||||
hook = source.fairplay_bridge() if bridged else None
|
||||
fn = hook or (source.get_playready_license if drm_system == "playready" else source.get_widevine_license)
|
||||
system_hooks = {
|
||||
"playready": source.get_playready_license,
|
||||
"custom": source.get_custom_drm_license,
|
||||
}
|
||||
fn = hook or system_hooks.get(drm_system, source.get_widevine_license)
|
||||
return fn(**declared_kwargs(fn, {**kwargs, "drm_system": drm_system} if hook else kwargs))
|
||||
|
||||
|
||||
|
||||
@@ -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_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
from unshackle.core.downloaders.requests import requests
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, CustomDRM, PlayReady, Widevine
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.cenc import cenc_key, init_kid
|
||||
from unshackle.core.drm.verify import (
|
||||
@@ -936,6 +936,10 @@ class Track:
|
||||
if isinstance(drm, wanted):
|
||||
return drm
|
||||
|
||||
for drm in self.drm:
|
||||
if isinstance(drm, CustomDRM):
|
||||
return drm
|
||||
|
||||
if is_widevine_cdm(cdm):
|
||||
for drm in self.drm:
|
||||
if isinstance(drm, Widevine):
|
||||
|
||||
+80
-18
@@ -35,7 +35,7 @@ from unshackle.core.drm import (
|
||||
BlowfishStripe,
|
||||
ClearKeyCENC,
|
||||
ClearKeyCTR,
|
||||
MonaLisa,
|
||||
CustomDRM,
|
||||
PlayReady,
|
||||
Widevine,
|
||||
)
|
||||
@@ -364,7 +364,7 @@ def build_music(songs: list[Title_T], info: Any) -> Album:
|
||||
|
||||
|
||||
def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
|
||||
"""Serialise DRM objects to JSON-serializable list. A MonaLisa entry holds its KID only, never its content key or ticket."""
|
||||
"""Serialise DRM objects to JSON-serializable list. A CustomDRM entry never leaks its content key or ticket."""
|
||||
if not drm_list:
|
||||
return None
|
||||
|
||||
@@ -373,9 +373,27 @@ def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
|
||||
|
||||
result = []
|
||||
for drm in drm_list:
|
||||
if isinstance(drm, MonaLisa):
|
||||
if drm.kid:
|
||||
result.append({"type": "monalisa", "kid": drm.kid.hex})
|
||||
if isinstance(drm, CustomDRM):
|
||||
if drm.kids or drm.kid:
|
||||
entry: dict[str, Any] = {
|
||||
"type": "custom",
|
||||
"label": drm.label,
|
||||
"kid": (drm.kid or drm.kids[0]).hex,
|
||||
"kids": [k.hex for k in drm.kids],
|
||||
"segment_decrypt": drm.supports_segment_decrypt,
|
||||
"probe_kid": drm.probe_kid,
|
||||
}
|
||||
if drm.decryptor:
|
||||
entry["decryptor"] = drm.decryptor
|
||||
if drm.tool_names:
|
||||
entry["tool_names"] = list(drm.tool_names)
|
||||
if drm.command_template:
|
||||
entry["command_template"] = list(drm.command_template)
|
||||
if drm.iv_hex:
|
||||
entry["iv"] = drm.iv_hex
|
||||
if drm.ivs:
|
||||
entry["ivs"] = {k.hex: v for k, v in drm.ivs.items()}
|
||||
result.append(entry)
|
||||
continue
|
||||
drm_info = {}
|
||||
drm_class = drm.__class__.__name__
|
||||
@@ -428,7 +446,7 @@ 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 not in ("blowfishstripe", "clearkeyctr", "monalisa"):
|
||||
if not pssh_str and drm_type not in ("blowfishstripe", "clearkeyctr", "custom"):
|
||||
continue
|
||||
try:
|
||||
if drm_type == "blowfishstripe":
|
||||
@@ -439,8 +457,22 @@ def reconstruct_drm(drm_list: list | None) -> list:
|
||||
None, drm_info["iv"], drm_info["magic"], drm_info.get("skip", 0), key=drm_info.get("key")
|
||||
)
|
||||
)
|
||||
elif drm_type == "monalisa":
|
||||
result.append(MonaLisa(kid=drm_info["kid"]))
|
||||
elif drm_type == "custom":
|
||||
raw_ivs = drm_info.get("ivs") or {}
|
||||
result.append(
|
||||
CustomDRM(
|
||||
label=drm_info.get("label", "Custom"),
|
||||
kid=drm_info.get("kid"),
|
||||
kids=drm_info.get("kids"),
|
||||
iv=drm_info.get("iv"),
|
||||
ivs={UUID(hex=k): v for k, v in raw_ivs.items()} if raw_ivs else None,
|
||||
probe_kid=bool(drm_info.get("probe_kid", False)),
|
||||
decryptor=drm_info.get("decryptor"),
|
||||
tool_names=drm_info.get("tool_names"),
|
||||
command_template=drm_info.get("command_template"),
|
||||
segment_decrypt=drm_info.get("segment_decrypt"),
|
||||
)
|
||||
)
|
||||
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
|
||||
@@ -461,13 +493,32 @@ def pssh_drm(system: str, pssh_b64: str, kids: list[str] | None) -> Widevine | P
|
||||
return Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None)
|
||||
|
||||
|
||||
def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC | MonaLisa) -> dict[str, Any]:
|
||||
def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC | CustomDRM) -> dict[str, Any]:
|
||||
"""A DRM in the export form: its system, PSSH, KIDs and the FairPlay bridged mark.
|
||||
|
||||
The export keeps the content keys once at title level, not here. A MonaLisa entry holds its KID only, as on the wire.
|
||||
The export keeps the content keys once at title level, not here. A CustomDRM entry holds its KID and decryptor spec only.
|
||||
"""
|
||||
if isinstance(drm, MonaLisa):
|
||||
return {"system": "MonaLisa", "kids": [kid.hex for kid in drm.kids]}
|
||||
if isinstance(drm, CustomDRM):
|
||||
data: dict[str, Any] = {
|
||||
"system": "CustomDRM",
|
||||
"label": drm.label,
|
||||
"kids": [kid.hex for kid in drm.kids],
|
||||
}
|
||||
if drm.decryptor:
|
||||
data["decryptor"] = drm.decryptor
|
||||
if drm.tool_names:
|
||||
data["tool_names"] = list(drm.tool_names)
|
||||
if drm.command_template:
|
||||
data["command_template"] = list(drm.command_template)
|
||||
if drm.iv_hex:
|
||||
data["iv"] = drm.iv_hex
|
||||
if drm.ivs:
|
||||
data["ivs"] = {k.hex: v for k, v in drm.ivs.items()}
|
||||
if drm.probe_kid:
|
||||
data["probe_kid"] = True
|
||||
if drm._segment_decrypt is not None:
|
||||
data["segment_decrypt"] = drm._segment_decrypt
|
||||
return data
|
||||
if isinstance(drm, ClearKeyCENC):
|
||||
data: dict[str, Any] = {
|
||||
"system": "ClearKeyCENC",
|
||||
@@ -486,10 +537,10 @@ def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC | MonaLisa) -> dict[str
|
||||
return data
|
||||
|
||||
|
||||
def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC | MonaLisa:
|
||||
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC/MonaLisa DRM instance from its export form.
|
||||
def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC | CustomDRM:
|
||||
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC/CustomDRM instance from its export form.
|
||||
|
||||
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey and MonaLisa, which have no PSSH, and for
|
||||
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey and CustomDRM, which have no PSSH, and for
|
||||
a bridged stub, whose PlayReady PSSH names only its first KID) and re-injects any saved
|
||||
content keys so the resulting object can decrypt without contacting a license server.
|
||||
"""
|
||||
@@ -499,9 +550,20 @@ def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC |
|
||||
content_keys = data.get("content_keys") or {}
|
||||
|
||||
if system == "ClearKeyCENC":
|
||||
drm: Widevine | PlayReady | ClearKeyCENC | MonaLisa = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
|
||||
elif system == "MonaLisa":
|
||||
drm = MonaLisa(kid=kids[0] if kids else None)
|
||||
drm: Widevine | PlayReady | ClearKeyCENC | CustomDRM = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
|
||||
elif system == "CustomDRM":
|
||||
raw_ivs = data.get("ivs") or {}
|
||||
drm = CustomDRM(
|
||||
label=data.get("label", "Custom"),
|
||||
kids=kids,
|
||||
iv=data.get("iv"),
|
||||
ivs={UUID(hex=k): v for k, v in raw_ivs.items()} if raw_ivs else None,
|
||||
probe_kid=bool(data.get("probe_kid", False)),
|
||||
decryptor=data.get("decryptor"),
|
||||
tool_names=data.get("tool_names"),
|
||||
command_template=data.get("command_template"),
|
||||
segment_decrypt=data.get("segment_decrypt"),
|
||||
)
|
||||
elif data.get("bridged") and system in ("PlayReady", "Widevine"):
|
||||
drm = HLS.bridge_stub(system.lower(), [UUID(hex=kid) for kid in kids])
|
||||
elif not pssh_b64:
|
||||
|
||||
Reference in New Issue
Block a user