From 975d3a106df6d6faae56ff28aba2762ddcc59e10 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sun, 29 Nov 2026 12:03:50 -0700 Subject: [PATCH] refactor(commands): run the prd and wvd dump commands through the upstream pyplayready and pywidevine CLIs --- docs/guide/cli-reference.md | 24 ++- docs/guide/drm-and-cdm.md | 16 +- tests/commands/test_device_commands.py | 184 +++++++++++++++++++ unshackle/commands/prd.py | 234 ++++--------------------- unshackle/commands/wvd.py | 56 ++---- unshackle/core/__init__.py | 4 + 6 files changed, 265 insertions(+), 253 deletions(-) create mode 100644 tests/commands/test_device_commands.py diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 0d8d824c..be3c2cbc 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -494,7 +494,7 @@ unshackle wvd COMMAND [ARGS]... | `wvd add PATHS...` | Validate and move one or more `.wvd` files into the WVDs directory. | | `wvd delete NAMES...` | Delete `.wvd` files by name (without extension). Prompts for confirmation. | | `wvd parse PATH` | Parse a `.wvd` and print its System ID, security level, type, flags, and client info. Relative paths resolve against the WVDs directory. | -| `wvd dump WVD_PATHS... OUT_DIR` | Extract a device's contents (metadata, private key, client ID, VMP) into `OUT_DIR//`. With no paths, dumps every WVD in the WVDs directory. | +| `wvd dump WVD_PATHS... OUT_DIR` | Extract a device's contents (metadata, private key, client ID, VMP) into `OUT_DIR//`. With no paths, dumps every WVD in the WVDs directory. `dump` skips a device whose `OUT_DIR//` folder is not empty. | | `wvd new NAME PRIVATE_KEY CLIENT_ID [FILE_HASHES]` | Create a new `.wvd` from a PEM private key and a `ClientIdentification` blob, optionally with a VMP (`FileHashes`) blob. | `wvd new` options: @@ -517,7 +517,7 @@ unshackle wvd COMMAND [ARGS]... ## `prd` -Manage PlayReady Device (`.prd`) files. Devices live in the configured PRDs directory. Built on `pyplayready`. +Manage PlayReady Device (`.prd`) files. Devices live in the configured PRDs directory. Each command runs the matching `pyplayready` command. ``` unshackle prd COMMAND [ARGS]... @@ -525,19 +525,19 @@ unshackle prd COMMAND [ARGS]... ### `prd new PATHS...` -Make a new `.prd`. Give either a single folder that contains `zgpriv.dat` (group key) and `bgroupcert.dat` (group certificate), or two file paths (group key, then group certificate). +Make a new `.prd`. Give either a single folder that contains `zgpriv.dat` (group key) and `bgroupcert.dat` (group certificate), or two file paths (group key, then group certificate). `prd new` refuses a certificate chain that has a device certificate already or that has expired. | Option | Description | |---|---| | `-e`, `--encryption_key` | Optional device ECC private encryption key (generated if omitted). | | `-s`, `--signing_key` | Optional device ECC private signing key (generated if omitted). | -| `-o`, `--output` | Output directory or `.prd` file path. | +| `-o`, `--output` | Output directory or `.prd` file path. The default is the folder that you give, else the PRDs directory. | -`prd new` will not overwrite an existing file. +`prd new` does not overwrite an existing file. ### `prd reprovision PRD_PATH` -Reprovision an existing device by replacing its leaf certificate and keys. Only a device of version 3 or higher can do reprovisioning. Accepts the same `-e` / `-s` / `-o` options. By default it overwrites the device in place. +Reprovision an existing device by replacing its leaf certificate and keys. Only a provisioned device of version 3 or higher can do reprovisioning. Accepts the same `-e` / `-s` / `-o` options. By default it overwrites the device in place. ### `prd test DEVICE` @@ -548,12 +548,24 @@ Do a test of a device against the Microsoft PlayReady demo server and print the | `-c`, `--ckt` | `aesctr` | Content key encryption type: `aesctr` or `aescbc`. | | `-sl`, `--security-level` | `2000` | Minimum security level: `150`, `2000`, or `3000`. | +If the server refuses the licence, `prd test` logs the server reply and exits with code 0. + +### `prd export PRD_PATH` + +Write the group key (`zgpriv.dat`) and the group certificate (`bgroupcert.dat`) of a device into `OUT_DIR//`. `-o` sets `OUT_DIR`; the default is the current directory. A version 2 device has no group key, so `export` writes only the certificate. If the folder is not empty, `export` writes nothing. + +### `prd inspect` + +Show each certificate of a certificate chain: type, security level, expiry date, name, features and keys. Give `-d` with a `.prd` file, or `-c` with a chain file such as `bgroupcert.dat`. + !!! example ```shell unshackle prd new ./device_folder/ unshackle prd new zgpriv.dat bgroupcert.dat -o /out/dir unshackle prd reprovision mydevice.prd unshackle prd test mydevice.prd -sl 3000 -c aescbc + unshackle prd export mydevice.prd -o ./out_dir + unshackle prd inspect -d mydevice.prd ``` --- diff --git a/docs/guide/drm-and-cdm.md b/docs/guide/drm-and-cdm.md index 864d8f2e..14f89896 100644 --- a/docs/guide/drm-and-cdm.md +++ b/docs/guide/drm-and-cdm.md @@ -143,6 +143,7 @@ The `wvd` command group manages `.wvd` files. `delete` removes a device (with a confirmation prompt). `dump` extracts a device's contents (metadata, private key, Client ID, VMP) into a folder. + `dump` does not write into a device folder that is not empty. !!! warning "v1 WVD files must be migrated" If loading a device fails with a message about a "v1 WVD file", it was made with @@ -169,8 +170,8 @@ The `prd` command group creates and maintains `.prd` files. $ unshackle prd new ./device_folder/ ``` - unshackle makes a fresh leaf certificate and writes the device to the PRDs - directory (or to `-o/--output`). Use `-e/--encryption_key` and `-s/--signing_key` + unshackle makes a fresh leaf certificate. The device goes into the folder that + you give, or into the PRDs directory when you give two files, or to `-o/--output`. Use `-e/--encryption_key` and `-s/--signing_key` to supply your own ECC keys instead of generating them. === "Reprovision" @@ -194,6 +195,17 @@ The `prd` command group creates and maintains `.prd` files. `-sl/--security-level` accepts `150`, `2000`, or `3000` (default `2000`). `-c/--ckt` accepts `aesctr` or `aescbc`. +=== "Export / inspect" + + ```console + $ unshackle prd export ./data/PRDs/mydevice.prd -o ./out + $ unshackle prd inspect -d ./data/PRDs/mydevice.prd + ``` + + `export` writes the group key and group certificate of a device into a folder. + `inspect` shows each certificate in the chain of a device (`-d`) or of a chain + file (`-c`). + ## Selecting which device to use: the `cdm` config A device on disk is not enough. You must tell unshackle which device to use diff --git a/tests/commands/test_device_commands.py b/tests/commands/test_device_commands.py new file mode 100644 index 00000000..2bd327a9 --- /dev/null +++ b/tests/commands/test_device_commands.py @@ -0,0 +1,184 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import click +import pytest +import rich_click +from click.testing import CliRunner +from pyplayready import main as prd_upstream +from pywidevine import main as wvd_upstream + +from unshackle.commands import prd as prd_module +from unshackle.commands import wvd as wvd_module +from unshackle.core.config import config + + +def record(monkeypatch: pytest.MonkeyPatch, module: Any, name: str) -> list[dict[str, Any]]: + """Swap an upstream command for one with its parameters whose callback records the call.""" + real = getattr(module, name) + calls: list[dict[str, Any]] = [] + fake = click.Command(real.name, params=real.params, callback=lambda **kwargs: calls.append(kwargs)) + monkeypatch.setattr(module, name, fake) + return calls + + +def names(module: Any, name: str) -> set[str]: + return {param.name for param in getattr(module, name).params if param.name} + + +def files(folder: Path, *names: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + for name in names: + (folder / name).write_bytes(b"x") + return folder + + +def test_prd_new_from_a_folder_passes_its_files_and_saves_into_the_folder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + folder = files(tmp_path / "dev", "zgpriv.dat", "bgroupcert.dat") + calls = record(monkeypatch, prd_upstream, "create_device") + + result = CliRunner().invoke(prd_module.prd, ["new", str(folder)]) + + assert result.exit_code == 0, result.output + assert calls == [ + { + "group_key": folder / "zgpriv.dat", + "protected_group_key": None, + "group_certificate": folder / "bgroupcert.dat", + "encryption_key": None, + "signing_key": None, + "output": folder, + } + ] + assert set(calls[0]) == names(prd_upstream, "create_device") + + +def test_prd_new_from_two_paths_passes_the_keys_and_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + src = files(tmp_path, "key.dat", "cert.dat", "enc.dat", "sig.dat") + monkeypatch.setattr(config.directories, "prds", tmp_path / "PRDs") + calls = record(monkeypatch, prd_upstream, "create_device") + + result = CliRunner().invoke( + prd_module.prd, + [ + "new", + str(src / "key.dat"), + str(src / "cert.dat"), + "-e", + str(src / "enc.dat"), + "-s", + str(src / "sig.dat"), + "-o", + str(tmp_path / "out.prd"), + ], + ) + default = CliRunner().invoke(prd_module.prd, ["new", str(src / "key.dat"), str(src / "cert.dat")]) + + assert result.exit_code == 0, result.output + assert default.exit_code == 0, default.output + assert calls[1]["output"] == tmp_path / "PRDs" + assert calls[0]["group_key"] == src / "key.dat" + assert calls[0]["group_certificate"] == src / "cert.dat" + assert calls[0]["encryption_key"] == src / "enc.dat" + assert calls[0]["signing_key"] == src / "sig.dat" + assert calls[0]["output"] == tmp_path / "out.prd" + + +@pytest.mark.parametrize( + ("args", "message"), + [ + (["dev"], "Folder must contain zgpriv.dat and bgroupcert.dat"), + (["dev", "dev", "dev"], "Provide either a folder path"), + (["dev", "-e", "missing.dat"], None), + (["dev/zgpriv.dat", "missing.dat"], None), + ], +) +def test_prd_new_refuses_bad_paths_before_the_upstream_command( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, args: list[str], message: str | None +) -> None: + files(tmp_path / "dev", "zgpriv.dat") + monkeypatch.chdir(tmp_path) + calls = record(monkeypatch, prd_upstream, "create_device") + + result = CliRunner().invoke(prd_module.prd, ["new", *args]) + + assert result.exit_code == 2 + assert message is None or message in result.output + assert calls == [] + + +def test_prd_reprovision_passes_its_arguments(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + device = files(tmp_path, "d.prd") / "d.prd" + calls = record(monkeypatch, prd_upstream, "reprovision_device") + + result = CliRunner().invoke(prd_module.prd, ["reprovision", str(device), "-o", str(tmp_path / "new.prd")]) + + assert result.exit_code == 0, result.output + assert calls == [{"prd_path": device, "encryption_key": None, "signing_key": None, "output": tmp_path / "new.prd"}] + assert set(calls[0]) == names(prd_upstream, "reprovision_device") + + +def test_prd_test_sends_the_upstream_content_key_type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + device = files(tmp_path, "d.prd") / "d.prd" + calls = record(monkeypatch, prd_upstream, "test") + + result = CliRunner().invoke(prd_module.prd, ["test", str(device), "-c", "AESCBC", "-sl", "3000"]) + + assert result.exit_code == 0, result.output + assert calls == [{"device": device, "ckt": "AES128BitCBC", "security_level": "3000"}] + ckt = next(param for param in prd_upstream.test.params if param.name == "ckt") + assert set(prd_module.CONTENT_KEY_TYPES.values()) == set(ckt.type.choices) + assert set(calls[0]) == names(prd_upstream, "test") + + +def test_prd_lists_the_upstream_export_and_inspect_commands() -> None: + assert prd_module.prd.commands["export"] is prd_upstream.export_device + assert prd_module.prd.commands["inspect"] is prd_upstream.inspect + + +def test_wvd_dump_exports_each_device_and_resolves_a_bare_name_in_the_wvds_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config.directories, "wvds", files(tmp_path / "WVDs", "example.wvd")) + monkeypatch.chdir(tmp_path) + other = files(tmp_path / "elsewhere", "other.wvd") / "other.wvd" + calls = record(monkeypatch, wvd_upstream, "export_device") + + result = CliRunner().invoke(wvd_module.wvd, ["dump", "example", str(other), "out"]) + + assert result.exit_code == 0, result.output + assert calls == [ + {"wvd_path": tmp_path / "WVDs" / "example.wvd", "out_dir": Path("out")}, + {"wvd_path": other, "out_dir": Path("out")}, + ] + assert set(calls[0]) == names(wvd_upstream, "export_device") + + +def test_wvd_dump_names_a_missing_device_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(config.directories, "wvds", tmp_path / "WVDs") + calls = record(monkeypatch, wvd_upstream, "export_device") + + result = CliRunner().invoke(wvd_module.wvd, ["dump", "missing", "out"], standalone_mode=False) + + assert isinstance(result.exception, click.UsageError) + assert str(tmp_path / "WVDs" / "missing.wvd") in result.exception.message + assert calls == [] + + +def test_ctx_invoke_runs_a_command_of_another_package_in_a_sub_context() -> None: + seen: list[tuple[str | None, int]] = [] + foreign = rich_click.RichCommand( + "foreign", + params=[click.Option(["--value"], type=int, default=5)], + callback=click.pass_context(lambda ctx, value: seen.append((ctx.info_name, value))), + ) + outer = click.Command("outer", callback=lambda: click.get_current_context().invoke(foreign)) + + result = CliRunner().invoke(outer) + + assert result.exit_code == 0, result.output + assert seen == [("foreign", 5)] diff --git a/unshackle/commands/prd.py b/unshackle/commands/prd.py index e8706221..14dfc30c 100644 --- a/unshackle/commands/prd.py +++ b/unshackle/commands/prd.py @@ -1,19 +1,14 @@ -import logging from pathlib import Path import click -import requests -from Crypto.Random import get_random_bytes -from pyplayready import InvalidCertificateChain, OutdatedDevice -from pyplayready.cdm import Cdm -from pyplayready.crypto.ecc_key import ECCKey -from pyplayready.device import Device -from pyplayready.system.bcert import Certificate, CertificateChain -from pyplayready.system.pssh import PSSH +from pyplayready import main as upstream from unshackle.core.config import config from unshackle.core.constants import context_settings +CONTENT_KEY_TYPES = {"aesctr": "AES128BitCTR", "aescbc": "AES128BitCBC"} +EXISTING_FILE = click.Path(exists=True, dir_okay=False, path_type=Path) + @click.group( short_help="Manage creation of PRD (Playready Device) files.", @@ -24,22 +19,10 @@ def prd() -> None: @prd.command() -@click.argument("paths", type=Path, nargs=-1) -@click.option( - "-e", - "--encryption_key", - type=Path, - required=False, - help="Optional Device ECC private encryption key", -) -@click.option( - "-s", - "--signing_key", - type=Path, - required=False, - help="Optional Device ECC private signing key", -) -@click.option("-o", "--output", type=Path, default=None, help="Output Directory") +@click.argument("paths", type=click.Path(exists=True, path_type=Path), nargs=-1) +@click.option("-e", "--encryption_key", type=EXISTING_FILE, help="Optional Device ECC private encryption key") +@click.option("-s", "--signing_key", type=EXISTING_FILE, help="Optional Device ECC private signing key") +@click.option("-o", "--output", type=Path, default=None, help="Output Path or Directory") @click.pass_context def new( ctx: click.Context, @@ -54,165 +37,55 @@ def new( containing ``zgpriv.dat`` and ``bgroupcert.dat``. """ if len(paths) == 1 and paths[0].is_dir(): - device_dir = paths[0] - group_key = device_dir / "zgpriv.dat" - group_certificate = device_dir / "bgroupcert.dat" + device_dir: Path | None = paths[0] + group_key, group_certificate = paths[0] / "zgpriv.dat", paths[0] / "bgroupcert.dat" if not group_key.is_file() or not group_certificate.is_file(): raise click.UsageError("Folder must contain zgpriv.dat and bgroupcert.dat", ctx) elif len(paths) == 2: group_key, group_certificate = paths - if not group_key.is_file(): - raise click.UsageError("group_key: Not a path to a file, or it does not exist.", ctx) - if not group_certificate.is_file(): - raise click.UsageError("group_certificate: Not a path to a file, or it does not exist.", ctx) device_dir = None else: - raise click.UsageError( - "Provide either a folder path or paths to group_key and group_certificate", - ctx, - ) - if encryption_key and not encryption_key.is_file(): - raise click.UsageError("encryption_key: Not a path to a file, or it does not exist.", ctx) - if signing_key and not signing_key.is_file(): - raise click.UsageError("signing_key: Not a path to a file, or it does not exist.", ctx) + raise click.UsageError("Provide either a folder path or paths to group_key and group_certificate", ctx) - log = logging.getLogger("prd") - - encryption_key_obj = ECCKey.load(encryption_key) if encryption_key else ECCKey.generate() - signing_key_obj = ECCKey.load(signing_key) if signing_key else ECCKey.generate() - - group_key_obj = ECCKey.load(group_key) - certificate_chain = CertificateChain.load(group_certificate) - - if certificate_chain.get(0).get_issuer_key() != group_key_obj.public_bytes(): - raise InvalidCertificateChain("Group key does not match this certificate") - - new_certificate = Certificate.new_leaf_cert( - cert_id=get_random_bytes(16), - security_level=certificate_chain.get_security_level(), - client_id=get_random_bytes(16), - signing_key=signing_key_obj, - encryption_key=encryption_key_obj, - group_key=group_key_obj, - parent=certificate_chain, + ctx.invoke( + upstream.create_device, + group_key=group_key, + group_certificate=group_certificate, + encryption_key=encryption_key, + signing_key=signing_key, + output=output or device_dir or config.directories.prds, ) - certificate_chain.prepend(new_certificate) - certificate_chain.verify() - - device = Device( - group_key=group_key_obj.dumps(), - encryption_key=encryption_key_obj.dumps(), - signing_key=signing_key_obj.dumps(), - group_certificate=certificate_chain.dumps(), - ) - - if output and output.suffix: - if output.suffix.lower() != ".prd": - log.warning( - "Saving PRD with the file extension '%s' but '.prd' is recommended.", - output.suffix, - ) - out_path = output - else: - out_dir = output or (device_dir or config.directories.prds) - out_path = out_dir / f"{device.get_name()}.prd" - - if out_path.exists(): - log.error("A file already exists at the path '%s', cannot overwrite.", out_path) - return - - out_path.parent.mkdir(parents=True, exist_ok=True) - out_path.write_bytes(device.dumps()) - - log.info("Created Playready Device (.prd) file, %s", out_path.name) - log.info(" + Security Level: %s", device.security_level) - log.info(" + Group Key: %s bytes", len(device.group_key.dumps())) - log.info(" + Encryption Key: %s bytes", len(device.encryption_key.dumps())) - log.info(" + Signing Key: %s bytes", len(device.signing_key.dumps())) - log.info(" + Group Certificate: %s bytes", len(device.group_certificate.dumps())) - log.info(" + Saved to: %s", out_path.absolute()) @prd.command(name="reprovision") -@click.argument("prd_path", type=Path) -@click.option( - "-e", - "--encryption_key", - type=Path, - required=False, - help="Optional Device ECC private encryption key", -) -@click.option( - "-s", - "--signing_key", - type=Path, - required=False, - help="Optional Device ECC private signing key", -) +@click.argument("prd_path", type=EXISTING_FILE) +@click.option("-e", "--encryption_key", type=EXISTING_FILE, help="Optional Device ECC private encryption key") +@click.option("-s", "--signing_key", type=EXISTING_FILE, help="Optional Device ECC private signing key") @click.option("-o", "--output", type=Path, default=None, help="Output Path or Directory") @click.pass_context -def reprovision_device( +def reprovision( ctx: click.Context, prd_path: Path, encryption_key: Path | None, signing_key: Path | None, - output: Path | None = None, + output: Path | None, ) -> None: """Reprovision a PlayReady Device (.prd) file.""" - if not prd_path.is_file(): - raise click.UsageError("prd_path: Not a path to a file, or it does not exist.", ctx) - - log = logging.getLogger("prd") - log.info("Reprovisioning Playready Device (.prd) file, %s", prd_path.name) - - device = Device.load(prd_path) - - if device.group_key is None: - raise OutdatedDevice( - "Device does not support reprovisioning, re-create it or use a Device with a version of 3 or higher" - ) - - device.group_certificate.remove(0) - - encryption_key_obj = ECCKey.load(encryption_key) if encryption_key else ECCKey.generate() - signing_key_obj = ECCKey.load(signing_key) if signing_key else ECCKey.generate() - - device.encryption_key = encryption_key_obj - device.signing_key = signing_key_obj - - new_certificate = Certificate.new_leaf_cert( - cert_id=get_random_bytes(16), - security_level=device.group_certificate.get_security_level(), - client_id=get_random_bytes(16), - signing_key=signing_key_obj, - encryption_key=encryption_key_obj, - group_key=device.group_key, - parent=device.group_certificate, + ctx.invoke( + upstream.reprovision_device, + prd_path=prd_path, + encryption_key=encryption_key, + signing_key=signing_key, + output=output, ) - device.group_certificate.prepend(new_certificate) - - if output and output.suffix: - if output.suffix.lower() != ".prd": - log.warning( - "Saving PRD with the file extension '%s' but '.prd' is recommended.", - output.suffix, - ) - out_path = output - else: - out_path = prd_path - - out_path.parent.mkdir(parents=True, exist_ok=True) - out_path.write_bytes(device.dumps()) - - log.info("Reprovisioned Playready Device (.prd) file, %s", out_path.name) @prd.command() -@click.argument("device", type=Path) +@click.argument("device", type=EXISTING_FILE) @click.option( "-c", "--ckt", - type=click.Choice(["aesctr", "aescbc"], case_sensitive=False), + type=click.Choice(list(CONTENT_KEY_TYPES), case_sensitive=False), default="aesctr", help="Content Key Encryption Type", ) @@ -224,47 +97,10 @@ def reprovision_device( help="Minimum Security Level", ) @click.pass_context -def test( - ctx: click.Context, - device: Path, - ckt: str, - security_level: str, -) -> None: +def test(ctx: click.Context, device: Path, ckt: str, security_level: str) -> None: """Do a test of a PlayReady device on the Microsoft demo server.""" + ctx.invoke(upstream.test, device=device, ckt=CONTENT_KEY_TYPES[ckt], security_level=security_level) - if not device.is_file(): - raise click.UsageError("device: Not a path to a file, or it does not exist.", ctx) - log = logging.getLogger("prd") - - prd_device = Device.load(device) - log.info("Loaded Device: %s", prd_device.get_name()) - - cdm = Cdm.from_device(prd_device) - log.info("Loaded CDM") - - session_id = cdm.open() - log.info("Opened Session") - - pssh_b64 = "AAADfHBzc2gAAAAAmgTweZhAQoarkuZb4IhflQAAA1xcAwAAAQABAFIDPABXAFIATQBIAEUAQQBEAEUAUgAgAHgAbQBsAG4AcwA9ACIAaAB0AHQAcAA6AC8ALwBzAGMAaABlAG0AYQBzAC4AbQBpAGMAcgBvAHMAbwBmAHQALgBjAG8AbQAvAEQAUgBNAC8AMgAwADAANwAvADAAMwAvAFAAbABhAHkAUgBlAGEAZAB5AEgAZQBhAGQAZQByACIAIAB2AGUAcgBzAGkAbwBuAD0AIgA0AC4AMAAuADAALgAwACIAPgA8AEQAQQBUAEEAPgA8AFAAUgBPAFQARQBDAFQASQBOAEYATwA+ADwASwBFAFkATABFAE4APgAxADYAPAAvAEsARQBZAEwARQBOAD4APABBAEwARwBJAEQAPgBBAEUAUwBDAFQAUgA8AC8AQQBMAEcASQBEAD4APAAvAFAAUgBPAFQARQBDAFQASQBOAEYATwA+ADwASwBJAEQAPgA0AFIAcABsAGIAKwBUAGIATgBFAFMAOAB0AEcAawBOAEYAVwBUAEUASABBAD0APQA8AC8ASwBJAEQAPgA8AEMASABFAEMASwBTAFUATQA+AEsATABqADMAUQB6AFEAUAAvAE4AQQA9ADwALwBDAEgARQBDAEsAUwBVAE0APgA8AEwAQQBfAFUAUgBMAD4AaAB0AHQAcABzADoALwAvAHAAcgBvAGYAZgBpAGMAaQBhAGwAcwBpAHQAZQAuAGsAZQB5AGQAZQBsAGkAdgBlAHIAeQAuAG0AZQBkAGkAYQBzAGUAcgB2AGkAYwBlAHMALgB3AGkAbgBkAG8AdwBzAC4AbgBlAHQALwBQAGwAYQB5AFIAZQBhAGQAeQAvADwALwBMAEEAXwBVAFIATAA+ADwAQwBVAFMAVABPAE0AQQBUAFQAUgBJAEIAVQBUAEUAUwA+ADwASQBJAFMAXwBEAFIATQBfAFYARQBSAFMASQBPAE4APgA4AC4AMQAuADIAMwAwADQALgAzADEAPAAvAEkASQBTAF8ARABSAE0AXwBWAEUAUgBTAEkATwBOAD4APAAvAEMAVQBTAFQATwBNAEEAVABUAFIASQBCAFUAVABFAFMAPgA8AC8ARABBAFQAQQA+ADwALwBXAFIATQBIAEUAQQBEAEUAUgA+AA==" - pssh = PSSH(pssh_b64) - - challenge = cdm.get_license_challenge(session_id, pssh.wrm_headers[0]) - log.info("Created License Request") - - license_server = f"https://test.playready.microsoft.com/service/rightsmanager.asmx?cfg=(persist:false,sl:{security_level},ckt:{ckt})" - - response = requests.post( - url=license_server, - headers={"Content-Type": "text/xml; charset=UTF-8"}, - data=challenge, - ) - - cdm.parse_license(session_id, response.text) - log.info("License Parsed Successfully") - - for key in cdm.get_keys(session_id): - log.info(f"{key.key_id.hex}:{key.key.hex()}") - - cdm.close(session_id) - log.info("Closed Session") +prd.add_command(upstream.export_device, name="export") +prd.add_command(upstream.inspect) diff --git a/unshackle/commands/wvd.py b/unshackle/commands/wvd.py index df4121cd..99006a5b 100644 --- a/unshackle/commands/wvd.py +++ b/unshackle/commands/wvd.py @@ -3,8 +3,7 @@ import shutil from pathlib import Path import click -import yaml -from google.protobuf.json_format import MessageToDict +from pywidevine import main as upstream from pywidevine.device import Device, DeviceTypes from pywidevine.license_protocol_pb2 import FileHashes from rich.prompt import Prompt @@ -112,7 +111,8 @@ def parse(path: Path) -> None: @wvd.command() @click.argument("wvd_paths", type=Path, nargs=-1) @click.argument("out_dir", type=Path, nargs=1) -def dump(wvd_paths: list[Path], out_dir: Path) -> None: +@click.pass_context +def dump(ctx: click.Context, wvd_paths: tuple[Path, ...], out_dir: Path) -> None: """ Extract data from a .WVD device file to a folder structure. @@ -121,14 +121,15 @@ def dump(wvd_paths: list[Path], out_dir: Path) -> None: """ log = logging.getLogger("wvd") - if wvd_paths == (): + if not wvd_paths: if not config.directories.wvds.exists(): console.log(f"[bright_blue]{config.directories.wvds.absolute()}[/] does not exist...") - wvd_paths = list(x for x in config.directories.wvds.iterdir() if x.is_file() and x.suffix.lower() == ".wvd") + return + wvd_paths = tuple(x for x in config.directories.wvds.iterdir() if x.is_file() and x.suffix.lower() == ".wvd") if not wvd_paths: console.log(f"[bright_blue]{config.directories.wvds.absolute()}[/] is empty...") - for i, (wvd_path, out_path) in enumerate(zip(wvd_paths, (out_dir / x.stem for x in wvd_paths), strict=True)): + for i, wvd_path in enumerate(wvd_paths): if i > 0: log.info("") @@ -138,47 +139,10 @@ def dump(wvd_paths: list[Path], out_dir: Path) -> None: named = False if named: wvd_path = config.directories.wvds / f"{wvd_path.stem}.wvd" - out_path.mkdir(parents=True, exist_ok=True) + if not wvd_path.is_file(): + raise click.UsageError(f"No WVD file at {wvd_path}", ctx) - log.info(f"Dumping: {wvd_path}") - device = Device.load(wvd_path) - - log.info(f"L{device.security_level} {device.system_id} {device.type.name}") - log.info(f"Saving to: {out_path}") - - device_meta = { - "wvd": {"device_type": device.type.name, "security_level": device.security_level, **device.flags}, - "client_info": {}, - "capabilities": MessageToDict(device.client_id, preserving_proto_field_name=True)["client_capabilities"], - } - for client_info in device.client_id.client_info: - device_meta["client_info"][client_info.name] = client_info.value - - device_meta_path = out_path / "metadata.yml" - device_meta_path.write_text(yaml.dump(device_meta), encoding="utf8") - log.info(" + Device Metadata") - - if device.private_key: - private_key_path = out_path / "private_key.pem" - private_key_path.write_text(data=device.private_key.export_key().decode(), encoding="utf8") - private_key_path.with_suffix(".der").write_bytes(device.private_key.export_key(format="DER")) - log.info(" + Private Key") - else: - log.warning(" - No Private Key available") - - if device.client_id: - client_id_path = out_path / "client_id.bin" - client_id_path.write_bytes(device.client_id.SerializeToString()) - log.info(" + Client ID") - else: - log.warning(" - No Client ID available") - - if device.client_id.vmp_data: - vmp_path = out_path / "vmp.bin" - vmp_path.write_bytes(device.client_id.vmp_data) - log.info(" + VMP (File Hashes)") - else: - log.info(" - No VMP (File Hashes) available") + ctx.invoke(upstream.export_device, wvd_path=wvd_path, out_dir=out_dir) @wvd.command() diff --git a/unshackle/core/__init__.py b/unshackle/core/__init__.py index 09b91aed..6173baa8 100644 --- a/unshackle/core/__init__.py +++ b/unshackle/core/__init__.py @@ -3,9 +3,13 @@ import os from collections.abc import Callable from pathlib import Path +import click.core from rich_click.patch import patch as _patch_click_help +_CLICK_CLASSES = click.core.Command, click.core.Group _patch_click_help() +# The patch also rebinds these, which makes Context.invoke refuse a command that another package built. +click.core.Command, click.core.Group = _CLICK_CLASSES # type: ignore[misc] __version__ = "7.0.0"