-
Notifications
You must be signed in to change notification settings - Fork 0
/
phy-x86_64-uefi-grub-encrypt-lvm.sh
executable file
·1712 lines (1431 loc) · 47.8 KB
/
phy-x86_64-uefi-grub-encrypt-lvm.sh
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/sh -eu
# shellcheck disable=SC2039
#############################################################################
# Generated on Tue 10 Oct 2023 15:06:17 BST by create-alpine-disk-image
# version 0.3-DEV using the following options:
#
# --bootloader grub
# --boottype uefi
# --cpu-vendor intel
# --disable-optimisation
# --encryption-type luks
# --ethernet-module r8169
# --image-filename phy-x86_64-uefi-grub-encrypt-lvm.img
# --keymap "gb gb-extd"
# --locale en_GB
# --luks-passphrase test123
# --lvm
# --physical pc
# --script-filename output/phy-x86_64-uefi-grub-encrypt-lvm.sh
# --script-host-os alpine
# --use-ramdisk
#
#############################################################################
if [ "$(id -u)" -ne 0 ]; then
printf '\nThis script must be run as the root user!\n\n'
exit 1
fi
#############################################################################
## Functions
#############################################################################
#
# Checks that the host OS has all necessary packages installed.
#
check_for_required_packages() {
local _required_packages
local _host_os_major_version
local _host_os
_host_os=$(detect_host_os)
case $_host_os in
alpine )
_host_os_major_version="$(grep VERSION_ID /etc/os-release | sed -E -e 's/^VERSION_ID=([0-9]+\.[0-9]+).*/\1/g')"
_required_packages="blkid busybox coreutils jq lsblk qemu-img tar wget dosfstools parted e2fsprogs cryptsetup lvm2"
case $_host_os_major_version in
3.13 | 3.14 )
# Select:
# util-linux for: losetup, mount, umount
# (Busybox versions are not suitable)
_required_packages="$_required_packages util-linux"
;;
3.15 )
# Select:
# util-linux-misc for: losetup, mount, umount
# (Busybox versions are not suitable)
_required_packages="$_required_packages util-linux-misc"
;;
3.16 )
# Select:
# losetup & util-linux-misc for: losetup, mount, umount
# (Busybox versions are not suitable)
_required_packages="$_required_packages losetup util-linux-misc"
;;
* )
# Select:
# losetup, mount, & umount for: losetup, mount, umount
# (Busybox versions are not suitable)
_required_packages="$_required_packages losetup mount umount"
;;
esac
# shellcheck disable=SC2086
if ! apk info -e -q $_required_packages; then
printf '\nThe following Alpine packages need to be installed:\n\n'
printf ' %s\n\n' "$_required_packages"
exit 1
fi
;;
* )
case $_host_os in
alpine | debian | ubuntu )
printf \
'\nRe-run create-alpine-disk-image specifying '\''--script-host-os %s'\''!\n\n' \
"$_host_os"
;;
* )
printf '\nUnsupported host OS!\n\n' ;;
esac
exit 1
;;
esac
}
#
# Check that the host OS has necessary packages installed for
# running user-mode QEMU via binfmt and that it is configured.
#
check_binfmt_packages() {
local _alpine_arch_package="qemu-x86_64"
local _arch="x86_64"
local _binfmt_file="/proc/sys/fs/binfmt_misc/qemu-x86_64"
local _binfmt_arch_enabled _host_arch _host_os _required_packages
_host_arch=$(detect_host_arch)
if [ "$_host_arch" != "$_arch" ]; then
_host_os=$(detect_host_os)
case $_host_os in
alpine )
_required_packages="qemu-openrc $_alpine_arch_package"
# shellcheck disable=SC2086
if ! apk info -e -q $_required_packages; then
printf '\nThe following Alpine packages need to be installed:\n\n'
printf ' %s\n\n' "$_required_packages"
exit 1
fi
;;
* )
case $_host_os in
alpine | debian | ubuntu )
printf \
'\nRe-run create-alpine-disk-image specifying '\''--script-host-os %s'\''!\n\n' \
"$_host_os"
;;
* )
printf '\nUnsupported host OS!\n\n' ;;
esac
exit 1
;;
esac
# Is binfmt configured for this QEMU arch?
if [ -e "$_binfmt_file" ]; then
_binfmt_arch_enabled=$(head -1 ${_binfmt_file})
if [ "$_binfmt_arch_enabled" = "enabled" ]; then
return
else
printf '\nBinfmt is not enabled for %s\n\n' "$_arch"
exit 1
fi
else
printf '\nBinfmt and QEMU are not configured for %s\n\n' "$_arch"
exit 1
fi
fi
}
#
# Determine the host architecture that script is being run on.
#
detect_host_arch() {
uname -m
}
#
# Determine the Linux distro that script is being run on.
#
detect_host_os() {
grep "^ID=" /etc/os-release | sed -e 's/^ID=//'
}
#
# Unmount filesystems whenever an error occurs in the script.
#
# shellcheck disable=SC2317
error_cleanup() {
write_log
write_log
write_log "AN ERROR OCCURRED, cleaning up before aborting!"
write_log
write_log
if [ -f "$chroot_dir"/chroot.log ]; then
cat "$chroot_dir"/chroot.log >> "$logfile"
fi
normal_cleanup "error"
rm -f crypto_keyfile.bin
rm "$image_full_filename"
sync -f "$ramdisk_dir"
unmount_ramdisk
}
#
# Get the UUID of the filesystem in the specified device.
#
get_uuid_from_device() {
blkid -s UUID -o value "$1"
}
#
# Unmount filesystems mounted inside chroot directory.
#
normal_cleanup() {
local _param="${1:-}"
# Clear exit trap function
trap EXIT
if [ -z "$_param" ]; then
write_log "Normal cleanup"
fi
unmount_chroot_fs "/tmp"
if [ -n "$working_dir" ]; then
rmdir "$working_dir"
fi
unmount_chroot_fs "/dev"
unmount_chroot_fs "/sys"
unmount_chroot_fs "/proc"
unmount_chroot_fs "/boot/efi"
unmount_chroot_fs "/boot"
unmount_chroot_fs "/cidata"
unmount_chroot_fs "/"
vgchange -an >> "$logfile"
cryptsetup close lukspart >> "$logfile"
if [ -n "$loop_device" ]; then
write_log "Freeing up loop device '$loop_device'" 2
losetup -d "$loop_device" >> "$logfile"
_rc=$?
if [ $_rc -ne 0 ]; then
printf '\nThere was a problem freeing the loop device '\''%s'\''!\n\n' \
"$loop_device"
exit 1
fi
fi
}
#
# Unmount a filesystem inside chroot.
#
unmount_chroot_fs() {
local _mountpoint="$1"
local _where_from="${2:-inside chroot}"
local _full_path _pseudo_path
if [ "$_mountpoint" = "/" ]; then
_full_path="$chroot_dir"
_pseudo_path="root filesystem"
else
_full_path="${chroot_dir}${_mountpoint}"
_pseudo_path="$_mountpoint"
fi
if mount | grep -q "$_full_path" ; then
write_log "Unmounting ${_pseudo_path} ${_where_from}" 2
umount -l -f "$_full_path" >> "$logfile"
fi
}
#
# Unmount ramdisk.
#
unmount_ramdisk() {
local _rc
# Give any previous operations using the ramdisk time to complete
sleep 10
if mount | grep -q "$ramdisk_dir" ; then
_rc=1
while [ $_rc -ne 0 ]; do
write_log "Unmounting ramdisk"
umount "$ramdisk_dir" >> "$logfile"
_rc=$?
sleep 5
done
sleep 5
write_log "Deleting ramdisk directory"
rmdir "$ramdisk_dir" >> "$logfile"
fi
}
#
# Write debug messages only to the log file.
#
write_debug_log() {
local _log_entry="$1"
local _indent="${2:-0}"
local _current_time
# Debug not enabled so do nothing
true
}
#
# Write log messages to both logfile (with timestamp) and stdout.
#
write_log() {
local _log_entry="${1:-}"
local _indent="${2:-0}"
local _current_time
_current_time=$(printf "[%s]" "$(date -u "+%Y-%m-%d %H:%M:%S")")
# shellcheck disable=SC1117
printf "${_current_time} %${_indent}s${_log_entry}\n" >> "$logfile"
# shellcheck disable=SC1117
printf "%${_indent}s$_log_entry\n"
}
#############################################################################
## Main Section
#############################################################################
chroot_dir="./chroot"
images_dir="./alpine-images"
TMPDIR="/var/tmp"
image_filename="phy-x86_64-uefi-grub-encrypt-lvm.img"
logfile="phy-x86_64-uefi-grub-encrypt-lvm.log"
luks_passphrase="test123"
# Create empty logfile
:> $logfile
ramdisk_dir="./ramdisk"
image_full_filename="$ramdisk_dir/$image_filename"
working_dir=""
check_for_required_packages
check_binfmt_packages
# Ensure if any errors occur that various cleanup operations happen
trap error_cleanup EXIT
mkdir -p $images_dir
write_log "Setting up ramdisk"
mkdir -p $ramdisk_dir
mount -t tmpfs -o size=3G tmpfs $ramdisk_dir >> $logfile
write_log "Creating sparse disk image of 638MiB"
truncate -s 638M $image_full_filename >> $logfile
write_log "Partitioning disk image for UEFI"
{
write_debug_log "Creating gpt disk label" 2
parted --machine --script --align=optimal $image_full_filename \
mklabel gpt >> "$logfile" 2>&1
write_debug_log "Creating 16MiB ESP partition" 2
parted --machine --script --align=optimal $image_full_filename \
unit MiB mkpart primary fat16 1MiB 17MiB >> "$logfile" 2>&1
write_debug_log "Setting partition esp flag on" 2
parted --machine --script --align=optimal $image_full_filename \
set 1 esp on >> "$logfile" 2>&1
write_debug_log "Labelling GPT partition 1 as 'ESP'" 2
parted --machine --script $image_full_filename \
name 1 "ESP" >> "$logfile" 2>&1
write_debug_log "Creating 1MiB cidata partition" 2
parted --machine --script --align=optimal $image_full_filename \
unit MiB mkpart primary 17MiB 18MiB >> "$logfile" 2>&1
write_debug_log "Labelling GPT partition 2 as 'cidata'" 2
parted --machine --script $image_full_filename \
name 2 "cidata" >> "$logfile" 2>&1
write_debug_log "Creating 620MiB LUKS partition" 2
parted --machine --script --align=optimal $image_full_filename \
unit MiB mkpart primary 18MiB 100% >> "$logfile" 2>&1
write_debug_log "Labelling GPT partition 3 as 'LUKS'" 2
parted --machine --script $image_full_filename \
name 3 "LUKS" >> "$logfile" 2>&1
}
write_log "Setting up loop device for disk image"
{
write_log "Ensuring that loop driver is loaded (if necessary)" 2
if [ ! -c /dev/loop-control ]; then
loop_module_filename=$(modinfo -F filename loop 2>/dev/null)
if [ "$loop_module_filename" != "" ] && \
[ "$loop_module_filename" != "(builtin)" ]; then
modprobe loop 2>> $logfile
else
printf '\nThere is a problem with loop devices!\n\n'
exit 1
fi
fi
write_log "Setting up loop device with 512-byte sector size for disk image" 2
loop_device=$(losetup -P --show -b 512 -f $image_full_filename 2>> $logfile)
_rc=$?
if [ $_rc -ne 0 ]; then
if [ -n "$loop_device" ]; then
unset loop_device
printf '\nThere was a problem creating the loop device!\n\n'
else
printf \
'\nThere was a problem creating the loop device '\''%s'\''!\n\n' \
"$loop_device"
fi
exit 1
fi
if [ -z "$loop_device" ]; then
printf '\nThere was a problem creating the loop device. Aborting!\n\n'
exit 1
fi
}
write_log "Setting up LUKS v1 device using aes-xts-plain64 cipher"
{
luks_device="${loop_device}p3"
write_log "Formatting partition as LUKS version 1" 2
echo "$luks_passphrase" | cryptsetup -q --verbose luksFormat \
--pbkdf pbkdf2 --type luks1 --use-random \
--cipher aes-xts-plain64 --hash sha256 --key-size 512 \
"$luks_device" >> "$logfile" 2>&1
write_log "Creating keyfile for LUKS" 2
dd bs=512 count=4 if=/dev/random of=crypto_keyfile.bin iflag=fullblock \
>> "$logfile" 2>&1
write_log "Adding keyfile to LUKS device" 2
echo "$luks_passphrase" | \
cryptsetup luksAddKey --pbkdf pbkdf2 "$luks_device" ./crypto_keyfile.bin >> "$logfile"
write_log "Opening LUKS device" 2
cryptsetup open --type luks1 --key-file ./crypto_keyfile.bin \
"$luks_device" lukspart
luks_part_uuid=$(get_uuid_from_device "$luks_device")
}
write_log "Setting up LVM device"
{
lvm_device="/dev/mapper/lukspart"
write_log "Creating LVM physical volume" 2
pvcreate --verbose "$lvm_device" >> "$logfile" 2>&1
_pv_size=$(pvdisplay --verbose 2>&1 | grep "PV Size" | sed -e 's/^.*PV Size[ ]*//' -e 's/\.[0-9]* MiB.*$//')
write_debug_log " Resultant PV size ${_pv_size}MiB"
write_log "Creating LVM volume group" 2
vgcreate --verbose vg0 "$lvm_device" >> "$logfile" 2>&1
write_log "Creating 504MiB LVM logical volume for rootfs" 2
lvcreate --verbose -L 504m vg0 -n root >> "$logfile" 2>&1
write_log "Creating 68MiB LVM logical volume for boot" 2
lvcreate --verbose -L 68m vg0 -n boot >> "$logfile" 2>&1
write_log "Creating 20MiB LVM logical volume for logs" 2
lvcreate --verbose -L 20m vg0 -n logs >> "$logfile" 2>&1
}
write_log "Formatting and mounting filesystems"
{
uefi_part_device="${loop_device}p1"
write_log \
"Formatting FAT16 filesystem with 512-byte sectors on ESP partition" 2
mkfs.fat -F16 -s 1 -S 512 -n "SYSTEM EFI" "$uefi_part_device" \
>> "$logfile" 2>&1
esp_fs_uuid="$(get_uuid_from_device "$uefi_part_device")"
cidata_part_device="${loop_device}p2"
write_log \
"Formatting FAT12 CIDATA filesystem with 512-byte sectors on partition" 2
mkfs.fat -F12 -s 1 -S 512 -n CIDATA "$cidata_part_device" \
>> "$logfile" 2>&1
root_part_device="/dev/mapper/vg0-root"
logs_part_device="/dev/mapper/vg0-logs"
boot_part_device="/dev/mapper/vg0-boot"
write_log "Formatting Ext4 root filesystem on LVM-on-LUKS device" 2
mkfs.ext4 -L alpine-root -I 256 -q "$root_part_device" >> "$logfile" 2>&1
write_log "Formatting Ext4 boot filesystem on LVM-on-LUKS device" 2
mkfs.ext4 -L boot -I 256 -q "$boot_part_device" >> "$logfile" 2>&1
write_log "Formatting Ext4 logs filesystem on LVM-on-LUKS device" 2
mkfs.ext4 -L logs -I 256 -q "$logs_part_device" >> "$logfile" 2>&1
write_log "Mounting root filesystem onto $chroot_dir" 2
mkdir -p "$chroot_dir"
mount -o private "$root_part_device" "$chroot_dir" >> "$logfile" 2>&1
write_log "Mounting boot filesystem onto $chroot_dir/boot" 2
mkdir -p "$chroot_dir"/boot
mount -o private "$boot_part_device" "$chroot_dir"/boot >> "$logfile" 2>&1
write_log "Mounting ESP filesystem onto $chroot_dir/boot/efi" 2
mkdir -p "$chroot_dir"/boot/efi
mount -o private "$uefi_part_device" "$chroot_dir"/boot/efi \
>> "$logfile" 2>&1
write_log "Mounting logs filesystem onto $chroot_dir/var/logs" 2
mkdir -p "$chroot_dir"/var/log
mount -o private "$logs_part_device" "$chroot_dir"/var/log >> "$logfile" 2>&1
write_log "Mounting cloud-init YAML filesystem onto $chroot_dir/cidata" 2
mkdir -p "$chroot_dir"/cidata
mount -o private "$cidata_part_device" "$chroot_dir"/cidata >> "$logfile"
}
write_log "Moving LUKS keyfile into chroot directory" 2
{
mv crypto_keyfile.bin "$chroot_dir"/
chmod 400 "$chroot_dir"/crypto_keyfile.bin
}
write_log "Copying system's /etc/resolv.conf into chroot filesystem"
mkdir -p "$chroot_dir"/etc
cp /etc/resolv.conf "$chroot_dir"/etc/
write_log "Creating /etc/apk/repositories file inside chroot"
mkdir -p "$chroot_dir"/etc/apk/keys
{
printf '%s/%s/main\n' "https://dl-cdn.alpinelinux.org/alpine" "edge"
printf '%s/%s/community\n' "https://dl-cdn.alpinelinux.org/alpine" "edge"
printf '%s/%s/testing\n' "https://dl-cdn.alpinelinux.org/alpine" "edge"
} > "$chroot_dir"/etc/apk/repositories
write_log "Bootloader packages to be installed are: grub grub-efi"
write_log \
"Install base Alpine & bootloader packages for x86_64 arch inside chroot"
{
_apk_binary="apk"
# shellcheck disable=SC2086
$_apk_binary --arch "x86_64" --initdb --allow-untrusted \
--root $chroot_dir --update-cache \
add alpine-base efivar dosfstools ifupdown-ng mkinitfs grub grub-efi \
>> "$logfile" 2>&1
_rc=$?
if [ $_rc -ne 0 ]; then
write_log "Failure while installing base Alpine, error code: $_rc"
exit 1
fi
}
write_log "Mounting tmp, /proc, /sys, and /dev special filesystems in chroot"
{
working_dir=$(mktemp -d -p /tmp create-alpine.XXXXXX)
_rc=$?
if [ $_rc -ne 0 ]; then
printf '\nThere was a problem creating a temporary working directory!\n\n'
exit 1
fi
mount -v -t none -o rbind "$working_dir" $chroot_dir/tmp
mount -v --make-rprivate $chroot_dir/tmp
mount -v -t proc none $chroot_dir/proc
mount -v -t none -o rbind /sys $chroot_dir/sys
mount -v --make-rprivate $chroot_dir/sys
mount -v -t none -o rbind /dev $chroot_dir/dev
mount -v --make-rprivate $chroot_dir/dev
} >> $logfile 2>&1
#############################################################################
## Start of Chroot section
#############################################################################
cat <<EOT | chroot $chroot_dir /bin/sh -eu
#!/bin/sh -eu
keymap="gb gb-extd"
locale="en_GB.UTF-8"
umask="077"
timezone="America/New_York"
############################################################################
## Chroot Functions
############################################################################
add_fstab_entry() {
local _entry_type="\$1"
local _entry_value="\$2"
local _mount_point="\$3"
local _fs_type="\$4"
local _fs_options="\${5:-}"
local _entry_log="\${6:-}"
local _fstab_entry
if [ "\$_entry_type" = "BIND" ]; then
_fs_options="bind,\${_fs_options}"
local _fs_passno="0"
elif [ "\$_fs_type" = "swap" ]; then
_mount_point="none"
_fs_options="sw"
local _fs_passno="0"
_entry_log="Swap partition"
elif [ "\$_fs_type" = "tmpfs" ]; then
local _fs_passno="0"
elif [ "\$_mount_point" = "/" ]; then
local _fs_passno="1"
else
local _fs_passno="2"
fi
if [ "\$_entry_type" = "BIND" ] || [ "\$_entry_type" = "DEVICE" ]; then
_fstab_entry="\${_entry_value}"
else
_fstab_entry="\${_entry_type}=\${_entry_value}"
fi
_fstab_entry="\${_fstab_entry}\t\${_mount_point}\t\${_fs_type}\t\${_fs_options} 0 \${_fs_passno}"
write_log "Add \${_entry_log} entry" 2
# shellcheck disable=SC2059
printf "\${_fstab_entry}\n" >> /etc/fstab
}
all_entries_in_comma_list_except() {
local _cfaeicle_comma_list="\$1"
local _cfaeicle_cl_except="\$2"
all_entries_in_list_except "\$_cfaeicle_comma_list" \\
"\$_cfaeicle_cl_except" ","
}
all_entries_in_list_except() {
local _cfaeile_list="\$1"
local _cfaeile_keep_item="\$2"
local _cfaeile_separator="\$3"
local _cfaeile_check _cfaeile_check_item _cfaeile_resulting_list=""
_cfaeile_check="\$_cfaeile_list"
while true; do
_cfaeile_check_item="\$(first_entry_in_list "\$_cfaeile_check" "\$_cfaeile_separator")"
case \$_cfaeile_check_item in
generic )
: ;;
* )
if [ "\$_cfaeile_check_item" != "\$_cfaeile_keep_item" ]; then
if [ -n "\$_cfaeile_resulting_list" ]; then
_cfaeile_resulting_list="\${_cfaeile_resulting_list}\${_cfaeile_separator}\${_cfaeile_check_item}"
else
_cfaeile_resulting_list="\${_cfaeile_check_item}"
fi
fi
;;
esac
if [ "\${_cfaeile_check%\$_cfaeile_separator*}" = "\$_cfaeile_check" ]; then
# No more entries
break
else
_cfaeile_check="\${_cfaeile_check#\$_cfaeile_check_item\$_cfaeile_separator}"
fi
done
echo "\$_cfaeile_resulting_list"
}
check_list_of_modules_exist() {
local _cfclome_modules_list="\$1"
local _cfclome_filename _cfclome_search_list _cfclome_search_list_item
local _cfclome_resultant_list
_cfclome_search_list="\$_cfclome_modules_list"
_cfclome_resultant_list="\$_cfclome_modules_list"
while true; do
_cfclome_search_list_item="\$(first_entry_in_comma_list "\$_cfclome_search_list")"
_cfclome_filename="\$(modinfo -k \$(get_kernel_version) -F filename "\$_cfclome_search_list_item" 2>/dev/null)"
if [ -z "\$_cfclome_filename" ] || \\
[ "\$_cfclome_filename" = "(builtin)" ]; then
# Remove this module name from the resultant list
_cfclome_resultant_list="\$(all_entries_in_comma_list_except "\$_cfclome_resultant_list" "\$_cfclome_search_list_item")"
fi
if [ "\${_cfclome_search_list%,*}" = "\$_cfclome_search_list" ]; then
# No more entries
break
else
_cfclome_search_list="\${_cfclome_search_list#"\$_cfclome_search_list_item",}"
fi
done
echo "\$_cfclome_resultant_list"
}
define_cmdline_for_luks_encryption() {
echo "cryptroot=UUID=${luks_part_uuid} cryptdm=lukspart"
}
echo_lines_from_comma_list() {
local _cfelfcl_output_formatting="\$1"
local _cfelfcl_input_cl_list="\$2"
local _cfelfcl_cl_list _cfelfcl_cl_list_item
_cfelfcl_cl_list="\$_cfelfcl_input_cl_list"
while true; do
_cfelfcl_cl_list_item="\$(first_entry_in_comma_list "\$_cfelfcl_cl_list")"
printf "\$_cfelfcl_output_formatting\n" "\$_cfelfcl_cl_list_item"
if [ "\${_cfelfcl_cl_list%,*}" = "\$_cfelfcl_cl_list" ]; then
# No more entries
break
else
_cfelfcl_cl_list="\${_cfelfcl_cl_list#\$_cfelfcl_cl_list_item,}"
fi
done
}
find_module_full_path() {
local _module="\$1"
local _module_path
_module_path="\$(find /lib/modules/ -name "\$_module.ko*" | \\
sed -e 's/^.*kernel/kernel/' -e 's/\.ko.*$//')"
if [ -z "\$_module_path" ]; then
_module="\$(echo "\$_module" | sed -e 's/-/_/g')"
_module_path="\$(find /lib/modules/ -name "\$_module.ko*" | \\
sed -e 's/^.*kernel/kernel/' -e 's/\.ko.*$//')"
fi
if [ -n "\$_module_path" ]; then
_module_path="\${_module_path}.ko*"
fi
echo "\$_module_path"
}
first_entry_in_comma_list() {
local _cffeicl_comma_list="\$1"
first_entry_in_list "\$_cffeicl_comma_list" ","
}
first_entry_in_list() {
local _cffeil_list="\$1"
local _cffeil_separator="\$2"
echo "\${_cffeil_list%%"\$_cffeil_separator"*}"
}
get_kernel_package_version() {
apk info linux-lts | head -n 1 | sed -e "s/^linux-lts-//" \\
-e 's/ .*//'
}
get_kernel_version() {
apk info linux-lts | head -n 1 | sed -e "s/^linux-lts-//" \\
-e 's/-r/-/' -e 's/ .*//' -Ee "s/^(.*)$/\1-lts/"
}
write_debug_log() {
local _log_entry="\$1"
local _indent=\${2:-0}
local _current_time
# Debug not enabled so do nothing
true
}
write_log() {
local _log_entry="\$1"
local _indent=\${2:-0}
local _current_time
_current_time=\$(printf "[%s]" "\$(date -u "+%Y-%m-%d %H:%M:%S")")
# shellcheck disable=SC1117
printf "\$_current_time chroot: %\${_indent}s\${_log_entry}\n" >> /chroot.log
# shellcheck disable=SC1117
printf "chroot: %\${_indent}s\${_log_entry}\n"
}
############################################################################
## Chroot Main Section
############################################################################
write_log "Add /etc/fstab entries"
{
add_fstab_entry DEVICE "tmpfs" "/tmp" "tmpfs" "nosuid,nodev" "/tmp on tmpfs"
add_fstab_entry DEVICE "/dev/mapper/vg0-root" "/" "ext4" \\
"rw,relatime" "rootfs"
add_fstab_entry UUID "$esp_fs_uuid" "/boot/efi" "vfat" "rw" "ESP filesystem"
add_fstab_entry DEVICE "/dev/mapper/vg0-boot" "/boot" "ext4" "rw,relatime" "boot"
add_fstab_entry DEVICE "/dev/mapper/vg0-logs" "/var/log" "ext4" "rw,relatime" "logsfs"
}
write_log "Adding additional repos"
{
write_log "Adding community repo to /etc/apk/repositories" 2
cat <<-_SCRIPT_ >> /etc/apk/repositories
https://dl-cdn.alpinelinux.org/alpine/edge/community
_SCRIPT_
write_log "Adding testing repo to /etc/apk/repositories" 2
cat <<-_SCRIPT_ >> /etc/apk/repositories
https://dl-cdn.alpinelinux.org/alpine/edge/testing
_SCRIPT_
}
write_log "Updating packages info"
{
write_log "Updating packages list" 2
apk update >> /chroot.log
write_log "Upgrading base packages if necessary" 2
apk -a upgrade >> /chroot.log
}
write_log "Doing basic OS configuration"
{
write_log "Setting the login and MOTD messages" 2
printf '\nWelcome\n\n' > /etc/issue
printf '\n\n%s\n\n' "Alpine x86_64 PC server" > /etc/motd
write_log "Setting the keymap to '\$keymap'" 2
# shellcheck disable=SC2086
setup-keymap \$keymap >> "/chroot.log" 2>&1
locale_file="50-cloud-init-locale.sh"
if [ -e "\$locale_file" ]; then
write_log "Setting locale to \$locale" 2
sed -i -E -e "s/^(export LANG=)C.UTF-8/\1\$locale/" \\
/etc/profile.d/\${locale_file}
else
write_log "Creating profile file to set locale to \$locale" 2
{
printf '# Created by create-alpine-disk-image\n#\n'
printf 'export LANG=%s\n' "\$locale"
} > /etc/profile.d/\${locale_file}
fi
write_log "Setting system-wide UMASK" 2
{
umask_file="05-umask.sh"
write_log "Creating profile file to set umask to \$umask" 4
{
printf '# Created by create-alpine-disk-image\n\n'
printf 'umask %s\n' "\$umask"
} > /etc/profile.d/\${umask_file}
}
write_log "Set OpenRC to log init.d start/stop sequences" 2
sed -i -e 's|[#]rc_logger=.*|rc_logger="YES"|g' /etc/rc.conf
write_log \\
"Configure /etc/init.d/bootmisc to keep previous dmesg logfile" 2
sed -i -e 's|[#]previous_dmesg=.*|previous_dmesg=yes|g' /etc/conf.d/bootmisc
write_log "Enable colour shell prompt" 2
cp /etc/profile.d/color_prompt.sh.disabled /etc/profile.d/color_prompt.sh
write_log "Enable mdev init.d services" 2
setup-devd mdev >> /chroot.log 2>&1 || true
rmdir /media/floppy
}
write_log "Enable init.d scripts"
{
rc-update add devfs sysinit
rc-update add dmesg sysinit
rc-update add bootmisc boot
rc-update add hostname boot
rc-update add modules boot
rc-update add swap boot
rc-update add seedrng boot
rc-update add osclock boot
rc-update add networking default
rc-update add killprocs shutdown
rc-update add mount-ro shutdown
rc-update add savecache shutdown
} >> /chroot.log 2>&1
add_packages="doas cpio ca-certificates htop kbd-bkeymaps logrotate musl-locales sshguard hwinfo acct util-linux-login shadow cryptsetup lvm2 device-mapper iptables e2fsprogs-extra dhcpcd chrony openssh-server rsyslog"
write_log "Install additional packages: \$add_packages"
{
# shellcheck disable=SC2086
apk add \$add_packages >> /chroot.log 2>&1
}
add_os_cfg_pkgs="cloud-init lsblk parted sfdisk sgdisk ssh-import-id busybox"
write_log "Install OS configuration packages: \$add_os_cfg_pkgs"
{
# shellcheck disable=SC2086
apk add \$add_os_cfg_pkgs >> /chroot.log 2>&1
}
machine_specific_pkgs="cpufrequtils ethtool irqbalance lm-sensors smartmontools hd-idle hdparm acpid fwupd cpufrequtils ethtool irqbalance"
write_log \\
"Install additional machine specific packages: \$machine_specific_pkgs"
{
# shellcheck disable=SC2086
apk add \$machine_specific_pkgs >> /chroot.log 2>&1
}
write_log "Doing additional OS configuration"
{
write_log "Configure doas" 2
{
write_log "Adding doas configuration for root user" 4
cat <<-_SCRIPT_ >> /etc/doas.conf
# Allow root to run doas (i.e. "doas -u <user> <command>")
permit nopass root
_SCRIPT_
write_log "Enabling doas configuration for wheel group" 4
sed -i -E -e 's/^[#][ ]*(permit persist :wheel)$/\1/g' \\
/etc/doas.conf
}
}
write_log "Configuring cloud-init"
{
write_log "Running setup-cloud-init" 2
setup-cloud-init >> /chroot.log 2>&1 || true
write_log "Setting DataSources list with: NoCloud" 2
cat <<-_SCRIPT_ > /etc/cloud/cloud.cfg.d/01-datasources.cfg
# /etc/cloud/cloud.cfg.d/01-datasources.cfg
datasource_list: ['NoCloud']
_SCRIPT_
write_log "Setting up modules info" 2
cat <<-_SCRIPT_ > /etc/cloud/cloud.cfg.d/01-modules.cfg
# /etc/cloud/cloud.cfg.d/01-modules.cfg
# Modules that run in 'init' stage
cloud_init_modules:
- bootcmd
- write_files
- growpart
- resizefs
- disk_setup
- mounts
- set_hostname
- update_hostname
- update_etc_hosts
- resolv_conf
- ca_certs
- rsyslog
- users_groups
- ssh
# Modules that run in 'config' stage
cloud_config_modules:
- ssh_import_id
- keyboard
- locale
- set_passwords
- apk_configure
- ntp
- timezone
- runcmd
# Modules that run in 'final' stage
cloud_final_modules:
- package_update_upgrade_install
- write_files_deferred
- ansible
- scripts_vendor
- scripts_per_once
- scripts_per_boot
- scripts_per_instance
- scripts_user
- ssh_authkey_fingerprints
- keys_to_console
- phone_home
- final_message
- power_state_change
_SCRIPT_
write_log "Setting up System info" 2
cat <<-_SCRIPT_ > /etc/cloud/cloud.cfg.d/01-system-info.cfg
# /etc/cloud/cloud.cfg.d/01-system-info.cfg
system_info:
distro: alpine
default_user:
_SCRIPT_
write_log "Setting the default username to 'alpine'" 4
cat <<-_SCRIPT_ >> /etc/cloud/cloud.cfg.d/01-system-info.cfg
name: alpine
doas:
- permit nopass alpine