-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptsane
More file actions
executable file
·1265 lines (1142 loc) · 40.4 KB
/
Copy pathcryptsane
File metadata and controls
executable file
·1265 lines (1142 loc) · 40.4 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
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/env bash
# https://github.com/Embi/cryptsane.sh/blob/main/cryptsane
# Copyright (c) 2025 Embi
# Licensed under the MIT License.
set -o errtrace
set -o nounset
set -o pipefail
export LC_ALL="C"
umask 077
# CONFIGURATION:
#
# All default values are taken from https://github.com/drduh/YubiKey-Guide
# check the awesome guide for more info.
declare -r \
KEY_TYPE="${CRYPTSANE_KEY_TYPE:-rsa4096}" \
SUBKEY_EXPIRATION="${CRYPTSANE_SUBKEY_EXPIRATION:-2y}" \
VAULT_FS="${CRYPTSANE_VAULT_FS:-ext2}" \
CRYPTSANE_DOCKER="${CRYPTSANE_DOCKER:-false}" \
YK_DEFAULT_ADMIN_PIN="12345678" \
YK_DEFAULT_USER_PIN="123456"
declare \
PRIMARY_UID="" \
OTHER_UIDS="" \
KEYID="" \
CRYPTSANE_MODE="" \
TMP_GNUPGHOME="" \
VAULT_DEVICE="" \
VAULT_MOUNTDIR="" \
DETECTED_VAULT_DEVICES="" \
YUBIKEY="" \
PUBLIC_VAULT_MOUNT="" \
SECRET_VAULT_MOUNT="" \
LOGFILE=$(mktemp -t "cryptpi-$(date +%Y-%m-%d)-XXXXXXXXXX") \
GNUPGHOME=${GNUPGHOME:-$HOME/.gnupg}
declare -A CRYPTSANE_FLAGS
CRYPTSANE_FLAGS["private"]=0
export GNUPGHOME VAULT_FS VAULT_MOUNTDIR GUM_CHOOSE_HEADER GUM_FILE_HEADER LOGFILE
# Taken from https://raw.githubusercontent.com/drduh/config/master/gpg.conf
readonly HARDENED_GPG_CONF="
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
cert-digest-algo SHA512
s2k-digest-algo SHA512
s2k-cipher-algo AES256
charset utf-8
no-comments
no-emit-version
no-greeting
keyid-format 0xlong
list-options show-uid-validity
verify-options show-uid-validity
with-fingerprint
require-cross-certification
no-symkey-cache
use-agent
armor
throw-keyids
"
show_cli_help() {
local tool_filename="cryptsane"
[[ $CRYPTSANE_DOCKER == "true" ]] && tool_filename="cryptsane-docker"
printf '%s\n' "\
Usage: $tool_filename [OPTIONS]
Description:
Cryptsane is a TUI tool for managing OpenPGP/GnuPG/YubiKey madness.
The tools allows you to:
- Create an OpenPGP Identity (key pair + subkeys + UIDs).
- Create a Vault (a USB block device with one LUKS-encrypted and one unencrypted
partition)
- Export an OpenPGP Identity to a Vault.
- Import an OpenPGP Identity from a Vault
- Move subkeys to a YubiKey.
- Rotate subkeys (revoke existing and generate new ones)
- Some other usefull stuff
Options:
-h, --help Show this help message and exit.
-p, --private Run in private mode (root privileges required).
Examples:
$tool_filename
$tool_filename -p
"
}
function log_error {
# Log error to both stderr and LOGFILE
local error_message=$1
gum log --level error "$error_message"
gum log -t rfc822 -o "$LOGFILE" --level error "$error_message"
}
function log_info {
# Log info to both stdout and LOGFILE
local info_message=$1
gum log --level info "$info_message"
gum log -t rfc822 -o "$LOGFILE" --level info "$info_message"
}
function show_logs {
less "$LOGFILE"
}
function init_gnupg_home {
# Initialize GNUPGHOME:
# Take users GNUPGHOME if run in user mode or create a temporary
# directory if run in private mode.
if [[ "$CRYPTSANE_MODE" = "user" ]]; then
log_info "Using user's GNUPGHOME ($GNUPGHOME)..."
elif [[ "$CRYPTSANE_MODE" = "private" ]]; then
TMP_GNUPGHOME=$(mktemp -d -t "gnupg-$(date +%Y-%m-%d)-XXXXXXXXXX")
GNUPGHOME=$TMP_GNUPGHOME
echo "$HARDENED_GPG_CONF" > "$GNUPGHOME/gpg.conf"
echo "disable-ccid" > "$GNUPGHOME/scdaemon.conf"
log_info "Using temporary GNUPGHOME ($GNUPGHOME)..."
else
log_error "Cryptsane mode is not specified..."
exit 1
fi
}
function remove_tmp_gnupg_home {
if [[ -n "$TMP_GNUPGHOME" ]]; then
log_info "Removing temporary GNUPGHOME ($TMP_GNUPGHOME)..."
rm -r "$TMP_GNUPGHOME"
fi
}
function check_identity {
if [[ -z "$PRIMARY_UID" ]]; then
log_error "No identity selected. Either create new identity, import one from vault or select existing one."
return 1
fi
}
function check_vault_unmounted {
# Check that no vault partitions are mounted
local detected_pub_mount detected_sec_mount
detected_pub_mount=$(lsblk -r -n -o "mountpoint" \
| grep vault-public \
| cut -d" " -f2 \
)
detected_sec_mount=$(lsblk -r -n -o "mountpoint" \
| grep vault-secret \
| cut -d" " -f2 \
)
if [[ -n "$detected_pub_mount" || -n "$detected_sec_mount" ]]; then
log_error "Detected some vault mounts. Unmount them before continuing..."
return 1
fi
}
function check_vault_mounted {
# Check that vault partitions are mounted
local detected_pub_mount detected_sec_mount pub_tmp_dir sec_tmp_dir \
detected_mountdir=""
# Try to auto-detect existing vault mount points
detected_pub_mount=$(lsblk -r -n -o "mountpoint" \
| grep vault-public \
| cut -d" " -f2 \
)
detected_sec_mount=$(lsblk -r -n -o "mountpoint" \
| grep vault-secret \
| cut -d" " -f2 \
)
pub_tmp_dir=$(echo "$detected_pub_mount" | cut -d'/' -f3)
sec_tmp_dir=$(echo "$detected_sec_mount" | cut -d'/' -f3)
if [[ "$CRYPTSANE_MODE" = "private" ]]; then
if [[ "$pub_tmp_dir" = "$sec_tmp_dir" && -n "$pub_tmp_dir" ]]; then
detected_mountdir="/tmp/$pub_tmp_dir"
fi
elif [[ "$CRYPTSANE_MODE" = "user" ]]; then
if [[ -n "$pub_tmp_dir" ]]; then
detected_mountdir="/tmp/$pub_tmp_dir"
fi
fi
if [[ -n "$VAULT_MOUNTDIR" && "$VAULT_MOUNTDIR" == "$detected_mountdir" ]]
then
PUBLIC_VAULT_MOUNT="$detected_pub_mount"
SECRET_VAULT_MOUNT="$detected_sec_mount"
return 0
elif [[ -n "$detected_pub_mount" || -n "$detected_sec_mount" ]]; then
log_error "Vault is not mounted properly... Unmount it and try again."
return 1
else
log_error "Vault is not mounted..."
return 1
fi
}
function check_yubikey {
# Check that a YubiKey is accessible via ykman.
if ! ykman info &>> /dev/null; then
log_error "No YubiKey detected..."
return 1
fi
}
function check_yubikey_access {
# Check that a YubiKey is accessible via gpg.
if ! gpg --card-status &>> /dev/null; then
log_error "GPG unable to access YubiKey..."
return 1
fi
}
function detect_yubikey {
local yubikey_type yubikey_sn
{
ykman_info="$(ykman info)"
yubikey_type=$(echo "$ykman_info" | grep -E "Device type" | cut -d":" -f2)
yubikey_sn=$(echo "$ykman_info" | grep -E "Serial number" | cut -d":" -f2)
YUBIKEY="${yubikey_type:-None} (SN: ${yubikey_sn:- None})"
} &>> "$LOGFILE"
}
function yk_info {
ykman info
}
function ask_secret {
# Ask user to provide a secret twice
local secret secret_type secret_again
secret_type="$1"
secret=$(gum input --placeholder="Type secret..." \
--password --prompt "$secret_type: ")
secret_again=$(gum input --placeholder="Type secret again..." \
--password --prompt "$secret_type: ")
if [[ "$secret" = "$secret_again" ]]; then
echo "$secret"
else
log_error "Secrets don't match..."
return 1
fi
}
function ask_secret_once {
# Ask user to provide a secret once
local secret_type secret
secret_type="$1"
secret=$(gum input --placeholder="Type secret..." \
--password --prompt "$secret_type: ")
echo "$secret"
}
function __repartition_vault_device {
# Create vault partitions on the selected block device
# This is a helper function for create_vault operation
local vault_device
vault_device="$1"
log_info "Repartitioning vault device ($vault_device)..."
{
wipefs --all "$vault_device" || return 1
dd if=/dev/urandom of="$vault_device" bs=10M count=10 || return 1
echo -e "g\nw" | fdisk "$vault_device" || return 1
echo -e "n\n\n\n+100M\nn\n\n\n\nw" | fdisk "$vault_device" || return 1
} &>> "$LOGFILE"
log_info "Vault device repartitioned."
}
function __prepare_vault_secret_partition {
# Format end encrypt the secret vault partition
# This is a helper function for create_vault operation
local secret_vault_part vault_pass
#/dev/sdX1
secret_vault_part="${1}1"
log_info "Preparing secret vault partition ($secret_vault_part)..."
{
vault_pass=$2
echo "$vault_pass" | cryptsetup -q luksFormat "$secret_vault_part" || return 1
echo "$vault_pass" | cryptsetup -q luksOpen "$secret_vault_part" vault-secret || return 1
mkfs -t "$VAULT_FS" -L vault-secret /dev/mapper/vault-secret || return 1
cryptsetup luksClose vault-secret || return 1
} &>> "$LOGFILE"
log_info "Secret vault partition prepared."
}
function __prepare_vault_public_partition {
# Format the public vault partition
# This is a helper function for create_vault operation
#/dev/sdX2
local public_vault_part="${1}2"
log_info "Preparing public vault partition ($public_vault_part)..."
{
mkfs -t "$VAULT_FS" -L vault-public "$public_vault_part" || return 1
} &>> "$LOGFILE"
log_info "Public vault partition prepared."
}
function detect_vault_devices {
local detected_vault_pub_parts
if [[ $CRYPTSANE_DOCKER == true ]]; then
detected_vault_pub_parts=$(blkid \
| grep "vault-public" \
| awk -F: '{ print $1 }' \
)
if [[ -n $detected_vault_pub_parts ]]; then
DETECTED_VAULT_DEVICES=$(echo "$detected_vault_pub_parts" \
| xargs lsblk -r -n -o "pkname" \
| tr '\n' ' ' \
)
else
DETECTED_VAULT_DEVICES=""
fi
else
DETECTED_VAULT_DEVICES=$(lsblk -r -n -o "label,pkname" \
| grep vault-public \
| cut -d" " -f2 \
)
fi
}
function show_vault_info {
# Show info about dected/mounted vaults
detect_vault_devices
printf "\nDetected vault devices: %30s\nMounted vault device: %30s\nMount dir: %30s\n \n"\
"$DETECTED_VAULT_DEVICES" "$VAULT_DEVICE" "$VAULT_MOUNTDIR"
}
function __mount_public_vault {
# Mount unencrypted public-vault partition
# This is a helper function for mount_vault operation
local selected_vault_device=$1 use_sudo=""
if [[ $EUID -ne 0 ]]; then
log_info "Sudo is required to mount public vault..."
sudo -v
use_sudo="sudo"
fi
{
mkdir -p "$VAULT_MOUNTDIR/vault-public"
$use_sudo mount "/dev/${selected_vault_device}2" \
"$VAULT_MOUNTDIR/vault-public" || return 1
} &>> "$LOGFILE"
}
function __mount_secret_vault {
# Mount encrypted secret-vault partition
# This is a helper function for mount_vault operation
local selected_vault_device=$1 vault_pass
vault_pass=$(ask_secret_once "Vault password")
{
mkdir -p "$VAULT_MOUNTDIR/vault-secret"
echo "$vault_pass" | cryptsetup -q luksOpen \
"/dev/${selected_vault_device}1" vault-secret || return 1
mount /dev/mapper/vault-secret "$VAULT_MOUNTDIR/vault-secret" || return 1
} &>> "$LOGFILE"
}
function mount_vault {
# Mount vault device to a temp dir. Mount either both vault-secret and
# vault-public partitions for private mode, or only vault-public for user
# mode.
local selected_vault_device vault_pass mounted
check_vault_unmounted || return 1
GUM_CHOOSE_HEADER="Choose vault device:"
detect_vault_devices
selected_vault_device=$(gum choose $DETECTED_VAULT_DEVICES)
if [[ -z "$selected_vault_device" ]]; then
log_info "No vault device selected..."
return 1
fi
log_info "Mounting vault device: $selected_vault_device"
# Create vault mount directory
if [[ -z $VAULT_MOUNTDIR ]]; then
VAULT_MOUNTDIR=$(mktemp -d -t "vault-$(date +%Y-%m-%d)-XXXXXXXXXX")
fi
mounted=0
__mount_public_vault "$selected_vault_device"
mounted=$((mounted + $?))
if [[ "$CRYPTSANE_MODE" = "private" ]]; then
__mount_secret_vault "$selected_vault_device"
mounted=$((mounted + $?))
fi
if [[ $mounted -gt 0 ]]; then
log_error "Failed to mount vault..."
return 1
fi
PUBLIC_VAULT_MOUNT="$VAULT_MOUNTDIR/vault-public"
[[ "$CRYPTSANE_MODE" = "private" ]] && SECRET_VAULT_MOUNT="$VAULT_MOUNTDIR/vault-secret"
VAULT_DEVICE="$selected_vault_device"
log_info "Vault device $VAULT_DEVICE mounted to $VAULT_MOUNTDIR."
}
function __umount_secret_vault {
local detected_sec_mounts
detected_sec_mounts=$(lsblk -r -n -o "mountpoint" | grep vault-secret | cut -d" " -f2)
[[ -n "$detected_sec_mounts" ]] || return 0
log_info "Unmounting secret vault ($detected_sec_mounts)..."
{
for mountpoint in $detected_sec_mounts; do
umount "$mountpoint" || return 1
done
cryptsetup luksClose vault-secret || return 1
SECRET_VAULT_MOUNT=""
} &>> "$LOGFILE"
log_info "Unmounted secret vault ($detected_sec_mounts)"
}
function __umount_public_vault {
local use_sudo="" detected_pub_mounts
detected_pub_mounts=$(lsblk -r -n -o "mountpoint" | grep vault-public | cut -d" " -f2)
[[ -n "$detected_pub_mounts" ]] || return 0
log_info "Unmounting public vault ($detected_pub_mounts)..."
if [[ "$CRYPTSANE_MODE" = "user" && $EUID -ne 0 ]]; then
log_info "Sudo is required to unmount public vault..."
sudo -v
use_sudo="sudo"
fi
{
for mountpoint in $detected_pub_mounts; do
$use_sudo umount "$mountpoint" || return 1
done
} &>> "$LOGFILE"
log_info "Unmounted public vault ($detected_pub_mounts)"
}
function umount_vault {
__umount_public_vault || return 1
if [[ "$CRYPTSANE_MODE" == "private" ]]; then
__umount_secret_vault || return 1
fi
}
function create_vault {
# Create vault from the selected block device
#vault is a usb flashdisk with two partitions: 1. Luks encrypted 2. unencrypted
#the 1st partition is used for exporting private kays
#the 2nd for public key (and potentialy other public-ish stuff like e.g. gpg.conf)
local usb_block_devices selected_block_device device_info vault_pass confirm_message
umount_vault
usb_block_devices=$(lsblk -r -d -n -o "path,subsystems" | awk '/scsi:usb/ {print $1}')
GUM_CHOOSE_HEADER="Choose block device:"
selected_block_device=$(gum choose $usb_block_devices)
device_info=$(lsblk -r -d -n -o "path,size" | grep "$selected_block_device")
vault_pass=$(ask_secret "Create vault password")
confirm_message="Make $device_info a vault? This will wipe the device."
if gum confirm --default "$confirm_message"; then
log_info "creating vault from $selected_block_device block device"
gum spin --title "Repartitioning..." \
-- bash -c "__repartition_vault_device $selected_block_device" \
|| return 1
gum spin --title "Preparing vault-secret partition..." \
-- bash -c "__prepare_vault_secret_partition $selected_block_device $vault_pass" \
|| return 1
gum spin --title "Preparing vault-public partition..." \
-- bash -c "__prepare_vault_public_partition $selected_block_device" \
|| return 1
log_info "Vault created on $selected_block_device"
show_vault_info
fi
}
function save_identity_to_vault {
# Sync keys to the vault
# This exports the secret keys to the vault
# and also exports the public key to the public vault
local cert_pass keyid pubkey_output
check_identity || return 1
check_vault_mounted || return 1
log_info "Saving PGP identity to vault..."
cert_pass=$(ask_secret_once "Cert password")
keyid=$(gpg -k --with-colons "$PRIMARY_UID" | awk -F: '/^pub:/ { print $5; exit }')
{
echo "$cert_pass" | gpg --output "$SECRET_VAULT_MOUNT/$keyid-Certify.key" \
--batch --pinentry-mode=loopback --passphrase-fd 0 \
--armor --export-secret-keys "$keyid" \
|| return 1
echo "$cert_pass" | gpg --output "$SECRET_VAULT_MOUNT/$keyid-Subkeys.key" \
--batch --pinentry-mode=loopback --passphrase-fd 0 \
--armor --export-secret-subkeys "$keyid" \
|| return 1
pubkey_output="$PUBLIC_VAULT_MOUNT/$keyid-$(date +%F).asc"
gpg --output "$pubkey_output" --armor --export "$keyid" \
|| return 1
# Add read rights to everybody for the vault exported public key
chmod o+r "$pubkey_output"
} &>> "$LOGFILE"
log_info "PGP Identity saved to vault"
}
function reset_yk_openpgp {
# Reset all OpenPGP information on YubiKey (keys, pins...)
local confirm_message
check_yubikey || return 1
confirm_message="This action will wipe all OpenPGP data on your YubiKey, and set all PINs to their default values. Continue?"
if gum confirm --default "$confirm_message"; then
{
ykman openpgp reset --force \
|| return 1
ykman openpgp access set-retries 5 5 5 -f -a $YK_DEFAULT_ADMIN_PIN \
|| return 1
} &>> "$LOGFILE"
fi
log_info "YubiKey OpenPGP reset"
}
function enable_kdf {
check_yubikey_access || return 1
if ! gpg --card-status | grep "KDF setting"; then
log_error "KDF is not supported by this YubiKey version."
return 1
fi
local confirm_message commands
confirm_message="Is YubiKey OpenPGP reset to factory defaults?"
if gum confirm --default "$confirm_message"; then
{
commands="admin\nkdf-setup\n$YK_DEFAULT_ADMIN_PIN\nquit\n"
echo "$commands" | gpg --batch --command-fd=0 \
--pinentry-mode=loopback --edit-card \
|| return 1
} &>> "$LOGFILE"
else
log_error "KDF can be only enabled on a factory reset YubiKey."
return 1
fi
}
function configure_yk_touch {
# Require touch for YubiKey OpenPGP Operations
GUM_CHOOSE_HEADER="Choose touch option:"
options=( \
"No touch required:off" \
"Touch required:on" \
"Touch required, can't be disabled without deleting the private key:fixed" \
"Touch required, cached for 15s after use:cached" \
"Touch required, cached for 15s after use, can't be disabled without deleting the private key:cached-fixed" \
)
selected_op=$(gum choose --ordered --label-delimiter=":" "${options[@]}")
log_info "Configuring encryption key touch..."
ykman openpgp keys set-touch dec "$selected_op" \
|| return 1
log_info "Configuring signature key touch..."
ykman openpgp keys set-touch sig "$selected_op" \
|| return 1
log_info "Configuring authentication key touch..."
ykman openpgp keys set-touch aut "$selected_op" \
|| return 1
log_info "Touch for YubiKey OpenPGP operations configured."
}
function change_yk_admin_pin {
local admin_pin new_admin_pin
check_yubikey || return 1
admin_pin="$YK_DEFAULT_ADMIN_PIN"
gum confirm --default "Has default admin PIN?" \
|| admin_pin=$(ask_secret_once "Old admin PIN")
new_admin_pin=$(ask_secret "New admin PIN")
ykman openpgp access change-admin-pin -a "$admin_pin" -n "$new_admin_pin" \
|| return 1
}
function change_yk_user_pin {
# Change YubiKey user PIN
local user_pin new_user_pin
check_yubikey || return 1
user_pin="$YK_DEFAULT_USER_PIN"
gum confirm --default "Has default user PIN?" \
|| user_pin=$(ask_secret_once "Old user PIN")
new_user_pin=$(ask_secret "New User PIN")
ykman openpgp access change-pin -P "$user_pin" -n "$new_user_pin" \
|| return 1
}
#function set_smartcard_attributes {
#local cardholder_fn cardholder_sn login admin_pin
#cardholder_fn=$(gum input --prompt "Cardholder firstname: ")
#cardholder_sn=$(gum input --prompt "Cardholder surname: ")
#login=$(gum input --prompt "Login: ")
#admin_pin=$(ask_secret_once "YubiKey Admin PIN")
## Set cardholder name
#{
#commands="admin\nname\n$cardholder_sn\n$cardholder_fn\n$admin_pin\nquit"
#echo -e "$commands" | gpg --batch --command-fd=0 --pinentry-mode=loopback \
#--edit-card || return 1
## Set login
#commands="admin\nlogin\n$login\n$admin_pin\nquit"
#echo -e "$commands" | gpg --batch --command-fd=0 --pinentry-mode=loopback \
#--edit-card || return 1
#} &>> "$LOGFILE"
#}
function __set_card_login {
# Set $PRIMARY_UID as smartcard login attribute
# This is done to prevent the following issue:
# https://github.com/drduh/YubiKey-Guide/issues/461
# This is a helper function for transfer_subkeys_to_card operation
local admin_pin=$1
commands="admin\nlogin\n$PRIMARY_UID\n$admin_pin\nquit"
{
log_info "Setting card login to $PRIMARY_UID..."
echo -e "$commands" | gpg --batch --command-fd=0 \
--pinentry-mode=loopback --edit-card \
|| return 1
} &>> "$LOGFILE"
}
function __should_overwrite_slot {
# When a card slot is not empty, the user is asked if they want to overwrite it
# and needs to confirm by typing 'y' and pressing enter.
# This is a helper function for transfer_subkeys_to_card operation
local fpr_column slot_num
slot_num=$1
((fpr_column=slot_num+1))
slot_fpr=$(gpg --with-colons --card-status \
| awk -F: "/^fpr:/ { print \$$fpr_column; }")
output=""
[[ -n "$slot_fpr" ]] && output="y\n"
echo "$output"
}
function transfer_subkeys_to_card {
local admin_pin cert_pass confirm_message commands sig_id enc_id aut_id
if ! (check_yubikey && check_yubikey_access); then
log_error "Yubikey not detected or not accessible..."
return 1
fi
confirm_message="This action will wipe out keys present on the card. Continue?"
if gum confirm --default "$confirm_message"; then
admin_pin=$(ask_secret_once "YubiKey Admin PIN")
cert_pass=$(ask_secret_once "Cert pass")
# See https://github.com/drduh/YubiKey-Guide/issues/461
__set_card_login "$admin_pin" || return 1
# Find key ids of current active subkeys
# When there are multiple revoked subkeys within this PGP Identity
# the key ids of currently active may be different (than 1, 2, 3)
subkeys=$(gpg --list-secret-keys --with-colon "$PRIMARY_UID" | grep "ssb" | nl)
sig_id=$(echo "$subkeys" | grep "ssb:u:.*::s::" | cut -f1)
enc_id=$(echo "$subkeys" | grep "ssb:u:.*::e::" | cut -f1)
aut_id=$(echo "$subkeys" | grep "ssb:u:.*::a::" | cut -f1)
log_info "Transferring subkeys to card..."
{
# Transfer signature key (1)
confirm=$(__should_overwrite_slot 1)
commands="key $sig_id\nkeytocard\n1\n${confirm}$cert_pass\n$admin_pin\nsave"
echo -e "$commands" | gpg --batch --yes --command-fd=0 \
--pinentry-mode=loopback --edit-key "$PRIMARY_UID" \
|| return 1
# Transfer encryption key (2)
confirm=$(__should_overwrite_slot 2)
commands="key $enc_id\nkeytocard\n2\n${confirm}$cert_pass\n$admin_pin\nsave"
echo -e "$commands" | gpg --batch --yes --command-fd=0 \
--pinentry-mode=loopback --edit-key "$PRIMARY_UID" \
|| return 1
# Transfer authentication key (3)
confirm=$(__should_overwrite_slot 3)
commands="key $aut_id\nkeytocard\n3\n${confirm}$cert_pass\n$admin_pin\nsave"
echo -e "$commands" | gpg --batch --yes --command-fd=0 \
--pinentry-mode=loopback --edit-key "$PRIMARY_UID" \
|| return 1
} &>> "$LOGFILE"
#show_identity
#message="Subkeys transferred to card. The '>' (ssb>) symbol indicates the key is on the card. Don't forget to sync the public key to the vault."
#log_info "$message"
log_info "Subkeys transferred to card."
fi
}
function parse_gpg_identity {
# Parse gpg -K output (primary uid, additional uids, keypair id, subkeys)
# Parsed information is then used for the info header.
local sig_ssb_id="" sig_app_id="" sig_card_sn="" sig="" \
enc_ssb_id="" enc_app_id="" enc_card_sn="" enc="" \
aut_ssb_id="" aut_app_id="" aut_card_sn="" aut="" \
gpg_identity=""
{
OTHER_UIDS=""
KEYID=""
if [[ -n $PRIMARY_UID ]]; then
gpg_identity="$(gpg -K --with-colons "$PRIMARY_UID")"
OTHER_UIDS="$(echo "$gpg_identity" \
| awk -F: '/^uid:/ { print $10 }' \
| tail -n +2 \
| awk '{ printf "\n - %s", $0 }' \
)"
KEYID="$(echo "$gpg_identity" \
| awk -F: '/^sec:u/ { print $5; exit }')"
sig_ssb_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:s:/ { print $5; exit }')"
sig_app_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:s:/ { print $15; exit }')"
sig_card_sn="${sig_app_id:20:8}"
enc_ssb_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:e:/ { print $5; exit }')"
enc_app_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:e:/ { print $15; exit }')"
enc_card_sn="${enc_app_id:20:8}"
aut_ssb_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:a:/ { print $5; exit }')"
aut_app_id="$(echo "$gpg_identity" \
| awk -F: '/^ssb:u:.*:a:/ { print $15; exit }')"
aut_card_sn="${aut_app_id:20:8}"
fi
sig="${sig_ssb_id:-None} (Card: ${sig_card_sn:-None})"
enc="${enc_ssb_id:-None} (Card: ${enc_card_sn:-None})"
aut="${aut_ssb_id:-None} (Card: ${aut_card_sn:-None})"
SUBKEYS="
sig: $sig
enc: $enc
aut: $aut
"
} &>> "$LOGFILE"
}
function add_uid {
# Add uid to an existing OpenPGP Identity
check_identity || return 1
local new_uid cert_pass
new_uid=$(gum input --prompt "Add UID (fullname <email>): ")
cert_pass=$(ask_secret_once "Cert password")
{
echo "$cert_pass" | gpg --batch --passphrase-fd 0 \
--pinentry-mode=loopback --quick-add-uid "$PRIMARY_UID" "$new_uid" \
|| return 1
} &>> "$LOGFILE"
log_info "New UID ($new_uid) added to the PGP Identity."
}
function generate_identity {
# Generate OpenPGP identity
# i.e. one master key, pubkey and three subkeys for signing,
# encryption and authentication.
local keyfp cert_pass subkey_type primary_uid
primary_uid=$(gum input --prompt "User identity (fullname <email>): ")
cert_pass=$(ask_secret "Create cert password")
log_info "Generating PGP identity for $primary_uid..."
{
echo "$cert_pass" | gpg --batch --passphrase-fd 0 \
--quick-generate-key "$primary_uid" "$KEY_TYPE" cert never \
|| return 1
keyfp=$(gpg -k --with-colons "$primary_uid" | awk -F: '/^fpr:/ { print $10; exit }')
for subkey_type in sign encrypt auth ; do \
echo "$cert_pass" | gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--quick-add-key "$keyfp" "$KEY_TYPE" "$subkey_type" "$SUBKEY_EXPIRATION" \
|| return 1
done
commands="uid 1\nprimary\n$cert_pass\nsave\n"
echo -e "$commands" | gpg --batch --command-fd=0 \
--pinentry-mode=loopback --edit-key "$primary_uid"
} &>> "$LOGFILE"
PRIMARY_UID="$primary_uid"
log_info "PGP identity generated."
}
function change_identity {
# Forget current selected identity
check_identity || return 0
PRIMARY_UID=""
}
function select_identity {
# Select OpenPGP Identity (represented by a primary UID) from
# the list of available OpenPGP Identities in GNUPGHOME.
local primary_uids selected_uid
primary_uids=$(gpg --list-secret-keys --with-colon \
| awk -F: '/^sec:u:/ { print $5 }' \
| xargs -I {} sh -c 'gpg --list-secret-keys --with-colon {} | grep uid | head -n1 | cut -d: -f 10'
)
GUM_CHOOSE_HEADER="Choose identity:"
selected_uid=$(echo "$primary_uids" | gum choose)
if [[ -n "$selected_uid" ]]; then
PRIMARY_UID="$selected_uid"
log_info "Identity selected: $PRIMARY_UID"
else
log_error "No identity selected..."
return 1
fi
}
function revoke_subkeys {
# Revoke current active subkeys of the OpenPGP Identity
local reason cert_pass sig_id enc_id aut_id commands
reason=$(gum input --prompt "Give revocation reason: ")
cert_pass=$(ask_secret_once Cert pass)
# Find key ids of current active subkeys
subkeys=$(gpg --list-secret-keys --with-colon "$PRIMARY_UID" | grep "ssb" | nl)
sig_id=$(echo "$subkeys" | grep "ssb:u:.*::s::" | cut -f1)
enc_id=$(echo "$subkeys" | grep "ssb:u:.*::e::" | cut -f1)
aut_id=$(echo "$subkeys" | grep "ssb:u:.*::a::" | cut -f1)
log_info "Revoking subkeys: $sig_id (sig), $enc_id (enc), $aut_id (aut)..."
commands="key $sig_id\nkey $enc_id\nkey $aut_id\nrevkey\ny\n0\n$reason\n\ny\n$cert_pass\nsave\n"
{
echo -e "$commands" | gpg --batch --command-fd=0 --pinentry-mode=loopback \
--edit-key "$PRIMARY_UID" || return 1
} &>> "$LOGFILE"
show_identity
log_info "Subkeys revoked."
}
function generate_subkeys {
# Generate new subkeys (if they don't already exists) for the OpenPGP
# Identity
local cert_pass keyfpr subkey
# Find if there are any subkeys already
subkeys=$(gpg --list-secret-keys --with-colon "$PRIMARY_UID" | grep "ssb" | nl)
sig_id=$(echo "$subkeys" | grep "ssb:u:.*::s::" | cut -f1)
enc_id=$(echo "$subkeys" | grep "ssb:u:.*::e::" | cut -f1)
aut_id=$(echo "$subkeys" | grep "ssb:u:.*::a::" | cut -f1)
if [[ -n "$sig_id" || -n "$enc_id" || -n "$aut_id" ]]; then
log_error "Subkeys already exist... Revoke them before generating new ones."
return 1
fi
cert_pass=$(ask_secret_once Cert pass)
keyfpr=$(gpg -k --with-colons "$PRIMARY_UID" | awk -F: '/^fpr:/ { print $10; exit }')
log_info "Generating subkeys for $PRIMARY_UID..."
{
for subkey in sign encrypt auth ; do \
echo "$cert_pass" | gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--quick-add-key "$keyfpr" "$KEY_TYPE" "$subkey" "$SUBKEY_EXPIRATION" \
|| return 1
done
} &>> "$LOGFILE"
log_info "Subkeys generated."
}
function load_public_identity_from_vault {
# Import pubkey of an OpenPGP Identity from the mounted vault-public
# partition. Intended for user mode
check_vault_mounted || return 1
available_fprs=$(basename -a "$PUBLIC_VAULT_MOUNT/"*????-??-??.asc \
| cut -d"-" -f1 \
| sort -u
)
GUM_CHOOSE_HEADER="Choose fingerprint:"
selected_fpr=$(echo "$available_fprs" | gum choose)
pubkey=$(basename -a "${PUBLIC_VAULT_MOUNT}/"*"${selected_fpr}"*.asc | sort -r | head -n1)
{
gpg --import "$PUBLIC_VAULT_MOUNT/$pubkey" || return 1
PRIMARY_UID=$(gpg --with-colons --fingerprint "$selected_fpr" \
| grep '^uid' \
| awk -F: '{print $10}' \
| head -n1
)
log_info "Setting ultimate trust for $PRIMARY_UID..."
commands="trust\n5\ny\nsave\n"
echo -e "$commands" | gpg --batch --command-fd=0 \
--pinentry-mode=loopback --edit-key "$PRIMARY_UID" \
|| return 1
} &>> "$LOGFILE"
log_info "PGP Identity for $PRIMARY_UID loaded from vault."
show_identity
}
function load_secret_identity_from_vault {
# Import secret keys (cert, subkeys) from the mounted vault-secret partition
# and also import pubkey from the mounted vault-public partition.
local available_fprs cert subkeys pubkey selected_fpr commands
check_vault_mounted || return 1
available_fprs=$(basename -a "$SECRET_VAULT_MOUNT/"*Certify.key | cut -d"-" -f1)
GUM_CHOOSE_HEADER="Choose fingerprint:"
selected_fpr=$(gum choose $available_fprs)
cert=$(basename -a "${SECRET_VAULT_MOUNT}/"*"${selected_fpr}-Certify.key")
subkeys=$(basename -a "${SECRET_VAULT_MOUNT}/"*"${selected_fpr}-Subkeys.key")
# There may be multiple versions of the pubkey, take the latest one
pubkey=$(basename -a "${PUBLIC_VAULT_MOUNT}/"*"${selected_fpr}"*.asc | sort -r | head -n1)
if [[ -z $pubkey ]]; then
# TODO Check pubkey exists
log_info "Unable to detect pubkey for $selected_fpr..."
fi
cert_pass=$(ask_secret_once "Cert pass")
{
log_info "Importing cert key ($SECRET_VAULT_MOUNT/$cert)..."
echo "$cert_pass" | gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--import "$SECRET_VAULT_MOUNT/$cert"
log_info "Importing subkeys ($SECRET_VAULT_MOUNT/$subkeys)..."
echo "$cert_pass" | gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--import "$SECRET_VAULT_MOUNT/$subkeys"
log_info "Importing pubkey ($PUBLIC_VAULT_MOUNT/$pubkey)..."
gpg --import "$PUBLIC_VAULT_MOUNT/$pubkey"
# Set to ultimate trust
PRIMARY_UID=$(gpg --with-colons --fingerprint "$selected_fpr" \
| grep '^uid' \
| awk -F: '{print $10}' \
| head -n1
)
log_info "Setting ultimate trust for $PRIMARY_UID..."
commands="trust\n5\ny\nsave\n"
echo -e "$commands" | gpg --batch --command-fd=0 \
--pinentry-mode=loopback --edit-key "$PRIMARY_UID"
} &>> "$LOGFILE"
log_info "PGP Identity for $PRIMARY_UID loaded from vault."
show_identity
}
function edit_identity {
# Enter GPG repl for key editing
gpg --edit-key "$PRIMARY_UID"
}
function edit_card {
# Enter GPG repl for card editing
gpg --edit-card
}
function kill_gpg_agents {
# Kill running gpg agents
killall gpg-agent &>> /dev/null
}
function show_identity {
gpg -K "$PRIMARY_UID"
}
function show_card {
gpg --card-status
}
function encrypt_message {
local recipient message
GUM_CHOOSE_HEADER="Choose recipient:"
recipient=$(gpg --list-keys --with-colons \
| grep '^uid' \
| cut -d: -f10 \
| gum choose \
)
message=$(gum write --placeholder "Type your secret message...")
if gum confirm --default "Save to file?"; then
echo "$message" | gpg --encrypt --armor \
--recipient "$recipient" > "/tmp/message.$(date +%s).enc" \
|| return 1
log_info "Encrypted message saved to /tmp/message.$(date +%s).enc"
else
echo "$message" | gpg --encrypt --armor \
--recipient "$recipient" | less \
|| return 1
log_info "Message encrypted and displayed"
fi
}
function encrypt_file {
local recipient file file_basename output
GUM_CHOOSE_HEADER="Choose recipient:"
recipient=$(gpg --list-keys --with-colons | grep '^uid' | cut -d: -f10 | gum choose)
GUM_FILE_HEADER="Choose file to encrypt"
file=$(gum file -a --height=10 "$HOME")
file_basename=$(basename "$file")
output="/tmp/${file_basename}".$(date +%s).enc
gpg --armor --recipient "$recipient" --output "$output" --encrypt "$file" \
|| return 1
log_info "Encrypted $file saved to $output"
}
function decrypt_message {
if gum confirm --default "Read from file?"; then
GUM_FILE_HEADER="Choose file containing encrypted message"
file=$(gum file -a --height=10 ~)
gpg --decrypt "$file" | less \
|| return 1
log_info "Message from $file decrypted and displayed."
else
gum write --char-limit 0 --placeholder "Paste your encrypted message..." \
| gpg --decrypt | less \
|| return 1
log_info "Message decrypted and displayed."
fi
}
function decrypt_file {
local file file_basename
GUM_FILE_HEADER="Choose file to decrypt"