-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy path_openpgp.py
696 lines (574 loc) · 22.7 KB
/
_openpgp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# Copyright (c) 2015 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Classes and functions for interacting with the OpenPGP application on a YubiKey.
WARNING: This file is not part of the stable API, and thus changes to is can occur
without a major version increase of the project.
Keep this in mind when using these classes for scripting purposes!
"""
from yubikit.core import (
Tlv,
NotSupportedError,
require_version,
int2bytes,
bytes2int,
)
from yubikit.core.smartcard import (
SmartCardConnection,
SmartCardProtocol,
ApduError,
AID,
SW,
)
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import (
Encoding,
PrivateFormat,
NoEncryption,
)
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from enum import Enum, IntEnum, unique
from dataclasses import dataclass
from typing import Optional, Tuple
import time
import struct
import logging
from typing import NamedTuple
logger = logging.getLogger(__name__)
class _KeySlot(NamedTuple):
value: str
indx: int
key_id: int
fingerprint: int
gen_time: int
uif: int # touch policy
crt: bytes # Control Reference Template
@unique
class KEY_SLOT(_KeySlot, Enum): # type: ignore # noqa: N801
SIG = _KeySlot("SIGNATURE", 1, 0xC1, 0xC7, 0xCE, 0xD6, Tlv(0xB6))
ENC = _KeySlot("ENCRYPTION", 2, 0xC2, 0xC8, 0xCF, 0xD7, Tlv(0xB8))
AUT = _KeySlot("AUTHENTICATION", 3, 0xC3, 0xC9, 0xD0, 0xD8, Tlv(0xA4))
ATT = _KeySlot(
"ATTESTATION", 4, 0xDA, 0xDB, 0xDD, 0xD9, Tlv(0xB6, Tlv(0x84, b"\x81"))
)
@unique
class TOUCH_MODE(IntEnum): # noqa: N801
OFF = 0x00
ON = 0x01
FIXED = 0x02
CACHED = 0x03
CACHED_FIXED = 0x04
@property
def is_fixed(self):
return "FIXED" in self.name
def __str__(self):
if self == TOUCH_MODE.OFF:
return "Off"
elif self == TOUCH_MODE.ON:
return "On"
elif self == TOUCH_MODE.FIXED:
return "On (fixed)"
elif self == TOUCH_MODE.CACHED:
return "Cached"
elif self == TOUCH_MODE.CACHED_FIXED:
return "Cached (fixed)"
@unique
class PIN_POLICY(IntEnum): # noqa: N801
ALWAYS = 0x00
ONCE = 0x01
def __str__(self):
name = self.name
return name[0] + name[1:].lower()
@unique
class INS(IntEnum): # noqa: N801
VERIFY = 0x20
CHANGE_PIN = 0x24
RESET_RETRY_COUNTER = 0x2C
ACTIVATE = 0x44
GENERATE_ASYM = 0x47
SELECT_DATA = 0xA5
SEND_REMAINING = 0xC0
GET_DATA = 0xCA
PUT_DATA = 0xDA
PUT_DATA_ODD = 0xDB
TERMINATE = 0xE6
GET_VERSION = 0xF1
SET_PIN_RETRIES = 0xF2
GET_ATTESTATION = 0xFB
class PinRetries(NamedTuple):
pin: int
reset: int
admin: int
PW1 = 0x81
PW2 = 0x82 # Resetting Code
PW3 = 0x83
INVALID_PIN = b"\0" * 8
TOUCH_METHOD_BUTTON = 0x20
@unique
class DO(IntEnum):
AID = 0x4F
PW_STATUS = 0xC4
RESETTING_CODE = 0xD3
KDF = 0xF9
ATT_CERTIFICATE = 0xFC
CARDHOLDER_CERTIFICATE = 0x7F21
@unique
class OID(bytes, Enum):
SECP256R1 = b"\x2a\x86\x48\xce\x3d\x03\x01\x07"
SECP256K1 = b"\x2b\x81\x04\x00\x0a"
SECP384R1 = b"\x2b\x81\x04\x00\x22"
SECP521R1 = b"\x2b\x81\x04\x00\x23"
BRAINPOOLP256R1 = b"\x2b\x24\x03\x03\x02\x08\x01\x01\x07"
BRAINPOOLP384R1 = b"\x2b\x24\x03\x03\x02\x08\x01\x01\x0b"
BRAINPOOLP512R1 = b"\x2b\x24\x03\x03\x02\x08\x01\x01\x0d"
X25519 = b"\x2b\x06\x01\x04\x01\x97\x55\x01\x05\x01"
ED25519 = b"\x2b\x06\x01\x04\x01\xda\x47\x0f\x01"
@classmethod
def for_name(cls, name):
try:
return getattr(cls, name.upper())
except AttributeError:
raise ValueError("Unsupported curve: " + name)
def _get_curve_name(key):
if isinstance(key, ec.EllipticCurvePrivateKey):
return key.curve.name
cls_name = key.__class__.__name__
if "Ed25519" in cls_name:
return "ed25519"
if "X25519" in cls_name:
return "x25519"
raise ValueError("Unsupported private key")
def _format_rsa_attributes(key_size):
return struct.pack(">BHHB", 0x01, key_size, 32, 0)
def _format_ec_attributes(key_slot, curve_name):
if curve_name in ("ed25519", "x25519"):
algorithm = b"\x16"
elif key_slot == KEY_SLOT.ENC:
algorithm = b"\x12"
else:
algorithm = b"\x13"
return algorithm + OID.for_name(curve_name)
def _get_key_attributes(key, key_slot):
if isinstance(key, rsa.RSAPrivateKeyWithSerialization):
if key.private_numbers().public_numbers.e != 65537:
raise ValueError("RSA keys with e != 65537 are not supported!")
return _format_rsa_attributes(key.key_size)
curve_name = _get_curve_name(key)
return _format_ec_attributes(key_slot, curve_name)
def _get_key_template(key, key_slot, crt=False):
def _pack_tlvs(tlvs):
header = b""
body = b""
for tlv in tlvs:
header += tlv[: -tlv.length]
body += tlv.value
return Tlv(0x7F48, header) + Tlv(0x5F48, body)
values: Tuple[Tlv, ...]
if isinstance(key, rsa.RSAPrivateKeyWithSerialization):
rsa_numbers = key.private_numbers()
ln = (key.key_size // 8) // 2
e = Tlv(0x91, b"\x01\x00\x01") # e=65537
p = Tlv(0x92, int2bytes(rsa_numbers.p, ln))
q = Tlv(0x93, int2bytes(rsa_numbers.q, ln))
values = (e, p, q)
if crt:
dp = Tlv(0x94, int2bytes(rsa_numbers.dmp1, ln))
dq = Tlv(0x95, int2bytes(rsa_numbers.dmq1, ln))
qinv = Tlv(0x96, int2bytes(rsa_numbers.iqmp, ln))
n = Tlv(0x97, int2bytes(rsa_numbers.public_numbers.n, 2 * ln))
values += (dp, dq, qinv, n)
elif isinstance(key, ec.EllipticCurvePrivateKeyWithSerialization):
ec_numbers = key.private_numbers()
ln = key.key_size // 8
privkey = Tlv(0x92, int2bytes(ec_numbers.private_value, ln))
values = (privkey,)
elif _get_curve_name(key) in ("ed25519", "x25519"):
privkey = Tlv(
0x92, key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
)
values = (privkey,)
return Tlv(0x4D, key_slot.crt + _pack_tlvs(values))
@unique
class HashAlgorithm(IntEnum):
SHA256 = 0x08
SHA512 = 0x0A
def create_digest(self):
algorithm = getattr(hashes, self.name)
return hashes.Hash(algorithm(), default_backend())
@unique
class KdfAlgorithm(IntEnum):
NONE = 0x00
KDF_ITERSALTED_S2K = 0x03
def _kdf_none(pin, salt, hash_algorithm, iteration_count):
return pin
def _kdf_itersalted_s2k(pin, salt, hash_algorithm, iteration_count):
data = salt + pin
digest = hash_algorithm.create_digest()
# Although the field is called "iteration count", it's actually
# the number of bytes to be passed to the hash function, which
# is called only once. Go figure!
data_count, trailing_bytes = divmod(iteration_count, len(data))
for _ in range(data_count):
digest.update(data)
digest.update(data[:trailing_bytes])
return digest.finalize()
_KDFS = {
KdfAlgorithm.NONE: _kdf_none,
KdfAlgorithm.KDF_ITERSALTED_S2K: _kdf_itersalted_s2k,
}
def _parse_int(data, tag, func=lambda x: x, default=None):
return func(int.from_bytes(data[tag], "big")) if tag in data else default
@dataclass
class KdfData:
kdf_algorithm: KdfAlgorithm
hash_algorithm: Optional[HashAlgorithm]
iteration_count: Optional[int]
pw1_salt_bytes: Optional[bytes]
pw2_salt_bytes: Optional[bytes]
pw3_salt_bytes: Optional[bytes]
pw1_initial_hash: Optional[bytes]
pw3_initial_hash: Optional[bytes]
def process(self, pw, pin):
kdf = _KDFS[self.kdf_algorithm]
if pw == PW1:
salt = self.pw1_salt_bytes
elif pw == PW2:
salt = self.pw2_salt_bytes or self.pw1_salt_bytes
elif pw == PW3:
salt = self.pw3_salt_bytes or self.pw1_salt_bytes
else:
raise ValueError("Invalid value for pw")
return kdf(pin, salt, self.hash_algorithm, self.iteration_count)
@classmethod
def parse(cls, data: bytes) -> "KdfData":
fields = Tlv.parse_dict(data)
return cls(
_parse_int(fields, 0x81, KdfAlgorithm, KdfAlgorithm.NONE),
_parse_int(fields, 0x82, HashAlgorithm),
_parse_int(fields, 0x83),
fields.get(0x84),
fields.get(0x85),
fields.get(0x86),
fields.get(0x87),
fields.get(0x88),
)
class OpenPgpController(object):
def __init__(self, connection: SmartCardConnection):
protocol = SmartCardProtocol(connection)
self._app = protocol
try:
protocol.select(AID.OPENPGP)
except ApduError as e:
if e.sw in (SW.NO_INPUT_DATA, SW.CONDITIONS_NOT_SATISFIED):
protocol.send_apdu(0, INS.ACTIVATE, 0, 0)
protocol.select(AID.OPENPGP)
else:
raise
self._version = self._read_version()
@property
def version(self):
return self._version
def _get_data(self, do):
return self._app.send_apdu(0, INS.GET_DATA, do >> 8, do & 0xFF)
def _put_data(self, do, data):
self._app.send_apdu(0, INS.PUT_DATA, do >> 8, do & 0xFF, data)
def _select_certificate(self, key_slot):
try:
require_version(self.version, (5, 2, 0))
data: bytes = Tlv(0x60, Tlv(0x5C, b"\x7f\x21"))
if self.version <= (5, 4, 3):
# These use a non-standard byte in the command.
data = b"\x06" + data # 6 is the length of the data.
self._app.send_apdu(
0,
INS.SELECT_DATA,
3 - key_slot.indx,
0x04,
data,
)
except NotSupportedError:
if key_slot == KEY_SLOT.AUT:
return # Older version still support AUT, which is the default slot.
raise
def _read_version(self):
bcd_hex = self._app.send_apdu(0, INS.GET_VERSION, 0, 0).hex()
return tuple(int(bcd_hex[i : i + 2]) for i in range(0, 6, 2))
def get_openpgp_version(self):
data = self._get_data(DO.AID)
return data[6], data[7]
def get_remaining_pin_tries(self):
data = self._get_data(DO.PW_STATUS)
return PinRetries(*data[4:7])
def get_signature_pin_policy(self):
data = self._get_data(DO.PW_STATUS)
try:
return PIN_POLICY(data[0])
except ValueError:
return PIN_POLICY.ONCE
def set_signature_pin_policy(self, pin_policy):
"""Requires Admin PIN verification."""
data = struct.pack(">B", pin_policy)
self._put_data(DO.PW_STATUS, data)
def _block_pins(self):
retries = self.get_remaining_pin_tries()
for _ in range(retries.pin):
try:
self._app.send_apdu(0, INS.VERIFY, 0, PW1, INVALID_PIN)
except ApduError:
pass
for _ in range(retries.admin):
try:
self._app.send_apdu(0, INS.VERIFY, 0, PW3, INVALID_PIN)
except ApduError:
pass
def reset(self):
if self.version < (1, 0, 6):
raise ValueError("Resetting OpenPGP data requires version 1.0.6 or later.")
self._block_pins()
self._app.send_apdu(0, INS.TERMINATE, 0, 0)
self._app.send_apdu(0, INS.ACTIVATE, 0, 0)
def _get_kdf(self):
try:
data = self._get_data(DO.KDF)
except ApduError:
data = b""
return KdfData.parse(data)
def _verify(self, pw, pin):
try:
pin = self._get_kdf().process(pw, pin.encode())
self._app.send_apdu(0, INS.VERIFY, 0, pw, pin)
except ApduError:
pw_remaining = self.get_remaining_pin_tries()[pw - PW1]
raise ValueError(f"Invalid PIN, {pw_remaining} tries remaining.")
def verify_pin(self, pin):
self._verify(PW1, pin)
def verify_admin(self, admin_pin):
self._verify(PW3, admin_pin)
def _change(self, pw, pin, new_pin):
try:
pin = self._get_kdf().process(pw, pin.encode())
new_pin = self._get_kdf().process(pw, new_pin.encode())
self._app.send_apdu(0, INS.CHANGE_PIN, 0, pw, pin + new_pin)
except ApduError as e:
if e.sw == SW.CONDITIONS_NOT_SATISFIED:
raise ValueError("Conditions of use not satisfied.")
else:
pw_remaining = self.get_remaining_pin_tries()[pw - PW1]
raise ValueError(f"Invalid PIN, {pw_remaining} tries remaining.")
def change_pin(self, pin, new_pin):
self._change(PW1, pin, new_pin)
def change_admin(self, admin_pin, new_admin_pin):
self._change(PW3, admin_pin, new_admin_pin)
def change_reset_code(self, reset_code):
data = self._get_kdf().process(PW2, reset_code.encode())
self._put_data(DO.RESETTING_CODE, data)
def reset_pin(self, new_pin, reset_code=None):
p1 = 2
data = self._get_kdf().process(PW1, new_pin.encode())
if reset_code:
rc = self._get_kdf().process(PW2, reset_code.encode())
p1 = 0
data = rc + data
try:
self._app.send_apdu(0, INS.RESET_RETRY_COUNTER, p1, PW1, data)
except ApduError as e:
if e.sw == SW.CONDITIONS_NOT_SATISFIED:
raise ValueError("Conditions of use not satisfied.")
else:
reset_remaining = self.get_remaining_pin_tries().reset
raise ValueError(
f"Invalid Reset Code, {reset_remaining} tries remaining."
)
@property
def supported_touch_policies(self):
if self.version < (4, 2, 0):
return []
if self.version < (5, 2, 1):
return [TOUCH_MODE.ON, TOUCH_MODE.OFF, TOUCH_MODE.FIXED]
if self.version >= (5, 2, 1):
return [
TOUCH_MODE.ON,
TOUCH_MODE.OFF,
TOUCH_MODE.FIXED,
TOUCH_MODE.CACHED,
TOUCH_MODE.CACHED_FIXED,
]
@property
def supports_attestation(self):
return self.version >= (5, 2, 1)
def get_touch(self, key_slot):
if not self.supported_touch_policies:
raise ValueError("Touch policy is available on YubiKey 4 or later.")
if key_slot == KEY_SLOT.ATT and not self.supports_attestation:
raise ValueError("Attestation key not available on this device.")
data = self._get_data(key_slot.uif)
return TOUCH_MODE(data[0])
def set_touch(self, key_slot, mode):
"""Requires Admin PIN verification."""
if not self.supported_touch_policies:
raise ValueError("Touch policy is available on YubiKey 4 or later.")
if mode not in self.supported_touch_policies:
raise ValueError("Touch policy not available on this device.")
self._put_data(key_slot.uif, struct.pack(">BB", mode, TOUCH_METHOD_BUTTON))
def set_pin_retries(self, pw1_tries, pw2_tries, pw3_tries):
"""Requires Admin PIN verification."""
if (1, 0, 0) <= self.version < (1, 0, 7): # For YubiKey NEO
raise ValueError(
"Setting PIN retry counters requires version 1.0.7 or later."
)
if (4, 0, 0) <= self.version < (4, 3, 1): # For YubiKey 4
raise ValueError(
"Setting PIN retry counters requires version 4.3.1 or later."
)
self._app.send_apdu(
0,
INS.SET_PIN_RETRIES,
0,
0,
struct.pack(">BBB", pw1_tries, pw2_tries, pw3_tries),
)
def read_certificate(self, key_slot):
if key_slot == KEY_SLOT.ATT:
require_version(self.version, (5, 2, 0))
data = self._get_data(DO.ATT_CERTIFICATE)
else:
self._select_certificate(key_slot)
data = self._get_data(DO.CARDHOLDER_CERTIFICATE)
if not data:
raise ValueError("No certificate found!")
return x509.load_der_x509_certificate(data, default_backend())
def import_certificate(self, key_slot, certificate):
"""Requires Admin PIN verification."""
cert_data = certificate.public_bytes(Encoding.DER)
if key_slot == KEY_SLOT.ATT:
require_version(self.version, (5, 2, 0))
self._put_data(DO.ATT_CERTIFICATE, cert_data)
else:
self._select_certificate(key_slot)
self._put_data(DO.CARDHOLDER_CERTIFICATE, cert_data)
def import_key(self, key_slot, key, fingerprint=None, timestamp=None):
"""Requires Admin PIN verification."""
if self.version >= (4, 0, 0):
attributes = _get_key_attributes(key, key_slot)
self._put_data(key_slot.key_id, attributes)
template = _get_key_template(key, key_slot, self.version < (4, 0, 0))
self._app.send_apdu(0, INS.PUT_DATA_ODD, 0x3F, 0xFF, template)
if fingerprint is not None:
self._put_data(key_slot.fingerprint, fingerprint)
if timestamp is not None:
self._put_data(key_slot.gen_time, struct.pack(">I", timestamp))
def generate_rsa_key(self, key_slot, key_size, timestamp=None):
"""Requires Admin PIN verification."""
if (4, 2, 0) <= self.version < (4, 3, 5):
raise NotSupportedError("RSA key generation not supported on this YubiKey")
if timestamp is None:
timestamp = int(time.time())
neo = self.version < (4, 0, 0)
if not neo:
attributes = _format_rsa_attributes(key_size)
self._put_data(key_slot.key_id, attributes)
elif key_size != 2048:
raise ValueError("Unsupported key size!")
resp = self._app.send_apdu(0, INS.GENERATE_ASYM, 0x80, 0x00, key_slot.crt)
data = Tlv.parse_dict(Tlv.unpack(0x7F49, resp))
numbers = rsa.RSAPublicNumbers(bytes2int(data[0x82]), bytes2int(data[0x81]))
self._put_data(key_slot.gen_time, struct.pack(">I", timestamp))
# TODO: Calculate and write fingerprint
return numbers.public_key(default_backend())
def generate_ec_key(self, key_slot, curve_name, timestamp=None):
require_version(self.version, (5, 2, 0))
"""Requires Admin PIN verification."""
if timestamp is None:
timestamp = int(time.time())
attributes = _format_ec_attributes(key_slot, curve_name)
self._put_data(key_slot.key_id, attributes)
resp = self._app.send_apdu(0, INS.GENERATE_ASYM, 0x80, 0x00, key_slot.crt)
data = Tlv.parse_dict(Tlv.unpack(0x7F49, resp))
pubkey_enc = data[0x86]
self._put_data(key_slot.gen_time, struct.pack(">I", timestamp))
# TODO: Calculate and write fingerprint
if curve_name == "x25519":
# Added in 2.0
from cryptography.hazmat.primitives.asymmetric import x25519
return x25519.X25519PublicKey.from_public_bytes(pubkey_enc)
if curve_name == "ed25519":
# Added in 2.6
from cryptography.hazmat.primitives.asymmetric import ed25519
return ed25519.Ed25519PublicKey.from_public_bytes(pubkey_enc)
curve = getattr(ec, curve_name.upper())
return ec.EllipticCurvePublicKey.from_encoded_point(curve(), pubkey_enc)
def delete_key(self, key_slot):
"""Requires Admin PIN verification."""
if self.version < (4, 0, 0):
# Import over the key
self.import_key(
key_slot,
rsa.generate_private_key(65537, 2048, default_backend()),
b"\0" * 20,
0,
)
else:
# Delete key by changing the key attributes twice.
self._put_data(key_slot.key_id, _format_rsa_attributes(4096))
self._put_data(key_slot.key_id, _format_rsa_attributes(2048))
def delete_certificate(self, key_slot):
"""Requires Admin PIN verification."""
if key_slot == KEY_SLOT.ATT:
require_version(self.version, (5, 2, 0))
self._put_data(DO.ATT_CERTIFICATE, b"")
else:
self._select_certificate(key_slot)
self._put_data(DO.CARDHOLDER_CERTIFICATE, b"")
def attest(self, key_slot):
"""Requires User PIN verification."""
require_version(self.version, (5, 2, 0))
self._app.send_apdu(0x80, INS.GET_ATTESTATION, key_slot.indx, 0)
return self.read_certificate(key_slot)
def get_openpgp_info(controller: OpenPgpController):
"""Get human readable information about the OpenPGP configuration."""
retries = controller.get_remaining_pin_tries()
data = {
"OpenPGP version": "%d.%d" % controller.get_openpgp_version(),
"Application version": "%d.%d.%d" % controller.version,
"PIN tries remaining": retries.pin,
"Reset code tries remaining": retries.reset,
"Admin PIN tries remaining": retries.admin,
"Require PIN for signature": controller.get_signature_pin_policy(),
}
# Touch only available on YK4 and later
if controller.version >= (4, 2, 6):
touch = {
"Signature key": controller.get_touch(KEY_SLOT.SIG),
"Encryption key": controller.get_touch(KEY_SLOT.ENC),
"Authentication key": controller.get_touch(KEY_SLOT.AUT),
}
if controller.supports_attestation:
touch["Attestation key"] = controller.get_touch(KEY_SLOT.ATT)
data["Touch policies"] = touch
return data