#!/usr/bin/env python3 """Check a DFU zip the way the signed (SIGNED_FW) Adafruit bootloader will. usage: bl_verify_pkg.py [key-file] key-file X||Y hex of the P-256 public key (default: tools/bl_allowed_key) Mirrors src/dfu_init.c of adafruit/Adafruit_nRF52_Bootloader (>= 0.10.0): device type 0x0052, the extended init packet marked ECDS (2), the ECDSA P-256 signature (r||s) over SHA-256 of the init packet up to and including the image length and hash, and that length/hash against the image itself. Exit 0 only when the bootloader would take it -- so a package that a locked node would refuse after the transfer is caught before it is published or sent. """ import sys if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"): print(__doc__.strip()) sys.exit(0) import hashlib import json import os import struct import zipfile from ecdsa import BadSignatureError, NIST256p, VerifyingKey from ecdsa.util import sigdecode_string ADAFRUIT_DEVICE_TYPE = 0x0052 USES_ECDS = 2 EXT_SIGNED_LEN = 40 # identifier + image length + sha256 def fail(msg): print(f"REFUSED: {msg}") sys.exit(1) def load_key(path): with open(path) as f: lines = [ln.strip() for ln in f if ln.strip() and not ln.startswith("#")] raw = bytes.fromhex(lines[0]) if len(raw) != 64: fail(f"{path}: expected 64 bytes (X||Y), got {len(raw)}") return VerifyingKey.from_string(raw, curve=NIST256p) def main(): pkg = sys.argv[1] keyfile = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(__file__), "bl_allowed_key") vk = load_key(keyfile) with zipfile.ZipFile(pkg) as z: man = json.loads(z.read("manifest.json"))["manifest"] if "application" not in man: fail(f"no application image in {sorted(man)}") app = man["application"] init = z.read(app["dat_file"]) image = z.read(app["bin_file"]) # dfu_init_packet_t: device_type, device_rev, app_version, softdevice_len, softdevice[] if len(init) < 10: fail("init packet too short") dev_type, _dev_rev, _app_ver, sd_len = struct.unpack_from("