-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecboot.py
executable file
·3112 lines (2505 loc) · 156 KB
/
secboot.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
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
import os
import re
import sys
import abc
import time
import shutil
import distro
import logging
import pexpect
import argparse
import typing as t
import pathlib as pl
from enum import Enum
import unittest as ut
import tempfile as tempf
import dataclasses as dc
logging.basicConfig(format='%(asctime)s %(levelname)s %(funcName)s:%(lineno)d: %(message)s')
# Exit on critical log
class ShutdownHandler(logging.Handler):
def emit(self, record):
print(record, file=sys.stderr)
logging.shutdown()
sys.exit(1)
logger = logging.getLogger()
logger.addHandler(ShutdownHandler(level=logging.CRITICAL))
# ==============================================================================================================
# ==============================================================================================================
# Common
def safe_move(dry_run: bool, src: pl.Path, dst: pl.Path) -> None: # Not using exceptions for error handling:
logger.debug(f'{"NOT " if dry_run else ""}Moving {src} to {dst}')
if dry_run:
return
try:
shutil.move(src, dst)
except:
logger.critical(f'Failed to move {src} to {dst}: {sys.exc_info()[0]}')
def safe_copy(dry_run: bool, src: pl.Path, dst: pl.Path) -> None: # Not using exceptions for error handling:
logger.debug(f'{"NOT " if dry_run else ""}Copying {src} to {dst}')
if dry_run:
return
try:
shutil.copy(src, dst)
except:
logger.critical(f'Failed to copy {src} to {dst}: {sys.exc_info()[0]}')
def safe_rm(dry_run: bool, path: pl.Path) -> None: # Not using exceptions for error handling:
logger.debug(f'{"NOT " if dry_run else ""}Removing {path}')
if dry_run:
return
try:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(path)
except:
logger.critical(f'Failed to remove {path}: {sys.exc_info()[0]}')
def safe_rm_dir(dry_run: bool, path: pl.Path) -> None:
logger.debug(f'{"NOT " if dry_run else ""}Removing {path}')
if dry_run:
return
try:
shutil.rmtree(path)
except:
logger.critical(f'Failed to remove {path}: {sys.exc_info()[0]}')
@dc.dataclass
class ExecRes:
out: str = ""
ret: int = 0
def is_ok(self) -> bool:
return self.ret == 0
def is_err(self) -> bool:
return not self.is_ok()
def exec(dry_run: bool, command: str, echo_output: t.Union[bool, None] = None, root_is_required = False) -> ExecRes:
if echo_output == None:
echo_output=logger.level <= logging.DEBUG
if root_is_required and os.geteuid() != 0:
command = "sudo " + command
if echo_output:
logger.info(f'{"NOT " if dry_run else ""}executing: {command}')
else:
logger.debug(f'{"NOT " if dry_run else ""}executing: {command}')
if dry_run:
return ExecRes()
# Curses try #2: https://stackoverflow.com/questions/24946988/using-python-subprocess-call-to-launch-an-ncurses-process
child = None
# Unfortunately pexpect.spawn throws exceptions, let's fix it:
try:
child = pexpect.spawn(command, logfile=None)
except:
return ExecRes(out=f'Failed to start new process: {command}: {sys.exc_info()}', ret=1)
# child.interact()
child.wait()
output: str = child.read().decode("utf-8").rstrip()
if echo_output:
print(f'{output}')
child.close()
return ExecRes(out=output, ret=child.exitstatus)
shell_program_positive_cache: t.Set[str] = set()
def shell_program_exists(program: str) -> bool:
if program in shell_program_positive_cache:
return True
# Output of "command -v uname" is totally useless even in DEBUG, so, echo_output=False
result: bool = exec(False, f'bash -c "command -v {program}"', echo_output=False).is_ok()
if result:
shell_program_positive_cache.add(program)
return result
class TestShellCommandExists(ut.TestCase):
def test_existing_command_exist(self):
self.assertTrue(shell_program_exists('uname'))
def test_nonexisting_command_does_not_exist(self):
self.assertFalse(shell_program_exists('unameqwer1324'))
@dc.dataclass
class ProviderPair: # Both: entity and package can change from one version of OS to another:
entity: t.Union[str, pl.Path] = "" # File or executable
pkg: str = "" # Package
def __iter__(self): # For structural binding to work
return iter((self.entity, self.pkg))
class ProviderEfiStub:
linuxx64_efi_stub: pl.Path = pl.Path('/usr/lib/systemd/boot/efi/linuxx64.efi.stub')
default: ProviderPair = ProviderPair(entity=linuxx64_efi_stub, pkg="systemd-boot-efi")
overrides: t.Dict[str, ProviderPair] = {"Ubuntu-22.10": ProviderPair(entity=linuxx64_efi_stub, pkg='systemd'),
"Ubuntu-22.04": ProviderPair(entity=linuxx64_efi_stub, pkg='systemd')}
class ProviderPkcs11:
pkcs11_so_1: pl.Path = pl.Path("/usr/lib/x86_64-linux-gnu/engines-1.1/pkcs11.so") # Before Ubuntu 22.04
pkcs11_so_2: pl.Path = pl.Path("/usr/lib/x86_64-linux-gnu/engines-3/pkcs11.so") # Starting from Ubuntu 22.04
default: ProviderPair = ProviderPair(entity=pkcs11_so_2, pkg="libengine-pkcs11-openssl")
overrides: t.Dict[str, ProviderPair] = {"Ubuntu-21.10": ProviderPair(entity=pkcs11_so_1, pkg='libengine-pkcs11-openssl')}
class ProviderSbsign:
default: ProviderPair = ProviderPair(entity='sbsign', pkg='sbsigntool')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderSbverify:
default: ProviderPair = ProviderPair(entity='sbverify', pkg='sbsigntool')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderYubicoPivTool:
default: ProviderPair = ProviderPair(entity='yubico-piv-tool', pkg='yubico-piv-tool')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderOpenssl:
default: ProviderPair = ProviderPair(entity='openssl', pkg='openssl')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderEfiUpdatevar:
default: ProviderPair = ProviderPair(entity='efi-updatevar', pkg='efitools')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderCertToEfiSigList:
default: ProviderPair = ProviderPair(entity='cert-to-efi-sig-list', pkg='efitools')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderSignEfiSigList:
default: ProviderPair = ProviderPair(entity='sign-efi-sig-list', pkg='efitools')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderEfiReadvar:
default: ProviderPair = ProviderPair(entity='efi-readvar', pkg='efitools')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderPesign:
default: ProviderPair = ProviderPair(entity='pesign', pkg='pesign')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderGpg:
default: ProviderPair = ProviderPair(entity='gpg', pkg='gpg')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderGrubMkstandalone:
default: ProviderPair = ProviderPair(entity='grub-mkstandalone', pkg='grub-common')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderGrubMkconfig:
default: ProviderPair = ProviderPair(entity='grub-mkconfig', pkg='grub-common')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderObjcopy:
default: ProviderPair = ProviderPair(entity='objcopy', pkg='binutils')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderEfibootmgr:
default: ProviderPair = ProviderPair(entity='efibootmgr', pkg='efibootmgr')
overrides: t.Dict[str, ProviderPair] = {}
class ProviderQemuImg:
default: ProviderPair = ProviderPair(entity='qemu-img', pkg='qemu-utils')
overrides: t.Dict[str, ProviderPair] = {}
def get_provider_pair(provider: t.Type[t.Any]) -> ProviderPair:
key: str = f'{distro.name()}-{distro.version()}'
return provider.overrides.get(key, provider.default)
@dc.dataclass
class ProgPack:
program: str = ""
package: str = ""
def __init__(self, provider: t.Type[t.Any]):
self.program, self.package = get_provider_pair(provider)
def exec(self, dry_run: bool, command: str, root_is_required: bool = False) -> ExecRes:
def install_if_program_does_not_exist(dry_run: bool, pp: ProgPack) -> None:
if shell_program_exists(pp.program):
return
logger.warning(f'Program: {pp.program} does not exist => installing it via package: {pp.package}')
# Disable questions like: needrestart
os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
res: ExecRes = exec(dry_run=dry_run, command=f'apt install -y {pp.package}', root_is_required=True)
if res.is_err():
logger.critical(f"Program: {pp.program} does not exist, and we failed to install it via package: "
f"{pp.package}: {res}")
if not shell_program_exists(pp.program) and not dry_run:
logger.critical(f"Program: {pp.program} still does not exist even after installing {pp.package}")
install_if_program_does_not_exist(dry_run=dry_run, pp=self)
return exec(dry_run=dry_run, command=command, root_is_required=root_is_required)
def install_if_none_of_files_exist(dry_run: bool, files: t.List[pl.Path], package: str) -> None:
if any(file.exists() for file in files):
return
logger.info(f'None of the files: {files} exists => installing it via package: {package}')
res: ExecRes = exec(dry_run=dry_run, command=f'apt install -y {package}')
if res.is_err():
logger.critical(f"Failed to install package: {package}: {res}")
if not any(file.exists() for file in files) and not dry_run:
logger.critical(f"None of the files: {files} still exists even after installing {package}")
all_providers: t.Dict[str, t.Type[t.Any]] = {
"EfiStub" : ProviderEfiStub ,
"Pkcs11" : ProviderPkcs11 ,
"Sbsign" : ProviderSbsign ,
"Sbverify" : ProviderSbverify ,
"YubicoPivTool" : ProviderYubicoPivTool ,
"Openssl" : ProviderOpenssl ,
"EfiUpdatevar" : ProviderEfiUpdatevar ,
"CertToEfiSigList": ProviderCertToEfiSigList,
"SignEfiSigList" : ProviderSignEfiSigList ,
"EfiReadvar" : ProviderEfiReadvar ,
"Pesign" : ProviderPesign ,
"Gpg" : ProviderGpg ,
"GrubMkstandalone": ProviderGrubMkstandalone,
"GrubMkconfig" : ProviderGrubMkconfig ,
"Objcopy" : ProviderObjcopy ,
"Efibootmgr" : ProviderEfibootmgr ,
"QemuImg" : ProviderQemuImg ,
}
def print_all_providers_info():
for name, provider in all_providers.items():
pair: ProviderPair = get_provider_pair(provider)
assert(len(str(pair.entity)) and len(str(pair.pkg)))
print(f'{name}: {pair.entity} => {pair.pkg}')
# ==============================================================================================================
# ==============================================================================================================
# SSL.
# The classes below work only with one given key/certificate - they do not know about DB/KEK/...
class SslEngine(metaclass=abc.ABCMeta):
@abc.abstractmethod
def sign(self, file: pl.Path, out: pl.Path):
pass
@abc.abstractmethod
def verify(self, file: pl.Path):
pass
@staticmethod
def key_path(dir: pl.Path, component: str) -> pl.Path:
return dir / f'{component}.key' # Private key. Ex: .../PK.key
@staticmethod
def crt_path(dir: pl.Path, component: str) -> pl.Path:
return dir / f'{component}.crt' # PEM-encoded certificate (public key + metainfo). Ex: .../PK.crt
@staticmethod
def cer_path(dir: pl.Path, component: str) -> pl.Path:
return dir / f'{component}.cer' # DER-encoded certificate (public key + metainfo). Ex: .../PK.crt
@staticmethod
def esl_path(dir: pl.Path, component: str) -> pl.Path:
return dir / f'{component}.esl' # EFI Sig List. Ex: .../PK.esl
@staticmethod
def auth_path(dir: pl.Path, component: str) -> pl.Path:
return dir / f'{component}.auth' # signed ESL file. Ex: .../PK.auth
# SSL Engine implementation based that knows about key info on filesystem
class FsSsl(SslEngine):
def __init__(self, dry_run: bool, path_to_basename: str) -> None:
self.dry_run = dry_run
self.basename = path_to_basename
def sign(self, file: pl.Path, out: pl.Path):
# sbsign --key dsk1.key --cert dsk1.crt shimx64.efi
key_path: pl.Path = pl.Path(f'{self.basename}.key').expanduser().resolve()
crt_path: pl.Path = pl.Path(f'{self.basename}.crt').expanduser().resolve()
cmd: str = f'sbsign --key {key_path} --cert {crt_path} --output {out} {file}'
res: ExecRes = ProgPack(ProviderSbsign).exec(self.dry_run, cmd)
if res.is_err():
logger.critical(f'Failed to sign {file} with {key_path} and {crt_path} and/or save it to {out}: {res}')
def verify(self, file: pl.Path):
crt_path: pl.Path = pl.Path(f'{self.basename}.crt').expanduser().resolve()
cmd: str = f'sbverify --cert {crt_path} {file}'
res: ExecRes = ProgPack(ProviderSbverify).exec(self.dry_run, cmd)
if res.is_err():
logger.critical(f'Failed to verify signed file: {file} with cert {crt_path}: {res}')
NFC_READER_HINT: str = ''
def get_scard_devices_paths(dry_run: bool) -> t.List[str]:
usb_dev: ExecRes = exec(dry_run, "usb-devices")
if usb_dev.is_err():
logger.critical(f'Failed to get list of usb-devices: {usb_dev}')
bus_pattern = re.compile(r'T:.*Bus=([0-9]+)')
dev_pattern = re.compile(r'T:.*Dev#= *([0-9]+)')
res = []
for section in usb_dev.out.replace('\r\n', '\n').strip().split('\n\n'):
if 'Cls=0b(scard)' not in section:
continue
bus_match = bus_pattern.search(section)
dev_match = dev_pattern.search(section)
if not bus_match or not dev_match:
continue
bus = int(bus_match.group(1))
dev = int(dev_match.group(1))
res.append(f"/dev/bus/usb/{bus:03d}/{dev:03d}")
return res
# class OutputLogger:
# def __init__(self, encode='utf-8'):
# self.encode = encode
# def write(self, s):
# if isinstance(s, bytes):
# s = s.decode(self.encode, errors='ignore')
# sys.stdout.write(s)
# sys.stdout.flush()
# def flush(self):
# sys.stdout.flush()
# SSL Engine implementation that can use Yubikey
class YubikeySsl(SslEngine):
def __init__(self, dry_run: bool, work_dir: pl.Path, key_name: str, slot: str, pkcs11_obj: str, password: str) -> None:
self.dry_run = dry_run
self.password = password
# self.work_dir = work_dir
# self.slot = slot
self.pkcs11_obj = pkcs11_obj
work_dir = work_dir / ".SSL"
work_dir.mkdir(parents=True, exist_ok=True)
self.crt_path: pl.Path = SslEngine.crt_path(work_dir, key_name)
YubikeySsl.extract_certificate(dry_run=self.dry_run, slot_id=slot, dst=self.crt_path)
@staticmethod
def extract_certificate(dry_run: bool, slot_id: str, dst: pl.Path) -> str:
# yubico-piv-tool -a read-certificate -s 9c -o db_from_yu.crt -K PEM
command: str = f'yubico-piv-tool {NFC_READER_HINT} -a read-certificate --slot {slot_id} -o {dst} -K PEM'
res: ExecRes = ProgPack(ProviderYubicoPivTool).exec(dry_run, command)
if res.is_err():
logger.critical(f'Failed read certificate from Yubikey, from slot {slot_id} and/or save it to {dst}: {res}')
return command
def sign(self, file: pl.Path, out: pl.Path):
# sbsign --engine pkcs11 --key 'pkcs11:manufacturer=piv_II;id=%02' --cert PK.crt --output bzImage.signed.efi shimx64.efi
# Without the package, sbsign with engine pkcs11 complains:
# DSO support routines:dlfcn_load:could not load the shared
# library:../crypto/dso/dso_dlfcn.c:118:filename(/usr/lib/x86_64-linux-gnu/engines-1.1/pkcs11.so):
# /usr/lib/x86_64-linux-gnu/engines-1.1/pkcs11.so: cannot open shared object file: No such file or directory
file_pkg: ProviderPair = get_provider_pair(ProviderPkcs11)
install_if_none_of_files_exist(dry_run=self.dry_run, files=[file_pkg.entity], package=file_pkg.pkg)
cmd: str = f"sbsign --engine pkcs11 --key '{self.pkcs11_obj}' --cert {self.crt_path} --output {out} {file}"
if f'{distro.name()}-{distro.version()}' == "Ubuntu-24.04":
# sbsign is broken in Ubuntu-24.04, use sbsign from docker (assume it has been built)
usb_dev: str = " ".join(f'--device {p}' for p in get_scard_devices_paths(dry_run=False))
cmd = f"""
docker run -it --rm
--volume {self.crt_path}:{self.crt_path}:ro
--volume {file}:{file}:rw
--volume {out.parent}:{out.parent}:rw
{usb_dev}
dimanne/gpg
{cmd}
"""
# Make it a single clean line (better for logs):
cmd = re.sub(r'\s+', ' ', cmd.replace('\n', ' ')).strip()
# Need to kill host scdaemon and pcscd, as they claims USB devices and interfere with pcscd in container
exec(self.dry_run, "sudo pkill -9 \"(scdaemon|pcscd)\"")
logger.debug(f'{"NOT " if self.dry_run else ""}executing: {cmd}')
if self.dry_run:
return
# Curses try #2: https://stackoverflow.com/questions/24946988/using-python-subprocess-call-to-launch-an-ncurses-process
child = pexpect.spawn(cmd)
# child.logfile = OutputLogger() # debugging
# child.wait()
child.expect('Enter engine key pass phrase:')
child.sendline(self.password)
child.expect('Enter PKCS#11 key PIN for .* key:')
child.sendline(self.password)
# child.expect(pexpect.EOF)
child.wait()
child.close()
if child.exitstatus != 0:
logger.critical(f"Failed to sign {file} with {self.crt_path} and/or save result in {out}. exitstatus: {child.exitstatus}, output: {child.before}")
def verify(self, file: pl.Path):
FsSsl(self.dry_run, str(self.crt_path.with_suffix(""))).verify(file)
# ==============================================================================================================
# UEFI Keys and certificates
class UefiVars(Enum):
PK = 1 # PK component name
KEK = 2 # KEK component name
db = 3 # db component name
dbx = 4 # dbx component name
class UefiEngine(metaclass=abc.ABCMeta):
@abc.abstractmethod
def enroll_certs_to_uefi(self) -> None:
pass
@abc.abstractmethod
def sign(self, file: pl.Path, out: pl.Path) -> None:
pass
@abc.abstractmethod
def verify(self, file: pl.Path) -> str:
pass
@abc.abstractmethod
def __str__(self) -> str:
pass
# Responsible for operations with UEFI with key info on FileSystem
class FsUefi(UefiEngine):
def __init__(self, dry_run: bool, keys_dir: pl.Path, var: UefiVars) -> None:
self.dry_run = dry_run
self.keys_dir = keys_dir
self.var = var
@staticmethod
def enroll_certs_to_uefi_from_dir(dry_run: bool, dir: pl.Path) -> None:
print(f'Not implemented yet.')
print(f'You will need to do it manually:')
print(f' - Copy *.cer files from {dir} to a FAT-formatted flash drive, _or_ /boot/efi directory')
print(f' - Reboot and enter UEFI setup => SecureBoot settings')
print(f' - In the settings, remove all existing keys (PK, KEK, db)')
print(f' - Enroll your own (db.cer, KEK.cer, PK.cer)')
# def enroll_esl(dry_run: bool, dir: pl.Path, esl_var: UefiVars) -> None:
# esl: pl.Path = SslEngine.esl_path(dir, esl_var.name)
# res: ExecRes = ProgPack(ProviderEfiUpdatevar).exec(dry_run,
# f'efi-updatevar -e -f {esl} {esl_var.name}')
# if res.is_err():
# logger.critical(f'Failed to enroll: {esl}: {res}')
# logger.info(f'Successfully enrolled {esl_var.name}: {esl}')
#
# # Install keys into EFI (PK last as it will enable Custom Mode locking out further unsigned changes):
# enroll_esl(dry_run, dir, esl_var=UefiVars.db) # sudo efi-updatevar -e -f sec_out/db.esl db
# enroll_esl(dry_run, dir, esl_var=UefiVars.KEK) # sudo efi-updatevar -e -f sec_out/KEK.esl KEK
# enroll_esl(dry_run, dir, esl_var=UefiVars.PK) # sudo efi-updatevar -f sec_out/PK.auth PK
# # sudo efi-updatevar -e -c sec_out/db.crt db
# # sudo efi-updatevar -e -c sec_out/KEK.crt KEK
# # sudo efi-updatevar -e -c sec_out/PK.crt PK
# # sudo efi-updatevar -f sec_out/PK.auth PK
# # sudo efi-updatevar -e -f sec_out/PK.auth PK
#
# # The EFI variables may be immutable (i-flag in lsattr output) in recent kernels (e.g. 4.5.4).
# # Use chattr -i to make them mutable again if you can’t update the variables with the commands above:
# # chattr -i /sys/firmware/efi/efivars/{PK,KEK,db,dbx}-*
def enroll_certs_to_uefi(self) -> None:
self.enroll_certs_to_uefi_from_dir(self.dry_run, self.keys_dir)
def sign(self, file: pl.Path, out: pl.Path) -> None:
FsSsl(dry_run=self.dry_run, path_to_basename=str(self.keys_dir / self.var.name)).sign(file, out)
def verify(self, file: pl.Path) -> str:
FsSsl(dry_run=self.dry_run, path_to_basename=str(self.keys_dir / self.var.name)).verify(file)
return f'"pesign -S -i {file}" and/or ' \
f'"sbverify --cert {(self.keys_dir / (self.var.name + ".crt")).resolve()} {file}"'
def __str__(self) -> str:
return f'FsUefi({self.keys_dir / self.var.name})'
@staticmethod
def generate_keys(dry_run: bool, keys_dir: pl.Path, id: str) -> None:
def id_for(name: str, id: str) -> str: # "PK of Asdf" or "Custom PK"
return f'{name} of {id}' if id else f'Custom {name}'
def generate(dry_run: bool, output_dir: pl.Path, id: str, var: UefiVars):
# openssl req –new -x509 –newkey rsa:2048 –subj "/CN=Custom PK/" –keyout PK.key –out PK.crt –days 3650 –nodes –sha256
# openssl x509 -outform der -in PK.crt -out PK.cer
# cert-to-efi-sig-list -g (uuidgen) sec_out/PK.crt sec_out/PK.esl
key_out: pl.Path = SslEngine.key_path(output_dir, var.name)
crt_out: pl.Path = SslEngine.crt_path(output_dir, var.name)
cer_out: pl.Path = SslEngine.cer_path(output_dir, var.name)
esl_out: pl.Path = SslEngine.esl_path(output_dir, var.name)
gen_res: ExecRes = ProgPack(ProviderOpenssl).exec(dry_run,
f'openssl req -new -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 '
f'-subj "/CN={id_for(var.name, id)}/" -keyout {key_out} -out {crt_out}')
if gen_res.is_ok():
logger.info(f'Generated private key in {key_out}, cert in {crt_out}. You might want to check that '
f'everything is fine: "openssl x509 -inform pem -in {crt_out} -text"')
else:
logger.critical(f'Failed to generate {var.name} and/or save it to {key_out} and {crt_out}: {gen_res}')
cer_res: ExecRes = ProgPack(ProviderOpenssl).exec(dry_run,
f'openssl x509 -outform der -in {crt_out} -out {cer_out}')
if cer_res.is_ok():
logger.info(f'Converted PEM-encoded .crt to DER-encoded .cer at: {cer_out}')
else:
logger.critical(f'Failed to convert PEM-encoded .crt to DER-encoded .cer and/or save it to {cer_out}: {cer_res}')
# esl_res: ExecRes = ProgPack(ProviderCertToEfiSigList).exec(dry_run,
# f'bash -c "cert-to-efi-sig-list -g $(uuidgen) {cer_out} {esl_out}"')
# if esl_res.is_ok():
# logger.info(f'Converted cer {cer_out} to esl: {esl_out}')
# else:
# logger.critical(f'Failed to convert cer {cer_out} to esl and/or save it to {esl_out}: {esl_res}')
# def sign_esl(dry_run: bool, output_dir: pl.Path, var_to_sign: UefiVars, with_var: UefiVars) -> None:
# with_key: pl.Path = SslEngine.key_path(output_dir, with_var.name)
# with_crt: pl.Path = SslEngine.crt_path(output_dir, with_var.name)
# esl_to_sign: pl.Path = SslEngine.esl_path(output_dir, var_to_sign.name)
# auth_out: pl.Path = SslEngine.auth_path(output_dir, var_to_sign.name)
# res: ExecRes = ProgPack(ProviderSignEfiSigList).exec(dry_run,
# f'sign-efi-sig-list -k {with_key} -c {with_crt} {var_to_sign.name} {esl_to_sign} {auth_out}')
# if res.is_err():
# logger.critical(f'Failed to sign esl: {esl_to_sign} with {with_var.name} '
# f'and/or save it to {auth_out}: {res}')
# logger.info(f'Signed esl: {esl_to_sign} with {with_var.name}: {auth_out}')
keys_dir.mkdir(parents=True, exist_ok=True)
generate(dry_run=dry_run, output_dir=keys_dir, id=id, var=UefiVars.PK)
generate(dry_run=dry_run, output_dir=keys_dir, id=id, var=UefiVars.KEK)
generate(dry_run=dry_run, output_dir=keys_dir, id=id, var=UefiVars.db)
# Some tools require the use of signed ESL files - AUTH files - even when Secure Boot is not enforcing or
# does not have a PK loaded. Only AUTH files can be used to carry out updates to Secure Boot's value stores
# while Secure Boot is enforcing checks. So, let's generate AUTH files, in case they are needed.
# sign_esl(dry_run=dry_run, output_dir=keys_dir, var_to_sign=UefiVars.PK, with_var=UefiVars.PK)
# sign_esl(dry_run=dry_run, output_dir=keys_dir, var_to_sign=UefiVars.KEK, with_var=UefiVars.PK)
# sign_esl(dry_run=dry_run, output_dir=keys_dir, var_to_sign=UefiVars.db, with_var=UefiVars.KEK)
# Responsible for operations with UEFI with key info on Yubikey
class YubikeyUefi(UefiEngine):
def __init__(self, dry_run: bool, work_dir: pl.Path, var: UefiVars, password: str) -> None:
self.dry_run = dry_run
self.work_dir = work_dir
self.var = var
self.password = password
self.ssl = None
def enroll_certs_to_uefi(self) -> None:
def extract(dry_run: bool, var: UefiVars, work_dir: pl.Path):
YubikeySsl.extract_certificate(dry_run=dry_run,
slot_id=YubikeyUefi.slot_for(var),
dst=SslEngine.crt_path(work_dir, var.name))
with tempf.TemporaryDirectory(prefix="secboot_certs_for_uefi_") as str_work_dir:
work_dir: pl.Path = pl.Path(str_work_dir)
extract(self.dry_run, UefiVars.PK, work_dir)
extract(self.dry_run, UefiVars.KEK, work_dir)
extract(self.dry_run, UefiVars.db, work_dir)
FsUefi.enroll_certs_to_uefi_from_dir(dry_run=self.dry_run, dir=work_dir)
input('\nPress any key to exit...')
def _slot(self):
return YubikeyUefi.slot_for(self.var)
def _pkcs11(self):
return YubikeyUefi.pkcs11_obj_for(self.var)
def _ssl(self):
if self.ssl:
return self.ssl
self.ssl = YubikeySsl(dry_run=self.dry_run,
work_dir=self.work_dir,
key_name=self.var.name,
slot=self._slot(),
pkcs11_obj=self._pkcs11(),
password=self.password)
return self.ssl
def sign(self, file: pl.Path, out: pl.Path) -> None:
self._ssl().sign(file, out)
def verify(self, file: pl.Path) -> str:
self._ssl().verify(file)
extract_command: str = YubikeySsl.extract_certificate(dry_run=True,
slot_id=self._slot(),
dst=pl.Path(f'{self.var.name}.crt'))
return f'"pesign -S -i {file}" and/or "sbverify --cert {self.var.name}.crt {file}", ' \
f'where "{self.var.name}.crt" is extracted from Yubikey with: "{extract_command}"'
def __str__(self) -> str:
return f'YubikeyUefi({self.var.name} in slot: {self._slot()}, {self._pkcs11()})'
@staticmethod
def enroll_to_yubikey(dry_run: bool, dir: pl.Path) -> None:
logger.warning(f'You might want to setup your Yubikey: '
f'(1) Set PIN: "yubico-piv-tool {NFC_READER_HINT} --action change-pin -P 123456", '
f'(2) Set PUK: "yubico-piv-tool {NFC_READER_HINT} --action change-puk -P 12345678", '
f'(3) Enable PIV over NFC: "ykman config nfc -f -e PIV". '
f'Other action see here: https://developers.yubico.com/yubico-piv-tool/Actions/')
def enable_retired_slots(dry_run: bool) -> None:
# http://cedric.dufour.name/blah/IT/YubiKeyHowto.html
# escaped_nfc_reader_hint = NFC_READER_HINT.replace('"', '\\"')
res: ExecRes = ProgPack(ProviderYubicoPivTool).exec(dry_run,
f'bash -c "echo -n C10114C20100FE00 | yubico-piv-tool {NFC_READER_HINT} -a write-object --id 0x5FC10C -i -"')
if res.is_err():
logger.critical(f'Failed to enable retired slots: {res}')
logger.info(f'Retired slots enabled')
def enroll(dry_run: bool, dir: pl.Path, var: UefiVars) -> None:
# yubico-piv-tool --action import-key --slot 82 --input PK.key --key-format PEM
# yubico-piv-tool --action import-certificate --slot 82 --input PK.crt --key-format PEM
slot: str = YubikeyUefi.slot_for(var)
key_in: pl.Path = SslEngine.key_path(dir, var.name)
crt_in: pl.Path = SslEngine.crt_path(dir, var.name)
ikcmd: str = f'yubico-piv-tool {NFC_READER_HINT} -a import-key --slot {slot} --input {key_in} --key-format PEM'
key_res: ExecRes = ProgPack(ProviderYubicoPivTool).exec(dry_run, ikcmd)
if key_res.is_err():
logger.critical(f'Failed to add key: {key_in} in slot: {slot}')
logger.info(f'Added key: {key_in} in slot: {slot}')
iccmd: str = f'yubico-piv-tool {NFC_READER_HINT} -a import-certificate --slot {slot} --input {crt_in} --key-format PEM'
crt_res: ExecRes = ProgPack(ProviderYubicoPivTool).exec(dry_run, iccmd)
if crt_res.is_err():
logger.critical(f'Failed to add certificate: {crt_in} in slot: {slot}')
logger.info(f'Added certificate: {crt_in} in slot: {slot}')
enable_retired_slots(dry_run)
enroll(dry_run, dir, UefiVars.PK)
enroll(dry_run, dir, UefiVars.KEK)
enroll(dry_run, dir, UefiVars.db)
@staticmethod
def slot_for(var: UefiVars) -> str:
return YubikeyUefi._YUBIKEY_SLOT_MAPPING[var][0]
@staticmethod
def pkcs11_obj_for(var: UefiVars) -> str:
return YubikeyUefi._YUBIKEY_SLOT_MAPPING[var][1]
# Slot 9c: Digital Signature <-> KEK
# This certificate and its associated private key is used for digital signatures for the purpose of document
# signing, or signing files and executables.
# Slot 9d: Key Management <-> DB
# This certificate and its associated private key is used for encryption for the purpose of confidentiality.
# This slot is used for things like encrypting e-mails or files.
# Other slots naming and mapping: https://developers.yubico.com/yubico-piv-tool/YKCS11/Functions_and_values.html
# Slot 82: Private key for Retired Key 1 <-> PK
# You can find "id=%05" via:
# apt install gnutls-bin ykcs11
# p11tool --provider /usr/lib/x86_64-linux-gnu/libykcs11.so --list-privkeys --login
# or: pkcs11-tool --module /usr/lib/x86_64-linux-gnu/libykcs11.so -O
_YUBIKEY_SLOT_MAPPING: t.Dict[UefiVars, t.Tuple[str, str]] = {
UefiVars.PK: ("82", "pkcs11:manufacturer=piv_II;id=%05"), # Retired Key 1
UefiVars.KEK: ("9d", "pkcs11:manufacturer=piv_II;id=%03"), # Key Management
UefiVars.db: ("9c", "pkcs11:manufacturer=piv_II;id=%02"), # Digital Signature
}
BACKUP_CERTS_FROM_UEFI_CMD_LINE_OPT: str = "ot/backup-certs-from-uefi"
def backup_certs_from_uefi(dry_run: bool, output_dir: pl.Path) -> None:
# efi-readvar -v PK -o PK.old.esl
def save(dry_run: bool, output_dir: pl.Path, var_name: str, file_name: str):
out = str(output_dir / file_name)
res: ExecRes = ProgPack(ProviderEfiReadvar).exec(dry_run, f'efi-readvar -v {var_name} -o {out}')
if res.is_ok():
logger.info(f'Saved {var_name} to {out}. You might want to extract der certificates from it with: '
f'"sig-list-to-certs {out} {var_name}" and inspect it further with '
f'"openssl x509 -inform der -in {var_name}-<n>.der -text"')
else:
logger.critical(f'Failed to save {var_name} to {out}: {res}')
output_dir.mkdir(parents=True, exist_ok=True)
save(dry_run, output_dir, UefiVars.PK.name, f'{UefiVars.PK.name}.old.esl')
save(dry_run, output_dir, UefiVars.KEK.name, f'{UefiVars.KEK.name}.old.esl')
save(dry_run, output_dir, UefiVars.db.name, f'{UefiVars.db.name}.old.esl')
save(dry_run, output_dir, UefiVars.dbx.name, f'{UefiVars.dbx.name}.old.esl')
def remove_all_ssl_signatures_inplace(dry_run: bool, filepath: pl.Path) -> None:
def get_number_of_signatures(dry_run: bool, filepath: pl.Path) -> int:
res: ExecRes = ProgPack(ProviderPesign).exec(dry_run, f'pesign -S -i {filepath}')
if res.is_err():
logger.critical(f'Failed to get signatures from {filepath}: {res}')
# Example of output:
# ---------------------------------------------
# certificate address is 0x7f591bf17f80
# Content was not encrypted.
# Content is detached; signature cannot be verified.
# The signer's common name is Canonical Ltd. Secure Boot Signing (2017)
# ...
# ---------------------------------------------
# certificate address is 0x7f591bf18700
# Content was not encrypted.
# Content is detached; signature cannot be verified.
# The signer's common name is Microsoft Windows UEFI Driver Publisher
# ...
# ---------------------------------------------
# Or
# No signatures found.
if dry_run:
return 2
count: int = res.out.count("---------------------------------------------")
return 0 if count == 0 else count - 1
def remove_one_signature(dry_run: bool, inp: pl.Path, out: pl.Path) -> None:
# pesign --signature-number 0 -r -i shimx64.efi -o shimx64.efi
res: ExecRes = ProgPack(ProviderPesign).exec(dry_run,
f'pesign --signature-number 0 --remove-signature -i {inp} -o {out}')
if res.is_ok():
logger.debug(f'Removed existing signature from {inp}, and wrote result in {out}')
else:
logger.critical(f'Failed to remove existing signature from {inp} and/or save result in {out}: {res}')
number_of_signatures: int = get_number_of_signatures(dry_run=dry_run, filepath=filepath)
logger.debug(f'{number_of_signatures} signatures found in {filepath}. '
f'{"Removing them..." if number_of_signatures else "Nothing to remove."}')
if number_of_signatures == 0:
return
tmp_filepath: pl.Path = filepath.with_suffix(f'{filepath.suffix}.tmp')
for i in range(0, number_of_signatures):
safe_move(dry_run=dry_run, src=filepath, dst=tmp_filepath)
remove_one_signature(dry_run=dry_run, inp=tmp_filepath, out=filepath)
safe_rm(dry_run=dry_run, path=tmp_filepath)
GENERATE_UEFI_KEYS_CMD_LINE_OPT: str = "ot/generate-uefi-keys"
ENROLL_SSL_TO_YUBIKEY_CMD_LINE_OPT: str = "ot/enroll-ssl-to-yubikey"
ENROLL_SSL_TO_UEFI_CMD_LINE_OPT: str = "ot/enroll-certs-to-uefi"
RE_SIGN_EFI_FILE_CMD_LINE_OPT: str = "re-sign-efi-file"
def re_sign_efi_file(dry_run: bool,
file_to_sign: pl.Path,
signed_file_path: pl.Path,
uefi: UefiEngine,
do_log: bool = True):
remove_all_ssl_signatures_inplace(dry_run=dry_run, filepath=file_to_sign)
uefi.sign(file_to_sign, signed_file_path)
verify_desc = uefi.verify(signed_file_path)
if do_log:
logger.info(f'(Re-)signed and verified {signed_file_path} with {uefi}. '
f'You can verify it yourself with {verify_desc}')
# ==============================================================================================================
# ==============================================================================================================
# GPG
def write_gpg_conf(dry_run: bool, gpg_home: pl.Path) -> None:
# wget -O $GNUPGHOME/gpg.conf https://raw.githubusercontent.com/drduh/config/master/gpg.conf
GPG_CONFIG: str = """
# https://github.com/drduh/config/blob/master/gpg.conf
# https://www.gnupg.org/documentation/manuals/gnupg/GPG-Configuration-Options.html
# https://www.gnupg.org/documentation/manuals/gnupg/GPG-Esoteric-Options.html
# Use AES256, 192, or 128 as cipher
personal-cipher-preferences AES256 AES192 AES
# Use SHA512, 384, or 256 as digest
personal-digest-preferences SHA512 SHA384 SHA256
# Use ZLIB, BZIP2, ZIP, or no compression
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
# Default preferences for new keys
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
# SHA512 as digest to sign keys
cert-digest-algo SHA512
# SHA512 as digest for symmetric ops
s2k-digest-algo SHA512
# AES256 as cipher for symmetric ops
s2k-cipher-algo AES256
# UTF-8 support for compatibility
charset utf-8
# Show Unix timestamps
fixed-list-mode
# No comments in signature
no-comments
# No version in output
no-emit-version
# Disable banner
no-greeting
# Long hexidecimal key format
keyid-format 0xlong
# Display UID validity
list-options show-uid-validity
verify-options show-uid-validity
# Display all keys and their fingerprints
with-fingerprint
# Display key origins and updates
#with-key-origin
# Cross-certify subkeys are present and valid
require-cross-certification
# Disable caching of passphrase for symmetrical ops
no-symkey-cache
# Enable smartcard
use-agent
# Disable recipient key ID in messages
throw-keyids
# Keyserver URL
#keyserver hkps://keys.openpgp.org
#keyserver hkps://keyserver.ubuntu.com:443
#keyserver hkps://hkps.pool.sks-keyservers.net
#keyserver hkps://pgp.ocf.berkeley.edu
# Proxy to use for keyservers
#keyserver-options http-proxy=http://127.0.0.1:8118
#keyserver-options http-proxy=socks5-hostname://127.0.0.1:9050
# Verbose output
#verbose
# Show expired subkeys
#list-options show-unusable-subkeys
"""
if dry_run:
return
with open(gpg_home / "gpg.conf", "w") as gpg_conf:
gpg_conf.write(GPG_CONFIG)
@dc.dataclass
class FileAndSig:
file: pl.Path
sig: pl.Path
def default_sig(self) -> pl.Path:
return self.file.with_suffix(self.file.suffix + ".sig")
def __init__(self, f: pl.Path, s: t.Union[pl.Path, None] = None) -> None:
self.file = f
self.sig = self.default_sig() if s is None else s
def __repr__(self):
return f'FileWithGpgSig({self.file}, {self.sig})'
class Gpg:
def __init__(self, dry_run: bool, GNUPGHOME: pl.Path, key_id: str, password: t.Union[None, str]):
self.dry_run = dry_run
self.GNUPGHOME = GNUPGHOME
self.key_id = key_id
self.password = password
def sign_detached(self, file_and_sig: FileAndSig) -> None:
# gpg --default-key $KEYID --detach-sign sec_out/shimx64.efi
if self.password is None:
cmd: str = f'gpg --yes --default-key {self.key_id} --detach-sign {file_and_sig.file}'
else:
cmd: str = f'gpg --passphrase "{self.password}" --pinentry-mode loopback --batch ' \
f'--yes --default-key {self.key_id} --detach-sign {file_and_sig.file}'
res: ExecRes = self.exec_in_home(cmd)
if res.is_err():
logger.critical(f"Failed to sign {file_and_sig.file}")
safe_move(self.dry_run, file_and_sig.default_sig(), file_and_sig.sig)
def verify(self, file_and_sig: FileAndSig) -> str:
# gpg --verify sec_out/shimx64.efi.sig sec_out/shimx64.efi
# gpg: Signature made Mon 19 Apr 2021 17:56:17 BST
# gpg: using RSA key FCC...
# gpg: Good signature from "..." [unknown]
res: ExecRes = self.exec_in_home(f'gpg --verify {file_and_sig.sig} {file_and_sig.file}')
if res.is_err():
logger.critical(f"Failed to verify {file_and_sig.file} against signature: {file_and_sig.sig}: {res}")
return f'"gpg --verify {file_and_sig.sig} {file_and_sig.file}"'
def export_pub_key(self, work_dir: pl.Path) -> pl.Path:
# gpg --export $GPG_KEY > gpg.key
result: pl.Path = work_dir / 'gpg_pub.key'
res: ExecRes = self.exec_in_home(f'bash -c "gpg --export {self.key_id} > {result}"')
if res.is_err():
logger.critical(f"Failed to export public key of {self.key_id}: {res}")
return result
def exec_in_home(self, cmd: str) -> ExecRes:
return Gpg.exec_in(dry_run=self.dry_run, in_dir=self.GNUPGHOME, cmd=cmd)
@staticmethod
def exec_in(dry_run: bool, in_dir: pl.Path, cmd: str) -> ExecRes:
os.environ["GNUPGHOME"] = str(in_dir)
res: ExecRes = ProgPack(ProviderGpg).exec(dry_run, cmd)
del os.environ["GNUPGHOME"]
return res
def __str__(self) -> str:
return f'Gpg({self.GNUPGHOME}, key_id: {self.key_id})'
@staticmethod
def get_last_added_primary_key_fingerprint(dry_run: bool, gpg_home: pl.Path) -> str:
# gpg --list-keys --with-fingerprint --with-colons | tac | grep "^fpr:" | head -n 1 | cut -d : -f 10
res: ExecRes = Gpg.exec_in(dry_run, gpg_home,
f'bash -c "gpg --list-keys --with-fingerprint --with-colons 2>/dev/null | '
f'tac | grep \"^fpr:\" | head -n 1 | cut -d : -f 10"')
if res.is_err():
logger.critical(f'Failed to get fingerpriint of primary key: {res}')
return res.out
@staticmethod
def generate_keys(dry_run: bool, gpg_home: pl.Path, id: str, passphrase: str) -> None:
# https://serverfault.com/a/962553/304045
# https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Key-Management.html
# gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key "Generate BatchKey" rsa4096 cert never
# gpg --batch --pinentry-mode loopback --passphrase '' --quick-add-key 54203CB155CD20D034994814F17CED43965D5D69 rsa4096 sign never
# gpg --batch --pinentry-mode loopback --passphrase '' --quick-add-key 54203CB155CD20D034994814F17CED43965D5D69 rsa4096 encrypt never
# gpg --batch --pinentry-mode loopback --passphrase '' --quick-add-key 54203CB155CD20D034994814F17CED43965D5D69 rsa4096 auth never
if not dry_run:
gpg_home.mkdir(parents=True, exist_ok=True)
if not (gpg_home / "gpg.conf").exists():
write_gpg_conf(dry_run, gpg_home)
primary_res: ExecRes = Gpg.exec_in(dry_run, gpg_home,
f'gpg --batch --pinentry-mode loopback --passphrase "{passphrase}" '
f'--quick-generate-key "{id}" rsa4096 cert never')
if primary_res.is_err():
logger.critical(f'Failed to generate primary key: {primary_res}')
key_id: str = Gpg.get_last_added_primary_key_fingerprint(dry_run, gpg_home)
logger.info(f'Generated primary rsa4096 cert key with keyid: {key_id}')
def add_sub_key(dry_run: bool, keys_dir: pl.Path, key_id: str, passphrase: str, usage: str) -> None: