| 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 enum |
| 9 |
import hashlib |
| 10 |
import json |
| 11 |
import logging |
| 12 |
import sys |
| 13 |
from abc import abstractmethod |
| 14 |
from dataclasses import dataclass |
| 15 |
from io import BytesIO |
| 16 |
from re import Pattern |
| 17 |
from typing import TYPE_CHECKING, Callable, Dict, Optional, Tuple, Union |
| 18 |
from zipfile import ZipFile |
| 19 |
|
| 20 |
from .._base import Model, TrussedBase |
| 21 |
from .._utils import Version |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from .nrf52 import SignatureKey |
| 25 |
|
| 26 |
logger = logging.getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
ProgressCallback = Callable[[int, int], None] |
| 30 |
|
| 31 |
|
| 32 |
@dataclass |
| 33 |
class ModelData: |
| 34 |
firmware_repository_name: str |
| 35 |
firmware_pattern_string: str |
| 36 |
nrf52_signature_keys: list["SignatureKey"] |
| 37 |
|
| 38 |
|
| 39 |
def get_model_data(model: Model) -> ModelData: |
| 40 |
if model == Model.NK3: |
| 41 |
from nitrokey.nk3 import _NK3_DATA |
| 42 |
|
| 43 |
return _NK3_DATA |
| 44 |
if model == Model.NKPK: |
| 45 |
from nitrokey.nkpk import _NKPK_DATA |
| 46 |
|
| 47 |
return _NKPK_DATA |
| 48 |
raise ValueError(f"Unknown model {model}") |
| 49 |
|
| 50 |
|
| 51 |
class Variant(enum.Enum): |
| 52 |
LPC55 = "lpc55" |
| 53 |
NRF52 = "nrf52" |
| 54 |
|
| 55 |
@classmethod |
| 56 |
def from_str(cls, s: str) -> "Variant": |
| 57 |
for variant in cls: |
| 58 |
if variant.value == s: |
| 59 |
return variant |
| 60 |
raise ValueError(f"Unknown variant {s}") |
| 61 |
|
| 62 |
|
| 63 |
def _validate_checksum(checksums: dict[str, str], path: str, data: bytes) -> None: |
| 64 |
if path not in checksums: |
| 65 |
raise ValueError(f"Missing checksum for file {path} in firmware container") |
| 66 |
m = hashlib.sha256() |
| 67 |
m.update(data) |
| 68 |
checksum = m.hexdigest() |
| 69 |
if checksum != checksums[path]: |
| 70 |
raise ValueError(f"Invalid checksum for file {path} in firmware container") |
| 71 |
|
| 72 |
|
| 73 |
@dataclass |
| 74 |
class FirmwareContainer: |
| 75 |
version: Version |
| 76 |
pynitrokey: Optional[Version] |
| 77 |
sdk: Optional[Version] |
| 78 |
images: Dict[Variant, bytes] |
| 79 |
|
| 80 |
@classmethod |
| 81 |
def parse(cls, path: Union[str, BytesIO], model: Model) -> "FirmwareContainer": |
| 82 |
with ZipFile(path) as z: |
| 83 |
checksum_lines = z.read("sha256sums").decode("utf-8").splitlines() |
| 84 |
checksum_pairs = [line.split(" ", maxsplit=1) for line in checksum_lines] |
| 85 |
checksums = {path: checksum for checksum, path in checksum_pairs} |
| 86 |
|
| 87 |
manifest_bytes = z.read("manifest.json") |
| 88 |
_validate_checksum(checksums, "manifest.json", manifest_bytes) |
| 89 |
manifest = json.loads(manifest_bytes) |
| 90 |
actual_model = Model.from_str(manifest["device"]) |
| 91 |
if actual_model != model: |
| 92 |
raise ValueError(f"Expected firmware container for {model}, got {actual_model}") |
| 93 |
version = Version.from_v_str(manifest["version"]) |
| 94 |
pynitrokey = None |
| 95 |
if "pynitrokey" in manifest: |
| 96 |
pynitrokey = Version.from_v_str(manifest["pynitrokey"]) |
| 97 |
sdk = None |
| 98 |
if "sdk" in manifest: |
| 99 |
sdk = Version.from_v_str(manifest["sdk"]) |
| 100 |
|
| 101 |
images = {} |
| 102 |
for variant, image in manifest["images"].items(): |
| 103 |
image_bytes = z.read(image) |
| 104 |
_validate_checksum(checksums, image, image_bytes) |
| 105 |
images[Variant.from_str(variant)] = image_bytes |
| 106 |
|
| 107 |
return cls(version=version, pynitrokey=pynitrokey, sdk=sdk, images=images) |
| 108 |
|
| 109 |
|
| 110 |
@dataclass |
| 111 |
class FirmwareMetadata: |
| 112 |
version: Version |
| 113 |
signed_by: Optional[str] = None |
| 114 |
signed_by_nitrokey: bool = False |
| 115 |
|
| 116 |
|
| 117 |
class TrussedBootloader(TrussedBase): |
| 118 |
@abstractmethod |
| 119 |
def update(self, image: bytes, callback: Optional[ProgressCallback] = None) -> None: ... |
| 120 |
|
| 121 |
@property |
| 122 |
@abstractmethod |
| 123 |
def variant(self) -> Variant: ... |
| 124 |
|
| 125 |
|
| 126 |
def get_firmware_filename_pattern(variant: Variant) -> Pattern[str]: |
| 127 |
from .lpc55 import FILENAME_PATTERN as FILENAME_PATTERN_LPC55 |
| 128 |
from .nrf52 import FILENAME_PATTERN as FILENAME_PATTERN_NRF52 |
| 129 |
|
| 130 |
if variant == Variant.LPC55: |
| 131 |
return FILENAME_PATTERN_LPC55 |
| 132 |
elif variant == Variant.NRF52: |
| 133 |
return FILENAME_PATTERN_NRF52 |
| 134 |
else: |
| 135 |
raise ValueError(f"Unexpected variant {variant}") |
| 136 |
|
| 137 |
|
| 138 |
def parse_filename(filename: str) -> Optional[Tuple[Variant, Version]]: |
| 139 |
for variant in Variant: |
| 140 |
pattern = get_firmware_filename_pattern(variant) |
| 141 |
match = pattern.search(filename) |
| 142 |
if match: |
| 143 |
version = Version.from_v_str(match.group("version")) |
| 144 |
return (variant, version) |
| 145 |
return None |
| 146 |
|
| 147 |
|
| 148 |
def validate_firmware_image( |
| 149 |
variant: Variant, data: bytes, version: Optional[Version], model: Model |
| 150 |
) -> FirmwareMetadata: |
| 151 |
try: |
| 152 |
metadata = parse_firmware_image(variant, data, model) |
| 153 |
except Exception as e: |
| 154 |
logger.exception("Failed to parse firmware image", exc_info=sys.exc_info()) |
| 155 |
raise Exception("Failed to parse firmware image") from e |
| 156 |
|
| 157 |
if version: |
| 158 |
if version.core() != metadata.version: |
| 159 |
raise Exception( |
| 160 |
f"The firmware image for the release {version} has an unexpected product " |
| 161 |
f"version ({metadata.version})." |
| 162 |
) |
| 163 |
|
| 164 |
if not metadata.signed_by: |
| 165 |
raise Exception("Firmware image is not signed") |
| 166 |
|
| 167 |
if not metadata.signed_by_nitrokey: |
| 168 |
raise Exception( |
| 169 |
f"Firmware image is not signed by Nitrokey (signed by: {metadata.signed_by})" |
| 170 |
) |
| 171 |
|
| 172 |
return metadata |
| 173 |
|
| 174 |
|
| 175 |
def parse_firmware_image(variant: Variant, data: bytes, model: Model) -> FirmwareMetadata: |
| 176 |
from .lpc55 import parse_firmware_image as parse_firmware_image_lpc55 |
| 177 |
from .nrf52 import parse_firmware_image as parse_firmware_image_nrf52 |
| 178 |
|
| 179 |
if variant == Variant.LPC55: |
| 180 |
return parse_firmware_image_lpc55(data) |
| 181 |
elif variant == Variant.NRF52: |
| 182 |
return parse_firmware_image_nrf52(data, get_model_data(model).nrf52_signature_keys) |
| 183 |
else: |
| 184 |
raise ValueError(f"Unexpected variant {variant}") |