-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyubikey-piv.py
More file actions
975 lines (813 loc) · 41.9 KB
/
Copy pathyubikey-piv.py
File metadata and controls
975 lines (813 loc) · 41.9 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
######################################################################
# YubiKey PIV configuration and issuance
######################################################################
# version: 2.7
# last updated on: 2025-06-10 by Jonas Markström
# see readme.md for more info.
#
# DEPENDENCIES:
# - YubiKey Manager (ykman) must be installed on the system
# - Certvalidator must be installed on the system
#
# LIMITATIONS/ KNOWN ISSUES: N/A
#
# USAGE: ykman script yubikey-piv.py
#
# BSD 2-Clause License
# Copyright (c) 2025, Jonas Markström
#
# 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.
######################################################################
# IMPORTS
# Standard library imports
import sys
import os
import random
import time
import urllib.request
import binascii
import logging
import hashlib
from typing import List, Optional, Union, Dict, Any
# Third-party imports
import click
from yubikit.piv import (
PivSession,
SLOT,
KEY_TYPE,
MANAGEMENT_KEY_TYPE,
DEFAULT_MANAGEMENT_KEY,
)
from yubikit.core import NotSupportedError
from ykman.piv import sign_csr_builder
from ykman import scripting as s
from certvalidator import CertificateValidator, ValidationContext
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import load_pem_x509_certificate
from asn1crypto import x509 as asn1_x509
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.x509 import (
oid,
CertificateSigningRequestBuilder,
NameAttribute,
ObjectIdentifier,
OtherName,
BasicConstraints,
KeyUsage,
ExtendedKeyUsage,
SubjectAlternativeName,
RFC822Name,
)
# SETTINGS
# Default PIN and PUK values for the YubiKey PIV applet
DEFAULT_PIN = "123456"
DEFAULT_PUK = "12345678"
# Use slot 9A (authentication)
slot = SLOT.AUTHENTICATION
# Key type will be RSA 2048
key_type = KEY_TYPE.RSA2048
# Certificate URLs and files
YUBICO_URLS = {
"piv_ca_1": "https://developers.yubico.com/PKI/yubico-piv-ca-1.pem", # Pre fw. 5.7.4 PIV root CA
"ca_1": "https://developers.yubico.com/PKI/yubico-ca-1.pem", # 5.7.4 and later PIV root CA (2025)
"intermediate": "https://developers.yubico.com/PKI/yubico-intermediate.pem" # New intermediate CA certificates (2025)
}
CA_FILES = ["yubico-piv-ca-1.pem", "yubico-ca-1.pem", "yubico-intermediate.pem"]
# Form factor mapping for YubiKey models
FORM_FACTOR_NAMES: Dict[bytes, str] = {
b'\x00': "Unknown",
b'\x01': "Keychain (USB-A)",
b'\x02': "YubiKey Nano (USB-A)",
b'\x03': "Keychain (USB-C)",
b'\x04': "YubiKey Nano (USB-C)",
b'\x05': "Keychain (Lightning + USB-C)",
b'\x06': "YubiKey Bio MPE (USB-A)",
b'\x07': "YubiKey Bio MPE (USB-C)"
}
######################################################################################################################################
# CONFIGURE THE YUBIKEY (OPTION 1) #
######################################################################################################################################
# Function to check for trivial PIN or PUK selection
def is_trivial(value):
value_str = str(value)
# Check if all digits are the same (e.g.: "000000")
if all(digit == value_str[0] for digit in value_str):
return True
# Check if digits are incremental (e.g.: "123456")
incremental_pattern = ''.join(str(i) for i in range(int(value_str[0]), int(value_str[0]) + len(value_str)))
if value_str == incremental_pattern:
return True
# Check if digits are decremental (e.g.: "654321")
decremental_pattern = ''.join(str(i) for i in range(int(value_str[0]), int(value_str[0]) - len(value_str), -1))
if value_str == decremental_pattern:
return True
return False
def configure_yubikey():
click.clear()
# We should warn the user on the effects of resetting the PIV applet!
click.secho(" ________________________________________________________________________________________________ ", bg="yellow")
click.secho(" | | ", bg="yellow")
click.secho(" | WARNING! | ", bg="yellow")
click.secho(" | This option will *reset* the YubiKey PIV applet and any existing certificate credential on | ", bg="yellow")
click.secho(" | the YubiKey will be lost. FIDO2, U2F, OATH and other non-PIV credentials are not affected. | ", bg="yellow")
click.secho(" | | ", bg="yellow")
click.secho(" |________________________________________________________________________________________________| ", bg="yellow")
click.secho(" ", bg="yellow")
# Prompt user to continue
def continue_or_exit():
if click.confirm("Do you want to continue?", default=True):
click.clear()
else:
click.echo("Exiting the program...")
# Perform cleanup or any necessary steps before exiting
raise SystemExit
continue_or_exit()
click.clear()
# Connect to a YubiKey
yubikey = s.single()
# Establish a PIV session
piv = PivSession(yubikey.smart_card())
'''
# Get firmware version for comparison e.g determine if a feature is supported...
version_info = yubikey.info.version
fw = f"{version_info.major}.{version_info.minor}.{version_info.patch}"
'''
# Reset the PIV applet
piv.reset()
# MANAGEMENT KEY
# Check if YubiKey takes TDES or AES Management key
"""
If there is no metadata support, then the YubiKey uses TDES.
Otherwise we use the metadata to determine what key type to use.
"""
try:
mgmt_key_type = piv.get_management_key_metadata().key_type
except NotSupportedError:
print("NotSupportedError")
mgmt_key_type = MANAGEMENT_KEY_TYPE.TDES
# Unlock with the management key
piv.authenticate(mgmt_key_type,(DEFAULT_MANAGEMENT_KEY))
# Define hex_key with a default value of None
hex_key = None
# Prompt user
create_random_key = click.confirm("Do you want us to create a *randomized* Management Key for you?", default=True)
if create_random_key:
# Generate a random Management Key
hex_key = os.urandom(24).hex()
else:
# Prompt user to set a new Management Key (48 digits)
while True:
# TODO: confirm hexadecimal conversion
hex_key = click.prompt("Please enter a new Management Key (48 hex digits)", hide_input=False)
try:
int(hex_key, 16) # Make sure format is valid
if len(hex_key) == 48:
break
else:
click.secho("⛔ Invalid Management Key length. Please enter a key of 48 hex digits.", fg="red")
continue
except ValueError:
click.secho("⛔ The Management Key must be hexadecimal. Please try again!", fg="red")
continue
break
# Set new management key from random key or user input key
piv.set_management_key(mgmt_key_type, bytes.fromhex(hex_key))
click.clear()
# PUK
# TODO: check for trivial PUKs
create_random_puk = click.confirm(
"Do you want us to create a *randomized* PUK for you?", default=True
)
if create_random_puk:
# Generate a random 8 digit PUK
puk = str(random.randint(00000000, 99999999)).rjust(8, "0")
else:
# Prompt user to set a new PUK (8 digits)
while True:
puk = click.prompt("Please enter a new PUK (8 digits)", hide_input=False)
if not puk.isdigit():
click.secho("⛔ The PUK must be numeric. Please try again!", fg="red")
elif len(puk) != 8:
click.secho("⛔ Invalid PUK length. Please enter a PUK of 8 digits.", fg="red")
elif is_trivial(puk): # Check selected user input for triviality!
click.secho("⛔ The provided PUK is too easy to guess! Please choose a non-trivial PUK!", fg="red")
else:
break
piv.change_puk(DEFAULT_PUK, puk)
click.clear()
# PIN
# Prompt user to set a new PIN (6-8 digits)
while True:
pin = click.prompt("Please enter a new PIN (6-8 digits)", hide_input=False)
if not pin.isdigit():
click.secho("⛔ The PIN must be numeric. Please try again!", fg="red")
elif len(pin) < 6 or len(pin) > 8:
click.secho("⛔ Invalid PIN length. Please enter a PIN between 6 and 8 digits.", fg="red")
elif is_trivial(pin): # Check selected user input for triviality!
click.secho("⛔ The provided PIN is too easy to guess! Please choose a non-trivial PIN!", fg="red")
else:
break
piv.change_pin(DEFAULT_PIN, pin)
click.clear()
# Inform the user
click.echo("Please note the following YubiKey details:\n")
click.echo("-----------------------------------------------------------------------------")
click.echo(f"YubiKey device info: {yubikey}")
click.echo(f"Management Key: {hex_key}")
click.echo(f"PIN: {pin}")
click.echo(f"PUK: {puk}")
click.echo("=============================================================================")
click.echo("")
# Return to menu system
click.pause("\nPress any key to return to the main menu.")
click.clear()
######################################################################################################################################
# CREATE A CSR (OPTION 2) #
######################################################################################################################################
def create_csr():
click.clear()
# Inform the user
click.secho(" ________________________________________________________________________________________________ ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" | INFO | ", bg="blue")
click.secho(" | This option will create Certificate Signing Request (CSR) based on user input. The script | ", bg="blue")
click.secho(" | will output the CSR as well as necessary artifacts to support Attestation (optional task). | ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" |________________________________________________________________________________________________| ", bg="blue")
click.secho(" ", bg="blue")
# Prompt user to continue
def continue_or_exit():
if click.confirm("Do you want to continue?", default=True):
click.clear()
else:
click.echo("Exiting the program...")
# Perform cleanup or any necessary steps before exiting
raise SystemExit
continue_or_exit()
click.clear()
# Connect to a YubiKey
yubikey = s.single()
# Establish a PIV session
piv = PivSession(yubikey.smart_card())
# Check if YubiKey takes TDES or AES Management key
"""
If there is no metadata support, then the YubiKey uses TDES.
Otherwise we use the metadata to determine what key type to use.
"""
try:
mgmt_key_type = piv.get_management_key_metadata().key_type
except NotSupportedError:
print("NotSupportedError")
mgmt_key_type = MANAGEMENT_KEY_TYPE.TDES
# Authenticate with management key to perform key generation
for i in range(3):
try:
# TODO: confirm hexadecimal and not decimal properties
key = click.prompt("Please enter your Management Key", default=DEFAULT_MANAGEMENT_KEY.hex())
piv.authenticate(mgmt_key_type, bytes.fromhex(key))
#piv.authenticate(MANAGEMENT_KEY_TYPE.TDES, bytes.fromhex(key))
#piv.authenticate(key_type,(DEFAULT_MANAGEMENT_KEY))
break
except:
click.clear()
click.secho("⛔ That does not look like the correct key!\n", fg="red")
click.pause("Press any key to try again.")
click.clear()
if i == 2:
click.clear()
click.secho("🛑 No valid key provided. Exiting program...", fg="red")
time.sleep(2) # Pause for 2 seconds
click.clear()
sys.exit()
click.clear()
# Generate a new key pair on the YubiKey
click.echo(f"Generating {key_type.name} private key in slot {slot:X}...")
try:
pub_key = piv.generate_key(slot, key_type)
except Exception as exc:
print(exc)
click.clear()
# Prepare the subject:
'''
NOTE: For more details on CSR creation, please refer to:
https://cryptography.io/en/latest/x509/reference/#x-509-csr-certificate-signing-request-builder-object
https://cryptography.io/en/latest/x509/reference/#object-identifiers
'''
email = click.prompt("Please enter your email", default="alice.smith@contoso.com")
commonName = click.prompt("Please enter your name", default="Alice Smith")
orgName = click.prompt("Please enter your organization name", default="Users")
domainName = click.prompt("Please enter your domain name", default="contoso")
topDomain = click.prompt("Please enter your top domain name", default="com")
''' TODO: Solve *this* to better mimic the Entra ID / Azure AD expected certificate structure!
Define the Object Identifier (OID) for OtherName
oid_other_name = ObjectIdentifier('1.3.6.1.4.1.311.20.2.3')'''
subject = x509.Name(
[
NameAttribute(oid.NameOID.EMAIL_ADDRESS, email),
NameAttribute(oid.NameOID.COMMON_NAME, commonName),
NameAttribute(oid.NameOID.ORGANIZATION_NAME, orgName),
NameAttribute(oid.NameOID.DOMAIN_COMPONENT, domainName),
NameAttribute(oid.NameOID.DOMAIN_COMPONENT, topDomain),
]
)
# Prepare the certificate
builder = (
CertificateSigningRequestBuilder()
.subject_name(subject)
# Some examples of extensions to add, many more are possible:
.add_extension(
BasicConstraints(ca=False, path_length=None),
critical=True,
)
.add_extension(
KeyUsage(
digital_signature=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
ExtendedKeyUsage(
[
oid.ExtendedKeyUsageOID.CLIENT_AUTH,
oid.ExtendedKeyUsageOID.SMARTCARD_LOGON,
]
),
critical=True,
)
.add_extension(
SubjectAlternativeName(
[
RFC822Name(email),
# TODO: Instead of 'RFC822Name(email' create Other Name > Principal Name = UPN
]
),
critical=False,
)
)
click.clear()
# The user must input PIN
for i in range(3):
try:
pin = click.prompt("Please enter your PIN", default=DEFAULT_PIN)
piv.verify_pin(pin)
break
except:
click.clear()
click.secho("⛔ That does not look like the correct PIN!\n", fg="red")
click.pause("Press any key to try again.")
click.clear()
if i == 2:
click.clear()
click.secho("🛑 No valid PIN provided. Exiting program...", fg="red")
time.sleep(2) # Pause for 2 seconds
click.clear()
sys.exit()
click.clear()
# Sign the CSR
csr = sign_csr_builder(piv, slot, pub_key, builder)
pem = csr.public_bytes(serialization.Encoding.PEM)
# Save CSR to file
with open('csr.pem', 'wb') as f:
f.write(pem)
click.clear()
# Attest the key
click.echo(f"Attesting the created key in slot {slot:X}...")
attestation = piv.attest_key(slot)
attest_pem = attestation.public_bytes(serialization.Encoding.PEM)
# Save attestation certificate to file
with open('attestation.pem', 'wb') as f:
f.write(attest_pem)
click.clear()
# Export intermediate certificate from slot 9F
intermediate = piv.get_certificate(slot.ATTESTATION)
# Save intermediate certificate to file
with open('SlotF9Intermediate.pem', 'wb') as f:
f.write(intermediate.public_bytes(serialization.Encoding.PEM))
click.clear()
click.secho("✅ CSR and attestation certificates have been saved to current directory!", fg="green")
# Return to menu system
click.pause("\nPress any key to return to the main menu.")
click.clear()
######################################################################################################################################
# VALIDATE ATTESTATION (OPTION 3) #
######################################################################################################################################
def validate_attestation():
click.clear()
# Inform the user
click.secho(" ________________________________________________________________________________________________ ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" | INFO | ", bg="blue")
click.secho(" | This option tests the authenticity of a certificate signing request (CSR) by verifying it's | ", bg="blue")
click.secho(" | private key attestation against the YubiKey intermediate certificate (exported from slot 9F) | ", bg="blue")
click.secho(" | and in turn verifying that certificate against Yubico Intermediate and Root CA certificates. | ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" | If attestation checks are successful the script returns the results as well as attested | ", bg="blue")
click.secho(" | details about the YubiKey such as form factor and serial number. If attestation checks fail | ", bg="blue")
click.secho(" | the script will detail what fail as well as output troubleshooting information. | ", bg="blue")
click.secho(" | DO NOT issue a certificate if attestation checks fail for any reason! | ", bg="blue")
click.secho(" |________________________________________________________________________________________________| ", bg="blue")
click.secho(" ", bg="blue")
# Prompt user to continue;)
def continue_or_exit():
if click.confirm("Do you want to continue?", default=True):
click.clear()
else:
click.echo("Exiting the program...")
# Perform cleanup or any necessary steps before exiting
raise SystemExit
continue_or_exit()
click.clear()
# Load all certificates from PEM file
def load_all_pem_certificates(pem_data: bytes) -> List[x509.Certificate]:
"""
Load all certificates from a PEM file that may contain multiple certificates.
Args:
pem_data: Raw bytes containing one or more PEM-encoded certificates
Returns:
List of cryptography.x509.Certificate objects
Raises:
ValueError: If the PEM data is invalid
"""
try:
certs = []
parts = pem_data.split(b"-----END CERTIFICATE-----")
for part in parts:
if b"-----BEGIN CERTIFICATE-----" in part:
cert_pem = part + b"-----END CERTIFICATE-----\n"
certs.append(x509.load_pem_x509_certificate(cert_pem, default_backend()))
return certs
except Exception as e:
raise ValueError(f"Failed to load PEM certificates: {str(e)}")
# Function to convert certificate(s) for processing
def to_asn1(cert: x509.Certificate) -> asn1_x509.Certificate:
"""
Convert a cryptography.x509.Certificate to asn1crypto.x509.Certificate.
Args:
cert: cryptography.x509.Certificate object
Returns:
asn1crypto.x509.Certificate object
Raises:
ValueError: If conversion fails
"""
try:
return asn1_x509.Certificate.load(cert.public_bytes(Encoding.DER))
except Exception as e:
raise ValueError(f"Failed to convert certificate to ASN1 format: {str(e)}")
# Function to perform certificate chain validation
def validate_with_certvalidator(
leaf_cert: x509.Certificate,
intermediates: List[x509.Certificate],
trust_roots: List[x509.Certificate]
) -> None:
"""
Validate a certificate chain using certvalidator.
Args:
leaf_cert: End-entity certificate to validate
intermediates: List of intermediate certificates
trust_roots: List of trusted root certificates
Raises:
ValueError: If certificate validation fails
"""
try:
context = ValidationContext(trust_roots=[to_asn1(c) for c in trust_roots])
validator = CertificateValidator(
end_entity_cert=to_asn1(leaf_cert),
intermediate_certs=[to_asn1(c) for c in intermediates],
validation_context=context
)
validator.validate_usage(set())
except Exception as e:
raise ValueError(f"Certificate validation failed: {str(e)}")
# Function to verify certifcate signature
def verify_signature(parent: x509.Certificate, child: x509.Certificate) -> None:
"""
Verify that a child certificate is signed by a parent certificate.
Args:
parent: Parent certificate that should have signed the child
child: Child certificate to verify
Raises:
ValueError: If signature verification fails
"""
try:
parent.public_key().verify(
child.signature,
child.tbs_certificate_bytes,
padding.PKCS1v15(),
child.signature_hash_algorithm
)
except Exception as e:
raise ValueError(f"Signature verification failed: {str(e)}")
# Function to display attested YubiKey attributes
def get_yubikey_metadata(attestation_cert: x509.Certificate) -> None:
"""
Extract and display YubiKey metadata from attestation certificate.
Args:
attestation_cert: x509 certificate containing YubiKey metadata
Returns:
None - prints metadata to console
"""
firmware_version = serial_number = pin_policy = touch_policy = "Not Found"
form_factor = "Unknown"
fips_status = "false"
try:
for ext in attestation_cert.extensions:
if ext.oid.dotted_string == "1.3.6.1.4.1.41482.3.9":
form_factor = FORM_FACTOR_NAMES.get(ext.value.value, "Unknown")
elif ext.oid.dotted_string == "1.3.6.1.4.1.41482.3.10":
fips_status = "true"
elif ext.oid.dotted_string == "1.3.6.1.4.1.41482.3.7":
ext_data = ext.value.value
serial_number = int(binascii.hexlify(ext_data[2:]), 16)
elif ext.oid.dotted_string == "1.3.6.1.4.1.41482.3.3":
ext_data = binascii.hexlify(ext.value.value).decode('utf-8')
firmware_version = f"{int(ext_data[:2], 16)}.{int(ext_data[2:4], 16)}.{int(ext_data[4:6], 16)}"
elif ext.oid.dotted_string == "1.3.6.1.4.1.41482.3.8":
ext_data = binascii.hexlify(ext.value.value).decode('utf-8')
pin_policy = {"01": "never", "02": "once per session", "03": "always"}.get(ext_data[:2], "Unknown")
touch_policy = {"01": "never", "02": "always", "03": "cached for 15s"}.get(ext_data[2:4], "Unknown")
click.secho(f"✅ Model: {form_factor}", fg="green")
click.secho(f"✅ FIPS certified: {fips_status}", fg="green")
click.secho(f"✅ Serial Number: {serial_number}", fg="green")
click.secho(f"✅ Firmware Version: {firmware_version}", fg="green")
click.secho(f"✅ PIN Policy: {pin_policy}", fg="green")
click.secho(f"✅ Touch Policy: {touch_policy}", fg="green")
except Exception as e:
click.secho(f"⚠️ Warning: Failed to extract some YubiKey metadata: {str(e)}", fg="yellow")
# Get file paths from user input or use default values
csr_file = click.prompt("Please provide the path to the Certificate Signing Request (CSR)", default="csr.pem")
click.clear()
attestation_file = click.prompt("Please provide the path to the PIV Attestation Certificate", default="attestation.pem")
click.clear()
slotF9Intermediate_file = click.prompt("Please provide the path to the Intermediate Certificate", default="SlotF9Intermediate.pem")
click.clear()
# Yubico Root and Intermediate CA certificates.
ca_files = ["yubico-piv-ca-1.pem", "yubico-ca-1.pem", "yubico-intermediate.pem"]
ca_certs = []
# Check if all CA root and intermediate certificates exist
all_files_exist = all(os.path.isfile(f) for f in ca_files)
if all_files_exist:
# Look for the certificates on current working directory
click.echo("Found Yubico CA certificates on current working directory...")
click.echo("")
click.pause()
click.clear()
else:
# If we cannot find the files, download them!
click.echo("Downloading Yubico CA certificates...")
urllib.request.urlretrieve(YUBICO_URLS["piv_ca_1"], CA_FILES[0])
urllib.request.urlretrieve(YUBICO_URLS["ca_1"], CA_FILES[1])
urllib.request.urlretrieve(YUBICO_URLS["intermediate"], CA_FILES[2])
click.echo("We successfully downloaded required certificates from yubico.com...")
click.echo("")
click.pause()
click.clear()
# Load certificate files and verify signatures
try:
# Load CSR
with open(csr_file, 'rb') as f:
csr = x509.load_pem_x509_csr(f.read(), default_backend())
# Load attestation certificate from slot 9A
with open(attestation_file, 'rb') as f:
attestation_cert = x509.load_pem_x509_certificate(f.read(), default_backend())
# Load intermediate certificate from slot 9F
with open(slotF9Intermediate_file, 'rb') as f:
slotF9_intermediate_cert = x509.load_pem_x509_certificate(f.read(), default_backend())
# Load all CA root and intermediate certificates
ca_certs = []
for ca_file in ca_files:
with open(ca_file, 'rb') as f:
cert_data = f.read()
ca_certs.extend(load_all_pem_certificates(cert_data))
# Separate loaded CA certs into roots and intermediates
root_candidates = []
intermediate_candidates = []
# Add slot 9F intermediate cert to intermediates
intermediate_candidates.append(slotF9_intermediate_cert)
for cert in ca_certs:
issuer = cert.issuer.rfc4514_string()
subject = cert.subject.rfc4514_string()
if issuer == subject:
root_candidates.append(cert)
else:
intermediate_candidates.append(cert)
# ---- Begin Validation ----
click.echo("-------------------")
click.echo("VALIDATION RESULTS:")
click.echo("===================")
# Step 1
try:
validate_with_certvalidator(
leaf_cert=attestation_cert,
intermediates=intermediate_candidates,
trust_roots=root_candidates
)
click.secho("✅ Attestation certificate is chained to a trusted Yubico root CA.", fg="green")
except Exception as e:
click.secho("💀 Certificate chain validation failed.", fg="red")
click.secho(f"🔍 Details: {e}", fg="yellow")
sys.exit(1)
# Step 2: Check CSR and attestation public key match
csr_pub = csr.public_key().public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
att_pub = attestation_cert.public_key().public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
if csr_pub == att_pub:
click.secho("✅ CSR public keys matches Attestation certificate public key.", fg="green")
else:
click.secho("💀 CSR public key does not match attestation public key", fg="red")
click.secho("🔍 Public key fingerprints (for debugging):", fg="yellow")
click.secho(f" CSR Public Key SHA256: {hashlib.sha256(csr_pub).hexdigest()}", fg="yellow")
click.secho(f" Attestation Public Key SHA256: {hashlib.sha256(att_pub).hexdigest()}", fg="yellow")
sys.exit(1)
# Step 4: Display YubiKey metadata
click.echo("-------------------")
click.echo("YubiKey details:")
click.echo("===================")
get_yubikey_metadata(attestation_cert)
except FileNotFoundError:
click.secho("⛔ One or more of the requested files were not found.", fg="red")
except Exception as e:
click.secho(f"⛔ CA path validation failed: {e}", fg="red")
# Return to menu system
click.pause("\nPress any key to return to the main menu.")
click.clear()
######################################################################################################################################
# IMPORT SIGNED CERTIFICATE (OPTION 4) #
######################################################################################################################################
def import_certificate():
click.clear()
# Inform the user
click.secho(" ________________________________________________________________________________________________ ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" | INFO | ", bg="blue")
click.secho(" | This option takes in a user provided card Management Key and then imports a *signed* (note!) | ", bg="blue")
click.secho(" | certificate into the default PIV authentication slot (9A). Once imported the user is able to | ", bg="blue")
click.secho(" | use the YubiKey for Certificate-Based Authentication (CBA). | ", bg="blue")
click.secho(" | | ", bg="blue")
click.secho(" |________________________________________________________________________________________________| ", bg="blue")
click.secho(" ", bg="blue")
# Prompt user to continue
def continue_or_exit():
if click.confirm("Do you want to continue?", default=True):
click.clear()
else:
click.echo("Exiting the program...")
# Perform cleanup or any necessary steps before exiting
raise SystemExit
continue_or_exit()
click.clear()
# Connect to a YubiKey
yubikey = s.single()
# Establish a PIV session
piv = PivSession(yubikey.smart_card())
# Check if YubiKey takes TDES or AES Management key
"""
If there is no metadata support, then the YubiKey uses TDES.
Otherwise we use the metadata to determine what key type to use.
"""
try:
mgmt_key_type = piv.get_management_key_metadata().key_type
except NotSupportedError:
print("NotSupportedError")
mgmt_key_type = MANAGEMENT_KEY_TYPE.TDES
# Authenticate with management key in order to support certificate import
for i in range(3):
try:
# TODO: confirm hexadecimal and not decimal properties
key = click.prompt("Please enter your Management Key", default=DEFAULT_MANAGEMENT_KEY.hex())
piv.authenticate(mgmt_key_type, bytes.fromhex(key))
break
except:
click.clear()
click.secho("⛔ That does not look like the correct key!\n", fg="red")
click.pause("Press any key to try again.")
click.clear()
if i == 2:
click.clear()
click.secho("🛑 No valid key provided. Exiting program...", fg="red")
time.sleep(2) # Pause for 2 seconds
click.clear()
sys.exit()
click.clear()
# Prompt user to supply signed CSR
signed_file = click.prompt("Please provide the path to the *signed* user certificate", default="signed.crt")
click.clear()
try:
with open(signed_file, 'rb') as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
piv.put_certificate(SLOT.AUTHENTICATION, cert)
# Only show success message if no exception occurred
click.secho(f"✅ Certificate successfully imported to slot {slot:X}.", fg="green")
except Exception as e:
click.secho(f"⛔ An error occurred while loading the certificate: {str(e)}", fg="red")
# Exit program on user acknowledgement
click.pause("\nPress any key to exit this program!")
click.clear()
# Function to exit program
def quit_program():
"""
Gracefully exit the program.
This function:
1. Displays a quit message
2. Clears the screen
3. Exits the program with a clean status code
Note: The cleanup() function needs to be implemented.
"""
click.echo("Quitting the program...")
#cleanup()
click.clear()
sys.exit()
######################################################################################################################################
# THIS IS OUR MAIN MENU SYSTEM #
######################################################################################################################################
menu = {
"1": "Configure YubiKey",
"2": "Create a CSR",
"3": "Validate attestation",
"4": "Import certificate",
"5": "Quit program"
}
while True:
options = menu.keys()
# Inform the user about the purpose of the script and its options
click.secho(" ________________________________________________________________________________________________ ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" | WELCOME | ", bg="green")
click.secho(" | This script is designed to perform administrative tasks related to YubiKey PIV lifecycle. | ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" | OPTION 1 resets the YubiKey PIV applet and then sets a new Management Key, a new PUK, & PIN. | ", bg="green")
click.secho(" | The script offers to randomize the Management Key as well as the PUK, but the PIN must be set | ", bg="green")
click.secho(" | by the user. PUK and PIN selection must not be trivial (easy to guess). | ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" | OPTION 2 generates a new key pair in the PIV Authentication slot (9A) to support CBA | ", bg="green")
click.secho(" | Certificate-Based Authentication. A Certificate Signing Request (CSR) is then generated based | ", bg="green")
click.secho(" | on end-user input. The script outputs the necessary files to support certificate issuance. | ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" | OPTION 3 validates the CSR and auxiliary certificates created in option 2 by checking the | ", bg="green")
click.secho(" | Attestation Certificate and the necessary CA signatures. This option is intended to be run by | ", bg="green")
click.secho(" | an administrator, prior to signing the CSR using a Certificate Authority (out of scope). | ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" | OPTION 4 imports a signed certificate to the PIV Authentication slot (9A), thus completing the | ", bg="green")
click.secho(" | Issuance process. This step is intended to be performed by the end-user. | ", bg="green")
click.secho(" | | ", bg="green")
click.secho(" |________________________________________________________________________________________________| ", bg="green")
click.secho(" ", bg="green")
click.pause("\nPress any key to continue.")
click.clear()
click.secho("MAIN MENU:")
click.secho("==========\n")
for option in options:
print(option + ". " + menu[option])
selection = input("\nPlease select an option: ")
if selection == "1":
configure_yubikey()
elif selection == "2":
create_csr()
elif selection == "3":
validate_attestation()
elif selection == "4":
import_certificate()
elif selection == "5":
quit_program()
else:
click.clear()
click.secho("⛔ Invalid selection, please try again!", fg="red")
click.pause("\nPress any key to return to the main menu.")
click.clear()