Repository navigation
Expand file tree
/
Copy pathsdm-cryptconfig
More file actions
executable file
·1169 lines (1043 loc) · 37.3 KB
/
Copy pathsdm-cryptconfig
File metadata and controls
executable file
·1169 lines (1043 loc) · 37.3 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
#!/bin/bash
# Guide: https://rr-developer.github.io/LUKS-on-Raspberry-Pi/ plus others
#
# This script can be run two different ways:
# * Automatically by sdm on the booted system as invoked by the cryptroot plugin via the sdm-auto-encrypt service
# * Manually on the booted system
#
function loadparams() {
local arg="$1"
source $SDMPT/etc/sdm/sdm-readparams $arg
}
function errexit() {
cryptolog "$1" noconsole
#echo -e "$1"
exit 1
}
function thisdate() {
echo "$(date +"$datefmt")"
}
function wait_startup_complete {
# $1 is the message to write
local lc=0 msg=$1
while [[ "$(systemctl show -p ActiveState graphical.target --value)" != "active" ]] && [[ "$(systemctl show -p ActiveState multi-user.target --value)" != "active" ]]
do
if [ $lc -eq 0 ]
then
logger "$msg"
echo "$msg" > /dev/console
lc=1
fi
sleep 1
done
}
function getgbstr() {
#
# $1: # of bytes in partition
#
# Returns the string "(nn.nnGB, mm.mmGiB)"
local nbytes=$1
local gb=1000000000 gib=1073741824 gb2=500000000 gi2=536870912
local ngbytes ngibytes
ngbytes=$(printf %.1f "$(( ((10 * nbytes)+gb2) / gb ))e-1")
ngibytes=$(printf %.1f "$(( ((10 * nbytes)+gi2) / gib))e-1")
echo "(${ngbytes}GB, ${ngibytes}GiB)"
return
}
function getfsdf() {
#
# $1: fs name
# $2: df component: pcent, avail, etc
#
echo "$(df --output=$2 $1 | tail -1 | (IFS="%" ; read a ; a="${a% }" ; a="${a# }" echo $a))"
}
function ispdevp() {
local dev="$1"
[[ "$dev" =~ "mmcblk" ]] || [[ "$dev" =~ "nvme0n1" ]] && return 0 || return 1
}
function getspname() {
local dev="$1" pn="$2"
ispdevp $dev && echo "${dev}p${pn}" || echo "${dev}${pn}"
}
function getpartname() {
local dev="$1" pn="$2"
ispdevp $dev && echo "p${pn}" || echo "$pn"
}
function cryptolog() {
local msg="$1" opts="$2" datefmt="%Y-%m-%d %H:%M:%S" pfx="sdm-cryptconfig:" msgc msgt
[[ "$msg" =~ "sdm-cryptconfig:" ]] && msgc="$msg" || msgc="$pfx $msg"
if [ $xsdm -eq 1 ]
then
[[ "$opts" =~ "noconsole" ]] || echo "$msgc" > /dev/console
else
if [ "$msg" == "" ]
then
echo "$msg" > /dev/tty
else
# don't prefix with ">" if msg starts with "?"
[ "$msg" == "${msg#?}" ] && msgt="> $msg" || msgt="$msg"
echo "$msgt" > /dev/tty
fi
fi
[[ "$opts" =~ "nojournal" ]] || logger "$msgc"
[ -f /etc/sdm/history ] && echo "$(thisdate) $msgc" >> /etc/sdm/history
}
function checknumeric() {
#
# Exit with error if $1 is not numeric
#
[[ "$1" = *[^0-9]* ]] && errexit "? Value '$1' for command switch '$2' is not numeric"
return
}
function iswifienabled() {
# Look for any wireless interface (wlan*, wlp*, etc)
for iface in /sys/class/net/w*
do
[ -d $iface/wireless ] && return 0
done
return 1
}
function askyn() {
local ans
echo -n "$1" '[y/n]? ' ; read $2 ans
case "$ans" in
y*|Y*) return 0 ;;
*) return 1 ;;
esac
}
function ispkginstalled() {
#
# $1 has package name
#
iver=$(apt-cache policy $1 | grep Installed: 2> /dev/null)
if [ "$iver" == "" ]
then
return 1
else
[[ "$iver" =~ "(none)" ]] && return 1 || return 0
fi
return
}
function installpkgsif() {
local pkglist="$1" pkgs=() newpkgs="" p
IFS=" " read -a pkgs <<< $pkglist
for p in "${pkgs[@]}"
do
ispkginstalled $p && cryptolog " Package '$p' is already installed" noconsole || newpkgs="$newpkgs $p"
done
[ "$newpkgs" == "" ] || apt-get install --no-install-recommends --yes $newpkgs
}
function getphrase() {
local pprompt="$1"
local phrase phrase2 silent="-s" #silent=""
while [ true ]
do
while [ true ]
do
read $silent -p "${pprompt}: " phrase
[ "$silent" != "" ] && echo "" >/dev/tty
[ "phrase" == "" ] || break
done
while [ true ]
do
read $silent -p "Retype ${pprompt}: " phrase2
[ "$silent" != "" ] && echo "" >/dev/tty
[ "$phrase2" == "" ] || break
done
[ "$phrase" == "$phrase2" ] && break
echo "% Phrases do not match; try again" >/dev/tty
done
echo "$phrase"
}
function printhelp() {
echo $"
sdm-cryptconfig has several command line switches, all of which are optional
> Unlock via SSH configuration
* --authorized-keys keyfile -- Provides SSH authorized_keys file for the initramfs. Required with --ssh
* --dns dnsaddr -- Set IP Address of DNS server
* --gateway gatewayaddr -- Set IP address of gateway
* --hostname hostname -- Set hostname
* --ipaddr ipaddr -- set IP address to use in initramfs
* --mask netmask -- Set network mask for initramfs
* --ssh -- Enable SSH in initramfs. Requires --authorized-keys
* --sshbash -- Leave ssh session bash enabled [Default: use cryptroot-unlock]
* --sshport port -- Specify initramfs SSH port [Default: 22]
* --sshtimeout timeout -- Specify initramfs SSH timeout [Default: 3600]
* --unique-ssh -- Use a different SSH host key in initramfs than the host OS SSH key
* --wifi-password -- Specify WiFi password for the WiFi connection
* --wifi-ssid -- Enable WiFi in initramfs and specify the WiFi SSID for connection
Requires --ssh, --authorized-keys, and --wifi-password
* --wifi-use-psk -- Convert WiFi password to a WPA PSK in wpa_supplicant.conf
> Encryption feature configuration
* --auto-encrypt devname -- Perform initramfs encryption automatically (non-stop) and use devname as scratch disk
* --crypto cryptalgo -- Specify crypto algorithm (aes [D]) or xchacha|xchacha12|xchacha20 (use on Pi4 and earlier)
* --keyfile keyfile -- Key file for USB-based key unlock. Create keydisk with sdm-make-luks-key. Required with --nopwd
* --mapper cryptmapname -- Set cryptroot mapper name [Default: cryptroot]
* --nbde-server http://<nbdeserver>:port -- Use Network Based Disk Encryption
* --no-expand-root -- Don't expand rootfs after rootfs encryption has completed
* --no-last-reboot -- Don't do final reboot after sdm-cryptfs-cleanup
* --nopwd -- No password on encrypted rootfs; keyfile (required) is only unlock
* --quiet -- Do not disable quiet boot for RasPiOS with desktop
* --reboot -- Reboot the system (into initramfs) when sdm-cryptconfig is complete
* --sdm -- sdm cryptroot plugin sets this
* --tries n -- Specify number of unlock tries before giving up [Default: 0 (infinite)]
The network configuration switches (dns, gateway, hostname, ipaddr, and mask) are only needed
and should only be used if you know that the system is unable to get an IP address and network
configuration information from the network (e.g., via DHCP). These settings are ONLY used in the
initramfs if SSH is enabled and are not automatically removed, so each time the system restarts
the initramfs will use these settings.
"
}
function printinfo() {
local used1k usedby usedstr rootfs sd
rootfs=$(findmnt --noheadings --output source /) # rootfs name
sd=${rootfs%$(getpartname $rootfs 2)} # dev name w/o partition name
used1k=$(getfsdf "/" used)
usedby=$((used1k*1024))
usedstr=$(getgbstr $usedby)
cryptolog "" noconsole
cryptolog "Rootfs '$rootfs' has $usedby bytes $usedstr used" noconsole
cryptolog "" noconsole
cryptolog "You will need another disk for the encryption process to use as a scratch disk" noconsole
cryptolog " This disk must be larger than $usedstr and it will be over-written" noconsole
cryptolog "" noconsole
cryptolog $"Reboot the system when you are ready to continue
The system will start to reboot, but hang trying to read rootfs. It will try 30 times
before giving up and dropping to the initramfs prompt: (initramfs)
** Ignore the 'ALERT! missing /dev/mapper' message. That is expected. **
Once at the (initramfs) prompt, connect the SSD or SD Card that will be used as a scratch drive
When you have the drive name enter the command:
(initramfs) sdmcryptfs $sd /dev/sdX
Where:
$sd is the name of your system disk
/dev/sdX is the name of your scratch disk
sdmcryptfs will:
* Print the size of rootfs $rootfs
* Save the contents of $rootfs to /dev/sdX
* NOTE: There will be no prompts for passphrases if --nopwd specified
* Enable encryption on $rootfs
* You will be prompted to enter YES (all in upper case) to continue
* You will then be prompted to provide the passphrase for $rootfs (unless --nopwd)
** Be sure that your CapsLock is set correctly (in case you changed it to type YES)!!! **
* After a short pause you'll be prompted for the passphrase again to unlock $rootfs (unless --nopwd)
* The saved rootfs content will be restored from /dev/sdX to the encrypted rootfs
* When the restore finishes sdmcryptfs will exit and drop you to the (initramfs) prompt
* Type 'exit' to continue the boot sequence
* Once the system boots the sdm-cryptfs-cleanup service will run which:
* Removes some one-time content and rebuilds initramfs
* Reboots the system one last time
" noconsole
if [ $xnopwd -eq 0 ]
then
cryptolog $"As the system reboots you'll once again be prompted for the rootfs passphrase (Without the 30 tries)
** The system will now ask for the rootfs passphrase like this every time the system boots **
" noconsole
else
cryptolog $"As the system reboots it will hang until the USB keyfile disk is found in a USB drive
" noconsole
fi
if [ $xssh -eq 1 ]
then
cryptolog $"
NOTE: You have configured SSH
Please review https://github.com/gitbls/sdm/blob/master/Docs/Disk-Encryption.md
" noconsole
fi
}
function wifimakewpa() {
local pwd="$1" hashed=$2 psks
cryptolog "Create wpa_supplicant config for WiFi in initramfs" noconsole
mkdir -p /etc/wpa_supplicant
[ "$hashed" == "" ] && psks="psk\"$pwd\"" || psks="psk=$pwd"
cat > /etc/wpa_supplicant/wpa_supplicant-luks.conf << EOF
ctrl_interface=/run/wpa_supplicant
update_config=1
network={
ssid="$xwifissid"
$psks
scan_ssid=1
}
EOF
chmod 600 /etc/wpa_supplicant/wpa_supplicant-luks.conf
}
function wificonfiginitramfs() {
cryptolog "Create WiFi initramfs hook /etc/initramfs-tools/hooks/sdm-enable-wifi" noconsole
cat > /etc/initramfs-tools/hooks/sdm-enable-wifi << 'EOF'
#!/bin/sh
set -e
PREREQ=""
prereqs() {
echo "${PREREQ}"
}
case "${1}" in
prereqs)
prereqs
exit 0
;;
esac
. /usr/share/initramfs-tools/hook-functions
# Add the wireless modules
manual_add_modules brcmfmac
manual_add_modules brcmfmac-wcc
# Copy wpa_supplicant binaries
copy_exec /sbin/wpa_supplicant
copy_exec /sbin/wpa_cli
# Copy rfkill to unblock WiFi radio
copy_exec /usr/sbin/rfkill
# Copy wpa_supplicant config
mkdir -p ${DESTDIR}/etc/wpa_supplicant
cp /etc/wpa_supplicant/wpa_supplicant-luks.conf ${DESTDIR}/etc/wpa_supplicant/wpa_supplicant.conf
# Copy Broadcom firmware (copy actual files, not symlinks)
mkdir -p ${DESTDIR}/usr/lib/firmware/brcm
mkdir -p ${DESTDIR}/usr/lib/firmware/cypress
# Copy the actual cyfmac files
cp /lib/firmware/cypress/cyfmac43455-sdio-standard.bin ${DESTDIR}/usr/lib/firmware/cypress/cyfmac43455-sdio.bin
cp /lib/firmware/cypress/cyfmac43455-sdio.clm_blob ${DESTDIR}/usr/lib/firmware/cypress/
# Copy all the brcm files, following symlinks to get actual content
cd /lib/firmware/brcm
for file in *43455*; do
if [ -e "$file" ]; then
cp -L "$file" ${DESTDIR}/usr/lib/firmware/brcm/ 2>/dev/null || true
fi
done
# Copy regulatory database (follow symlinks to get actual files)
cp -L /lib/firmware/regulatory.db ${DESTDIR}/usr/lib/firmware/regulatory.db 2>/dev/null || \
cp /lib/firmware/regulatory.db-debian ${DESTDIR}/usr/lib/firmware/regulatory.db
cp -L /lib/firmware/regulatory.db.p7s ${DESTDIR}/usr/lib/firmware/regulatory.db.p7s 2>/dev/null || \
cp /lib/firmware/regulatory.db.p7s-debian ${DESTDIR}/usr/lib/firmware/regulatory.db.p7s
EOF
chmod 755 /etc/initramfs-tools/hooks/sdm-enable-wifi
# Create init-premount script
cryptolog "Create WiFi initramfs init-premount script /etc/initramfs-tools/scripts/init-premount/sdm-premount-enable-wifi" noconsole
cat > /etc/initramfs-tools/scripts/init-premount/sdm-premount-enable-wifi << 'EOF'
#!/bin/sh
PREREQ=""
prereqs()
{
echo "$PREREQ"
}
case $1 in
prereqs)
prereqs
exit 0
;;
esac
. /scripts/functions
# Load the wireless module explicitly
log_begin_msg "Loading brcmfmac module"
modprobe brcmfmac
log_end_msg
# Wait for wireless interface to appear (with timeout)
log_begin_msg "Waiting for wireless interface"
TIMEOUT=10
COUNTER=0
WLAN_INTERFACE=""
while [ $COUNTER -lt $TIMEOUT ]; do
# Look for any wireless interface (wlan*, wlp*, etc)
for iface in /sys/class/net/w*; do
if [ -d "$iface/wireless" ]; then
WLAN_INTERFACE=$(basename "$iface")
break 2
fi
done
# Also check specifically for wlan0
if [ -d "/sys/class/net/wlan0" ]; then
WLAN_INTERFACE="wlan0"
break
fi
sleep 1
COUNTER=$((COUNTER + 1))
done
log_end_msg
if [ -z "$WLAN_INTERFACE" ]; then
log_failure_msg "No wireless interface found after ${TIMEOUT} seconds"
# Don't panic - allow boot to continue (ethernet might work)
exit 0
fi
log_success_msg "Found wireless interface: ${WLAN_INTERFACE}"
# Unblock WiFi radio (RF-kill)
log_begin_msg "Unblocking WiFi radio"
rfkill unblock wifi 2>/dev/null || true
rfkill unblock all 2>/dev/null || true
log_end_msg
# Bring interface up
log_begin_msg "Bring up ${WLAN_INTERFACE}"
ip link set ${WLAN_INTERFACE} up
sleep 2
log_end_msg
# Start wpa_supplicant
log_begin_msg "Starting wpa_supplicant on ${WLAN_INTERFACE}"
mkdir -p /run/wpa_supplicant
/sbin/wpa_supplicant -i${WLAN_INTERFACE} -c/etc/wpa_supplicant/wpa_supplicant.conf -P/run/initram-wpa_supplicant.pid -B -f /tmp/wpa_supplicant.log -C/run/wpa_supplicant
sleep 3
log_end_msg
# Wait for connection (with timeout)
log_begin_msg "Waiting for WiFi association"
TIMEOUT=30
COUNTER=0
CONNECTED=0
while [ $COUNTER -lt $TIMEOUT ]; do
if /sbin/wpa_cli -p/run/wpa_supplicant status 2>/dev/null | grep -q "wpa_state=COMPLETED"; then
CONNECTED=1
break
fi
sleep 1
COUNTER=$((COUNTER + 1))
done
if [ $CONNECTED -eq 1 ]; then
log_success_msg "WiFi connected"
# Configure IP address
log_begin_msg "Configuring IP address via DHCP"
ipconfig -t 10 ${WLAN_INTERFACE}
log_end_msg
else
log_failure_msg "WiFi connection failed after ${TIMEOUT} seconds"
fi
exit 0
EOF
chmod 755 /etc/initramfs-tools/scripts/init-premount/sdm-premount-enable-wifi
# Create local-bottom script to kill wpa_supplicant
cryptolog "Create WiFi initramfs local-bottom cleanup script /etc/initramfs-tools/scripts/local-bottom/sdm-kill-wireless" noconsole
cat > /etc/initramfs-tools/scripts/local-bottom/sdm-kill-wireless << 'EOF'
#!/bin/sh
PREREQ=""
prereqs()
{
echo "$PREREQ"
}
case $1 in
prereqs)
prereqs
exit 0
;;
esac
echo "Killing wpa_supplicant so the system takes over later."
if [ -f /run/initram-wpa_supplicant.pid ]; then
kill $(cat /run/initram-wpa_supplicant.pid) 2>/dev/null || true
fi
EOF
chmod 755 /etc/initramfs-tools/scripts/local-bottom/sdm-kill-wireless
}
function configcleanupsvc() {
#
# Set up service to run after next reboot that will rebuild initramfs (again) and reboot
#
cryptolog "Configure run-once service to cleanup and rebuild initramfs after rootfs encryption completes and boots" noconsole
cat > /etc/systemd/system/sdm-cryptfs-cleanup.service <<EOF
[Unit]
Description=sdm cryptroot cleanup service
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/local/bin/sdm-cryptfs-cleanup
StandardInput=tty
StandardOutput=journal+console
[Install]
WantedBy=multi-user.target
EOF
cryptolog "Create /usr/local/bin/sdm-cryptfs-cleanup script" noconsole
cat > /usr/local/bin/sdm-cryptfs-cleanup <<'EOF'
#!/bin/bash
function loadparams() {
local arg="$1"
source $SDMPT/etc/sdm/sdm-readparams $arg
}
function wait_startup_complete() {
# $1 is the message to write
local lc=0 msg=$1
while [[ "$(systemctl show -p ActiveState graphical.target --value)" != "active" ]] && [[ "$(systemctl show -p ActiveState multi-user.target --value)" != "active" ]]
do
if [ $lc -eq 0 ]
then
logger "$msg"
echo "$msg" > /dev/console
lc=1
fi
sleep 1
done
}
function thisdate() {
local datefmt="%Y-%m-%d %H:%M:%S"
echo "$(date +"$datefmt")"
}
function echolog() {
local msg="$1"
echo "$msg" >/dev/console
logger "$msg"
[ -f /etc/sdm/history ] && echo "$(thisdate) $msg" >> /etc/sdm/history
}
echolog "sdm-cryptfs-cleanup: Starting; System will restart automatically when completed"
echolog "sdm-cryptfs-cleanup: Clean up initramfs content"
mv /etc/initramfs-tools/hooks/luks-hooks /etc/initramfs-tools/hooks/.sdm.luks-hooks.old
# Leave bash in initramfs as required by sdmluksunlock
grep -v -E "sdmcryptfs|mapper|lz4|sgdisk|/etc/sdm/assets/cryptroot" /etc/initramfs-tools/hooks/.sdm.luks-hooks.old > /etc/initramfs-tools/hooks/luks-hooks
chmod 755 /etc/initramfs-tools/hooks/luks-hooks
grep -q -s xsshbash:0 /etc/sdmcryptctl && [ -f /etc/dropbear/initramfs/dropbear.conf ] && sed -i "s/bash/cryptroot-unlock/" /etc/dropbear/initramfs/dropbear.conf
rm -f /etc/initramfs-tools/scripts/local-top/sdm-autocrypt # Do this before update-initramfs
# Cleanup of lek files done later
echolog "sdm-cryptfs-cleanup: Rebuild initramfs"
update-initramfs -u
if grep -q -s xsdm:1 /etc/sdmcryptctl
then
[ -f /etc/sdm/sdm-readparams ] && loadparams || echolog "% sdm-cryptfs-cleanup: Unable to find expected /etc/sdm/sdm-readparams"
if [ -f /etc/sdm/assets/cryptbbh ]
then
echolog "sdm-cryptfs-cleanup: Enable delayed boot behavior '$(cat /etc/sdm/assets/cryptbbh)'"
cat /etc/sdm/assets/cryptbbh >| /etc/sdm/assets/gfxbbh
do_delayed_boot_behavior reboot
else
echolog "% sdm-cryptfs-cleanup: /etc/sdm/assets/cryptbbh not found; Boot behavior setting may not be correct"
fi
else
if grep -q -s graphical.target /etc/sdmcryptctl
then
echolog "sdm-cryptfs-cleanup: Reset systemctl default target to graphical.target"
systemctl set-default graphical.target
# Don't enable these services since no 'splash' in cmdline.txt (see below)
# if grep -q -s clsplash /etc/sdmcryptctl
# then
# for svc in plymouth-start plymouth-read-write plymouth-quit-wait # plymouth-reboot plymouth-quit
# do
# echolog "sdm-cryptfs-cleanup: Unmask service '$svc'"
# systemctl unmask $svc >/dev/null 2>&1
# done
# fi
fi
if grep -s -q xquiet:0 /etc/sdmcryptctl
then
if grep -q -s clquiet /etc/sdmcryptctl
then
echolog "sdm-cryptfs-cleanup: Reset 'quiet' in cmdline.txt"
sed -i "s/rootwait/rootwait quiet/g" /boot/firmware/cmdline.txt
fi
# 'splash' in cmdline.txt prevents booting after sdm-cryptfs-cleanup reboots (? because prompt to unlock disk is lost/hidden?)
# if grep -q -s clsplash /etc/sdmcryptctl
# then
# echolog "sdm-cryptfs-cleanup: Reset 'splash' in cmdline.txt"
# sed -i "s/rootwait/rootwait splash/g" /boot/firmware/cmdline.txt
# fi
fi
fi
wait_startup_complete "sdm-cryptfs-cleanup: Wait for system startup to complete"
#
# Configure NBDE if requested
#
if grep -q -s nbdeserver: /etc/sdmcryptctl
then
IFS=":" read zlabel zurl < <(grep nbdeserver: /etc/sdmcryptctl)
echolog "sdm-crytpfs-cleanup: Configure rootfs Network Bound Disk Encryption (NBDE) client"
IFS=":" read zlabel zmapper < <(grep mappername: /etc/sdmcryptctl)
IFS=$' \t' read junk partition therest < <(grep $zmapper /etc/crypttab)
zkeyfile=""
if grep -q -s keyfile: /etc/sdmcryptctl
then
IFS=":" read zlabel zkeyfile < <(grep keyfile: /etc/sdmcryptctl)
[ "$zkeyfile" == "" ] || zkeyfile=/etc/sdm/assets/cryptroot/$(basename $zkeyfile)
fi
if [ "$zkeyfile" == "" ]
then
luksupwd=$(systemd-ask-password "Enter LUKS unlock password for partition '$partition':")
printf "$luksupwd\n" | clevis luks bind -f -y -d $partition tang "{\"url\":\"$zurl\"}"
else
clevis luks bind -f -y -k $zkeyfile -d $partition tang "{\"url\":\"$zurl\"}"
fi
fi
#
# Done!
#
if grep -q -s re-enable-tty1 /etc/sdmcryptctl
then
echolog "sdm-cryptfs-cleanup: Re-enable getty@tty1"
systemctl -q enable getty@tty1
fi
systemctl disable sdm-cryptfs-cleanup
rm -f /etc/systemd/system/sdm-cryptfs-cleanup.service
rm -f /etc/systemd/system/sdm-auto-encrypt.service
systemctl daemon-reload
rm -f /etc/sdm/assets/cryptroot/*.lek /etc/*.lek
rm -f /etc/sdm/control/rootfs-encryption
if grep -q -s xnolastrb:0 /etc/sdmcryptctl
then
secs=5
echolog "sdm-cryptfs-cleanup: The system will restart in $secs seconds"
sleep $secs
echolog "sdm-cryptfs-cleanup: System restarting now"
#rm -f /usr/local/bin/sdm-cryptfs-cleanup
sleep 2
reboot
else
echolog "sdm-cryptfs-cleanup: Complete"
exit 0
fi
EOF
chmod 755 /usr/local/bin/sdm-cryptfs-cleanup
pgrep systemd >/dev/null 2>&1 && cryptolog " (Ignore any RequiresMountsFor errors in the system journal)" noconsole && systemctl daemon-reload
systemctl enable sdm-cryptfs-cleanup > /dev/null 2>&1
}
function parsecmd() {
local cmd="$1" args="$2"
local longopts="authorized-keys:,auto-encrypt:,crypto:,debug,dns:,gateway:,help,hostname:,ipaddr:,keyfile:,mapper:,mask:,nbde-server:,netmask:,no-expand-root,no-last-reboot,nopwd,ssh,sshbash,sshport:,sshtimeout:,reboot,sdm,tries:,unique-ssh,wifi-ssid:,wifi-password:,wifi-use-psk"
OARGS=$(getopt -o h --longoptions $longopts -n 'sdm' -- "$@")
[ $? -ne 0 ] && errexit "? $cmd: Unable to parse command"
eval set -- "$OARGS"
while true
do
case "${1,,}" in
# 'shift 2' if switch has argument, else just 'shift'
--authorized-keys) xauthkeys=$2 ; shift 2 ;;
--auto-encrypt) xautocrypt=$2 ; shift 2 ;;
--crypto) xcrypto=$2 ; shift 2 ;;
--debug) xdebug=1 ; shift 1 ;;
--dns) xdns=$2 ; shift 2 ;;
--gateway) xgateway=$2 ; shift 2 ;;
--hostname) xhostname=$2 ; shift 2 ;;
--ipaddr) xipaddr=$2 ; shift 2 ;;
--keyfile) xkeyfile=$2 ; shift 2 ;;
--mapper) xmapper=$2 ; shift 2 ;;
--mask|--netmask) xnetmask=$2 ; shift 2 ;;
--nbde-server) xnbdeserver=$2 ; shift 2 ;;
--no-expand-root) xnoexpand=1 ; shift 1 ;;
--no-last-reboot) xnolastrb=1 ; shift 1 ;;
--nopwd) xnopwd=1 ; shift 1 ;;
--quiet) xquiet=1 ; shift 1 ;;
--reboot) xreboot=1 ; shift 1 ;;
--ssh) xssh=1 ; shift 1 ;;
--sshbash) xsshbash=1 ; shift 1 ;;
--sshport) xsshport=$2 ; shift 2 ;;
--sshtimeout) xsshtimeout=$2 ; shift 2 ;;
--sdm) xsdm=1 ; shift 1 ;;
--tries) xtries=$2 ; shift 2 ;;
--unique-ssh) xunique=1 ; shift 1 ;;
--wifi-ssid) xwifissid="$2" ; shift 2 ;;
--wifi-password) xwifipwd="$2" ; shift 2 ;;
--wifi-use-psk) xwifipsk=1 ; shift 1 ;;
--) shift ; break ;;
-h|--help) printhelp ; shift ; exit ;;
*) errexit "? $0: Internal error" ;;
esac
done
if [ "$xauthkeys" != "" ]
then
! [ -f $xauthkeys ] && errexit "? --authorized-keys file '$xauthkeys' not found"
else
[ $xssh -eq 1 ] && errexit "? --ssh requires --authorized-keys"
fi
[[ $xnopwd -eq 1 ]] && [[ "$xkeyfile" == "" ]] && errexit "? --nopwd requires --keyfile"
if [ "$xautocrypt" != "" ]
then
[ $xnopwd -eq 0 ] && errexit "? --auto-encrypt requires --nopwd (and --keyfile)"
[ "$xkeyfile" == "" ] && errexit "? --autoencrypt requires --keyfile"
fi
[[ "$xtries" != "" ]] && checknumeric $xtries "--tries"
}
function doconfiginitramfs() {
local kcmd="" knopwd="" bootdisk
if [ "$xautocrypt" != "" ]
then
cryptolog "Configure initramfs for automatic encryption"
# Get boot disk devname /dev/xxx
bootdisk=$(findmnt / --noheadings --output source)
ispdevp $bootdisk && bootdisk=${bootdisk%p*} || bootdisk=${bootdisk%[0-9]}
printf "autosysdisk:$bootdisk\nautoscratch:$xautocrypt\n" >> /etc/sdmcryptctl
cat > /etc/initramfs-tools/scripts/local-top/sdm-autocrypt <<EOF
#!/bin/sh
PREREQ=""
prereqs() {
echo "\$PREREQ"
}
case "\$1" in
prereqs)
prereqs
exit 0
;;
esac
echo "Run SDM auto-encryption script"
sdmcryptfs $bootdisk $xuatoencrypt
EOF
chmod 755 /etc/initramfs-tools/scripts/local-top/sdm-autocrypt
fi
# These both need to be set on initramfs-tools 0.142+rpt1 and earlier. This assumes OK. Remove uncommented line for earlier initramfs-tools
cryptolog "Update initramfs configuration for 'MODULES=most' and 'update_initramfs=all'" noconsole
sed -i "s/^MODULES=dep/MODULES=most/" /etc/initramfs-tools/initramfs.conf
#* sed -i "s/^update_initramfs=yes/update_initramfs=all/" /etc/initramfs-tools/update-initramfs.conf
cryptolog "Create /usr/bin/sdmluksunlock; runs in initramfs to unlock rootfs" noconsole
cat > /usr/bin/sdmluksunlock <<'EOF'
#!/bin/bash
#
# called when it's time to read the LUKS unlock key, which is echoed to stdout/read by caller
#
function pmsg() {
echo "$1" >/dev/console
}
trydisks()
{
pmsg ""
pmsg "> sdmluksunlock: Looking for USB disk with luks Key file '${kfn}'"
pmsg ""
while :; do
sleep 1
while read usbpartition
do
usbdevice=$(readlink -f $usbpartition)
if mount $usbdevice /mnt 2>/dev/null
then
#pmsg "> Mounted disk $usbdevice"
if [ -e /mnt/$kfn ]
then
#pmsg "> Found Key file '$kfn'"
pmsg "> Unlocking rootfs"
cat /mnt/$kfn #cat to sdmluksunlock caller for unlock
umount $usbdevice >/dev/null 2>&1 || continue
#pmsg "> sdmluksunlock: Kill askpass; Ignore 'Killed' message"
aps=$(ps e | grep askpass | grep -v grep | awk '{print $1}')
[ "$aps" != "" ] && kill -KILL $aps >/dev/null 2>/dev/null
exit
else
#pmsg "% sdmluksunlock: Key '${kfn%.lek}' not found on this disk"
umount $usbdevice >/dev/null 2>&1 || continue
fi
else
#pmsg "% sdmluksunlock: This disk does not have a vfat partition"
umount $usbdevice >/dev/null 2>&1 || continue
fi
done < <(compgen -G "/dev/disk/by-id/usb-*-part1")
done
return 0
}
set -e
mkdir -p /mnt
if [ "$CRYPTTAB_KEY" != "" ]
then
kfn=$(basename $CRYPTTAB_KEY)
kfn=${kfn%.lek}.lek
fi
if [[ "$kfn" != "" ]]
then
if [[ "$2" == "trydisks" ]]
then
touch /tmp/ftrydisk
trydisks
exit
else
[ ! -f /tmp/ftrydisk ] && ( sdmluksunlock $CRYPTTAB_KEY trydisks </dev/null & )
fi
fi
pmsg ""
pmsg ""
/lib/cryptsetup/askpass "Insert USB Keyfile Disk or type passphrase then press ENTER:"
aps=$(ps e | grep trydisks | grep -v grep | awk '{print $1}')
[ "$aps" != "" ] && kill -KILL $aps >/dev/null 2>/dev/null
exit
EOF
chmod 755 /usr/bin/sdmluksunlock
cryptolog "Create /etc/initramfs-tools/hooks/luks-hooks" noconsole
[ "$xkeyfile" != "" ] && kcmd="copy_file text /etc/sdm/assets/cryptroot/$xkeyfile /etc/$xkeyfile"
# can't use quoted EOF here
cat > /etc/initramfs-tools/hooks/luks-hooks <<EOF
#!/bin/sh -e
PREREQS=""
case "\$1" in
prereqs) echo "\${PREREQS}"; exit 0;;
esac
. /usr/share/initramfs-tools/hook-functions
# Don't assume that sdmcryptfs-required pgms are in initramfs
copy_exec /usr/sbin/resize2fs /usr/sbin
copy_exec /usr/sbin/fdisk /usr/sbin
copy_exec /usr/sbin/parted /usr/sbin
copy_exec /usr/sbin/cryptsetup /usr/sbin
copy_exec /usr/bin/bash /usr/bin
copy_exec /usr/bin/dd /usr/bin
copy_exec /usr/bin/lsusb /usr/bin
copy_exec /usr/bin/lz4 /usr/bin
copy_exec /usr/sbin/sgdisk /usr/sbin
copy_file text /usr/bin/sdmcryptfs /usr/bin
# OK if this fails; means it was copied due to keyscript in crypttab and copied in /usr/share/initramfs-tools/hooks/cryptroot
copy_file text /usr/bin/sdmluksunlock || true
copy_file text /etc/sdmcryptctl
$kcmd
$knopwd
exit 0
EOF
chmod 755 /etc/initramfs-tools/hooks/luks-hooks
cryptolog "Update /etc/initramfs-tools/modules to include crypto '$xcrypto' modules" noconsole
case "$xcrypto" in
xchacha*)
[ "$crypto" == "xchacha" ] && crypto=xchacha12
cat >> /etc/initramfs-tools/modules <<EOF
algif_skcipher
$crypto
adiantum
aes_arm
sha256
nhpoly1305
dm-crypt
EOF
;;
aes|aes-*)
cat >> /etc/initramfs-tools/modules <<EOF
algif_skcipher
aes_arm64
aes_ce_blk
aes_ce_ccm
aes_ce_cipher
sha256_arm64
cbc
dm-crypt
EOF
;;
esac
cryptolog "Enable KEYMAP=y in /etc/initramfs-tools/initramfs.conf" noconsole
sed -i "s/KEYMAP=n/KEYMAP=y/" /etc/initramfs-tools/initramfs.conf
#
# Configure the network in initramfs.conf if requested
#
if [[ $xssh -eq 1 ]] && [[ "${xipaddr}${xgateway}${xnetmask}${xhostname}" != "" ]]
then
ips="IP=" # Configure DNS, gateway, hostname, ipaddr, netmask
[ "$xipaddr" != "" ] && ips="${ips}${xipaddr}:" || ips="${ips}:"
ips="${ips}:" # For the mystery 'server' value
[ "$xgateway" != "" ] && ips="${ips}${xgateway}:" || ips="${ips}:"
[ "$xnetmask" != "" ] && ips="${ips}${xnetmask}:" || ips="${ips}:"
[ "$xhostname" != "" ] && ips="${ips}${xhostname}:" || ips="${ips}:"
ips=${ips%:}
echo "$ips" >> /etc/initramfs-tools/initramfs.conf
fi
#
# Configure dropbear if requested
#
if [ $xssh -eq 1 ]
then
cryptolog "Configure SSH" noconsole
sed -i "s#\#DROPBEAR_OPTIONS=\"\"#DROPBEAR_OPTIONS=\"-I $xsshtimeout -j -k -s -p $xsshport -c bash -r /etc/dropbear/dropbear_ed25519_host_key\"#" /etc/dropbear/initramfs/dropbear.conf
cryptolog "Copy authorized keys file from '$xauthkeys'" noconsole
cp $xauthkeys /etc/dropbear/initramfs/authorized_keys
if [ $xunique -eq 0 ]
then
cryptolog "Convert openSSH host key for use in dropbear/initramfs" noconsole
dropbearconvert openssh dropbear /etc/ssh/ssh_host_ed25519_key /etc/dropbear/initramfs/dropbear_ed25519_host_key
else
cryptolog "Use unique SSH host key in dropbear/initramfs" noconsole
fi
fi
}
function domkinitramfs() {
cryptolog "Update initramfs with all the rootfs encryption settings in place" noconsole
update-initramfs -u
}
function doupdateconfig() {
local rootfs kfu="" kfuuid="none" ktries=""
rootfs=$(findmnt --noheadings --output source /)
cryptolog "Update root statement in cmdline.txt" noconsole
sed -i "s#root=[0-9a-zA-Z-]*[ =][0-9a-zA-Z-]* #root=/dev/mapper/$xmapper #" /boot/firmware/cmdline.txt
cryptolog "Add cryptdevice '$xmapper' to cmdline.txt" noconsole
# 'rw' needed so crypt device is mounted read/write
# luks.crypttab prevents systemd-cryptsetup-generator for reading crypttab
sed -i "s# rw cryptdevice=$rootfs:$xmapper luks.crypttab=no##g" /boot/firmware/cmdline.txt # Delete in case
sed -i "s#\$# rw cryptdevice=$rootfs:$xmapper luks.crypttab=no#" /boot/firmware/cmdline.txt
# mask the service in case other partitions encrypted; this will prevent systemd-cryptsetup errors in journal wrt already-mounted rootfs
systemctl -q mask systemd-cryptsetup@$xmapper.service 2>/dev/null
cryptolog "Updated cmdline:" noconsole
cryptolog " $(cat /boot/firmware/cmdline.txt)" noconsole
cryptolog "Update /etc/fstab for the encrypted rootfs" noconsole
sed -i "s#PARTUUID=[0-9a-zA-Z-]* */ #/dev/mapper/$xmapper / #" /etc/fstab
cryptolog "Update /etc/crypttab" noconsole
if [ "$xkeyfile" != "" ]
then
kfuuid=$(basename $xkeyfile)
kfuuid=${kfuuid%.lek}
kfu=",keyscript=/usr/bin/sdmluksunlock"
ktries=",tries=$xtries"
fi
# noauto prevents systemd-cryptsetup from touching it. Only needed for rootfs
echo "$xmapper $rootfs $kfuuid luks,noauto,discard${ktries}${kfu}" >> /etc/crypttab
}
#
# Main code
#
xauthkeys=""
xautocrypt=""
xcrypto=""
xdebug=0
xdns=""
xgateway=""
xhostname=""
xipaddr=""
xkeyfile=""
xmapper=""
xnbdeserver=""
xnetmask=""
xnoexpand=0
xnolastrb=0
xnopwd=0
xquiet=0
xreboot=0
xsdm=0
xssh=0
xsshbash=0
xsshport="22"
xsshtimeout="3600"
xtries="0"
xunique=0
xwifi=0
xwifissid=""
xwifipwd=""
xwifipsk=0
[[ ! $EUID -eq 0 ]] && errexit "? Please run as root: sudo $0 $*"
src=$(dirname "$(realpath "$0")")