forked from kenzuya/unshackle
refactor(drm): read PlayReady KIDs from pyplayready WRM headers and drop the hand XML scan
This commit is contained in:
+17
-135
@@ -41,22 +41,14 @@ class PlayReady(CencDrm):
|
||||
if not isinstance(pssh, PSSH):
|
||||
raise TypeError(f"Expected pssh to be a {PSSH}, not {pssh!r}")
|
||||
|
||||
kids: list[UUID] = []
|
||||
for header in pssh.wrm_headers:
|
||||
for header_kid in self.header_kids(header):
|
||||
if header_kid not in kids:
|
||||
kids.append(header_kid)
|
||||
if pssh_b64:
|
||||
for extra_kid in self.extract_kids_from_pssh_b64(pssh_b64):
|
||||
if extra_kid not in kids:
|
||||
kids.append(extra_kid)
|
||||
|
||||
self._kid = as_kid(kid)
|
||||
if self._kid and self._kid not in kids:
|
||||
kids = [k for header in pssh.wrm_headers for k in self.header_kids(header)]
|
||||
kids += [k for header in pssh.wrm_headers for k in self.custom_attribute_kids(header)]
|
||||
if self._kid:
|
||||
kids.append(self._kid)
|
||||
|
||||
self._pssh = pssh
|
||||
self._kids = kids
|
||||
self._kids = list(dict.fromkeys(kids))
|
||||
self._extra_headers: list[WRMHeader] = []
|
||||
self._refused_headers: set[str] = set()
|
||||
|
||||
@@ -68,93 +60,6 @@ class PlayReady(CencDrm):
|
||||
if pssh_b64:
|
||||
self.data.setdefault("pssh_b64", pssh_b64)
|
||||
|
||||
def extract_kids_from_pssh_b64(self, pssh_b64: str) -> list[UUID]:
|
||||
"""Extract all KIDs from base64-encoded PSSH data."""
|
||||
try:
|
||||
# PSSH XML comes from third-party manifests; defusedxml guards against entity expansion
|
||||
import defusedxml.ElementTree as ET
|
||||
|
||||
# Decode the PSSH
|
||||
pssh_bytes = base64.b64decode(pssh_b64)
|
||||
|
||||
# Try to find XML in the PSSH data
|
||||
pssh_str = pssh_bytes.decode("utf-16le", errors="ignore")
|
||||
|
||||
# Find WRMHEADER
|
||||
xml_start = pssh_str.find("<WRMHEADER")
|
||||
if xml_start == -1:
|
||||
# Try UTF-8
|
||||
pssh_str = pssh_bytes.decode("utf-8", errors="ignore")
|
||||
xml_start = pssh_str.find("<WRMHEADER")
|
||||
|
||||
if xml_start != -1:
|
||||
clean_xml = pssh_str[xml_start:]
|
||||
xml_end = clean_xml.find("</WRMHEADER>") + len("</WRMHEADER>")
|
||||
clean_xml = clean_xml[:xml_end]
|
||||
|
||||
root = ET.fromstring(clean_xml)
|
||||
ns = {"pr": "http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader"}
|
||||
|
||||
kids = []
|
||||
|
||||
kid_elements = root.findall(".//pr:CUSTOMATTRIBUTES/pr:KIDS/pr:KID", ns)
|
||||
for kid_elem in kid_elements:
|
||||
value = kid_elem.get("VALUE")
|
||||
if value:
|
||||
try:
|
||||
kid_bytes = base64.b64decode(value + "==")
|
||||
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||
kids.append(kid_uuid)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# v4.2/v4.3: DATA/PROTECTINFO/KIDS/KID
|
||||
protectinfo_kids = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KIDS/pr:KID", ns)
|
||||
for kid_elem in protectinfo_kids:
|
||||
value = kid_elem.get("VALUE")
|
||||
if value:
|
||||
try:
|
||||
kid_bytes = base64.b64decode(value + "==")
|
||||
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||
if kid_uuid not in kids:
|
||||
kids.append(kid_uuid)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# v4.1: DATA/PROTECTINFO/KID
|
||||
protectinfo_kid = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KID", ns)
|
||||
for kid_elem in protectinfo_kid:
|
||||
value = kid_elem.get("VALUE")
|
||||
if value:
|
||||
try:
|
||||
kid_bytes = base64.b64decode(value + "==")
|
||||
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||
if kid_uuid not in kids:
|
||||
kids.append(kid_uuid)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# v4.0: DATA/KID
|
||||
individual_kids = root.findall(".//pr:DATA/pr:KID", ns)
|
||||
for kid_elem in individual_kids:
|
||||
if kid_elem.text:
|
||||
try:
|
||||
kid_bytes = base64.b64decode(kid_elem.text.strip() + "==")
|
||||
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||
if kid_uuid not in kids:
|
||||
kids.append(kid_uuid)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return kids
|
||||
|
||||
# covers bad base64 (binascii.Error), defusedxml rejections (both ValueError) and XML
|
||||
# ParseError (SyntaxError) from arbitrary third-party PSSH data
|
||||
except (ValueError, SyntaxError):
|
||||
pass
|
||||
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def from_pssh_b64(cls, pssh_b64: str, kid: UUID | None = None) -> PlayReady:
|
||||
"""Load a base64 PSSH box or PlayReady Object, or a bare UTF-16LE WRMHEADER that some packagers emit.
|
||||
@@ -196,14 +101,18 @@ class PlayReady(CencDrm):
|
||||
@staticmethod
|
||||
def header_kids(header: WRMHeader) -> list[UUID]:
|
||||
"""Return the KIDs one WRM header names, in header order."""
|
||||
return [signed_key_id.value for signed_key_id in header.key_ids]
|
||||
|
||||
@staticmethod
|
||||
def custom_attribute_kids(header: WRMHeader) -> list[UUID]:
|
||||
"""Return the KIDs a WRM header lists under CUSTOMATTRIBUTES/KIDS, skipping a value that is not a KID."""
|
||||
if header.custom_attributes is None:
|
||||
return []
|
||||
kids: list[UUID] = []
|
||||
for signed_key_id in getattr(header, "key_ids", []):
|
||||
for element in header.custom_attributes.findall("KIDS/KID"):
|
||||
try:
|
||||
if isinstance(signed_key_id.value, UUID):
|
||||
kids.append(signed_key_id.value)
|
||||
else:
|
||||
kids.append(UUID(bytes_le=base64.b64decode(signed_key_id.value)))
|
||||
except (ValueError, TypeError):
|
||||
kids.append(UUID(bytes_le=base64.b64decode(element.get("VALUE", "") + "==")))
|
||||
except ValueError:
|
||||
continue
|
||||
return kids
|
||||
|
||||
@@ -259,36 +168,9 @@ class PlayReady(CencDrm):
|
||||
)
|
||||
return base64.b64encode(pro).decode()
|
||||
|
||||
def extract_keys_from_cdm(self, cdm: PlayReadyCdm, session_id: bytes) -> dict:
|
||||
"""Extract keys from CDM session with cross-library compatibility.
|
||||
|
||||
Args:
|
||||
cdm: CDM instance
|
||||
session_id: Session identifier
|
||||
|
||||
Returns:
|
||||
Dictionary mapping KID UUIDs to hex keys
|
||||
"""
|
||||
keys = {}
|
||||
for key in cdm.get_keys(session_id):
|
||||
if hasattr(key, "key_id"):
|
||||
kid = key.key_id
|
||||
elif hasattr(key, "kid"):
|
||||
kid = key.kid
|
||||
else:
|
||||
continue
|
||||
|
||||
if hasattr(key, "key") and hasattr(key.key, "hex"):
|
||||
key_hex = key.key.hex()
|
||||
elif hasattr(key, "key") and isinstance(key.key, bytes):
|
||||
key_hex = key.key.hex()
|
||||
elif hasattr(key, "key") and isinstance(key.key, str):
|
||||
key_hex = key.key
|
||||
else:
|
||||
continue
|
||||
|
||||
keys[kid] = key_hex
|
||||
return keys
|
||||
def extract_keys_from_cdm(self, cdm: PlayReadyCdm, session_id: bytes) -> dict[UUID, str]:
|
||||
"""Map each licence key to its hex content key: pyplayready names the KID key_id, pywidevine (HttpCdm) kid."""
|
||||
return {(key.key_id if hasattr(key, "key_id") else key.kid): key.key.hex() for key in cdm.get_keys(session_id)}
|
||||
|
||||
def get_content_keys(self, cdm: PlayReadyCdm, certificate: Callable, licence: Callable) -> None:
|
||||
"""License every distinct WRM header whose KIDs still lack a content key.
|
||||
|
||||
Reference in New Issue
Block a user