nitrokey 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. nitrokey/__init__.py +1 -0
  2. nitrokey/_helpers.py +36 -0
  3. nitrokey/nk3/__init__.py +54 -0
  4. nitrokey/nk3/_bootloader.py +82 -0
  5. nitrokey/nk3/_device.py +48 -0
  6. nitrokey/nk3/secrets_app.py +879 -0
  7. nitrokey/nk3/updates.py +367 -0
  8. nitrokey/nkpk.py +102 -0
  9. nitrokey/py.typed +0 -0
  10. nitrokey/trussed/__init__.py +21 -0
  11. nitrokey/trussed/_base.py +60 -0
  12. nitrokey/trussed/_bootloader/__init__.py +221 -0
  13. nitrokey/trussed/_bootloader/lpc55.py +146 -0
  14. nitrokey/trussed/_bootloader/nrf52.py +228 -0
  15. nitrokey/trussed/_bootloader/nrf52_upload/README.md +6 -0
  16. nitrokey/trussed/_bootloader/nrf52_upload/__init__.py +38 -0
  17. nitrokey/trussed/_bootloader/nrf52_upload/dfu/__init__.py +38 -0
  18. nitrokey/trussed/_bootloader/nrf52_upload/dfu/crc16.py +54 -0
  19. nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_cc_pb2.py +866 -0
  20. nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport.py +173 -0
  21. nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport_serial.py +589 -0
  22. nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_trigger.py +229 -0
  23. nitrokey/trussed/_bootloader/nrf52_upload/dfu/init_packet_pb.py +193 -0
  24. nitrokey/trussed/_bootloader/nrf52_upload/dfu/manifest.py +212 -0
  25. nitrokey/trussed/_bootloader/nrf52_upload/dfu/model.py +57 -0
  26. nitrokey/trussed/_bootloader/nrf52_upload/dfu/nrfhex.py +188 -0
  27. nitrokey/trussed/_bootloader/nrf52_upload/dfu/package.py +763 -0
  28. nitrokey/trussed/_bootloader/nrf52_upload/dfu/signing.py +256 -0
  29. nitrokey/trussed/_bootloader/nrf52_upload/exceptions.py +9 -0
  30. nitrokey/trussed/_bootloader/nrf52_upload/lister/__init__.py +38 -0
  31. nitrokey/trussed/_bootloader/nrf52_upload/lister/device_lister.py +88 -0
  32. nitrokey/trussed/_bootloader/nrf52_upload/lister/enumerated_device.py +71 -0
  33. nitrokey/trussed/_bootloader/nrf52_upload/lister/lister_backend.py +45 -0
  34. nitrokey/trussed/_bootloader/nrf52_upload/lister/unix/__init__.py +0 -0
  35. nitrokey/trussed/_bootloader/nrf52_upload/lister/unix/unix_lister.py +74 -0
  36. nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/__init__.py +0 -0
  37. nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/constants.py +90 -0
  38. nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/lister_win32.py +318 -0
  39. nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/structures.py +145 -0
  40. nitrokey/trussed/_device.py +135 -0
  41. nitrokey/trussed/_exceptions.py +15 -0
  42. nitrokey/trussed/_utils.py +245 -0
  43. nitrokey/trussed/admin_app.py +290 -0
  44. nitrokey/trussed/provisioner_app.py +57 -0
  45. nitrokey/updates.py +163 -0
  46. nitrokey-0.1.0.dist-info/LICENSES/Apache-2.0.txt +73 -0
  47. nitrokey-0.1.0.dist-info/LICENSES/MIT.txt +9 -0
  48. nitrokey-0.1.0.dist-info/METADATA +133 -0
  49. nitrokey-0.1.0.dist-info/RECORD +50 -0
  50. nitrokey-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,879 @@
1
+ """
2
+ Oath Authenticator client
3
+
4
+ Used through CTAPHID transport, via the custom vendor command.
5
+ Can be used directly over CCID as well.
6
+ """
7
+
8
+ import dataclasses
9
+ import hmac
10
+ import logging
11
+ import typing
12
+ from enum import Enum, IntEnum
13
+ from hashlib import pbkdf2_hmac
14
+ from secrets import token_bytes
15
+ from struct import pack
16
+ from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
17
+
18
+ import tlv8
19
+ from semver.version import Version
20
+
21
+ from nitrokey.nk3 import NK3
22
+ from nitrokey.trussed import App
23
+
24
+ LogFn = Callable[[str], Any]
25
+ WriteCorpusFn = Callable[[typing.Union["Instruction", "CCIDInstruction"], bytes], Any]
26
+
27
+
28
+ @dataclasses.dataclass
29
+ class ListItemProperties:
30
+ touch_required: bool
31
+ secret_encryption: bool
32
+ pws_data_exist: bool
33
+
34
+ @classmethod
35
+ def _get_bit(cls, x: int, n: int) -> bool:
36
+ return ((x >> n) & 1) == 1
37
+
38
+ @classmethod
39
+ def from_byte(cls, b: int) -> "ListItemProperties":
40
+ return ListItemProperties(
41
+ touch_required=cls._get_bit(b, 0),
42
+ secret_encryption=cls._get_bit(b, 1),
43
+ pws_data_exist=cls._get_bit(b, 2),
44
+ )
45
+
46
+ def __str__(self) -> str:
47
+ data = [
48
+ "touch required" if self.touch_required else "",
49
+ "PIN required" if self.secret_encryption else "",
50
+ "PWS data available" if self.pws_data_exist else "",
51
+ ]
52
+ return ",".join([d for d in data if d])
53
+
54
+
55
+ @dataclasses.dataclass
56
+ class ListItem:
57
+ kind: "Kind"
58
+ algorithm: "Algorithm"
59
+ label: bytes
60
+ properties: ListItemProperties
61
+
62
+ @classmethod
63
+ def get_type_name(cls, x: typing.Any) -> str:
64
+ return str(x).split(".")[-1]
65
+
66
+ def __str__(self) -> str:
67
+ return (
68
+ f"{self.label.decode()}"
69
+ f"\t{self.get_type_name(self.kind)}/{self.get_type_name(self.algorithm)}"
70
+ f"\t{self.properties}"
71
+ )
72
+
73
+
74
+ @dataclasses.dataclass
75
+ class PasswordSafeEntry:
76
+ login: Optional[bytes]
77
+ password: Optional[bytes]
78
+ metadata: Optional[bytes]
79
+ properties: Optional[bytes] = None
80
+ name: Optional[bytes] = None
81
+
82
+ def tlv_encode(self) -> list[tlv8.Entry]:
83
+ entries = [
84
+ (
85
+ tlv8.Entry(Tag.PwsLogin.value, self.login)
86
+ if self.login is not None
87
+ else None
88
+ ),
89
+ (
90
+ tlv8.Entry(Tag.PwsPassword.value, self.password)
91
+ if self.password is not None
92
+ else None
93
+ ),
94
+ (
95
+ tlv8.Entry(Tag.PwsMetadata.value, self.metadata)
96
+ if self.metadata is not None
97
+ else None
98
+ ),
99
+ ]
100
+ # Filter out empty entries
101
+ return [r for r in entries if r is not None]
102
+
103
+
104
+ @dataclasses.dataclass
105
+ class RawBytes:
106
+ data: list[int]
107
+
108
+
109
+ @dataclasses.dataclass
110
+ class SelectResponse:
111
+ # Application version
112
+ version: Optional[bytes]
113
+ # PIN attempt counter
114
+ pin_attempt_counter: Optional[int]
115
+ # Salt, challenge-response auth only, tag Name
116
+ salt: Optional[bytes]
117
+ # Challenge field, challenge-response auth only
118
+ challenge: Optional[bytes]
119
+ # Selected algorithm, challenge-response auth only
120
+ algorithm: Optional[bytes]
121
+ # Serial number of the device
122
+ serial_number: Optional[bytes]
123
+
124
+ def version_str(self) -> str:
125
+ if self.version:
126
+ return f"{self.version[0]}.{self.version[1]}.{self.version[2]}"
127
+ else:
128
+ return "unknown"
129
+
130
+ def __str__(self) -> str:
131
+ return (
132
+ "Nitrokey Secrets\n"
133
+ f"\tVersion: {self.version_str()}\n"
134
+ f"\tPIN attempt counter: {self.pin_attempt_counter}\n"
135
+ f"\tSerial number: {self.serial_number.hex() if self.serial_number else 'None'}"
136
+ )
137
+
138
+
139
+ class SecretsAppExceptionID(IntEnum):
140
+ MoreDataAvailable = 0x61FF
141
+ VerificationFailed = 0x6300
142
+ UnspecifiedNonpersistentExecutionError = 0x6400
143
+ UnspecifiedPersistentExecutionError = 0x6500
144
+ WrongLength = 0x6700
145
+ LogicalChannelNotSupported = 0x6881
146
+ SecureMessagingNotSupported = 0x6882
147
+ CommandChainingNotSupported = 0x6884
148
+ SecurityStatusNotSatisfied = 0x6982
149
+ ConditionsOfUseNotSatisfied = 0x6985
150
+ OperationBlocked = 0x6983
151
+ IncorrectDataParameter = 0x6A80
152
+ FunctionNotSupported = 0x6A81
153
+ NotFound = 0x6A82
154
+ NotEnoughMemory = 0x6A84
155
+ IncorrectP1OrP2Parameter = 0x6A86
156
+ KeyReferenceNotFound = 0x6A88
157
+ InstructionNotSupportedOrInvalid = 0x6D00
158
+ ClassNotSupported = 0x6E00
159
+ UnspecifiedCheckingError = 0x6F00
160
+ Success = 0x9000
161
+
162
+
163
+ class SecretsAppHealthCheckException(Exception):
164
+ pass
165
+
166
+
167
+ @dataclasses.dataclass
168
+ class SecretsAppException(Exception):
169
+ code: str
170
+ context: str
171
+
172
+ def to_id(self) -> SecretsAppExceptionID:
173
+ return SecretsAppExceptionID(int(self.code, 16))
174
+
175
+ def to_string(self) -> str:
176
+ d = {
177
+ "61FF": "MoreDataAvailable",
178
+ "6300": "VerificationFailed",
179
+ "6400": "UnspecifiedNonpersistentExecutionError",
180
+ "6500": "UnspecifiedPersistentExecutionError",
181
+ "6700": "WrongLength",
182
+ "6881": "LogicalChannelNotSupported",
183
+ "6882": "SecureMessagingNotSupported",
184
+ "6884": "CommandChainingNotSupported",
185
+ "6982": "SecurityStatusNotSatisfied",
186
+ "6985": "ConditionsOfUseNotSatisfied",
187
+ "6983": "OperationBlocked",
188
+ "6a80": "IncorrectDataParameter",
189
+ "6a81": "FunctionNotSupported",
190
+ "6a82": "NotFound",
191
+ "6a84": "NotEnoughMemory",
192
+ "6a86": "IncorrectP1OrP2Parameter",
193
+ "6a88": "KeyReferenceNotFound",
194
+ "6d00": "InstructionNotSupportedOrInvalid",
195
+ "6e00": "ClassNotSupported",
196
+ "6f00": "UnspecifiedCheckingError",
197
+ "9000": "Success",
198
+ }
199
+ return d.get(self.code, "Unknown SW code")
200
+
201
+ def __repr__(self) -> str:
202
+ return f"SecretsAppException(code={self.code}/{self.to_string()})"
203
+
204
+ def __str__(self) -> str:
205
+ return self.__repr__()
206
+
207
+
208
+ class CCIDInstruction(Enum):
209
+ Select = 0xA4
210
+
211
+
212
+ class Instruction(Enum):
213
+ Put = 0x1
214
+ Delete = 0x2
215
+ SetCode = 0x3
216
+ Reset = 0x4
217
+ List = 0xA1
218
+ Calculate = 0xA2
219
+ Validate = 0xA3
220
+ CalculateAll = 0xA4 # 0xA4 is Select as well # Unused
221
+ SendRemaining = 0xA5
222
+ VerifyCode = 0xB1
223
+ # Place extending commands in 0xBx space
224
+ VerifyPIN = 0xB2
225
+ ChangePIN = 0xB3
226
+ SetPIN = 0xB4
227
+ GetCredential = 0xB5
228
+ UpdateCredential = 0xB7
229
+
230
+
231
+ class Tag(Enum):
232
+ CredentialId = 0x71 # also known as Name
233
+ NameList = 0x72
234
+ Key = 0x73
235
+ Challenge = 0x74
236
+ Response = 0x75
237
+ Properties = 0x78
238
+ InitialCounter = 0x7A
239
+ Version = 0x79
240
+ Algorithm = 0x7B
241
+ # Touch = 0x7c,
242
+ # Extension starting from 0x80
243
+ Password = 0x80
244
+ NewPassword = 0x81
245
+ PINCounter = 0x82
246
+ PwsLogin = 0x83
247
+ PwsPassword = 0x84
248
+ PwsMetadata = 0x85
249
+ SerialNumber = 0x8F
250
+
251
+
252
+ class Kind(Enum):
253
+ Hotp = 0x10
254
+ Totp = 0x20
255
+ HotpReverse = 0x30
256
+ Hmac = 0x40
257
+ NotSet = 0xF0
258
+
259
+ @classmethod
260
+ def from_attribute_byte(cls, attribute_byte: bytes) -> str:
261
+ a = int(attribute_byte)
262
+ k = cls.from_attribute_byte_type(a)
263
+ if k != Kind.NotSet:
264
+ return str(k).split(".")[-1].upper()
265
+ else:
266
+ return "PWS"
267
+
268
+ @classmethod
269
+ def from_attribute_byte_type(cls, a: int) -> "Kind":
270
+ v = a & 0xF0
271
+ for k in Kind:
272
+ if k.value == v:
273
+ return k
274
+ raise ValueError("Invalid attribute byte")
275
+
276
+
277
+ STRING_TO_KIND = {
278
+ "HOTP": Kind.Hotp,
279
+ "TOTP": Kind.Totp,
280
+ "HOTP_REVERSE": Kind.HotpReverse,
281
+ "HMAC": Kind.Hmac,
282
+ }
283
+
284
+
285
+ class Algorithm(Enum):
286
+ Sha1 = 0x01
287
+ Sha256 = 0x02
288
+ Sha512 = 0x03
289
+
290
+
291
+ ALGORITHM_TO_KIND = {
292
+ "SHA1": Algorithm.Sha1,
293
+ "SHA256": Algorithm.Sha256,
294
+ }
295
+
296
+
297
+ class SecretsApp:
298
+ """
299
+ This is a Secrets App client
300
+ https://github.com/Nitrokey/trussed-secrets-app
301
+ """
302
+
303
+ log: logging.Logger
304
+ logfn: LogFn
305
+ dev: NK3
306
+ write_corpus_fn: Optional[WriteCorpusFn]
307
+ _cache_status: Optional[SelectResponse]
308
+ _metadata: dict[Any, Any]
309
+
310
+ def __init__(self, dev: NK3, logfn: Optional[LogFn] = None):
311
+ self._cache_status = None
312
+ self.write_corpus_fn = None
313
+ self.log = logging.getLogger("otpapp")
314
+ if logfn is not None:
315
+ self.logfn = logfn
316
+ else:
317
+ self.logfn = self.log.info
318
+ self.dev = dev
319
+ self._metadata = {}
320
+
321
+ def _custom_encode(
322
+ self, structure: Optional[Sequence[Union[tlv8.Entry, RawBytes, None]]] = None
323
+ ) -> bytes:
324
+ if not structure:
325
+ return b""
326
+
327
+ def transform(d: Union[tlv8.Entry, RawBytes, None]) -> bytes:
328
+ if not d:
329
+ return b""
330
+ if isinstance(d, RawBytes):
331
+ res = bytes(d.data)
332
+ # self.logfn(f"Transforming {d} -> {res.hex()}")
333
+ return res
334
+ elif isinstance(d, tlv8.Entry):
335
+ res = tlv8.encode([d])
336
+ # self.logfn(f"Transforming {d} -> {res.hex()}")
337
+ return res
338
+ return b""
339
+
340
+ encoded_structure = b"".join(map(transform, structure))
341
+ return encoded_structure
342
+
343
+ def _send_receive(
344
+ self,
345
+ ins: typing.Union[Instruction, CCIDInstruction],
346
+ structure: Optional[Sequence[Union[tlv8.Entry, RawBytes, None]]] = None,
347
+ ) -> bytes:
348
+ encoded_structure = self._custom_encode(structure)
349
+ ins_b, p1, p2 = self._encode_command(ins)
350
+ bytes_data = _iso7816_compose(ins_b, p1, p2, data=encoded_structure)
351
+ if self.write_corpus_fn:
352
+ self.write_corpus_fn(ins, bytes_data)
353
+ return self._send_receive_inner(bytes_data, log_info=f"{ins}")
354
+
355
+ def _send_receive_inner(self, data: bytes, log_info: str = "") -> bytes:
356
+ self.logfn(f"Sending {log_info if log_info else ''} (data: {len(data)} bytes)")
357
+
358
+ try:
359
+ result = self.dev._call_app(App.SECRETS, data=data)
360
+ except Exception as e:
361
+ self.logfn(f"Got exception: {e}")
362
+ raise
363
+
364
+ status_bytes, result = result[:2], result[2:]
365
+ self.logfn(f"Received [{status_bytes.hex()}] (data: {len(result)} bytes)")
366
+
367
+ log_multipacket = False
368
+ data_final = result
369
+ MORE_DATA_STATUS_BYTE = 0x61
370
+ while status_bytes[0] == MORE_DATA_STATUS_BYTE:
371
+ if log_multipacket:
372
+ self.logfn(f"Got RemainingData status: [{status_bytes.hex()}]")
373
+ log_multipacket = True
374
+ ins_b, p1, p2 = self._encode_command(Instruction.SendRemaining)
375
+ bytes_data = _iso7816_compose(ins_b, p1, p2)
376
+ try:
377
+ result = self.dev._call_app(App.SECRETS, data=bytes_data)
378
+ except Exception as e:
379
+ self.logfn(f"Got exception: {e}")
380
+ raise
381
+ # Data order is different here than in APDU - SW is first, then the data if any
382
+ status_bytes, result = result[:2], result[2:]
383
+ self.logfn(f"Received [{status_bytes.hex()}] (data: {len(result)} bytes)")
384
+ if status_bytes[0] in [0x90, MORE_DATA_STATUS_BYTE]:
385
+ data_final += result
386
+
387
+ if status_bytes != b"\x90\x00" and status_bytes[0] != MORE_DATA_STATUS_BYTE:
388
+ raise SecretsAppException(status_bytes.hex(), "Received error")
389
+
390
+ if log_multipacket:
391
+ self.logfn(
392
+ f"Received final data: [{status_bytes.hex()}] (data: {len(data_final)} bytes)"
393
+ )
394
+
395
+ if data_final:
396
+ try:
397
+ tlv8.decode(data_final)
398
+ self.logfn("TLV-decoding of data successful")
399
+ except Exception:
400
+ self.logfn("TLV-decoding of data failed")
401
+ pass
402
+
403
+ return data_final
404
+
405
+ @classmethod
406
+ def _encode_command(
407
+ cls, command: typing.Union[Instruction, CCIDInstruction]
408
+ ) -> bytes:
409
+ p1 = 0
410
+ p2 = 0
411
+ if command == Instruction.Reset:
412
+ p1 = 0xDE
413
+ p2 = 0xAD
414
+ elif command == CCIDInstruction.Select:
415
+ p1 = 0x04
416
+ p2 = 0x00
417
+ elif command == Instruction.Calculate or command == Instruction.CalculateAll:
418
+ p1 = 0x00
419
+ p2 = 0x01
420
+ return bytes([command.value, p1, p2])
421
+
422
+ def reset(self) -> None:
423
+ """
424
+ Remove all credentials from the database
425
+ """
426
+ self.logfn("Executing reset")
427
+ self._send_receive(Instruction.Reset)
428
+
429
+ def list(self, extended: bool = False) -> list[Union[Tuple[bytes, bytes], bytes]]:
430
+ """
431
+ Return a list of the registered credentials
432
+ :return: List of bytestrings, or tuple of bytestrings, if "extended" switch is provided
433
+ @deprecated
434
+ """
435
+ raw_res = self._send_receive(Instruction.List)
436
+ resd: tlv8.EntryList = tlv8.decode(raw_res)
437
+ res: list[Union[Tuple[bytes, bytes], bytes]] = []
438
+ for e in resd:
439
+ # e: tlv8.Entry
440
+ if extended:
441
+ res.append((e.data[0], e.data[1:]))
442
+ else:
443
+ res.append(e.data[1:])
444
+ return res
445
+
446
+ def list_with_properties(self, version: int = 1) -> List[ListItem]:
447
+ """
448
+ Return a list of the registered credentials with properties
449
+ :return: List of ListItems
450
+ """
451
+ data = [RawBytes([version])]
452
+ raw_res = self._send_receive(Instruction.List, data)
453
+ resd: tlv8.EntryList = tlv8.decode(raw_res)
454
+ res = []
455
+ for e in resd:
456
+ # e: tlv8.Entry
457
+ if self.feature_extended_list():
458
+ attribute_byte, label, properties = e.data[0], e.data[1:-1], e.data[-1]
459
+ else:
460
+ attribute_byte, label, properties = e.data[0], e.data[1:], 0
461
+ res.append(
462
+ ListItem(
463
+ kind=Kind.from_attribute_byte_type(attribute_byte),
464
+ algorithm=Algorithm.Sha1,
465
+ label=label,
466
+ properties=ListItemProperties.from_byte(properties),
467
+ )
468
+ )
469
+ return res
470
+
471
+ def get_credential(self, cred_id: bytes) -> PasswordSafeEntry:
472
+ structure = [
473
+ tlv8.Entry(Tag.CredentialId.value, cred_id),
474
+ ]
475
+ raw_res = self._send_receive(Instruction.GetCredential, structure=structure)
476
+ resd: tlv8.EntryList = tlv8.decode(raw_res)
477
+ res = {}
478
+ self.logfn("Per field dissection:")
479
+ for e in resd:
480
+ # e: tlv8.Entry
481
+ res[e.type_id] = e.data
482
+ self.logfn(f"{hex(e.type_id)} {hex(len(e.data))}")
483
+ p = PasswordSafeEntry(
484
+ login=res.get(Tag.PwsLogin.value),
485
+ password=res.get(Tag.PwsPassword.value),
486
+ metadata=res.get(Tag.PwsMetadata.value),
487
+ name=res.get(Tag.CredentialId.value),
488
+ properties=res.get(Tag.Properties.value),
489
+ )
490
+ p.properties = p.properties.hex().encode() if p.properties else None
491
+ return p
492
+
493
+ def rename_credential(self, cred_id: bytes, new_name: bytes) -> None:
494
+ """
495
+ Rename credential.
496
+ An alias for the update_credential() call.
497
+ @param cred_id: The credential ID to modify
498
+ @param new_name: New ID for the credential
499
+ """
500
+ return self.update_credential(cred_id, new_name)
501
+
502
+ def update_credential(
503
+ self,
504
+ cred_id: bytes,
505
+ new_name: Optional[bytes] = None,
506
+ login: Optional[bytes] = None,
507
+ password: Optional[bytes] = None,
508
+ metadata: Optional[bytes] = None,
509
+ touch_button: Optional[bool] = None,
510
+ ) -> None:
511
+ """
512
+ Update credential fields - name, attributes, and PWS fields.
513
+ Unpopulated fields will not be encoded and used during the update process
514
+ (won't change the current value).
515
+ @param cred_id: The credential ID to modify
516
+ @param new_name: New ID for the credential
517
+ @param login: New login field content
518
+ @param password: New password field content
519
+ @param metadata: New metadata field content
520
+ @param touch_button: Set if the touch button use should be required
521
+ """
522
+ structure = [
523
+ tlv8.Entry(Tag.CredentialId.value, cred_id),
524
+ tlv8.Entry(Tag.CredentialId.value, new_name) if new_name else None,
525
+ (
526
+ self.encode_properties_to_send(touch_button, False, tlv=True)
527
+ if touch_button is not None
528
+ else None
529
+ ),
530
+ tlv8.Entry(Tag.PwsLogin.value, login) if login is not None else None,
531
+ (
532
+ tlv8.Entry(Tag.PwsPassword.value, password)
533
+ if password is not None
534
+ else None
535
+ ),
536
+ (
537
+ tlv8.Entry(Tag.PwsMetadata.value, metadata)
538
+ if metadata is not None
539
+ else None
540
+ ),
541
+ ]
542
+ structure = list(filter(lambda x: x is not None, structure))
543
+ self._send_receive(Instruction.UpdateCredential, structure=structure)
544
+
545
+ def delete(self, cred_id: bytes) -> None:
546
+ """
547
+ Delete credential with the given id. Does not fail, if the given credential does not exist.
548
+ :param credid: Credential ID
549
+ """
550
+ self.logfn(f"Sending delete request for {cred_id!r}")
551
+ structure = [
552
+ tlv8.Entry(Tag.CredentialId.value, cred_id),
553
+ ]
554
+ self._send_receive(Instruction.Delete, structure)
555
+
556
+ def register_yk_hmac(self, slot: int, secret: bytes) -> None:
557
+ """
558
+ Register a Yubikey-compatible challenge-response slot.
559
+ @param slot: challenge-response slot
560
+ @param secret: the secret
561
+ """
562
+ assert slot in [1, 2]
563
+ self.register(
564
+ f"HmacSlot{slot}".encode(),
565
+ secret,
566
+ kind=Kind.Hmac,
567
+ )
568
+
569
+ def register(
570
+ self,
571
+ credid: bytes,
572
+ secret: bytes = b"0" * 20,
573
+ digits: int = 6,
574
+ kind: Kind = Kind.NotSet,
575
+ algo: Algorithm = Algorithm.Sha1,
576
+ initial_counter_value: int = 0,
577
+ touch_button_required: bool = False,
578
+ pin_based_encryption: bool = False,
579
+ login: Optional[bytes] = None,
580
+ password: Optional[bytes] = None,
581
+ metadata: Optional[bytes] = None,
582
+ ) -> None:
583
+ """
584
+ Register new OTP Credential
585
+ :param credid: Credential ID
586
+ :param secret: The shared key
587
+ :param digits: Digits of the produced code
588
+ :param kind: OTP variant - HOTP or TOTP
589
+ :param algo: The hash algorithm to use - SHA1, SHA256 or SHA512
590
+ :param initial_counter_value: The counter's initial value for the HOTP Credential (HOTP only)
591
+ :param touch_button_required: User Presence confirmation is required to use this Credential
592
+ :param pin_based_encryption: User preference for additional PIN-based encryption
593
+ :param login: Login field for Password Safe
594
+ :param password: Password field for Password Safe
595
+ :param metadata: Metadata field for Password Safe
596
+ :return: None
597
+ """
598
+ if initial_counter_value > 0xFFFFFFFF:
599
+ raise Exception("Initial counter value must be smaller than 4 bytes")
600
+ if algo == Algorithm.Sha512:
601
+ raise NotImplementedError(
602
+ "This hash algorithm is not supported by the firmware"
603
+ )
604
+
605
+ self.logfn(
606
+ f"Setting new credential: {credid!r}, {kind}, {algo}, counter: {initial_counter_value}, {touch_button_required=}, {pin_based_encryption=}"
607
+ )
608
+
609
+ structure: list[Optional[Union[tlv8.Entry, RawBytes]]] = [
610
+ tlv8.Entry(Tag.CredentialId.value, credid),
611
+ # header (2) + secret (N)
612
+ tlv8.Entry(
613
+ Tag.Key.value, bytes([kind.value | algo.value, digits]) + secret
614
+ ),
615
+ self.encode_properties_to_send(touch_button_required, pin_based_encryption),
616
+ (
617
+ tlv8.Entry(
618
+ Tag.InitialCounter.value, initial_counter_value.to_bytes(4, "big")
619
+ )
620
+ if kind in [Kind.Hotp, Kind.HotpReverse]
621
+ else None
622
+ ),
623
+ *PasswordSafeEntry(
624
+ name=credid, login=login, password=password, metadata=metadata
625
+ ).tlv_encode(),
626
+ ]
627
+ entries = [x for x in structure if x is not None]
628
+ self._send_receive(Instruction.Put, entries)
629
+
630
+ @classmethod
631
+ def encode_properties_to_send(
632
+ cls, touch_button_required: bool, pin_based_encryption: bool, tlv: bool = False
633
+ ) -> RawBytes:
634
+ """
635
+ Encode properties structure into a single byte
636
+ @param touch_button_required: whether the touch button use is required
637
+ @param pin_based_encryption: whether the PIN-encryption is requested (only during registration)
638
+ @param tlv: set True, if this should be encoded as TLV, as opposed to the default "TV", w/o L
639
+ """
640
+ structure = [
641
+ Tag.Properties.value,
642
+ 1 if tlv else None,
643
+ (0x02 if touch_button_required else 0x00)
644
+ | (0x04 if pin_based_encryption else 0x00),
645
+ ]
646
+ structure = list(filter(lambda x: x is not None, structure))
647
+ return RawBytes(structure) # type: ignore[arg-type]
648
+
649
+ def calculate(self, cred_id: bytes, challenge: Optional[int] = None) -> bytes:
650
+ """
651
+ Calculate the OTP code for the credential named `cred_id`, and with challenge `challenge`.
652
+ :param cred_id: The name of the credential
653
+ :param challenge: Challenge for the calculations (TOTP only).
654
+ Should be equal to: timestamp/period. The commonly used period value is 30.
655
+ :return: OTP code as a byte string
656
+ """
657
+ if challenge is None:
658
+ challenge = 0
659
+ self.logfn(
660
+ f"Sending calculate request for {cred_id!r} and challenge {challenge!r}"
661
+ )
662
+ structure = [
663
+ tlv8.Entry(Tag.CredentialId.value, cred_id),
664
+ tlv8.Entry(Tag.Challenge.value, pack(">Q", challenge)),
665
+ ]
666
+ res = self._send_receive(Instruction.Calculate, structure=structure)
667
+ header = res[:2]
668
+ assert header.hex() in ["7605", "7700"]
669
+ digits = res[2]
670
+ digest = res[3:]
671
+ truncated_code = int.from_bytes(digest, byteorder="big", signed=False)
672
+ code = (truncated_code & 0x7FFFFFFF) % pow(10, digits)
673
+ codes: bytes = str(code).zfill(digits).encode()
674
+ self.logfn(
675
+ f"Received digest: {digest.hex()}, for challenge {challenge}, digits: {digits}, truncated code: {truncated_code!r}, pre-code: {code!r},"
676
+ f" final code: {codes!r}"
677
+ )
678
+ return codes
679
+
680
+ def verify_code(self, cred_id: bytes, code: int) -> bool:
681
+ """
682
+ Proceed with the incoming OTP code verification (aka reverse HOTP).
683
+ :param cred_id: The name of the credential
684
+ :param code: The HOTP code to verify. u32 representation.
685
+ :return: fails with OTPAppException error; returns True if code matches the value calculated internally.
686
+ """
687
+ structure = [
688
+ tlv8.Entry(Tag.CredentialId.value, cred_id),
689
+ tlv8.Entry(Tag.Response.value, pack(">L", code)),
690
+ ]
691
+ self._send_receive(Instruction.VerifyCode, structure=structure)
692
+ return True
693
+
694
+ def set_code(self, passphrase: str) -> None:
695
+ """
696
+ Set the code with the defaults as suggested in the protocol specification:
697
+ - https://developers.yubico.com/OATH/YKOATH_Protocol.html
698
+ """
699
+ secret = self.get_secret_for_passphrase(passphrase)
700
+ challenge = token_bytes(8)
701
+ response = self.get_response_for_secret(challenge, secret)
702
+ self.set_code_raw(secret, challenge, response)
703
+
704
+ def get_secret_for_passphrase(self, passphrase: str) -> bytes:
705
+ # secret = PBKDF2(USER_PASSPHRASE, DEVICEID, 1000)[:16]
706
+ # salt = self.select().name
707
+ # FIXME use the proper SALT
708
+ # FIXME USB/IP Sim changes its ID after each reset and after setting the code (??)
709
+ salt = b"a" * 8
710
+ secret = pbkdf2_hmac("sha256", passphrase.encode(), salt, 1000)
711
+ return secret[:16]
712
+
713
+ def get_response_for_secret(self, challenge: bytes, secret: bytes) -> bytes:
714
+ response = hmac.HMAC(key=secret, msg=challenge, digestmod="sha1").digest()
715
+ return response
716
+
717
+ def set_code_raw(self, key: bytes, challenge: bytes, response: bytes) -> None:
718
+ """
719
+ Set or clear the passphrase used to authenticate to other commands. Raw interface.
720
+ :param key: User passphrase processed through PBKDF2(ID,1000), and limited to the first 16 bytes.
721
+ :param challenge: The current challenge taken from the SELECT command.
722
+ :param response: The data calculated on the client, as a proof of a correct setup.
723
+ """
724
+ algo = Algorithm.Sha1.value
725
+ kind = Kind.Totp.value
726
+ structure = [
727
+ tlv8.Entry(Tag.Key.value, bytes([kind | algo]) + key),
728
+ tlv8.Entry(Tag.Challenge.value, challenge),
729
+ tlv8.Entry(Tag.Response.value, response),
730
+ ]
731
+ self._send_receive(Instruction.SetCode, structure=structure)
732
+
733
+ def clear_code(self) -> None:
734
+ """
735
+ Clear the passphrase used to authenticate to other commands.
736
+ """
737
+ structure = [
738
+ tlv8.Entry(Tag.Key.value, bytes()),
739
+ ]
740
+ self._send_receive(Instruction.SetCode, structure=structure)
741
+
742
+ def validate(self, passphrase: str) -> None:
743
+ """
744
+ Authenticate using a passphrase
745
+ """
746
+ stat = self.select()
747
+ if stat.algorithm != bytes([Algorithm.Sha1.value]):
748
+ raise RuntimeError("For the authentication only SHA1 is supported")
749
+ challenge = stat.challenge
750
+ if challenge is None:
751
+ # This should never happen
752
+ raise RuntimeError(
753
+ "There is some problem with the device's state. Challenge is not available."
754
+ )
755
+ secret = self.get_secret_for_passphrase(passphrase)
756
+ response = self.get_response_for_secret(challenge, secret)
757
+ self.validate_raw(challenge, response)
758
+
759
+ def validate_raw(self, challenge: bytes, response: bytes) -> bytes:
760
+ """
761
+ Authenticate using a passphrase. Raw interface.
762
+ :param challenge: The current challenge taken from the SELECT command.
763
+ :param response: The response calculated against the challenge and the secret
764
+ """
765
+ structure = [
766
+ tlv8.Entry(Tag.Response.value, response),
767
+ tlv8.Entry(Tag.Challenge.value, challenge),
768
+ ]
769
+ raw_res = self._send_receive(Instruction.Validate, structure=structure)
770
+ resd: tlv8.EntryList = tlv8.decode(raw_res)
771
+ return resd.data # type: ignore[return-value]
772
+
773
+ def select(self) -> SelectResponse:
774
+ """
775
+ Execute SELECT command, which returns details about the device,
776
+ including the challenge needed for the authentication.
777
+ :return SelectResponse Status structure. Challenge and Algorithm fields are None, if the passphrase is not set.
778
+ """
779
+ AID = [0xA0, 0x00, 0x00, 0x05, 0x27, 0x21, 0x01]
780
+ structure = [RawBytes(AID)]
781
+ raw_res = self._send_receive(CCIDInstruction.Select, structure=structure)
782
+ resd: tlv8.EntryList = tlv8.decode(raw_res)
783
+ rd = {}
784
+ for e in resd:
785
+ # e: tlv8.Entry
786
+ rd[e.type_id] = e.data
787
+
788
+ counter = rd.get(Tag.PINCounter.value)
789
+ if counter is not None:
790
+ # counter is passed as 1B array - convert it to int
791
+ counter = int.from_bytes(counter, byteorder="big")
792
+
793
+ r = SelectResponse(
794
+ version=rd.get(Tag.Version.value),
795
+ pin_attempt_counter=counter,
796
+ salt=rd.get(Tag.CredentialId.value),
797
+ challenge=rd.get(Tag.Challenge.value),
798
+ algorithm=rd.get(Tag.Algorithm.value),
799
+ serial_number=rd.get(Tag.SerialNumber.value),
800
+ )
801
+ return r
802
+
803
+ def set_pin_raw(self, password: str) -> None:
804
+ structure = [
805
+ tlv8.Entry(Tag.Password.value, password),
806
+ ]
807
+ self._send_receive(Instruction.SetPIN, structure=structure)
808
+
809
+ def change_pin_raw(self, password: str, new_password: str) -> None:
810
+ structure = [
811
+ tlv8.Entry(Tag.Password.value, password),
812
+ tlv8.Entry(Tag.NewPassword.value, new_password),
813
+ ]
814
+ self._send_receive(Instruction.ChangePIN, structure=structure)
815
+
816
+ def verify_pin_raw(self, password: str) -> None:
817
+ structure = [
818
+ tlv8.Entry(Tag.Password.value, password),
819
+ ]
820
+ self._send_receive(Instruction.VerifyPIN, structure=structure)
821
+
822
+ def get_feature_status_cached(self) -> SelectResponse:
823
+ self._cache_status = (
824
+ self.select() if self._cache_status is None else self._cache_status
825
+ )
826
+ return self._cache_status
827
+
828
+ def feature_active_PIN_authentication(self) -> bool:
829
+ return self.get_feature_status_cached().challenge is None
830
+
831
+ def feature_old_application_version(self) -> bool:
832
+ v = self.get_feature_status_cached().version
833
+ return b"444" == v
834
+
835
+ def feature_challenge_response_support(self) -> bool:
836
+ if self.get_feature_status_cached().challenge is not None:
837
+ return True
838
+ return False
839
+
840
+ def feature_pws_support(self) -> bool:
841
+ return self._semver_equal_or_newer("4.11.0")
842
+
843
+ def feature_extended_list(self) -> bool:
844
+ return self._semver_equal_or_newer("4.11.0")
845
+
846
+ def protocol_v2_confirm_all_requests_with_pin(self) -> bool:
847
+ # 4.7.0 version requires providing PIN each request
848
+ return self.get_feature_status_cached().version_str() == "4.7.0"
849
+
850
+ def protocol_v3_separate_pin_and_no_pin_space(self) -> bool:
851
+ # 4.10.0 makes logical separation between the PIN-encrypted and non-PIN encrypted spaces, except
852
+ # for overwriting the credentials
853
+ return self._semver_equal_or_newer("4.10.0")
854
+
855
+ def is_pin_healthy(self) -> bool:
856
+ counter = self.select().pin_attempt_counter
857
+ return not (counter is None or counter == 0)
858
+
859
+ def _semver_equal_or_newer(self, required_version: str) -> bool:
860
+ current = Version.parse(self.get_feature_status_cached().version_str())
861
+ semver_req_version = Version.parse(required_version)
862
+ return current >= semver_req_version
863
+
864
+
865
+ def _iso7816_compose(
866
+ ins: int,
867
+ p1: int,
868
+ p2: int,
869
+ data: bytes = b"",
870
+ ) -> bytes:
871
+ cls = 0
872
+ data_len = len(data)
873
+ if data_len == 0:
874
+ return pack(">BBBB", cls, ins, p1, p2)
875
+ else:
876
+ if data_len <= 255:
877
+ return pack(">BBBBB", cls, ins, p1, p2, data_len) + data
878
+ else:
879
+ return pack(">BBBBBH", cls, ins, p1, p2, 0, data_len) + data