Debian Codegraph @

src/nitrokey/trussed/admin_app.py

raw
1 import enum
2 from dataclasses import dataclass
3 from enum import Enum, IntFlag
4 from typing import Optional
5
6 from fido2 import cbor
7 from fido2.ctap import CtapError
8
9 try:
10 from smartcard.Exceptions import CardConnectionException
11 except ImportError:
12
13 class CardConnectionException(Exception): # type: ignore[no-redef]
14 pass
15
16
17 from nitrokey.trussed._device import PcscError
18
19 from . import App, TimeoutException, TrussedDevice, Uuid, Version
20
21 RNG_LEN = 57
22 UUID_LEN = 16
23 VERSION_LEN = 4
24
25
26 @enum.unique
27 class AdminCommand(Enum):
28 # legacy commands -- can be called directly or using the admin namespace
29 UPDATE = 0x51
30 REBOOT = 0x53
31 RNG = 0x60
32 VERSION = 0x61
33 UUID = 0x62
34 LOCKED = 0x63
35
36 # new commands -- can only be called using the admin namespace
37 STATUS = 0x80
38 TEST_SE050 = 0x81
39 GET_CONFIG = 0x82
40 SET_CONFIG = 0x83
41 FACTORY_RESET = 0x84
42 FACTORY_RESET_APP = 0x85
43 LIST_AVAILABLE_FIELDS = 0x86
44
45 def is_legacy_command(self) -> bool:
46 if self == AdminCommand.UPDATE:
47 return True
48 if self == AdminCommand.REBOOT:
49 return True
50 if self == AdminCommand.RNG:
51 return True
52 if self == AdminCommand.VERSION:
53 return True
54 if self == AdminCommand.UUID:
55 return True
56 if self == AdminCommand.LOCKED:
57 return True
58 return False
59
60
61 @enum.unique
62 class BootMode(Enum):
63 FIRMWARE = enum.auto()
64 BOOTROM = enum.auto()
65
66
67 @enum.unique
68 class InitStatus(IntFlag):
69 NFC_ERROR = 0b0001
70 INTERNAL_FLASH_ERROR = 0b0010
71 EXTERNAL_FLASH_ERROR = 0b0100
72 MIGRATION_ERROR = 0b1000
73 SE050_ERROR = 0b00010000
74 CONFIG_ERROR = 0b00100000
75 RNG_ERROR = 0b01000000
76 EXT_FLASH_NEED_REFORMAT = 0b10000000
77
78 def is_error(self) -> bool:
79 return self.value != 0
80
81 def __str__(self) -> str:
82 if self == 0:
83 return "ok"
84 errors = [error for error in InitStatus if error in self if error.name]
85 value = sum(errors)
86 messages = [error.name for error in errors if error.name]
87 if self.value != value:
88 messages.append("UNKNOWN")
89 return ", ".join(messages) + " (" + hex(self.value) + ")"
90
91
92 @enum.unique
93 class Variant(Enum):
94 USBIP = 0
95 LPC55 = 1
96 NRF52 = 2
97
98
99 @dataclass
100 class Status:
101 init_status: Optional[InitStatus] = None
102 ifs_blocks: Optional[int] = None
103 efs_blocks: Optional[int] = None
104 variant: Optional[Variant] = None
105
106
107 @enum.unique
108 class FactoryResetStatus(Enum):
109 SUCCESS = 0
110 NOT_CONFIRMED = 0x01
111 APP_NOT_ALLOWED = 0x02
112 APP_FAILED_PARSE = 0x03
113
114 @classmethod
115 def from_int(cls, i: int) -> Optional["FactoryResetStatus"]:
116 for status in FactoryResetStatus:
117 if status.value == i:
118 return status
119 return None
120
121 @classmethod
122 def check(cls, i: int, msg: str) -> None:
123 status = FactoryResetStatus.from_int(i)
124 if status != FactoryResetStatus.SUCCESS:
125 if status is None:
126 raise Exception(f"Unknown error {i:x}")
127 if status == FactoryResetStatus.NOT_CONFIRMED:
128 error = "Operation was not confirmed with touch"
129 elif status == FactoryResetStatus.APP_NOT_ALLOWED:
130 error = "The application does not support factory reset through nitropy"
131 elif status == FactoryResetStatus.APP_FAILED_PARSE:
132 error = "The application name must be utf-8"
133 raise Exception(f"{msg}: {error}")
134
135
136 @enum.unique
137 class ConfigStatus(Enum):
138 SUCCESS = 0
139 READ_FAILED = 1
140 WRITE_FAILED = 2
141 DESERIALIZATION_FAILED = 3
142 SERIALIZATION_FAILED = 4
143 INVALID_KEY = 5
144 INVALID_VALUE = 6
145 DATA_TOO_LONG = 7
146
147 @classmethod
148 def from_int(cls, i: int) -> Optional["ConfigStatus"]:
149 for status in ConfigStatus:
150 if status.value == i:
151 return status
152 return None
153
154 @classmethod
155 def check(cls, i: int, msg: str) -> None:
156 status = ConfigStatus.from_int(i)
157 if status != ConfigStatus.SUCCESS:
158 if status:
159 error = str(status)
160 else:
161 error = f"unknown error {i:x}"
162 raise Exception(f"{msg}: {error}")
163
164
165 @enum.unique
166 class ConfigFieldType(Enum):
167 BOOL = 0
168 U8 = 1
169
170 @classmethod
171 def from_int(cls, i: int) -> Optional["ConfigFieldType"]:
172 for ty in ConfigFieldType:
173 if ty.value == i:
174 return ty
175 return None
176
177 def is_valid(self, value: str) -> bool:
178 if self == ConfigFieldType.BOOL:
179 return value in ["true", "false"]
180 elif self == ConfigFieldType.U8:
181 try:
182 intval = int(value)
183 if intval < 256 and intval >= 0:
184 return True
185 else:
186 return False
187 except ValueError:
188 return False
189 else:
190 # TODO: use typing.assert_never from Python 3.11
191 raise ValueError(self)
192
193 def __str__(self) -> str:
194 if self == ConfigFieldType.BOOL:
195 return "Bool"
196 elif self == ConfigFieldType.U8:
197 return "u8"
198 else:
199 # TODO: use typing.assert_never from Python 3.11
200 raise ValueError(self)
201
202
203 @dataclass
204 class ConfigField:
205 name: str
206 requires_touch_confirmation: bool
207 requires_reboot: bool
208 destructive: bool
209 ty: ConfigFieldType
210
211
212 class AdminApp:
213 def __init__(self, device: TrussedDevice) -> None:
214 self.device = device
215
216 def _call(
217 self, command: AdminCommand, response_len: Optional[int] = None, data: bytes = b""
218 ) -> Optional[bytes]:
219 try:
220 if command.is_legacy_command():
221 return self.device._call_admin_legacy(
222 command.value, command.name, response_len=response_len, data=data
223 )
224 else:
225 return self.device._call_app(
226 App.ADMIN,
227 response_len=response_len,
228 data=command.value.to_bytes(1, "big") + data,
229 )
230 except CtapError as e:
231 if e.code == CtapError.ERR.INVALID_COMMAND:
232 return None
233 else:
234 raise
235
236 def is_locked(self) -> bool:
237 response = self._call(AdminCommand.LOCKED, response_len=1)
238 assert response is not None
239 return response[0] == 1
240
241 def reboot(self, mode: BootMode = BootMode.FIRMWARE) -> bool:
242 try:
243 if mode == BootMode.FIRMWARE:
244 self._call(AdminCommand.REBOOT)
245 elif mode == BootMode.BOOTROM:
246 try:
247 self._call(AdminCommand.UPDATE)
248 except CtapError as e:
249 # The admin app returns an Invalid Length error if the user confirmation
250 # request times out
251 if e.code == CtapError.ERR.INVALID_LENGTH:
252 raise TimeoutException() from e
253 else:
254 raise e
255 except PcscError as e:
256 # The admin app returns ConditionsOfUseNotSatisfied if the user confirmation
257 # request times out
258 if e.sw1 == 0x69 and e.sw2 == 0x85:
259 raise TimeoutException() from None
260 else:
261 raise e
262
263 except (OSError, CardConnectionException) as e:
264 # OS error is expected as the device does not respond during the reboot
265 self.device._logger.debug("ignoring OSError after reboot", exc_info=e)
266 return True
267
268 def rng(self) -> bytes:
269 data = self._call(AdminCommand.RNG, response_len=RNG_LEN)
270 assert data is not None
271 return data
272
273 def status(self) -> Status:
274 status = Status()
275 reply = self._call(AdminCommand.STATUS)
276 if reply is not None:
277 if not reply:
278 raise ValueError("The device returned an empty status")
279 status.init_status = InitStatus(reply[0])
280 if len(reply) >= 4:
281 status.ifs_blocks = reply[1]
282 status.efs_blocks = int.from_bytes(reply[2:4], "big")
283 if len(reply) >= 5:
284 try:
285 status.variant = Variant(reply[4])
286 except ValueError:
287 pass
288 return status
289
290 def uuid(self) -> Optional[Uuid]:
291 uuid = self._call(AdminCommand.UUID)
292 if uuid is None or len(uuid) == 0:
293 # Firmware version 1.0.0 does not support querying the UUID
294 return None
295 if len(uuid) != UUID_LEN:
296 raise ValueError(f"UUID response has invalid length {len(uuid)}")
297 return Uuid(int.from_bytes(uuid, byteorder="big"))
298
299 def version(self) -> Version:
300 reply = self._call(AdminCommand.VERSION, data=bytes([0x01]))
301 assert reply is not None
302 if len(reply) == VERSION_LEN:
303 version = int.from_bytes(reply, "big")
304 return Version.from_int(version)
305 else:
306 return Version.from_str(reply.decode("utf-8"))
307
308 def se050_tests(self) -> Optional[bytes]:
309 return self._call(AdminCommand.TEST_SE050)
310
311 def has_config(self, key: str) -> bool:
312 reply = self._call(AdminCommand.GET_CONFIG, data=key.encode())
313 if not reply or len(reply) < 1:
314 return False
315 return ConfigStatus.from_int(reply[0]) == ConfigStatus.SUCCESS
316
317 def get_config(self, key: str) -> str:
318 reply = self._call(AdminCommand.GET_CONFIG, data=key.encode())
319 if not reply or len(reply) < 1:
320 raise ValueError("The device returned an empty response")
321 ConfigStatus.check(reply[0], "Failed to get config value")
322 return reply[1:].decode()
323
324 def set_config(self, key: str, value: str) -> None:
325 request = cbor.encode({"key": key, "value": value})
326 reply = self._call(AdminCommand.SET_CONFIG, data=request, response_len=1)
327 assert reply
328 ConfigStatus.check(reply[0], "Failed to set config value")
329
330 def list_available_fields(self) -> list[ConfigField]:
331 reply = self._call(AdminCommand.LIST_AVAILABLE_FIELDS)
332 # Function not supported, return values for 1.7.0 release
333 if not reply:
334 return [
335 ConfigField(
336 "fido.disable_skip_up_timeout", False, False, False, ConfigFieldType.BOOL
337 ),
338 ConfigField("opcard.use_se050_backend", True, True, True, ConfigFieldType.BOOL),
339 ]
340 parsed = cbor.decode(reply)
341 assert isinstance(parsed, list)
342 ret = []
343
344 for field in parsed:
345 ty = ConfigFieldType.from_int(field["t"])
346 if ty is None:
347 ty = ConfigFieldType.BOOL
348
349 ret.append(ConfigField(field["n"], field["c"], field["r"], field["d"], ty))
350 return ret
351
352 def factory_reset(self) -> bool:
353 try:
354 reply = self._call(AdminCommand.FACTORY_RESET, response_len=1)
355 except OSError as e:
356 if e.errno == 5:
357 self.device._logger.debug("ignoring OSError after reboot", exc_info=e)
358 return True
359 else:
360 raise e
361 if reply:
362 FactoryResetStatus.check(reply[0], "Failed to factory reset the device")
363 return reply is not None
364
365 def factory_reset_app(self, application: str) -> bool:
366 reply = self._call(
367 AdminCommand.FACTORY_RESET_APP, data=application.encode("ascii"), response_len=1
368 )
369 if reply:
370 FactoryResetStatus.check(reply[0], "Failed to factory reset the application")
371 return reply is not None