Debian Codegraph @

src/nitrokey/trussed/updates.py

raw
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 enum
9 import importlib.metadata
10 import logging
11 import platform
12 import re
13 import time
14 from abc import ABC, abstractmethod
15 from collections.abc import Set
16 from contextlib import contextmanager
17 from importlib.metadata import PackageNotFoundError
18 from io import BytesIO
19 from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Tuple, Union
20
21 from nitrokey._helpers import Retries
22 from nitrokey.trussed import TimeoutException, TrussedBase, Version
23 from nitrokey.trussed._base import Model
24 from nitrokey.trussed._bootloader import (
25 FirmwareContainer,
26 TrussedBootloader,
27 Variant,
28 get_model_data,
29 validate_firmware_image,
30 )
31 from nitrokey.trussed._bootloader.lpc55_upload.mboot.exceptions import McuBootConnectionError
32 from nitrokey.trussed._device import TrussedDevice
33 from nitrokey.trussed.admin_app import BootMode, Status
34 from nitrokey.trussed.admin_app import Variant as AdminAppVariant
35 from nitrokey.updates import Asset, Release, Repository
36
37 if TYPE_CHECKING:
38 import typing_extensions
39
40 logger = logging.getLogger(__name__)
41
42
43 @enum.unique
44 class Warning(enum.Enum):
45 """
46 A warning that can occur during a firmware update.
47
48 By default, these warnings abort the firmware update. This enum can be used to select types
49 of warnings that should be ignored and not cause the firmware update to fail.
50 """
51
52 IFS_MIGRATION_V2 = "ifs-migration-v2"
53 MISSING_STATUS = "missing-status"
54 SDK_VERSION = "sdk-version"
55 UPDATE_FROM_BOOTLOADER = "update-from-bootloader"
56
57 @property
58 def message(self) -> str:
59 if self == Warning.IFS_MIGRATION_V2:
60 return (
61 "Not enough space on the internal filesystem to perform the firmware"
62 " update. See the release notes for more information:"
63 " https://github.com/Nitrokey/nitrokey-3-firmware/releases/tag/v1.8.2"
64 )
65 if self == Warning.MISSING_STATUS:
66 return (
67 "Could not determine the device state as the current firmware is too old."
68 " Please update to firmware version v1.3.1 first."
69 )
70 if self == Warning.SDK_VERSION:
71 return (
72 "Your Nitrokey SDK version is outdated. Please update this program to the latest"
73 " version and try again."
74 )
75 if self == Warning.UPDATE_FROM_BOOTLOADER:
76 return (
77 "The current state of the device cannot be checked as it is already in bootloader"
78 " mode. Please review the release notes at:"
79 " https://github.com/Nitrokey/nitrokey-3-firmware/releases"
80 )
81
82 if TYPE_CHECKING:
83 typing_extensions.assert_never(self)
84
85 return self.value
86
87 @classmethod
88 def from_str(cls, s: str) -> "Warning":
89 for w in cls:
90 if w.value == s:
91 return w
92 raise ValueError(f"Unexpected update warning id: {s}")
93
94
95 @enum.unique
96 class _Migration(enum.Enum):
97 # IFS migration to use journaling on the NRF52 introduced in v1.3.0 (NK3)
98 NRF_IFS_MIGRATION = enum.auto()
99 # IFS migration to filesystem layout 2 (FIDO2 RK migration) in v1.8.2 (NK3)
100 IFS_MIGRATION_V2 = enum.auto()
101
102 @classmethod
103 def get(
104 cls,
105 model: Model,
106 variant: Union[Variant, AdminAppVariant],
107 current: Optional[Version],
108 new: Version,
109 ) -> frozenset["_Migration"]:
110 if model != Model.NK3:
111 return frozenset()
112
113 if isinstance(variant, AdminAppVariant):
114 if variant == AdminAppVariant.USBIP:
115 raise ValueError("Cannot perform firmware update for USBIP runner")
116 elif variant == AdminAppVariant.LPC55:
117 variant = Variant.LPC55
118 elif variant == AdminAppVariant.NRF52:
119 variant = Variant.NRF52
120 else:
121 if TYPE_CHECKING:
122 typing_extensions.assert_never(variant)
123
124 raise ValueError(f"Unsupported device variant: {variant}")
125
126 migrations = set()
127
128 if variant == Variant.NRF52:
129 if current is None or current <= Version(1, 2, 2) and new >= Version(1, 3, 0):
130 migrations.add(cls.NRF_IFS_MIGRATION)
131
132 ifs_migration_v2 = Version(1, 8, 2)
133 if current is not None and current < ifs_migration_v2 and new >= ifs_migration_v2:
134 migrations.add(cls.IFS_MIGRATION_V2)
135
136 return frozenset(migrations)
137
138
139 def get_firmware_repository(model: Model) -> Repository:
140 data = get_model_data(model)
141 return Repository(owner="Nitrokey", name=data.firmware_repository_name)
142
143
144 def get_firmware_update(model: Model, release: Release) -> Asset:
145 data = get_model_data(model)
146 return release.require_asset(re.compile(data.firmware_pattern_string))
147
148
149 def _get_extra_information(migrations: Set[_Migration]) -> List[str]:
150 """Return additional information for the device after update based on update-path"""
151
152 out = []
153 if _Migration.NRF_IFS_MIGRATION in migrations:
154 out += [
155 "",
156 "During this update process the internal filesystem will be migrated!",
157 "- Migration will only work, if your internal filesystem does not contain more than 45 Resident Keys. If you have more please remove some.",
158 "- After the update it might take up to 3 minutes for the first boot.",
159 "Never unplug the device while the LED is active!",
160 ]
161 return out
162
163
164 def _get_finalization_wait_retries(migrations: Set[_Migration]) -> int:
165 """Return number of retries to wait for the device after update based on update-path"""
166
167 out = 60
168 if _Migration.NRF_IFS_MIGRATION in migrations:
169 # max time 150secs == 300 retries
170 out = 500
171 return out
172
173
174 class UpdateUi(ABC):
175 @abstractmethod
176 def error(self, *msgs: Any) -> Exception:
177 pass
178
179 @abstractmethod
180 def show_warning(self, warning: Warning) -> None:
181 pass
182
183 @abstractmethod
184 def raise_warning(self, warning: Warning) -> Exception:
185 pass
186
187 @abstractmethod
188 def abort(self, *msgs: Any) -> Exception:
189 pass
190
191 @abstractmethod
192 def abort_downgrade(self, current: Version, image: Version) -> Exception:
193 pass
194
195 @abstractmethod
196 def abort_pynitrokey_version(self, current: Version, required: Version) -> Exception:
197 pass
198
199 @abstractmethod
200 def confirm_download(self, current: Optional[Version], new: Version) -> None:
201 pass
202
203 @abstractmethod
204 def confirm_update(self, current: Optional[Version], new: Version) -> None:
205 pass
206
207 @abstractmethod
208 def confirm_pynitrokey_version(self, current: Version, required: Version) -> None:
209 pass
210
211 @abstractmethod
212 def confirm_extra_information(self, extra_info: List[str]) -> None:
213 pass
214
215 @abstractmethod
216 def confirm_update_same_version(self, version: Version) -> None:
217 pass
218
219 @abstractmethod
220 def pre_bootloader_hint(self) -> None:
221 pass
222
223 @abstractmethod
224 def request_bootloader_confirmation(self) -> None:
225 pass
226
227 @abstractmethod
228 @contextmanager
229 def download_progress_bar(self, desc: str) -> Iterator[Callable[[int, int], None]]:
230 pass
231
232 @abstractmethod
233 @contextmanager
234 def update_progress_bar(self) -> Iterator[Callable[[int, int], None]]:
235 pass
236
237 @abstractmethod
238 @contextmanager
239 def finalization_progress_bar(self) -> Iterator[Callable[[int, int], None]]:
240 pass
241
242
243 class DeviceHandler(ABC):
244 @abstractmethod
245 def await_bootloader(self, model: Model) -> TrussedBootloader: ...
246
247 @abstractmethod
248 def await_device(
249 self,
250 model: Model,
251 wait_retries: Optional[int],
252 callback: Optional[Callable[[int, int], None]],
253 ) -> TrussedDevice: ...
254
255
256 class Updater:
257 def __init__(
258 self,
259 ui: UpdateUi,
260 device_handler: DeviceHandler,
261 ignore_warnings: Set[Warning] = frozenset(),
262 ) -> None:
263 self.ui = ui
264 self.device_handler = device_handler
265 self.ignore_warnings = ignore_warnings
266
267 def _trigger_warning(self, warning: Warning) -> None:
268 if warning in self.ignore_warnings:
269 self.ui.show_warning(warning)
270 else:
271 raise self.ui.raise_warning(warning)
272
273 def update(
274 self,
275 device: TrussedBase,
276 image: Optional[str] = None,
277 update_version: Optional[str] = None,
278 ignore_pynitrokey_version: bool = False,
279 ) -> Tuple[Version, Status]:
280 model = device.model
281
282 update_from_bootloader = False
283 current_version = None
284 status = None
285 if isinstance(device, TrussedBootloader):
286 update_from_bootloader = True
287 self._trigger_warning(Warning.UPDATE_FROM_BOOTLOADER)
288 elif isinstance(device, TrussedDevice):
289 current_version = device.admin.version()
290 status = device.admin.status()
291 else:
292 raise self.ui.error(f"Unexpected Trussed device: {device}")
293
294 logger.info(f"Firmware version before update: {current_version or ''}")
295 container = self._prepare_update(model, image, update_version, current_version)
296
297 if not update_from_bootloader:
298 if status is None:
299 if model == Model.NK3:
300 if container.version > Version.from_str("1.3.1"):
301 self._trigger_warning(Warning.MISSING_STATUS)
302 else:
303 self.ui.error(f"Missing status for {model} device")
304
305 self._check_minimum_version(container, ignore_pynitrokey_version)
306
307 self.ui.confirm_update(current_version, container.version)
308
309 migrations = None
310 if status is not None and status.variant is not None:
311 migrations = self._check_migrations(
312 model, status.variant, current_version, container.version, status
313 )
314 elif isinstance(device, TrussedBootloader):
315 migrations = self._check_migrations(
316 model, device.variant, current_version, container.version, status
317 )
318
319 with self._get_bootloader(device) as bootloader:
320 if bootloader.variant not in container.images:
321 raise self.ui.error(
322 "The firmware release does not contain an image for the "
323 f"{bootloader.variant.value} hardware variant"
324 )
325 try:
326 validate_firmware_image(
327 bootloader.variant,
328 container.images[bootloader.variant],
329 container.version,
330 model,
331 )
332 except Exception as e:
333 raise self.ui.error("Failed to validate firmware image", e) from e
334
335 if migrations is None:
336 migrations = self._check_migrations(
337 model, bootloader.variant, current_version, container.version, status
338 )
339
340 self._perform_update(bootloader, container)
341
342 wait_retries = _get_finalization_wait_retries(migrations)
343 with self.ui.finalization_progress_bar() as callback:
344 with self.device_handler.await_device(model, wait_retries, callback) as device:
345 version = device.admin.version()
346 if version != container.version:
347 raise self.ui.error(
348 f"The firmware update to {container.version} was successful, but the "
349 f"firmware is still reporting version {version}."
350 )
351 status = device.admin.status()
352
353 return container.version, status
354
355 def _prepare_update(
356 self,
357 model: Model,
358 image: Optional[str],
359 version: Optional[str],
360 current_version: Optional[Version],
361 ) -> FirmwareContainer:
362 if image:
363 try:
364 container = FirmwareContainer.parse(image, model)
365 except Exception as e:
366 raise self.ui.error("Failed to parse firmware container", e) from e
367 self._validate_version(current_version, container.version)
368 return container
369 else:
370 repository = get_firmware_repository(model)
371 if version:
372 try:
373 logger.info(f"Downloading firmare version {version}")
374 release = repository.get_release(version)
375 except Exception as e:
376 raise self.ui.error(f"Failed to get firmware release {version}", e) from e
377 else:
378 try:
379 release = repository.get_latest_release()
380 logger.info(f"Latest firmware version: {release}")
381 except Exception as e:
382 raise self.ui.error("Failed to find latest firmware release", e) from e
383
384 try:
385 release_version = Version.from_v_str(release.tag)
386 except ValueError as e:
387 raise self.ui.error("Failed to parse version from release tag", e) from e
388 self._validate_version(current_version, release_version)
389 self.ui.confirm_download(current_version, release_version)
390 return self._download_update(model, release)
391
392 def _download_update(self, model: Model, release: Release) -> FirmwareContainer:
393 try:
394 update = get_firmware_update(model, release)
395 except Exception as e:
396 raise self.ui.error(f"Failed to find firmware image for release {release}", e) from e
397
398 try:
399 logger.info(f"Trying to download firmware update from URL: {update.url}")
400
401 with self.ui.download_progress_bar(update.tag) as callback:
402 data = update.read(callback=callback)
403 except Exception as e:
404 raise self.ui.error(f"Failed to download latest firmware update {update.tag}", e) from e
405
406 try:
407 container = FirmwareContainer.parse(BytesIO(data), model)
408 except Exception as e:
409 raise self.ui.error(f"Failed to parse firmware container for {update.tag}", e) from e
410
411 release_version = Version.from_v_str(release.tag)
412 if release_version != container.version:
413 raise self.ui.error(
414 f"The firmware container for {update.tag} has the version {container.version}"
415 )
416
417 return container
418
419 def _check_minimum_version(
420 self, container: FirmwareContainer, ignore_pynitrokey_version: bool
421 ) -> None:
422 if container.sdk:
423 try:
424 sdk_version = Version.from_python_str(importlib.metadata.version("nitrokey"))
425 except PackageNotFoundError as e:
426 raise self.ui.error("Failed to determine the Nitrokey SDK version") from e
427
428 if container.sdk > sdk_version:
429 logger.warning(
430 f"Minimum SDK version required for update is {container.sdk} (current version: {sdk_version})"
431 )
432 self._trigger_warning(Warning.SDK_VERSION)
433 elif container.pynitrokey:
434 # The minimum pynitrokey version has been replaced by the minimum SDK version, so we
435 # only check it if there is no minimum SDK version set.
436
437 # this is the version of pynitrokey when we moved to the SDK
438 pynitrokey_version = Version.from_str("0.4.49")
439 if container.pynitrokey > pynitrokey_version:
440 if ignore_pynitrokey_version:
441 self.ui.confirm_pynitrokey_version(
442 current=pynitrokey_version, required=container.pynitrokey
443 )
444 else:
445 raise self.ui.abort_pynitrokey_version(
446 current=pynitrokey_version, required=container.pynitrokey
447 )
448
449 def _validate_version(self, current_version: Optional[Version], new_version: Version) -> None:
450 logger.info(f"Current firmware version: {current_version}")
451 logger.info(f"Updated firmware version: {new_version}")
452
453 if current_version:
454 if current_version.core() > new_version.core():
455 raise self.ui.abort_downgrade(current_version, new_version)
456 elif current_version == new_version:
457 if current_version.complete and new_version.complete:
458 same_version = current_version
459 else:
460 same_version = current_version.core()
461 self.ui.confirm_update_same_version(same_version)
462
463 @contextmanager
464 def _get_bootloader(self, device: TrussedBase) -> Iterator[TrussedBootloader]:
465 model = device.model
466 if isinstance(device, TrussedDevice):
467 self.ui.request_bootloader_confirmation()
468 try:
469 device.admin.reboot(BootMode.BOOTROM)
470 except TimeoutException as e:
471 raise self.ui.abort("The reboot was not confirmed with the touch button") from e
472
473 # needed for udev to properly handle new device
474 time.sleep(1)
475
476 self.ui.pre_bootloader_hint()
477
478 exc = None
479 for t in Retries(3):
480 logger.debug(f"Trying to connect to bootloader ({t})")
481 try:
482 with self.device_handler.await_bootloader(model) as bootloader:
483 # noop to test communication
484 _ = bootloader.uuid
485 yield bootloader
486 break
487 except McuBootConnectionError as e:
488 logger.debug("Received connection error", exc_info=True)
489 exc = e
490 else:
491 msgs = [f"Failed to connect to {model} bootloader"]
492 if platform.system() == "Linux":
493 msgs += ["Are the Nitrokey udev rules installed and active?"]
494 raise self.ui.error(*msgs, exc)
495 elif isinstance(device, TrussedBootloader):
496 yield device
497 else:
498 raise self.ui.error(f"Unexpected {model} device: {device}")
499
500 def _check_migrations(
501 self,
502 model: Model,
503 variant: Union[Variant, AdminAppVariant],
504 current_version: Optional[Version],
505 new_version: Version,
506 status: Optional[Status],
507 ) -> frozenset["_Migration"]:
508 try:
509 migrations = _Migration.get(
510 model=model, variant=variant, current=current_version, new=new_version
511 )
512 except ValueError as e:
513 raise self.ui.error(str(e)) from e
514
515 txt = _get_extra_information(migrations)
516 if len(txt) > 0:
517 self.ui.confirm_extra_information(txt)
518
519 if _Migration.IFS_MIGRATION_V2 in migrations:
520 if status and status.ifs_blocks is not None and status.ifs_blocks < 5:
521 self._trigger_warning(Warning.IFS_MIGRATION_V2)
522
523 return migrations
524
525 def _perform_update(self, device: TrussedBootloader, container: FirmwareContainer) -> None:
526 logger.debug("Starting firmware update")
527 image = container.images[device.variant]
528 with self.ui.update_progress_bar() as callback:
529 try:
530 device.update(image, callback=callback)
531 except Exception as e:
532 raise self.ui.error("Failed to perform firmware update", e) from e
533 logger.debug("Firmware update finished successfully")