Debian Codegraph @

src/nitrokey/nk3/secrets_app.py

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