Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55.py

raw
1 # Copyright 2021-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 logging
9 import platform
10 import re
11 import sys
12 from typing import Optional, TypeVar
13
14 from nitrokey.trussed import Uuid, Version
15
16 from . import FirmwareMetadata, ProgressCallback, TrussedBootloader, Variant
17 from .lpc55_upload.mboot.interfaces.usb import MbootUSBInterface
18 from .lpc55_upload.mboot.mcuboot import McuBoot
19 from .lpc55_upload.mboot.properties import PropertyTag
20 from .lpc55_upload.sbfile.sb2.images import BootImageV21
21 from .lpc55_upload.utils.interfaces.device.usb_device import UsbDevice
22
23 RKTH = bytes.fromhex("050aad3e77791a81e59c5b2ba5a158937e9460ee325d8ccba09734b8fdebb171")
24 KEK = bytes([0xAA] * 32)
25 UUID_LEN = 4
26 FILENAME_PATTERN = re.compile("(firmware|alpha)-nk3..-lpc55-(?P<version>.*)\\.sb2$")
27
28 T = TypeVar("T", bound="TrussedBootloaderLpc55")
29
30 logger = logging.getLogger(__name__)
31
32
33 class TrussedBootloaderLpc55(TrussedBootloader):
34 """A Nitrokey 3 device running the LPC55 bootloader."""
35
36 def __init__(self, device: UsbDevice) -> None:
37 self._validate_vid_pid(device.vid, device.pid)
38 self._path = device.path
39 self.device = McuBoot(MbootUSBInterface(device))
40
41 def __enter__(self: T) -> T:
42 self.device.open()
43 return self
44
45 @property
46 def variant(self) -> Variant:
47 return Variant.LPC55
48
49 @property
50 def path(self) -> str:
51 if isinstance(self._path, bytes):
52 return self._path.decode("UTF-8")
53 return self._path
54
55 @property
56 def status(self) -> str:
57 return self.device.status_string
58
59 def close(self) -> None:
60 self.device.close()
61
62 def reboot(self) -> bool:
63 if not self.device.reset(reopen=False):
64 # On Windows, this function returns false even if the reset was successful
65 if platform.system() == "Windows":
66 logger.warning("Failed to reboot Nitrokey 3 bootloader")
67 else:
68 raise Exception("Failed to reboot Nitrokey 3 bootloader")
69 return True
70
71 def uuid(self) -> Optional[Uuid]:
72 uuid = self.device.get_property(PropertyTag.UNIQUE_DEVICE_IDENT)
73 if not uuid:
74 raise ValueError("Missing response for UUID property query")
75 if len(uuid) != UUID_LEN:
76 raise ValueError(f"UUID response has invalid length {len(uuid)}")
77
78 # See GetProperties::device_uuid in the lpc55 crate:
79 # https://github.com/lpc55/lpc55-host/blob/main/src/bootloader/property.rs#L222
80 wrong_endian = (uuid[3] << 96) + (uuid[2] << 64) + (uuid[1] << 32) + uuid[0]
81 right_endian = wrong_endian.to_bytes(16, byteorder="little")
82 return Uuid(int.from_bytes(right_endian, byteorder="big"))
83
84 def update(
85 self, image: bytes, callback: Optional[ProgressCallback] = None, check_errors: bool = False
86 ) -> None:
87 success = self.device.receive_sb_file(
88 image, progress_callback=callback, check_errors=check_errors
89 )
90 logger.debug(f"Firmware update finished with status {self.status}")
91 if success:
92 self.reboot()
93 else:
94 raise Exception(f"Firmware update failed with status {self.status}")
95
96 @classmethod
97 def _list_vid_pid(cls: type[T], vid: int, pid: int) -> list[T]:
98 devices = []
99 for device in UsbDevice.enumerate(vid=vid, pid=pid):
100 try:
101 devices.append(cls(device))
102 except ValueError:
103 logger.warning(
104 f"Invalid Nitrokey 3 LPC55 bootloader returned by enumeration: {device}"
105 )
106 return devices
107
108 @classmethod
109 def _open(cls: type[T], path: str) -> Optional[T]:
110 devices = UsbDevice.enumerate(path=path)
111 if len(devices) == 0:
112 logger.warning(f"No HID device at {path}")
113 return None
114 if len(devices) > 1:
115 logger.warning(f"Multiple HID devices at {path}: {devices}")
116 return None
117
118 try:
119 return cls(devices[0])
120 except ValueError:
121 logger.warning(f"No Nitrokey 3 bootloader at path {path}", exc_info=sys.exc_info())
122 return None
123
124
125 def parse_firmware_image(data: bytes) -> FirmwareMetadata:
126 image = BootImageV21.parse(data, kek=KEK)
127 bcd_version = image.header.product_version
128 version = Version(major=bcd_version.major, minor=bcd_version.minor, patch=bcd_version.service)
129 metadata = FirmwareMetadata(version=version)
130 if image.cert_block:
131 if image.cert_block.rkth == RKTH:
132 metadata.signed_by = "Nitrokey"
133 metadata.signed_by_nitrokey = True
134 else:
135 metadata.signed_by = f"unknown issuer (RKTH: {image.cert_block.rkth.hex()})"
136 return metadata