| 1 |
# Copyright 2022 Nitrokey Developers |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or |
| 4 |
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or |
| 5 |
# http://opensource.org/licenses/MIT>, at your option. This file may not be |
| 6 |
# copied, modified, or distributed except according to those terms. |
| 7 |
|
| 8 |
import hashlib |
| 9 |
import logging |
| 10 |
import re |
| 11 |
import time |
| 12 |
from abc import abstractmethod |
| 13 |
from dataclasses import dataclass |
| 14 |
from io import BytesIO |
| 15 |
from typing import Optional, Sequence, TypeVar |
| 16 |
from zipfile import ZipFile |
| 17 |
|
| 18 |
from cryptography.exceptions import InvalidSignature |
| 19 |
from cryptography.hazmat.primitives import hashes, serialization |
| 20 |
from cryptography.hazmat.primitives.asymmetric import ec, utils |
| 21 |
|
| 22 |
from nitrokey.trussed import Uuid, Version |
| 23 |
|
| 24 |
from . import FirmwareMetadata, ProgressCallback, TrussedBootloader, Variant |
| 25 |
from .nrf52_upload.dfu.dfu_transport import DfuEvent |
| 26 |
from .nrf52_upload.dfu.dfu_transport_serial import DfuTransportSerial |
| 27 |
from .nrf52_upload.dfu.init_packet_pb import InitPacketPB |
| 28 |
from .nrf52_upload.dfu.manifest import Manifest |
| 29 |
from .nrf52_upload.lister.device_lister import DeviceLister |
| 30 |
|
| 31 |
logger = logging.getLogger(__name__) |
| 32 |
|
| 33 |
MANIFEST_FILENAME = "manifest.json" |
| 34 |
FILENAME_PATTERN = re.compile("(firmware|alpha)-(nk3..|nkpk)-nrf52-(?P<version>.*)\\.zip$") |
| 35 |
|
| 36 |
T = TypeVar("T", bound="TrussedBootloaderNrf52") |
| 37 |
|
| 38 |
|
| 39 |
@dataclass |
| 40 |
class SignatureKey: |
| 41 |
name: str |
| 42 |
is_official: bool |
| 43 |
# generate with: |
| 44 |
# $ openssl ec -in dfu_public.pem -inform pem -pubin -outform der | xxd -p |
| 45 |
der: str |
| 46 |
|
| 47 |
def public_key(self) -> ec.EllipticCurvePublicKey: |
| 48 |
public_key = serialization.load_der_public_key(bytes.fromhex(self.der)) |
| 49 |
assert isinstance(public_key, ec.EllipticCurvePublicKey) |
| 50 |
assert isinstance(public_key.curve, ec.SECP256R1) |
| 51 |
return public_key |
| 52 |
|
| 53 |
def verify(self, signature: bytes, message: bytes) -> bool: |
| 54 |
assert len(signature) == 64 |
| 55 |
r = int(signature[:32].hex(), 16) |
| 56 |
s = int(signature[32:].hex(), 16) |
| 57 |
try: |
| 58 |
self.public_key().verify( |
| 59 |
utils.encode_dss_signature(r, s), |
| 60 |
message, |
| 61 |
signature_algorithm=ec.ECDSA(hashes.SHA256()), |
| 62 |
) |
| 63 |
return True |
| 64 |
except InvalidSignature: |
| 65 |
return False |
| 66 |
|
| 67 |
|
| 68 |
@dataclass |
| 69 |
class Image: |
| 70 |
init_packet: InitPacketPB |
| 71 |
firmware_dat: bytes |
| 72 |
firmware_bin: bytes |
| 73 |
is_signed: bool = False |
| 74 |
signature_key: Optional[SignatureKey] = None |
| 75 |
|
| 76 |
@classmethod |
| 77 |
def parse(cls, data: bytes, keys: Sequence[SignatureKey]) -> "Image": |
| 78 |
io = BytesIO(data) |
| 79 |
with ZipFile(io) as pkg: |
| 80 |
with pkg.open(MANIFEST_FILENAME) as f: |
| 81 |
manifest = Manifest.from_json(f.read()) |
| 82 |
if not manifest.application: |
| 83 |
raise Exception("Missing application in firmware package manifest") |
| 84 |
if not manifest.application.dat_file: |
| 85 |
raise Exception("Missing dat file for application in firmware package manifest") |
| 86 |
if not manifest.application.bin_file: |
| 87 |
raise Exception("Missing bin file for application in firmware package manifest") |
| 88 |
with pkg.open(manifest.application.dat_file, "r") as f: |
| 89 |
firmware_dat = f.read() |
| 90 |
with pkg.open(manifest.application.bin_file, "r") as f: |
| 91 |
firmware_bin = f.read() |
| 92 |
init_packet = InitPacketPB(from_bytes=firmware_dat) |
| 93 |
|
| 94 |
if init_packet.init_command.app_size != len(firmware_bin): |
| 95 |
raise Exception("Invalid app size") |
| 96 |
|
| 97 |
h = hashlib.sha256() |
| 98 |
h.update(firmware_bin) |
| 99 |
hash = bytes(reversed(h.digest())) |
| 100 |
if hash != init_packet.init_command.hash.hash: |
| 101 |
raise Exception("Invalid hash for firmware image") |
| 102 |
|
| 103 |
image = cls(init_packet=init_packet, firmware_dat=firmware_dat, firmware_bin=firmware_bin) |
| 104 |
|
| 105 |
if init_packet.packet.signed_command: |
| 106 |
image.is_signed = True |
| 107 |
signature = init_packet.packet.signed_command.signature |
| 108 |
# see nordicsemi.dfu.signing.Signing.sign |
| 109 |
signature = signature[31::-1] + signature[63:31:-1] |
| 110 |
message = init_packet.get_init_command_bytes() |
| 111 |
for key in keys: |
| 112 |
if key.verify(signature, message): |
| 113 |
image.signature_key = key |
| 114 |
|
| 115 |
return image |
| 116 |
|
| 117 |
|
| 118 |
class TrussedBootloaderNrf52(TrussedBootloader): |
| 119 |
def __init__(self, path: str, uuid: int) -> None: |
| 120 |
self._path = path |
| 121 |
self._uuid = uuid |
| 122 |
|
| 123 |
@property |
| 124 |
def variant(self) -> Variant: |
| 125 |
return Variant.NRF52 |
| 126 |
|
| 127 |
@property |
| 128 |
def path(self) -> str: |
| 129 |
return self._path |
| 130 |
|
| 131 |
@property |
| 132 |
@abstractmethod |
| 133 |
def _signature_keys(self) -> Sequence[SignatureKey]: ... |
| 134 |
|
| 135 |
def close(self) -> None: |
| 136 |
pass |
| 137 |
|
| 138 |
def reboot(self) -> bool: |
| 139 |
return False |
| 140 |
|
| 141 |
def uuid(self) -> Optional[Uuid]: |
| 142 |
return Uuid(self._uuid) |
| 143 |
|
| 144 |
def update(self, image: bytes, callback: Optional[ProgressCallback] = None) -> None: |
| 145 |
# based on https://github.com/NordicSemiconductor/pc-nrfutil/blob/1caa347b1cca3896f4695823f48abba15fbef76b/nordicsemi/dfu/dfu.py |
| 146 |
# we have to implement this ourselves because we want to read the files |
| 147 |
# from memory, not from the filesystem |
| 148 |
|
| 149 |
parsed_image = Image.parse(image, self._signature_keys) |
| 150 |
|
| 151 |
time.sleep(3) |
| 152 |
|
| 153 |
dfu = DfuTransportSerial(self.path) |
| 154 |
|
| 155 |
if callback: |
| 156 |
total = len(parsed_image.firmware_bin) |
| 157 |
callback(0, total) |
| 158 |
dfu.register_events_callback(DfuEvent.PROGRESS_EVENT, CallbackWrapper(callback, total)) |
| 159 |
|
| 160 |
dfu.open() |
| 161 |
dfu.send_init_packet(parsed_image.firmware_dat) |
| 162 |
dfu.send_firmware(parsed_image.firmware_bin) |
| 163 |
dfu.close() |
| 164 |
|
| 165 |
@classmethod |
| 166 |
def _list_vid_pid(cls: type[T], vid: int, pid: int) -> list[T]: |
| 167 |
return [cls(port, serial) for port, serial in _list_ports(vid, pid)] |
| 168 |
|
| 169 |
@classmethod |
| 170 |
def _open_vid_pid(cls: type[T], vid: int, pid: int, path: str) -> Optional[T]: |
| 171 |
for port, serial in _list_ports(vid, pid): |
| 172 |
if path == port: |
| 173 |
return cls(path, serial) |
| 174 |
return None |
| 175 |
|
| 176 |
|
| 177 |
@dataclass |
| 178 |
class CallbackWrapper: |
| 179 |
callback: ProgressCallback |
| 180 |
total: int |
| 181 |
n: int = 0 |
| 182 |
|
| 183 |
def __call__(self, progress: int) -> None: |
| 184 |
self.n += progress |
| 185 |
self.callback(self.n, self.total) |
| 186 |
|
| 187 |
|
| 188 |
def _list_ports(vid: int, pid: int) -> list[tuple[str, int]]: |
| 189 |
ports = [] |
| 190 |
for device in DeviceLister().enumerate(): |
| 191 |
vendor_id = int(device.vendor_id, base=16) |
| 192 |
product_id = int(device.product_id, base=16) |
| 193 |
assert device.com_ports |
| 194 |
if len(device.com_ports) > 1: |
| 195 |
logger.warning( |
| 196 |
f"Nitrokey 3 NRF52 bootloader has multiple com ports: {device.com_ports}" |
| 197 |
) |
| 198 |
if vendor_id == vid and product_id == pid: |
| 199 |
port = device.com_ports[0] |
| 200 |
serial = int(device.serial_number, base=16) |
| 201 |
logger.debug(f"Found Nitrokey 3 NRF52 bootloader with port {port}") |
| 202 |
ports.append((port, serial)) |
| 203 |
else: |
| 204 |
logger.debug( |
| 205 |
f"Skipping device {vendor_id:x}:{product_id:x} with ports {device.com_ports}" |
| 206 |
) |
| 207 |
return ports |
| 208 |
|
| 209 |
|
| 210 |
def parse_firmware_image(data: bytes, keys: Sequence[SignatureKey]) -> FirmwareMetadata: |
| 211 |
image = Image.parse(data, keys) |
| 212 |
version = Version.from_int(image.init_packet.init_command.fw_version) |
| 213 |
metadata = FirmwareMetadata(version=version) |
| 214 |
|
| 215 |
if image.is_signed: |
| 216 |
metadata.signed_by = image.signature_key.name if image.signature_key else "unknown" |
| 217 |
if image.signature_key: |
| 218 |
metadata.signed_by_nitrokey = image.signature_key.is_official |
| 219 |
|
| 220 |
return metadata |