suf2 0.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
suf2/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Host-side tooling for the draft SUF2 format."""
2
+
3
+ from importlib import metadata as _metadata
4
+
5
+ try:
6
+ __version__ = _metadata.version("suf2")
7
+ except _metadata.PackageNotFoundError:
8
+ # Source-only checkouts have no installed distribution metadata.
9
+ __version__ = "0.0.0.dev0"
suf2/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
suf2/cli.py ADDED
@@ -0,0 +1,183 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ from .image import load
5
+ from .keys import generate_keys, load_master_key
6
+ from .packer import pack, text_field
7
+
8
+ ADDRESS_LIMIT = 1 << 32
9
+ HEX_DIGITS = "0123456789abcdefABCDEF"
10
+
11
+ HELP = """\
12
+ SUF2 packer (current draft profile)
13
+ Usage:
14
+ suf2 [--cli] pack --input firmware.{bin,hex,elf} --output firmware.suf2
15
+ --key signing-private.pem --product <name> --key-id <nonzero u32>
16
+ --family <u32> --base <0x...>
17
+ [--end <exclusive address>] [--fill <byte>]
18
+ [--security-version <u32>] [--timestamp <u64>] [--creator <name>]
19
+ [--encrypt none|firmware|all --master-key <PEM> --master-key-id <nonzero u32>]
20
+ suf2 [--cli] keygen --output <directory> [--signing-only|--master-only]
21
+ suf2 [--cli] --help
22
+
23
+ All addresses are decimal or 0x-prefixed hexadecimal. The base is required.
24
+ Fill is a decimal or 0x-prefixed byte (0..255).
25
+ Sparse regions are preserved. Filling requires BOTH --end and --fill.
26
+ Product names are 0..12 printable ASCII characters; creators are 0..15.
27
+ Signing/master-key IDs are provisioned labels, not hashes; no bytes are rebased.
28
+ Images are limited to 16 MiB. Only unencrypted PKCS#8 P-256 private PEM keys
29
+ are accepted. Output is created exclusively; existing files are never replaced.
30
+ Encryption needs a SUF2 AES-256 MASTER KEY PEM bundle, not a legacy AES key.
31
+ Salts are generated afresh; user-supplied salts and nonces are not supported.
32
+ Keygen creates local test keys: signing-private.pem, signing-public.pem and
33
+ master-key.pem. The master bundle is marked test-only. Never use these in products.
34
+ The output directory is required. Existing keys are never replaced.
35
+ On Unix, new directories use 0700 and files 0600; existing directories must
36
+ not allow group or other access. On Windows, protect the directory with ACLs.
37
+ Use --help to show this text.
38
+ """
39
+
40
+ ALLOWED = ("--input", "--output", "--key", "--product", "--key-id", "--family",
41
+ "--base", "--end", "--fill", "--security-version", "--timestamp",
42
+ "--creator", "--encrypt", "--master-key", "--master-key-id")
43
+
44
+
45
+ def number(text: str, maximum: int, name: str) -> int:
46
+ hexadecimal = text[:2].lower() == "0x"
47
+ digits = text[2:] if hexadecimal else text
48
+ valid = "0123456789" if not hexadecimal else HEX_DIGITS
49
+ if not digits or any(c not in valid for c in digits):
50
+ raise ValueError(f"Invalid {name} value.")
51
+ digits = digits.lstrip("0") or "0"
52
+ if len(digits) > len(format(maximum, "x" if hexadecimal else "d")):
53
+ raise ValueError(f"Invalid {name} value.")
54
+ value = int(digits, 16 if hexadecimal else 10)
55
+ if value > maximum:
56
+ raise ValueError(f"Invalid {name} value.")
57
+ return value
58
+
59
+
60
+ def parse(args: list[str]) -> dict:
61
+ if not args or args[0] != "pack":
62
+ raise ValueError("Expected 'pack' or 'keygen'; use --help for usage.")
63
+ values: dict[str, str] = {}
64
+ for i in range(1, len(args), 2):
65
+ if (args[i] not in ALLOWED or i + 1 == len(args)
66
+ or (args[i + 1].startswith("--") and args[i] not in ("--product", "--creator"))
67
+ or args[i] in values):
68
+ raise ValueError("Unknown, duplicate or incomplete option; use --help.")
69
+ values[args[i]] = args[i + 1]
70
+
71
+ def required(name: str, *, empty: bool = False) -> str:
72
+ if name not in values or (not empty and not values[name]):
73
+ raise ValueError(f"Missing {name}.")
74
+ return values[name]
75
+
76
+ options = {"input": required("--input"), "output": required("--output"), "key": required("--key")}
77
+ options["product"] = required("--product", empty=True)
78
+ text_field(options["product"], 12, "Product name")
79
+ options["key_id"] = number(required("--key-id"), 0xFFFFFFFF, "signing-key ID")
80
+ if not options["key_id"]:
81
+ raise ValueError("Signing-key ID must be nonzero.")
82
+ options["family"] = number(required("--family"), 0xFFFFFFFF, "family")
83
+ options["security_version"] = number(values.get("--security-version", "0"), 0xFFFFFFFF,
84
+ "security version")
85
+ options["timestamp"] = number(values.get("--timestamp", "0"), 0xFFFFFFFFFFFFFFFF, "timestamp")
86
+ options["creator"] = values.get("--creator", "")
87
+ text_field(options["creator"], 16, "Creator", terminated=True)
88
+ options["encrypt"] = values.get("--encrypt", "none")
89
+ if options["encrypt"] not in ("none", "firmware", "all"):
90
+ raise ValueError("--encrypt must be none, firmware or all.")
91
+ options["master_key_path"] = None
92
+ options["master_key_id"] = None
93
+ if options["encrypt"] == "none":
94
+ if "--master-key" in values or "--master-key-id" in values:
95
+ raise ValueError("Master-key options require --encrypt firmware or all.")
96
+ else:
97
+ options["master_key_path"] = required("--master-key")
98
+ options["master_key_id"] = number(required("--master-key-id"), 0xFFFFFFFF, "master-key ID")
99
+ if not options["master_key_id"]:
100
+ raise ValueError("Master-key ID must be nonzero.")
101
+ options["base"] = number(required("--base"), 0xFFFFFFFF, "base")
102
+ options["end"] = number(values["--end"], ADDRESS_LIMIT, "end") if "--end" in values else None
103
+ options["fill"] = number(values["--fill"], 255, "fill") if "--fill" in values else None
104
+ if options["fill"] is not None and options["end"] is None:
105
+ raise ValueError("--fill requires --end.")
106
+ if options["end"] is not None and options["fill"] is None:
107
+ raise ValueError("--end requires --fill.")
108
+ if options["end"] is not None and options["end"] <= options["base"]:
109
+ raise ValueError("--end must be greater than --base.")
110
+ return options
111
+
112
+
113
+ def keygen(args: list[str]) -> None:
114
+ output = None
115
+ flags = set()
116
+ i = 0
117
+ while i < len(args):
118
+ option = args[i]
119
+ if option == "--output" and output is None:
120
+ if i + 1 == len(args) or args[i + 1].startswith("--"):
121
+ raise ValueError("Unknown, duplicate or incomplete option; use --help.")
122
+ output = args[i + 1]
123
+ i += 2
124
+ elif option in ("--signing-only", "--master-only") and option not in flags:
125
+ flags.add(option)
126
+ i += 1
127
+ else:
128
+ raise ValueError("Unknown, duplicate or incomplete option; use --help.")
129
+ if not output:
130
+ raise ValueError("Missing --output.")
131
+ if len(flags) > 1:
132
+ raise ValueError("Use only one of --signing-only and --master-only.")
133
+ kind = "signing" if "--signing-only" in flags else "master" if flags else "all"
134
+ generate_keys(Path(output), kind)
135
+
136
+
137
+ def main(argv: list[str] | None = None) -> int:
138
+ args = sys.argv[1:] if argv is None else argv
139
+ if args[:1] == ["--cli"]:
140
+ args = args[1:]
141
+ if not args or args in (["--help"], ["-h"], ["pack", "--help"], ["pack", "-h"],
142
+ ["keygen", "--help"], ["keygen", "-h"]):
143
+ print(HELP, end="")
144
+ return 0
145
+ created_output = None
146
+ try:
147
+ if args[0] == "keygen":
148
+ keygen(args[1:])
149
+ print("Created local key material. Never use it in production.")
150
+ return 0
151
+ options = parse(args)
152
+ with Path(options["key"]).open("rb") as source:
153
+ pem = source.read(16 * 1024 + 1)
154
+ if len(pem) > 16 * 1024:
155
+ raise ValueError("Signing key PEM is too large.")
156
+ image = load(Path(options["input"]), options["base"], options["end"], options["fill"])
157
+ master_key = (load_master_key(Path(options["master_key_path"]))[0]
158
+ if options["master_key_path"] is not None else None)
159
+ result = pack(image, options["product"], pem, key_id=options["key_id"],
160
+ family=options["family"], security_version=options["security_version"],
161
+ timestamp=options["timestamp"], creator=options["creator"],
162
+ encrypt=options["encrypt"], master_key=master_key,
163
+ master_key_id=options["master_key_id"])
164
+ with Path(options["output"]).open("xb") as output:
165
+ created_output = Path(options["output"])
166
+ output.write(result)
167
+ except (OSError, ValueError, TypeError) as error:
168
+ if isinstance(error, OSError):
169
+ message = "Cannot read input/keys or create output (existing outputs are not overwritten)."
170
+ else:
171
+ message = str(error)
172
+ print(f"Error: {message}", file=sys.stderr)
173
+ if created_output is not None:
174
+ try:
175
+ created_output.unlink(missing_ok=True)
176
+ except OSError as cleanup_error:
177
+ print(f"Error: Cannot remove incomplete output '{created_output}': {cleanup_error}",
178
+ file=sys.stderr)
179
+ return 1
180
+ length = sum(len(content) for _, content in image)
181
+ print(f"Created signed package: {length} image bytes in {len(image)} region(s); "
182
+ f"encryption: {options['encrypt']}.")
183
+ return 0
suf2/image.py ADDED
@@ -0,0 +1,164 @@
1
+ import struct
2
+ from pathlib import Path
3
+
4
+ MAX_SIZE = 16 * 1024 * 1024
5
+
6
+
7
+ def intel_hex(data: bytes) -> list[tuple[int, bytes]]:
8
+ segments = []
9
+ offset = 0
10
+ segmented = False
11
+ ended = False
12
+ for line in data.decode("ascii").splitlines():
13
+ if not line.strip():
14
+ continue
15
+ if ended:
16
+ raise ValueError("Intel HEX data follows the end-of-file record")
17
+ if not line.startswith(":") or len(line) % 2 != 1:
18
+ raise ValueError("Invalid Intel HEX record")
19
+ if any(c not in "0123456789abcdefABCDEF" for c in line[1:]):
20
+ raise ValueError("Invalid Intel HEX hexadecimal data")
21
+ raw = bytes.fromhex(line[1:])
22
+ if len(raw) < 5 or len(raw) != raw[0] + 5 or sum(raw) % 256:
23
+ raise ValueError("Invalid Intel HEX length or checksum")
24
+ count, address, kind = raw[0], int.from_bytes(raw[1:3], "big"), raw[3]
25
+ payload = raw[4:-1]
26
+ if kind == 0:
27
+ leading = min(count, 0x10000 - address) if segmented else count
28
+ if offset + address + leading > 0x100000000:
29
+ raise ValueError("Intel HEX data overflows the 32-bit address range")
30
+ if leading:
31
+ segments.append((offset + address, payload[:leading]))
32
+ if leading < count:
33
+ segments.append((offset, payload[leading:]))
34
+ elif kind == 1:
35
+ if count != 0 or address != 0:
36
+ raise ValueError("Invalid Intel HEX end-of-file record")
37
+ ended = True
38
+ elif kind in (2, 4):
39
+ if count != 2 or address != 0:
40
+ raise ValueError("Invalid Intel HEX extended-address record")
41
+ offset = int.from_bytes(payload, "big") << (4 if kind == 2 else 16)
42
+ segmented = kind == 2
43
+ elif kind in (3, 5):
44
+ if count != 4 or address != 0:
45
+ raise ValueError("Invalid Intel HEX entry-point record")
46
+ else:
47
+ raise ValueError("Unsupported Intel HEX record type")
48
+ if not ended:
49
+ raise ValueError("Intel HEX end-of-file record is missing")
50
+ return segments
51
+
52
+
53
+ def elf(data: bytes) -> list[tuple[int, bytes]]:
54
+ if len(data) < 16 or data[:4] != b"\x7fELF":
55
+ raise ValueError("Invalid ELF header")
56
+ elf_class = data[4]
57
+ if data[5:7] != b"\x01\x01" or elf_class not in (1, 2):
58
+ raise ValueError("Only little-endian ELF32/ELF64 version 1 is supported")
59
+ header_size = 52 if elf_class == 1 else 64
60
+ if len(data) < header_size:
61
+ raise ValueError("Truncated ELF header")
62
+ if struct.unpack_from("<H", data, 16)[0] != 2:
63
+ raise ValueError("Only executable ELF files (ET_EXEC) are supported")
64
+ if struct.unpack_from("<I", data, 20)[0] != 1:
65
+ raise ValueError("Unsupported ELF version")
66
+ if elf_class == 1:
67
+ phoff = struct.unpack_from("<I", data, 28)[0]
68
+ ehsize, phsize, count = struct.unpack_from("<HHH", data, 40)
69
+ expected = 32
70
+ else:
71
+ phoff = struct.unpack_from("<Q", data, 32)[0]
72
+ ehsize, phsize, count = struct.unpack_from("<HHH", data, 52)
73
+ expected = 56
74
+ if ehsize != header_size or phsize != expected or count in (0, 0xFFFF):
75
+ raise ValueError("Unsupported ELF program-header layout")
76
+ if phoff < header_size or phoff + phsize * count > len(data):
77
+ raise ValueError("Truncated ELF program-header table")
78
+ segments = []
79
+ for index in range(count):
80
+ pos = phoff + index * phsize
81
+ if elf_class == 1:
82
+ kind, start, _, address, size, memory, _, _ = struct.unpack_from("<8I", data, pos)
83
+ else:
84
+ kind, _, start, _, address, size, memory, _ = struct.unpack_from("<II6Q", data, pos)
85
+ if kind != 1:
86
+ continue
87
+ if size > memory or start + size > len(data):
88
+ raise ValueError("Invalid ELF load segment")
89
+ if size:
90
+ segments.append((address, data[start:start + size]))
91
+ return segments
92
+
93
+
94
+ def normalize(segments: list[tuple[int, bytes]]) -> list[tuple[int, bytes]]:
95
+ if not segments:
96
+ raise ValueError("Firmware image must be nonempty")
97
+ total = 0
98
+ for address, payload in segments:
99
+ if not isinstance(address, int) or isinstance(address, bool) or not 0 <= address <= 0xFFFFFFFF:
100
+ raise ValueError("Firmware address must be an unsigned 32-bit address")
101
+ if not payload:
102
+ raise ValueError("Firmware regions must be nonempty")
103
+ if address + len(payload) > 0x100000000:
104
+ raise ValueError("Firmware address range exceeds 32 bits")
105
+ total += len(payload)
106
+ if total > MAX_SIZE:
107
+ raise ValueError("Image must be nonempty and at most 16 MiB")
108
+ regions = []
109
+ start = 0
110
+ content = bytearray()
111
+ for address, payload in sorted(segments, key=lambda segment: segment[0]):
112
+ if content and address < start + len(content):
113
+ raise ValueError("Overlapping firmware segments are not supported")
114
+ if content and address != start + len(content):
115
+ regions.append((start, bytes(content)))
116
+ content.clear()
117
+ if not content:
118
+ start = address
119
+ content.extend(payload)
120
+ regions.append((start, bytes(content)))
121
+ return regions
122
+
123
+
124
+ def assemble(segments: list[tuple[int, bytes]], base: int,
125
+ end: int | None = None, fill: int | None = None) -> list[tuple[int, bytes]]:
126
+ if not 0 <= base <= 0xFFFFFFFF:
127
+ raise ValueError("Execution base must be an unsigned 32-bit address")
128
+ if (end is None) != (fill is None):
129
+ raise ValueError("Gap filling requires both --end and --fill")
130
+ if fill is not None and not 0 <= fill <= 255:
131
+ raise ValueError("Fill must be a byte (0..255)")
132
+ regions = normalize(segments)
133
+ if regions[0][0] != base:
134
+ raise ValueError("Execution base must match the lowest loaded address")
135
+ if end is None or fill is None:
136
+ return regions
137
+ if end < regions[-1][0] + len(regions[-1][1]) or end > 0x100000000:
138
+ raise ValueError("Image range must include every loaded byte without overflow")
139
+ length = end - base
140
+ if not 0 < length <= MAX_SIZE:
141
+ raise ValueError("Image must be nonempty and at most 16 MiB")
142
+ result = bytearray([fill]) * length
143
+ for address, payload in regions:
144
+ start = address - base
145
+ result[start:start + len(payload)] = payload
146
+ return [(base, bytes(result))]
147
+
148
+
149
+ def load(path: Path, base: int, end: int | None = None,
150
+ fill: int | None = None) -> list[tuple[int, bytes]]:
151
+ with path.open("rb") as source:
152
+ data = source.read(MAX_SIZE + 1)
153
+ if len(data) > MAX_SIZE:
154
+ raise ValueError("Input file exceeds the 16 MiB limit")
155
+ extension = path.suffix.lower()
156
+ if extension == ".bin":
157
+ segments = [(base, data)] if data else []
158
+ elif extension == ".hex":
159
+ segments = intel_hex(data)
160
+ elif extension == ".elf":
161
+ segments = elf(data)
162
+ else:
163
+ raise ValueError("Input must be a .bin, .hex or .elf file")
164
+ return assemble(segments, base, end, fill)
suf2/keys.py ADDED
@@ -0,0 +1,87 @@
1
+ import base64
2
+ import os
3
+ from pathlib import Path
4
+ import secrets
5
+ import sys
6
+
7
+ from cryptography.hazmat.primitives import serialization
8
+ from cryptography.hazmat.primitives.asymmetric import ec
9
+
10
+
11
+ def generate_keys(output: Path, kind: str = "all") -> None:
12
+ if kind not in ("all", "signing", "master"):
13
+ raise ValueError("Invalid key kind.")
14
+ names = ([] if kind == "master" else ["signing-private.pem", "signing-public.pem"])
15
+ if kind != "signing":
16
+ names.append("master-key.pem")
17
+ paths = [output / name for name in names]
18
+ if any(path.exists() or path.is_symlink() for path in paths):
19
+ raise ValueError("Output files already exist; refusing to overwrite keys.")
20
+ output.mkdir(mode=0o700, parents=True, exist_ok=True)
21
+ if os.name == "posix" and output.stat().st_mode & 0o077:
22
+ raise ValueError("Output directory must not allow group or other access.")
23
+
24
+ material = []
25
+ if kind != "master":
26
+ key = ec.generate_private_key(ec.SECP256R1())
27
+ material.extend((
28
+ key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
29
+ serialization.NoEncryption()),
30
+ key.public_key().public_bytes(serialization.Encoding.PEM,
31
+ serialization.PublicFormat.SubjectPublicKeyInfo),
32
+ ))
33
+ if kind != "signing":
34
+ master = secrets.token_bytes(32)
35
+ while not any(master):
36
+ master = secrets.token_bytes(32)
37
+ encoded = base64.b64encode(b"SUF2KMR1\x01" + master)
38
+ material.append(b"-----BEGIN SUF2 AES-256 MASTER KEY-----\n" + encoded
39
+ + b"\n-----END SUF2 AES-256 MASTER KEY-----\n")
40
+ created = []
41
+ try:
42
+ for path, value in zip(paths, material):
43
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
44
+ created.append(path)
45
+ with os.fdopen(descriptor, "wb") as stream:
46
+ stream.write(value)
47
+ except OSError:
48
+ for path in created:
49
+ try:
50
+ path.unlink(missing_ok=True)
51
+ except OSError as cleanup_error:
52
+ print(f"Error: Cannot remove incomplete key '{path}': {cleanup_error}",
53
+ file=sys.stderr)
54
+ raise
55
+
56
+
57
+ def load_master_key(path: Path) -> tuple[bytes, bool]:
58
+ with path.open("rb") as source:
59
+ data = source.read(16385)
60
+ if len(data) > 16384:
61
+ raise ValueError("PEM file is too large")
62
+ try:
63
+ lines = data.decode("ascii").splitlines()
64
+ except UnicodeDecodeError as error:
65
+ raise ValueError("PEM file must contain ASCII text") from error
66
+ if (len(lines) < 3 or lines[0] != "-----BEGIN SUF2 AES-256 MASTER KEY-----"
67
+ or lines[-1] != "-----END SUF2 AES-256 MASTER KEY-----"):
68
+ raise ValueError("expected a SUF2 AES-256 MASTER KEY PEM block")
69
+ encoded_lines = lines[1:-1]
70
+ encoded = "".join(encoded_lines)
71
+ if (not encoded_lines or any(not line or len(line) > 64 for line in encoded_lines)
72
+ or encoded_lines != [encoded[i:i + 64] for i in range(0, len(encoded), 64)]):
73
+ raise ValueError("PEM body must use canonical 64-character base64 lines")
74
+ try:
75
+ payload = base64.b64decode(encoded, validate=True)
76
+ except ValueError as error:
77
+ raise ValueError("PEM body must contain valid base64") from error
78
+ if base64.b64encode(payload).decode("ascii") != encoded:
79
+ raise ValueError("PEM body must contain canonical base64")
80
+ if len(payload) != 41 or payload[:8] != b"SUF2KMR1":
81
+ raise ValueError("PEM payload must contain a 41-byte SUF2KMR1 master-key bundle")
82
+ flags, key = payload[8], payload[9:]
83
+ if flags & ~1:
84
+ raise ValueError("PEM bundle contains unsupported flags")
85
+ if not any(key):
86
+ raise ValueError("K_master must not be all zero")
87
+ return key, bool(flags & 1)
suf2/packer.py ADDED
@@ -0,0 +1,105 @@
1
+ import hashlib
2
+ import os
3
+ import struct
4
+
5
+ from cryptography.hazmat.primitives import hashes, serialization
6
+ from cryptography.hazmat.primitives.asymmetric import ec, utils
7
+ from cryptography.exceptions import UnsupportedAlgorithm
8
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
9
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
10
+
11
+ from .image import normalize
12
+
13
+ ORDER = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
14
+
15
+
16
+ def uint(value: object, bits: int, name: str, *, nonzero: bool = False) -> int:
17
+ if (not isinstance(value, int) or isinstance(value, bool)
18
+ or not int(nonzero) <= value < 1 << bits):
19
+ raise ValueError(f"{name} must be {'a nonzero' if nonzero else 'an'} unsigned {bits}-bit integer")
20
+ return value
21
+
22
+
23
+ def text_field(value: str, length: int, name: str, *, terminated: bool = False) -> bytes:
24
+ limit = length - int(terminated)
25
+ if (not isinstance(value, str) or len(value) > limit
26
+ or any(not 0x20 <= ord(character) <= 0x7E for character in value)):
27
+ raise ValueError(f"{name} must contain at most {limit} printable ASCII characters")
28
+ return value.encode("ascii").ljust(length, b"\0")
29
+
30
+
31
+ def pack(regions: list[tuple[int, bytes]], product: str, pem: bytes, *,
32
+ key_id: int, family: int, security_version: int = 0, timestamp: int = 0,
33
+ creator: str = "", encrypt: str = "none", master_key: bytes | None = None,
34
+ master_key_id: int | None = None) -> bytes:
35
+ regions = normalize(regions)
36
+ product_field = text_field(product, 12, "Product name")
37
+ creator_field = text_field(creator, 16, "Creator", terminated=True)
38
+ uint(key_id, 32, "Signing-key ID", nonzero=True)
39
+ uint(family, 32, "Family")
40
+ uint(security_version, 32, "Security version")
41
+ uint(timestamp, 64, "Timestamp")
42
+ if encrypt not in ("none", "firmware", "all"):
43
+ raise ValueError("Encryption must be none, firmware or all")
44
+ encryption_id = 0
45
+ if encrypt == "none":
46
+ if master_key is not None or master_key_id is not None:
47
+ raise ValueError("Master-key options require encryption")
48
+ else:
49
+ if master_key is None or len(master_key) != 32 or not any(master_key):
50
+ raise ValueError("Encryption requires a nonzero 32-byte master key")
51
+ encryption_id = uint(master_key_id, 32, "Master-key ID", nonzero=True)
52
+ if not pem.startswith(b"-----BEGIN PRIVATE KEY-----"):
53
+ raise ValueError("Use an unencrypted PKCS#8 PEM private key")
54
+ try:
55
+ key = serialization.load_pem_private_key(pem, password=None)
56
+ except (ValueError, TypeError, UnsupportedAlgorithm) as error:
57
+ raise ValueError("Cannot parse the PKCS#8 signing key") from error
58
+ if not isinstance(key, ec.EllipticCurvePrivateKey) or not isinstance(key.curve, ec.SECP256R1):
59
+ raise ValueError("Signing key must use ECDSA P-256")
60
+ manifest = bytearray(b"SUF2" + product_field)
61
+ manifest += struct.pack("<IIQ", key_id, len(regions), timestamp)
62
+ manifest += creator_field + struct.pack("<II", security_version, family)
63
+ for address, content in regions:
64
+ manifest += struct.pack("<II", address, len(content)) + hashlib.sha256(content).digest()
65
+ signature = key.sign(b"SUF2-REGION-MANIFEST\0" + manifest, ec.ECDSA(hashes.SHA256()))
66
+ r, s = utils.decode_dss_signature(signature)
67
+ s = min(s, ORDER - s)
68
+ manifest += r.to_bytes(32, "big") + s.to_bytes(32, "big")
69
+ fragments = (len(manifest) + 431) // 432
70
+ count = fragments + sum((len(content) + 255) // 256 for _, content in regions)
71
+ aead = None
72
+ salt = bytes(16)
73
+ if master_key is not None:
74
+ salt = os.urandom(16)
75
+ package_key = HKDF(hashes.SHA256(), 32, salt, b"SUF2-PACKAGE-AEAD-v1").derive(master_key)
76
+ aead = AESGCM(package_key)
77
+
78
+ def chunks():
79
+ for offset in range(0, len(manifest), 432):
80
+ yield 10, offset, bytes(manifest[offset:offset + 432])
81
+ for address, content in regions:
82
+ for offset in range(0, len(content), 256):
83
+ yield 8, address + offset, content[offset:offset + 256]
84
+
85
+ result = bytearray()
86
+ for number, (flags, target, content) in enumerate(chunks()):
87
+ useful = len(content)
88
+ key_field = 0
89
+ block = bytearray(512)
90
+ if aead is not None and (encrypt == "all" or flags == 8):
91
+ flags += 1
92
+ key_field = encryption_id
93
+ aad = b"SUF2-PACKAGE-BLOCK-AEAD\0" + struct.pack(
94
+ "<7I", family, flags, key_field, count, number, target, useful) + salt
95
+ sealed = aead.encrypt(struct.pack("<I", number) + bytes(8), content, aad)
96
+ content, tag = sealed[:-16], sealed[-16:]
97
+ block[44:60] = salt
98
+ block[60:76] = tag
99
+ struct.pack_into("<11I", block, 0, 0x32465553, 0x9E5D5157, 0x2001,
100
+ target, 4 * ((44 + useful + 3) // 4), number, count, family,
101
+ useful, flags, key_field)
102
+ block[76:76 + useful] = content
103
+ struct.pack_into("<I", block, 508, 0x0AB16F30)
104
+ result.extend(block)
105
+ return bytes(result)
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: suf2
3
+ Version: 0.0.5
4
+ Summary: Signed firmware packaging for the draft SUF2 authenticated UF2 profile
5
+ Author: Ji Dong
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/djwinter29-oss/suf2
8
+ Project-URL: Documentation, https://github.com/djwinter29-oss/suf2/blob/main/docs/cli.md
9
+ Project-URL: Source, https://github.com/djwinter29-oss/suf2
10
+ Project-URL: Issues, https://github.com/djwinter29-oss/suf2/issues
11
+ Project-URL: Releases, https://github.com/djwinter29-oss/suf2/releases
12
+ Keywords: uf2,firmware,embedded,ecdsa,signed-updates
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Security :: Cryptography
20
+ Classifier: Topic :: Software Development :: Build Tools
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: cryptography>=43
25
+ Dynamic: license-file
26
+
27
+ # Python CLI
28
+
29
+ The Python implementation is CLI-only. See the common
30
+ [CLI user guide](https://github.com/djwinter29-oss/suf2/blob/main/docs/cli.md) for commands, options, image conversion, signing,
31
+ encryption and build/CI usage.
32
+
33
+ ## Install in a virtual environment (recommended)
34
+
35
+ Requires Python 3.10+; installation includes the `cryptography` dependency.
36
+ The wheel includes SUF2's [BSD-3-Clause license](https://github.com/djwinter29-oss/suf2/blob/main/LICENSE); dependency
37
+ distributions provide their own license texts and notices.
38
+ From the repository root:
39
+
40
+ ```sh
41
+ python -m venv .venv
42
+ ```
43
+
44
+ Activate the environment for your shell:
45
+
46
+ | Shell | Activate |
47
+ | --- | --- |
48
+ | POSIX shell | `. .venv/bin/activate` |
49
+ | Windows PowerShell | `.\.venv\Scripts\Activate.ps1` |
50
+
51
+ Then install and run:
52
+
53
+ ```sh
54
+ python -m pip install ./host/python
55
+ python -m suf2 --help
56
+ suf2 --help
57
+ ```
58
+
59
+ While activated, `python` and the installed `suf2` command use the venv. If the
60
+ package is already installed there, skip installation. Commands work from any
61
+ directory after installation; only the install command above assumes the
62
+ repository root. Use `python3` instead of `python` if that is your Python 3
63
+ interpreter's name.
64
+
65
+ Activation is optional. Invoke the venv interpreter directly when it is not
66
+ activated, or if PowerShell activation is restricted:
67
+
68
+ ```sh
69
+ .venv/bin/python -m suf2 --help
70
+ ```
71
+
72
+ On Windows, use `.\.venv\Scripts\python.exe -m suf2 --help`. Use that same
73
+ interpreter with `-m pip install ./host/python` to install without activation.
74
+
75
+ ## Install for your local user
76
+
77
+ Outside a venv, where the interpreter permits user installations:
78
+
79
+ ```sh
80
+ python -m pip install --user ./host/python
81
+ python -m suf2 --help
82
+ ```
83
+
84
+ The `suf2` console command also works if Python's user scripts directory is on
85
+ `PATH`; pip reports when it is missing. `python -m suf2` does not require that
86
+ scripts directory on `PATH`, but must use the interpreter that owns the
87
+ installation. User-installed packages are normally not visible inside an
88
+ isolated venv.
89
+
90
+ If pip reports an externally managed environment, use a venv rather than
91
+ overriding the system Python's protections.
92
+
93
+ ## Published packages and installed version
94
+
95
+ Once a release is published to PyPI, install it with the selected interpreter:
96
+
97
+ ```sh
98
+ python -m pip install suf2
99
+ ```
100
+
101
+ Inspect the version installed in that same interpreter:
102
+
103
+ ```sh
104
+ python -m pip show suf2
105
+ python -c "import suf2; print(suf2.__version__)"
106
+ ```
107
+
108
+ Both report the installed distribution version. A release tag such as
109
+ `v1.2.3` produces package version `1.2.3`; there is no manually maintained
110
+ version constant to update for each release. Installed Git checkouts can
111
+ have development versions. A source-only checkout without distribution
112
+ metadata reports `0.0.0.dev0`, which is not a released version.
113
+
114
+ This is the host package version, not the SUF2 wire profile or the firmware's
115
+ `--security-version` counter. See the
116
+ [release guide](https://github.com/djwinter29-oss/suf2/blob/main/docs/deployment/releasing.md)
117
+ for artifact versioning and publication gates.
118
+
119
+ ## Run from the source tree
120
+
121
+ Without installing the package, use `PYTHONPATH` with an already installed
122
+ `cryptography` dependency (POSIX shell):
123
+
124
+ ```sh
125
+ PYTHONPATH=host/python/src python -m suf2 --help
126
+ ```
127
+
128
+ ## Checks
129
+
130
+ From the repository root, without installing the package:
131
+
132
+ ```sh
133
+ PYTHONPATH=host/python/src python -m unittest discover -s host/python/tests -v
134
+ ```
@@ -0,0 +1,12 @@
1
+ suf2/__init__.py,sha256=9N_JYo9cwlUw7bI6xADDtkrwDKnA8xbfjxIa05WDoK8,285
2
+ suf2/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ suf2/cli.py,sha256=VRFshFfOR-6J8w9dMwMdQ_UykJ1FpvIGNzf7Xw9Qemo,8899
4
+ suf2/image.py,sha256=gYTEkECfNEOiQvwYjrcdz_O6c112bi8NPF9KX6sdWnw,7073
5
+ suf2/keys.py,sha256=SyJwRkxbqzr3RoqNDfUv2b5bUsyzliaXtEbCW6_spok,3896
6
+ suf2/packer.py,sha256=F8jq1dCWhqiu1f9qDeCpbGKnEU6jCfT0YICC1zeJ3U0,5113
7
+ suf2-0.0.5.dist-info/licenses/LICENSE,sha256=brgyVmbGdyjDx2HX7lNYPzgdtFSLXDbkk50rMc9yHNg,1494
8
+ suf2-0.0.5.dist-info/METADATA,sha256=Ok98RLWpI-9D1kiOGGdvt8EtHFu_-wsTG93wXwIDS04,4524
9
+ suf2-0.0.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ suf2-0.0.5.dist-info/entry_points.txt,sha256=X-BYvZrnm2rRHbskmUnkOe-0HcLRGrNu90hKABNFWwk,39
11
+ suf2-0.0.5.dist-info/top_level.txt,sha256=Pd4F0zHFrKaGTpVoEnp-p2OhzuUx10aD32CwOr0cT5o,5
12
+ suf2-0.0.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ suf2 = suf2.cli:main
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Ji Dong
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ suf2