| 1 |
# Copyright 2021-2024 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 dataclasses |
| 9 |
from dataclasses import dataclass, field |
| 10 |
from functools import total_ordering |
| 11 |
from typing import Optional, Sequence |
| 12 |
|
| 13 |
|
| 14 |
@dataclass(order=True, frozen=True) |
| 15 |
class Uuid: |
| 16 |
"""UUID of a Nitrokey Trussed device.""" |
| 17 |
|
| 18 |
value: int |
| 19 |
|
| 20 |
def __str__(self) -> str: |
| 21 |
return f"{self.value:032X}" |
| 22 |
|
| 23 |
def __int__(self) -> int: |
| 24 |
return self.value |
| 25 |
|
| 26 |
|
| 27 |
@dataclass(eq=False, frozen=True) |
| 28 |
@total_ordering |
| 29 |
class Version: |
| 30 |
""" |
| 31 |
The version of a Nitrokey Trussed device, following Semantic Versioning |
| 32 |
2.0.0. |
| 33 |
|
| 34 |
Some sources for version information, namely the version returned by older |
| 35 |
devices and the firmware binaries, do not contain the pre-release |
| 36 |
component. These instances are marked with *complete=False*. This flag |
| 37 |
affects comparison: The pre-release version is only taken into account if |
| 38 |
both version instances are complete. |
| 39 |
|
| 40 |
>>> Version(1, 0, 0) |
| 41 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 42 |
>>> Version.from_str("1.0.0") |
| 43 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 44 |
>>> Version.from_v_str("v1.0.0") |
| 45 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 46 |
>>> Version(1, 0, 0, "rc.1") |
| 47 |
Version(major=1, minor=0, patch=0, pre='rc.1', build=None) |
| 48 |
>>> Version.from_str("1.0.0-rc.1") |
| 49 |
Version(major=1, minor=0, patch=0, pre='rc.1', build=None) |
| 50 |
>>> Version.from_v_str("v1.0.0-rc.1") |
| 51 |
Version(major=1, minor=0, patch=0, pre='rc.1', build=None) |
| 52 |
>>> Version.from_v_str("v1.0.0-rc.1+git") |
| 53 |
Version(major=1, minor=0, patch=0, pre='rc.1', build='git') |
| 54 |
""" |
| 55 |
|
| 56 |
major: int |
| 57 |
minor: int |
| 58 |
patch: int |
| 59 |
pre: Optional[str] = None |
| 60 |
build: Optional[str] = None |
| 61 |
complete: bool = field(default=False, repr=False) |
| 62 |
|
| 63 |
def __str__(self) -> str: |
| 64 |
""" |
| 65 |
>>> str(Version(major=1, minor=0, patch=0)) |
| 66 |
'v1.0.0' |
| 67 |
>>> str(Version(major=1, minor=0, patch=0, pre="rc.1")) |
| 68 |
'v1.0.0-rc.1' |
| 69 |
>>> str(Version(major=1, minor=0, patch=0, pre="rc.1", build="git")) |
| 70 |
'v1.0.0-rc.1+git' |
| 71 |
""" |
| 72 |
|
| 73 |
version = f"v{self.major}.{self.minor}.{self.patch}" |
| 74 |
if self.pre: |
| 75 |
version += f"-{self.pre}" |
| 76 |
if self.build: |
| 77 |
version += f"+{self.build}" |
| 78 |
return version |
| 79 |
|
| 80 |
def __eq__(self, other: object) -> bool: |
| 81 |
""" |
| 82 |
>>> Version(1, 0, 0) == Version(1, 0, 0) |
| 83 |
True |
| 84 |
>>> Version(1, 0, 0) == Version(1, 0, 1) |
| 85 |
False |
| 86 |
>>> Version.from_str("1.0.0-rc.1") == Version.from_str("1.0.0-rc.1") |
| 87 |
True |
| 88 |
>>> Version.from_str("1.0.0") == Version.from_str("1.0.0-rc.1") |
| 89 |
False |
| 90 |
>>> Version.from_str("1.0.0") == Version.from_str("1.0.0+git") |
| 91 |
True |
| 92 |
>>> Version(1, 0, 0, complete=False) == Version.from_str("1.0.0-rc.1") |
| 93 |
True |
| 94 |
>>> Version(1, 0, 0, complete=False) == Version.from_str("1.0.1") |
| 95 |
False |
| 96 |
""" |
| 97 |
if not isinstance(other, Version): |
| 98 |
return NotImplemented |
| 99 |
lhs = (self.major, self.minor, self.patch) |
| 100 |
rhs = (other.major, other.minor, other.patch) |
| 101 |
|
| 102 |
if lhs != rhs: |
| 103 |
return False |
| 104 |
if self.complete and other.complete: |
| 105 |
return self.pre == other.pre |
| 106 |
return True |
| 107 |
|
| 108 |
def __lt__(self, other: object) -> bool: |
| 109 |
""" |
| 110 |
>>> def cmp(a, b): |
| 111 |
... return Version.from_str(a) < Version.from_str(b) |
| 112 |
>>> cmp("1.0.0", "1.0.0") |
| 113 |
False |
| 114 |
>>> cmp("1.0.0", "1.0.1") |
| 115 |
True |
| 116 |
>>> cmp("1.1.0", "2.0.0") |
| 117 |
True |
| 118 |
>>> cmp("1.1.0", "1.0.3") |
| 119 |
False |
| 120 |
>>> cmp("1.0.0-rc.1", "1.0.0-rc.1") |
| 121 |
False |
| 122 |
>>> cmp("1.0.0-rc.1", "1.0.0") |
| 123 |
True |
| 124 |
>>> cmp("1.0.0", "1.0.0-rc.1") |
| 125 |
False |
| 126 |
>>> cmp("1.0.0-rc.1", "1.0.0-rc.2") |
| 127 |
True |
| 128 |
>>> cmp("1.0.0-rc.2", "1.0.0-rc.1") |
| 129 |
False |
| 130 |
>>> cmp("1.0.0-alpha.1", "1.0.0-rc.1") |
| 131 |
True |
| 132 |
>>> cmp("1.0.0-alpha.1", "1.0.0-rc.1.0") |
| 133 |
True |
| 134 |
>>> cmp("1.0.0-alpha.1", "1.0.0-alpha.1.0") |
| 135 |
True |
| 136 |
>>> cmp("1.0.0-rc.2", "1.0.0-rc.10") |
| 137 |
True |
| 138 |
>>> Version(1, 0, 0, "rc.1") < Version(1, 0, 0) |
| 139 |
False |
| 140 |
""" |
| 141 |
|
| 142 |
if not isinstance(other, Version): |
| 143 |
return NotImplemented |
| 144 |
|
| 145 |
lhs = (self.major, self.minor, self.patch) |
| 146 |
rhs = (other.major, other.minor, other.patch) |
| 147 |
|
| 148 |
if lhs == rhs and self.complete and other.complete: |
| 149 |
# relevant rules: |
| 150 |
# 1. pre-releases sort before regular releases |
| 151 |
# 2. two pre-releases for the same core version are sorted by the pre-release component |
| 152 |
# (split into subcomponents) |
| 153 |
if self.pre == other.pre: |
| 154 |
return False |
| 155 |
elif self.pre is None: |
| 156 |
# self is regular release, other is pre-release |
| 157 |
return False |
| 158 |
elif other.pre is None: |
| 159 |
# self is pre-release, other is regular release |
| 160 |
return True |
| 161 |
else: |
| 162 |
# both are pre-releases |
| 163 |
def int_or_str(s: str) -> object: |
| 164 |
if s.isdigit(): |
| 165 |
return int(s) |
| 166 |
else: |
| 167 |
return s |
| 168 |
|
| 169 |
lhs_pre = [int_or_str(s) for s in self.pre.split(".")] |
| 170 |
rhs_pre = [int_or_str(s) for s in other.pre.split(".")] |
| 171 |
return lhs_pre < rhs_pre |
| 172 |
else: |
| 173 |
return lhs < rhs |
| 174 |
|
| 175 |
def core(self) -> "Version": |
| 176 |
""" |
| 177 |
Returns the core part of this version, i. e. the version without the |
| 178 |
pre-release and build components. |
| 179 |
|
| 180 |
>>> Version(1, 0, 0).core() |
| 181 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 182 |
>>> Version(1, 0, 0, "rc.1").core() |
| 183 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 184 |
>>> Version(1, 0, 0, "rc.1", "git").core() |
| 185 |
Version(major=1, minor=0, patch=0, pre=None, build=None) |
| 186 |
""" |
| 187 |
return dataclasses.replace(self, pre=None, build=None) |
| 188 |
|
| 189 |
@classmethod |
| 190 |
def from_int(cls, version: int) -> "Version": |
| 191 |
# This is the reverse of the calculation in runners/lpc55/build.rs (CARGO_PKG_VERSION): |
| 192 |
# https://github.com/Nitrokey/nitrokey-3-firmware/blob/main/runners/lpc55/build.rs#L131 |
| 193 |
major = version >> 22 |
| 194 |
minor = (version >> 6) & ((1 << 16) - 1) |
| 195 |
patch = version & ((1 << 6) - 1) |
| 196 |
return cls(major=major, minor=minor, patch=patch) |
| 197 |
|
| 198 |
@classmethod |
| 199 |
def from_str(cls, s: str) -> "Version": |
| 200 |
version_parts = s.split("+", maxsplit=1) |
| 201 |
s = version_parts[0] |
| 202 |
build = version_parts[1] if len(version_parts) == 2 else None |
| 203 |
|
| 204 |
version_parts = s.split("-", maxsplit=1) |
| 205 |
pre = version_parts[1] if len(version_parts) == 2 else None |
| 206 |
|
| 207 |
str_parts = version_parts[0].split(".") |
| 208 |
if len(str_parts) != 3: |
| 209 |
raise ValueError(f"Invalid firmware version: {s}") |
| 210 |
|
| 211 |
try: |
| 212 |
int_parts = [int(part) for part in str_parts] |
| 213 |
except ValueError as e: |
| 214 |
raise ValueError(f"Invalid component in firmware version: {s}") from e |
| 215 |
|
| 216 |
[major, minor, patch] = int_parts |
| 217 |
return cls(major=major, minor=minor, patch=patch, pre=pre, build=build, complete=True) |
| 218 |
|
| 219 |
@classmethod |
| 220 |
def from_v_str(cls, s: str) -> "Version": |
| 221 |
if not s.startswith("v"): |
| 222 |
raise ValueError(f"Missing v prefix for firmware version: {s}") |
| 223 |
return Version.from_str(s[1:]) |
| 224 |
|
| 225 |
@classmethod |
| 226 |
def from_python_str(cls, s: str) -> "Version": |
| 227 |
""" |
| 228 |
Parses a Python version number, e. g. 0.4.0 or 0.5.0rc1. |
| 229 |
|
| 230 |
>>> Version.from_python_str("0.4.0") |
| 231 |
Version(major=0, minor=4, patch=0, pre=None, build=None) |
| 232 |
>>> Version.from_python_str("0.5.0rc1") |
| 233 |
Version(major=0, minor=5, patch=0, pre='rc.1', build=None) |
| 234 |
""" |
| 235 |
if "rc" in s: |
| 236 |
head, tail = s.split("rc", 1) |
| 237 |
v = Version.from_str(head) |
| 238 |
return Version(major=v.major, minor=v.minor, patch=v.patch, pre=f"rc.{tail}") |
| 239 |
return Version.from_str(s) |
| 240 |
|
| 241 |
|
| 242 |
@dataclass |
| 243 |
class Fido2Certs: |
| 244 |
start: Version |
| 245 |
hashes: list[str] |
| 246 |
|
| 247 |
@staticmethod |
| 248 |
def get(certs: Sequence["Fido2Certs"], version: Version) -> Optional["Fido2Certs"]: |
| 249 |
matching_certs = [c for c in certs if version >= c.start] |
| 250 |
if matching_certs: |
| 251 |
return max(matching_certs, key=lambda c: c.start) |
| 252 |
else: |
| 253 |
return None |
| 254 |
|
| 255 |
|
| 256 |
class Iso7816Apdu: |
| 257 |
def __init__( |
| 258 |
self, |
| 259 |
cla: int, |
| 260 |
ins: int, |
| 261 |
p1: int, |
| 262 |
p2: int, |
| 263 |
data: Optional[bytes] = None, |
| 264 |
le: Optional[int] = None, |
| 265 |
) -> None: |
| 266 |
self.cla = cla |
| 267 |
self.ins = ins |
| 268 |
self.p1 = p1 |
| 269 |
self.p2 = p2 |
| 270 |
self.data = data or b"" |
| 271 |
self.le = le |
| 272 |
|
| 273 |
def _encode_lc(self) -> bytes: |
| 274 |
"""Encode Lc according to short / extended format.""" |
| 275 |
lc_len = len(self.data) |
| 276 |
if lc_len == 0: |
| 277 |
return b"" |
| 278 |
if lc_len <= 0xFF: |
| 279 |
return bytes([lc_len]) |
| 280 |
if lc_len <= 0xFFFF: |
| 281 |
return b"\x00" + lc_len.to_bytes(2, "big") |
| 282 |
raise ValueError("Data too long (max 6535 bytes)") |
| 283 |
|
| 284 |
def _encode_le(self) -> bytes: |
| 285 |
"""Encode Le according to short / extended format.""" |
| 286 |
if self.le is None: |
| 287 |
return b"" |
| 288 |
if self.le == 0: |
| 289 |
return b"\x00" |
| 290 |
if self.le <= 0xFF: |
| 291 |
return bytes([self.le]) |
| 292 |
if self.le <= 0xFFFF: |
| 293 |
return b"\x00" + self.le.to_bytes(2, "big") |
| 294 |
raise ValueError("Le out of range (max 65535)") |
| 295 |
|
| 296 |
def to_bytes(self) -> bytes: |
| 297 |
"""Serialize the APDU to its binary representation.""" |
| 298 |
header = bytes([self.cla, self.ins, self.p1, self.p2]) |
| 299 |
|
| 300 |
# No data, no Le → case 1 |
| 301 |
if not self.data and self.le is None: |
| 302 |
return header |
| 303 |
|
| 304 |
lc = self._encode_lc() |
| 305 |
le = self._encode_le() |
| 306 |
|
| 307 |
# Cases: |
| 308 |
# 2: no data, Le present |
| 309 |
# 3: data present, no Le |
| 310 |
# 4: data present, Le present |
| 311 |
return header + lc + self.data + le |