Files
unshackle/unshackle/core/drm/clearkey_cenc.py
T

211 lines
8.1 KiB
Python

from __future__ import annotations
import base64
import json
from pathlib import Path
from typing import Any, Callable, Iterable, Optional, Union
from uuid import UUID
from requests import Session
from unshackle.core.config import config
from unshackle.core.drm import key_args as drm_key_args
from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt
from unshackle.core.utilities import log_event
from unshackle.core.utils import run_proxy
def b64url_encode_nopad(data: bytes) -> str:
# W3C EME uses base64url without padding for key IDs and key values
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def b64url_decode(data: str) -> bytes:
return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
class ClearKeyCENC:
"""W3C EME ClearKey (org.w3.clearkey) DRM System over MPEG-CENC tracks.
Distinct from the HLS AES-128 `ClearKey` class: a license server gives the keys
here as a JWK Set keyed by KID, and the media is standard CENC
(decrypted with shaka-packager/mp4decrypt KID:KEY pairs, same as Widevine).
"""
urn = "urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e"
def __init__(
self,
kids: Iterable[Union[UUID, str, bytes]],
laurl: Optional[str] = None,
content_keys: Optional[dict[UUID, str]] = None,
**kwargs: Any,
) -> None:
kid_list: list[UUID] = []
for kid in kids or []:
if isinstance(kid, str):
kid = UUID(hex=kid)
elif isinstance(kid, bytes):
kid = UUID(bytes=kid)
if not isinstance(kid, UUID):
raise ValueError(f"Expected kid to be a {UUID}, str, or bytes, not {kid!r}")
kid_list.append(kid)
if not kid_list:
raise ClearKeyCENC.Exceptions.KIDNotFound("No Key ID was provided.")
self.kids: list[UUID] = kid_list
self.laurl: Optional[str] = laurl
self.content_keys: dict[UUID, str] = dict(content_keys or {})
self.data: dict = kwargs or {}
@property
def kid(self) -> Optional[UUID]:
"""Get first Key ID, if any."""
return next(iter(self.kids), None)
def to_dict(self) -> dict[str, Any]:
"""Serialise this DRM instance for export/import (KIDs + license URL).
unshackle stores the content keys once at the export's track level, and does not
duplicate them here.
"""
data: dict[str, Any] = {
"system": "ClearKeyCENC",
"kids": [kid.hex for kid in self.kids],
}
if self.laurl:
data["laurl"] = self.laurl
return data
def get_license_challenge(self) -> bytes:
"""Assemble the W3C EME ClearKey JSON license request for the unkeyed KIDs."""
kids = [kid for kid in self.kids if kid not in self.content_keys] or self.kids
request = {"kids": [b64url_encode_nopad(kid.bytes) for kid in kids], "type": "temporary"}
return json.dumps(request).encode("utf8")
def get_content_keys(self, *, licence: Callable, session: Optional[Session] = None) -> None:
"""
Get Content Keys for this DRM Instance from a ClearKey license server.
The licence param is a function. unshackle gives it the W3C JSON license
request as `challenge`. It may return the JWK Set license as a dict, JSON str,
or bytes. If it returns None and the manifest gave a Laurl, unshackle POSTs the
challenge there directly instead.
"""
if all(kid in self.content_keys for kid in self.kids):
return
challenge = self.get_license_challenge()
log_event(
"drm_license_request",
level="DEBUG",
message=f"Requesting ClearKey license for {len(self.kids)} KID(s)",
drm_type="ClearKeyCENC",
kids=[kid.hex for kid in self.kids],
challenge_size=len(challenge),
)
response = licence(challenge=challenge)
if response is None and self.laurl:
if not session:
session = run_proxy.fallback_session()
session.headers.update(config.headers)
r = session.post(self.laurl, data=challenge, headers={"Content-Type": "application/json"})
r.raise_for_status()
response = r.content
if not response:
raise ClearKeyCENC.Exceptions.EmptyLicense("No ClearKey license was returned and no Laurl is available.")
if isinstance(response, (bytes, bytearray)):
document = json.loads(bytes(response).decode("utf8"))
elif isinstance(response, str):
document = json.loads(response)
elif isinstance(response, dict):
document = response
else:
raise ValueError(f"Expected the ClearKey license to be bytes, str, or dict, not {response!r}")
for jwk in document.get("keys") or []:
kty = jwk.get("kty")
if kty not in (None, "oct"):
continue
if kty is None:
log_event(
"drm_license_warning",
level="WARNING",
message="ClearKey JWK is missing 'kty'; assuming 'oct' per W3C EME",
drm_type="ClearKeyCENC",
)
kid_b64 = jwk.get("kid")
key_b64 = jwk.get("k")
if not kid_b64 or not key_b64:
continue
kid = UUID(bytes=b64url_decode(kid_b64))
key = b64url_decode(key_b64)
if len(key) != 16:
# A CENC content key is always 16 bytes; a wrong-length key would make the
# external tool fail opaquely. Skip it rather than pass it through.
log_event(
"drm_license_warning",
level="WARNING",
message=f"ClearKey JWK for KID {kid.hex} has a {len(key)}-byte key (expected 16); skipping",
drm_type="ClearKeyCENC",
)
continue
self.content_keys[kid] = key.hex()
if not self.content_keys:
raise ClearKeyCENC.Exceptions.EmptyLicense("No Content Keys were within the License")
for kid in self.kids:
if kid not in self.content_keys:
raise ClearKeyCENC.Exceptions.CEKNotFound(f"No Content Key for KID {kid.hex} within the License")
log_event(
"drm_content_keys",
level="INFO",
message=f"Recovered {len(self.content_keys)} ClearKey content key(s)",
drm_type="ClearKeyCENC",
key_count=len(self.content_keys),
keys=[{"kid": k.hex, "key": v} for k, v in self.content_keys.items()],
)
def decrypt(self, path: Path) -> None:
"""Decrypt the file at ``path`` in place with this track's ClearKey (standard CENC) content keys."""
decrypt_cenc(self, path, "ClearKeyCENC")
def mp4decrypt_key_args(self, track_kids: Optional[dict[int, UUID]] = None) -> list[str]:
"""Build the mp4decrypt --key arguments for every content key, and by track ID for each ``track_kids`` KID."""
key_args = []
for kid, key in self.content_keys.items():
key_args.extend(["--key", f"{kid.hex}:{key}"])
return key_args + drm_key_args.track_key_args(self.content_keys, track_kids)
def decrypt_with_mp4decrypt(self, path: Path) -> None:
"""Decrypt with mp4decrypt."""
mp4decrypt(path, self.mp4decrypt_key_args)
def decrypt_with_shaka_packager(self, path: Path) -> None:
"""Decrypt with shaka-packager."""
keys = ",".join(
"label={}:key_id={}:key={}".format(i, kid.hex, key.lower())
for i, (kid, key) in enumerate(self.content_keys.items())
)
shaka_decrypt(path, keys, "ClearKey")
class Exceptions:
class KIDNotFound(Exception):
"""KID (Encryption Key ID) was not found."""
class CEKNotFound(Exception):
"""CEK (Content Encryption Key) for KID was not found in License."""
class EmptyLicense(Exception):
"""License returned no Content Encryption Keys."""
__all__ = ("ClearKeyCENC",)