-
Notifications
You must be signed in to change notification settings - Fork 28
/
ubuntu_server_encrypted_root_zfs.sh
executable file
·2345 lines (1907 loc) · 70.8 KB
/
ubuntu_server_encrypted_root_zfs.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/bash
##Script installs ubuntu on the zfs file system with snapshot rollback at boot. Options include encryption and headless remote unlocking.
##Script: https://github.com/Sithuk/ubuntu-server-zfsbootmenu
##Script date: 2024-11-02
# shellcheck disable=SC2317 # Don't warn about unreachable commands in this file
set -euo pipefail
#set -x
##Usage: <script_filename> initial | postreboot | remoteaccess | datapool
##Script to be run in two parts.
##Part 1: Run with "initial" option from Ubuntu live iso (desktop version) terminal.
##Part 2: Reboot into new install.
##Part 2: Run with "postreboot" option after first boot into new install (login as user/password defined in variable section below).
##Remote access can be installed by either:
## setting the remoteaccess variable to "yes" in the variables section below, or
## running the script with the "remoteaccess" option after part 1 and part 2 are run.
##Connect as "root" on port 222 to the server's ip address.
##It's better to leave the remoteaccess variable below as "no" and run the script with the "remoteaccess" option
## as that will use the user's authorized_keys file. Setting the remoteaccess variable to "yes" will use root's authorized_keys.
##Login as "root" during remote access, even if using a user's authorized_keys file. No other users are available during remote access.
##A non-root drive can be setup as an encrypted data pool using the "datapool" option.
##The drive will be unlocked automatically after the root drive password is entered at boot.
##If running in a Virtualbox virtualmachine, setup tips below:
##1. Enable EFI.
##2. Set networking to bridged mode so VM gets its own IP. Fewer problems with ubuntu keyserver.
##3. Minimum drive size of 5GB.
##Rescuing using a Live CD
##zpool export -a #Export all pools.
##zpool import -N -R /mnt rpool #"rpool" should be the root pool name.
##zfs load-key -r -L prompt -a #-r Recursively loads the keys. -a Loads the keys for all encryption roots in all imported pools. -L is for a keylocation or to "prompt" user for an input.
##zfs mount -a #Mount all datasets.
##Variables:
ubuntuver="noble" #Ubuntu release to install. "jammy" (22.04). "noble" (24.04).
distro_variant="server" #Ubuntu variant to install. "server" (Ubuntu server; cli only.) "desktop" (Default Ubuntu desktop install). "kubuntu" (KDE plasma desktop variant). "xubuntu" (Xfce desktop variant). "budgie" (Budgie desktop variant). "MATE" (MATE desktop variant).
user="testuser" #Username for new install.
PASSWORD="testuser" #Password for user in new install.
hostname="ubuntu" #Name to identify the main system on the network. An underscore is DNS non-compliant.
zfs_root_password="testtest" #Password for encrypted root pool. Minimum 8 characters. "" for no password encrypted protection. Unlocking root pool also unlocks data pool, unless the root pool has no password protection, then a separate data pool password can be set below.
zfs_root_encrypt="native" #Encryption type. "native" for native zfs encryption. "luks" for luks. Required if there is a root pool password, otherwise ignored.
locale="en_GB.UTF-8" #New install language setting.
timezone="Europe/London" #New install timezone setting.
zfs_rpool_ashift="12" #Drive setting for zfs pool. ashift=9 means 512B sectors (used by all ancient drives), ashift=12 means 4KiB sectors (used by most modern hard drives), and ashift=13 means 8KiB sectors (used by some modern SSDs).
mirror_archive="" #"" to use the default ubuntu repository. Set to an ISO 3166-1 alpha-2 country code to use a country mirror archive, e.g. "GB". A speed test is run and the fastest archive is selected. Country codes: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
RPOOL="rpool" #Root pool name.
topology_root="single" #"single", "mirror", "raid0", "raidz1", "raidz2", or "raidz3" topology on root pool.
disks_root="1" #Number of disks in array for root pool. Not used with single topology.
EFI_boot_size="512" #EFI boot loader partition size in mebibytes (MiB).
swap_size="500" #Swap partition size in mebibytes (MiB). Size of swap will be larger than defined here with Raidz topologies.
datapool="datapool" #Non-root drive data pool name.
topology_data="single" #"single", "mirror", "raid0", "raidz1", "raidz2", or "raidz3" topology on data pool.
disks_data="1" #Number of disks in array for data pool. Not used with single topology.
zfs_data_password="testtest" #If no root pool password is set, a data pool password can be set here. Minimum 8 characters. "" for no password protection.
zfs_data_encrypt="native" #Encryption type. "native" for native zfs encryption. "luks" for luks. Required if there is a data pool password, otherwise ignored.
datapoolmount="/mnt/$datapool" #Non-root drive data pool mount point in new install.
zfs_dpool_ashift="12" #See notes for rpool ashift. If ashift is set too low, a significant read/write penalty is incurred. Virtually no penalty if set higher.
zfs_compression="zstd" #"lz4" is the zfs default; "zstd" may offer better compression at a cost of higher cpu usage.
mountpoint="/mnt/ub_server" #Mountpoint in live iso.
remoteaccess_first_boot="no" #"yes" to enable remoteaccess during first boot. Recommend leaving as "no" and run script with "remoteaccess". See notes in section above.
timeout_rEFInd="3" #Timeout in seconds for rEFInd boot screen until default choice selected.
timeout_zbm_no_remote_access="3" #Timeout in seconds for zfsbootmenu when no remote access enabled.
timeout_zbm_remote_access="45" #Timeout in seconds for zfsbootmenu when remote access enabled. The password prompt for an encrypted root pool with allow an indefinite time to connect. An unencrypted root pool will boot the system when the timer runs out, preventing remote access.
quiet_boot="yes" #Set to "no" to show boot sequence.
ethprefix="e" #First letter of ethernet interface. Used to identify ethernet interface to setup networking in new install.
install_log="ubuntu_setup_zfs_root.log" #Installation log filename.
log_loc="/var/log" #Installation log location.
ipv6_apt_fix_live_iso="no" #Try setting to "yes" gif apt-get is slow in the ubuntu live iso. Doesn't affect ipv6 functionality in the new install.
remoteaccess_hostname="zbm" #Name to identify the zfsbootmenu system on the network.
remoteaccess_ip_config="dhcp" #"dhcp", "dhcp,dhcp6", "dhcp6", or "static". Automatic (dhcp) or static IP assignment for zfsbootmenu remote access.
remoteaccess_ip="192.168.0.222" #Remote access static IP address to connect to ZFSBootMenu. Not used for automatic IP configuration.
remoteaccess_netmask="255.255.255.0" #Remote access subnet mask. Not used for "dhcp" automatic IP configuration.
ubuntu_original="http://archive.ubuntu.com/ubuntu" #Default ubuntu repository.
install_warning_level="PRIORITY=critical" #"PRIORITY=critical", or "FRONTEND=noninteractive". Pause install to show critical messages only or do not pause (noninteractive). Script still pauses for keyboard selection at the end.
extra_programs="no" #"yes", or "no". Install additional programs if not included in the ubuntu distro package. Programs: cifs-utils, locate, man-db, openssh-server, tldr.
##Check for root priviliges
if [ "$(id -u)" -ne 0 ]; then
echo "Please run as root."
exit 1
fi
##Check for EFI boot environment
if [ -d /sys/firmware/efi ]; then
echo "Boot environment check passed. Found EFI boot environment."
else
echo "Boot environment check failed. EFI boot environment not found. Script requires EFI."
exit 1
fi
##Check encryption defined if password defined
if [ -n "$zfs_root_password" ];
then
if [ -z $zfs_root_encrypt ];
then
echo "Password entered but no encryption method defined. Please define the zfs_root_encrypt variable."
else true
fi
else true
fi
##Functions
live_desktop_check(){
##Check for live desktop environment
if [ "$(dpkg -l ubuntu-desktop)" ];
then
echo "Desktop environment test passed."
if grep casper /proc/cmdline >/dev/null 2>&1;
then
echo "Live environment present."
else
echo "Live environment test failed. Run script from a live desktop environment."
exit 1
fi
else
echo "Desktop environment test failed. Run script from a live desktop environment."
exit 1
fi
##Check live desktop version
live_desktop_version="$( . /etc/os-release && echo ${VERSION_CODENAME} )"
if [ $(echo "${live_desktop_version}" | tr '[:upper:]' '[:lower:]') = $(echo "${ubuntuver}" | tr '[:upper:]' '[:lower:]') ];
then
echo "Live environment version test passed."
else
##The zfs pool will be created with the zfs version of the live environment.
##If the zfs version is older in the distro to be installed than in the live environment then zfsbootmenu may be unable to mount the root pool at boot.
##The system will then fail to load. The reason is that Zfsbootmenu is installed with the zfs version in the distro to be installed, not the version in the live environment.
echo "Live environment version test failed."
echo "The live environment version does not match the Ubuntu version to be installed. Re-run script from an environment which matches the version to be installed. This is to avoid zfs version conflicts."
exit 1
fi
}
topology_min_disk_check(){
##Check that number of disks meets minimum number for selected topology. Disks_{root,data} variable ignored for single topology.
pool="$1"
echo "Checking script variables for $pool pool..."
topology_pool_pointer="topology_$pool"
eval echo "User defined topology for ${pool} pool: \$${topology_pool_pointer}"
eval topology_pool_pointer="\$${topology_pool_pointer}"
topology_pool_pointer_tmp="/tmp/topology_pool_pointer.txt"
printf "%s" "${topology_pool_pointer}" > "${topology_pool_pointer_tmp}"
disks_pointer="disks_${pool}"
eval echo "User defined number of disks in pool: \$${disks_pointer}"
eval disks_pointer=\$"${disks_pointer}"
disks_pointer_tmp="/tmp/disks_pointer.txt"
printf "%s" "${disks_pointer}" > "${disks_pointer_tmp}"
num_disks_check(){
min_num_disks="$1"
if [ "$disks_pointer" -lt "$min_num_disks" ]
then
echo "A ${topology_pool_pointer} topology requires at least ${min_num_disks} disks. Check variable for number of disks or change the selected topology."
exit 1
else true
fi
}
case "$topology_pool_pointer" in
single) true ;;
mirror|raid0|raidz1)
num_disks_check "2"
;;
raidz2)
num_disks_check "3"
;;
raidz3)
num_disks_check "4"
;;
*)
echo "Pool topology not recognised. Check pool topology variable."
exit 1
;;
esac
printf "%s\n\n" "Minimum disk topology check passed for $pool pool."
}
logFunc(){
# Log everything we do
exec > >(tee -a "$log_loc"/"$install_log") 2>&1
}
disclaimer(){
echo "***WARNING*** This script could wipe out all your data, or worse! I am not responsible for your decisions. Press Enter to Continue or CTRL+C to abort."
read -r _
}
connectivity_check(){
##https://unix.stackexchange.com/a/190610
test_site=google.com
if nc -zw1 "${test_site}" 443
then
echo "Internet connectivity test passed."
else
echo "No internet connectivity available. Please check connectivity."
exit 1
fi
}
getdiskID(){
pool="$1"
diskidnum="$2"
total_discs="$3"
##Get disk ID(s)
manual_read(){
ls -la /dev/disk/by-id
echo "Enter Disk ID for disk $diskidnum of $total_discs on $pool pool (must match exactly):"
read -r DISKID
}
#manual_read
menu_read(){
diskidmenu_loc="/tmp/diskidmenu.txt"
ls -la /dev/disk/by-id | awk '{ print $9, $11 }' | sed -e '1,3d' | grep -v "part\|CD-ROM" > "$diskidmenu_loc"
echo "Please enter Disk ID option for disk $diskidnum of $total_discs on $pool pool."
nl "$diskidmenu_loc"
count="$(wc -l "$diskidmenu_loc" | cut -f 1 -d' ')"
n=""
while true;
do
read -r -p 'Select option: ' n
if [ "$n" -eq "$n" ] && [ "$n" -gt 0 ] && [ "$n" -le "$count" ]; then
break
fi
done
DISKID="$(sed -n "${n}p" "$diskidmenu_loc" | awk '{ print $1 }' )"
printf "%s\n\n" "Option number $n selected: '$DISKID'"
}
menu_read
#DISKID=ata-VBOX_HARDDISK_VBXXXXXXXX-XXXXXXXX ##manual override
##error check
errchk="$(find /dev/disk/by-id -maxdepth 1 -mindepth 1 -name "$DISKID")"
if [ -z "$errchk" ];
then
echo "Disk ID not found. Exiting."
exit 1
fi
errchk="$(grep "$DISKID" /tmp/diskid_check_"${pool}".txt || true)"
if [ -n "$errchk" ];
then
echo "Disk ID has already been entered. Exiting."
exit 1
fi
printf "%s\n" "$DISKID" >> /tmp/diskid_check_"${pool}".txt
}
getdiskID_pool(){
pool="$1"
##Check that number of disks meets minimum number for selected topology.
topology_min_disk_check "$pool"
echo "Carefully enter the ID of the disk(s) YOU WANT TO DESTROY in the next step to ensure no data is accidentally lost."
##Create temp file to check for duplicated disk ID entry.
true > /tmp/diskid_check_"${pool}".txt
case "$topology_pool_pointer" in
single)
echo "The $pool pool disk topology is a single disk."
getdiskID "$pool" "1" "1"
;;
mirror|raid0|raidz*)
echo "The $pool pool disk topology is $topology_pool_pointer with $disks_pointer disks."
diskidnum="1"
while [ "$diskidnum" -le "$disks_pointer" ];
do
getdiskID "$pool" "$diskidnum" "$disks_pointer"
diskidnum=$(( diskidnum + 1 ))
done
;;
*)
echo "Pool topology not recognised. Check pool topology variable."
exit 1
;;
esac
}
clear_partition_table(){
pool="$1" #root or data
while IFS= read -r diskidnum;
do
echo "Clearing partition table on disk ${diskidnum}."
sgdisk --zap-all /dev/disk/by-id/"$diskidnum"
done < /tmp/diskid_check_"${pool}".txt
}
identify_ubuntu_dataset_uuid(){
rootzfs_full_name=0
rootzfs_full_name="$(zfs list -o name | awk '/ROOT\/ubuntu/{print $1;exit}'|sed -e 's,^.*/,,')"
}
ipv6_apt_live_iso_fix(){
##Try diabling ipv6 in the live iso if setting the preference to ipv4 doesn't work \
## to resolve slow apt-get and slow debootstrap in the live Ubuntu iso.
##https://askubuntu.com/questions/620317/apt-get-update-stuck-connecting-to-security-ubuntu-com
prefer_ipv4(){
sed -i 's,#precedence ::ffff:0:0/96 100,precedence ::ffff:0:0/96 100,' /etc/gai.conf
}
dis_ipv6(){
cat >> /etc/sysctl.conf <<-EOF
net.ipv6.conf.all.disable_ipv6 = 1
#net.ipv6.conf.default.disable_ipv6 = 1
#net.ipv6.conf.lo.disable_ipv6 = 1
EOF
tail -n 3 /etc/sysctl.conf
sudo sysctl -p /etc/sysctl.conf
sudo netplan apply
}
if [ "$ipv6_apt_fix_live_iso" = "yes" ]; then
prefer_ipv4
#dis_ipv6
else
true
fi
}
identify_apt_data_sources(){
if [ -f /etc/apt/sources.list.d/ubuntu.sources ];
then
apt_data_sources_loc="/etc/apt/sources.list.d/ubuntu.sources"
else
apt_data_sources_loc="/etc/apt/sources.list"
fi
}
apt_sources(){
##Initial system apt sources config
script_env="$1" ##chroot, base
source_archive="$2"
cat > /tmp/apt_sources.sh <<-EOF
#!/bin/sh
if [ -f /etc/apt/sources.list.d/ubuntu.sources ];
then
apt_data_sources_loc="/etc/apt/sources.list.d/ubuntu.sources"
cp "\${apt_data_sources_loc}" "\${apt_data_sources_loc}".orig
if [ "${ubuntu_original}" != "${source_archive}" ];
then
sed -i 's,${ubuntu_original},${source_archive},g' "\${apt_data_sources_loc}"
else true
fi
else
apt_data_sources_loc="/etc/apt/sources.list"
cp "\${apt_data_sources_loc}" "\${apt_data_sources_loc}".orig
cat > "\${apt_data_sources_loc}" <<-EOLIST
deb ${ubuntu_original} $ubuntuver main universe restricted multiverse
#deb-src ${ubuntu_original} $ubuntuver main universe restricted multiverse
deb ${ubuntu_original} $ubuntuver-updates main universe restricted multiverse
#deb-src ${ubuntu_original} $ubuntuver-updates main universe restricted multiverse
deb ${ubuntu_original} $ubuntuver-backports main universe restricted multiverse
#deb-src ${ubuntu_original} $ubuntuver-backports main universe restricted multiverse
deb http://security.ubuntu.com/ubuntu $ubuntuver-security main universe restricted multiverse
#deb-src http://security.ubuntu.com/ubuntu $ubuntuver-security main universe restricted multiverse
EOLIST
if [ "${ubuntu_original}" != "${source_archive}" ];
then
cp "\${apt_data_sources_loc}" "\${apt_data_sources_loc}".non-mirror
sed -i 's,${ubuntu_original},${source_archive},g' "\${apt_data_sources_loc}"
else true
fi
fi
EOF
case "${script_env}" in
chroot)
cp /tmp/apt_sources.sh "$mountpoint"/tmp
chroot "$mountpoint" /bin/bash -x /tmp/apt_sources.sh
;;
base)
/bin/bash /tmp/apt_sources.sh
;;
*)
exit 1
;;
esac
}
apt_mirror_source(){
identify_apt_data_sources
identify_apt_mirror(){
##Identify fastest mirror.
echo "Choosing fastest up-to-date ubuntu mirror based on download speed."
apt update
apt install -y curl
ubuntu_mirror=$({
##Choose mirrors that are up-to-date by checking the Last-Modified header.
##https://github.com/actions/runner-images/issues/675#issuecomment-1381837292
{
curl -s http://mirrors.ubuntu.com/"${mirror_archive}".txt | shuf -n 20
} | xargs -I {} sh -c 'echo "$(curl -m 5 -sI {}dists/$(lsb_release -c | cut -f2)-security/Contents-$(dpkg --print-architecture).gz | sed s/\\r\$//|grep Last-Modified|awk -F": " "{ print \$2 }" | LANG=C date -f- -u +%s)" "{}"' | sort -rg | awk '{ if (NR==1) TS=$1; if ($1 == TS) print $2 }'
} | xargs -I {} sh -c 'echo "$(curl -r 0-102400 -m 5 -s -w %{speed_download} -o /dev/null {}ls-lR.gz)" {}' \
| sort -g -r | head -1 | awk '{ print $2 }')
}
identify_apt_mirror
if [ -z "${ubuntu_mirror}" ];
then
echo "No mirror identified. No changes made."
else
if [ "${ubuntu_original}" != "${ubuntu_mirror}" ];
then
cp "${apt_data_sources_loc}" "${apt_data_sources_loc}".non-mirror
sed -i "s,${ubuntu_original},${ubuntu_mirror},g" "${apt_data_sources_loc}"
echo "Selected '${ubuntu_mirror}'."
else
echo "Identified mirror is already selected. No changes made."
fi
fi
}
reinstate_apt(){
script_env="$1" ##chroot, base
cat > /tmp/reinstate_apt.sh <<-EOF
#!/bin/sh
if [ -n "${mirror_archive}" ];
then
if [ -f /etc/apt/sources.list.d/ubuntu.sources ];
then
apt_data_sources_loc="/etc/apt/sources.list.d/ubuntu.sources"
else
apt_data_sources_loc="/etc/apt/sources.list"
fi
cp "\${apt_data_sources_loc}" /tmp
if [ -f "\${apt_data_sources_loc}".non-mirror ];
then
cp "\${apt_data_sources_loc}".non-mirror /tmp
mv "\${apt_data_sources_loc}".non-mirror "\${apt_data_sources_loc}"
else true
fi
else true
fi
if [ -f /etc/apt/apt.conf.d/30apt_error_on_transient ];
then
mv /etc/apt/apt.conf.d/30apt_error_on_transient /tmp ##Remove apt update error on transient in new install.
else true
fi
EOF
case "${script_env}" in
chroot)
cp /tmp/reinstate_apt.sh "$mountpoint"/tmp
chroot "$mountpoint" /bin/bash -x /tmp/reinstate_apt.sh
;;
base)
/bin/bash /tmp/reinstate_apt.sh
;;
*)
exit 1
;;
esac
}
logcopy(){
##Copy install log to new installation.
if [ -d "$mountpoint" ]; then
cp "$log_loc"/"$install_log" "$mountpoint""$log_loc"
echo "Log file copied into new installation at ${log_loc}."
else
echo "No mountpoint dir present. Install log not copied."
fi
}
script_copy(){
##Copy script to new installation
cp "$(readlink -f "$0")" "$mountpoint"/home/"${user}"/
script_new_install_loc=/home/"${user}"/"$(basename "$0")"
chroot "$mountpoint" /bin/bash -x <<-EOCHROOT
chown "${user}":"${user}" "$script_new_install_loc"
chmod +x "$script_new_install_loc"
EOCHROOT
if [ -f "$mountpoint""$script_new_install_loc" ];
then
echo "Install script copied to ${user} home directory in new installation."
else
echo "Error copying install script to new installation."
fi
}
create_zpool_Func(){
##Create zfs pool
pool=$1 ##root, data
##Set pool variables
case "$pool" in
root)
ashift="$zfs_rpool_ashift"
keylocation="prompt"
zpool_password="$zfs_root_password"
zpool_encrypt="$zfs_root_encrypt"
zpool_partition="-part3"
zpool_name="$RPOOL"
topology_pool="${topology_root}"
;;
data)
ashift="$zfs_dpool_ashift"
if [ -n "$zfs_root_password" ];
then
##Set data pool key to use rpool key for single unlock at boot. So data pool uses the same password as the root pool.
case "$zfs_root_encrypt" in
native)
datapool_keyloc="/etc/zfs/$RPOOL.key"
;;
luks)
datapool_keyloc="/etc/cryptsetup-keys.d/$RPOOL.key"
;;
esac
keylocation="file://$datapool_keyloc"
else
if [ -n "$zfs_data_password" ];
then
keylocation="prompt"
else
true
fi
fi
zpool_password="$zfs_data_password"
zpool_encrypt="$zfs_data_encrypt"
zpool_partition=""
zpool_name="$datapool"
topology_pool="${topology_data}"
;;
esac
zpool_create_temp="/tmp/${pool}_creation.sh"
cat > "$zpool_create_temp" <<-EOF
zpool create -f \\
-o ashift="$ashift" \\
-o autotrim=on \\
-O acltype=posixacl \\
-O compression=$zfs_compression \\
-O normalization=formD \\
-O relatime=on \\
-O dnodesize=auto \\
-O xattr=sa \\
EOF
case "$pool" in
root)
echo -O canmount=off \\ >> "$zpool_create_temp"
;;
esac
if [ -n "$zpool_password" ];
then
case "$zpool_encrypt" in
native)
echo "-O encryption=aes-256-gcm -O keylocation=$keylocation -O keyformat=passphrase \\" >> "$zpool_create_temp"
;;
esac
else
true
fi
case "$pool" in
root)
echo "-O mountpoint=/ -R $mountpoint \\" >> "$zpool_create_temp"
;;
data)
echo "-O mountpoint=$datapoolmount \\" >> "$zpool_create_temp"
;;
esac
add_zpool_disks(){
loop_counter="$(mktemp)"
echo 1 > "$loop_counter" ##Assign starting counter value.
while IFS= read -r diskidnum;
do
if [ -n "$zpool_password" ];
then
case "$zpool_encrypt" in
native)
echo "/dev/disk/by-id/${diskidnum}${zpool_partition} \\" >> "$zpool_create_temp"
;;
luks)
echo -e "$zpool_password" | cryptsetup -q luksFormat -c aes-xts-plain64 -s 512 -h sha256 /dev/disk/by-id/${diskidnum}${zpool_partition}
i="$(cat "$loop_counter")"
echo "$i"
luks_dmname_base=luks
luks_dmname=${luks_dmname_base}$i
##Check for luks device name conflict
while [ $(find /dev/mapper -name ${luks_dmname} | wc -l) = 1 ];
do
i=$((i + 1)) ##Increment counter.
luks_dmname=${luks_dmname_base}$i
done
echo -e "$zpool_password" | cryptsetup luksOpen /dev/disk/by-id/${diskidnum}${zpool_partition} "${luks_dmname}"
printf "%s\n" "${luks_dmname}" >> /tmp/luks_dmname_"${pool}".txt
echo "/dev/mapper/${luks_dmname} \\" >> "$zpool_create_temp"
i=$((i + 1)) ##Increment counter.
echo "$i" > "$loop_counter"
;;
*)
echo "zpool_encrypt variable not recognised."
exit 1
;;
esac
else
echo "/dev/disk/by-id/${diskidnum}${zpool_partition} \\" >> "$zpool_create_temp"
fi
done < /tmp/diskid_check_"$pool".txt
sed -i '$s,\\,,' "$zpool_create_temp" ##Remove escape character at end of file.
}
case "${topology_pool}" in
single|raid0)
echo "${zpool_name} \\" >> "$zpool_create_temp"
add_zpool_disks
;;
mirror)
echo "${zpool_name} mirror \\" >> "$zpool_create_temp"
add_zpool_disks
;;
raidz1)
echo "${zpool_name} raidz1 \\" >> "$zpool_create_temp"
add_zpool_disks
;;
raidz2)
echo "${zpool_name} raidz2 \\" >> "$zpool_create_temp"
add_zpool_disks
;;
raidz3)
echo "${zpool_name} raidz3 \\" >> "$zpool_create_temp"
add_zpool_disks
;;
*)
echo "Pool topology not recognised. Check pool topology variable."
exit 1
;;
esac
echo "$zpool_password" | sh "$zpool_create_temp"
}
update_crypttab_Func(){
##Auto unlock using crypttab and keyfile
script_env=$1 ##chroot, base
pool=$2 ##root, data
cat <<-EOH >/tmp/update_crypttab_$pool.sh
##Set pool variables
case "$pool" in
root)
zpool_password="$zfs_root_password"
zpool_partition="-part3"
crypttab_parameters="luks,discard,initramfs"
;;
data)
zpool_password="$zfs_data_password"
zpool_partition=""
crypttab_parameters="luks,discard"
;;
esac
apt install -y cryptsetup
loop_counter="\$(mktemp)"
echo 1 > "\${loop_counter}" ##Assign starting counter value.
while IFS= read -r diskidnum;
do
i="\$(cat "\$loop_counter")"
echo "\$i"
luks_dmname="\$(sed "\${i}q;d" /tmp/luks_dmname_"${pool}".txt)"
blkid_luks="\$(blkid -s UUID -o value /dev/disk/by-id/\${diskidnum}\${zpool_partition})"
echo "\${zpool_password}" | cryptsetup -v luksAddKey /dev/disk/by-uuid/\${blkid_luks} /etc/cryptsetup-keys.d/$RPOOL.key
cryptsetup luksDump /dev/disk/by-uuid/\${blkid_luks}
##https://cryptsetup-team.pages.debian.net/cryptsetup/README.initramfs.html
echo \${luks_dmname} UUID=\${blkid_luks} /etc/cryptsetup-keys.d/$RPOOL.key \${crypttab_parameters} >> /etc/crypttab
i=\$((i + 1)) ##Increment counter.
echo "\$i" > "\$loop_counter"
done < /tmp/diskid_check_"${pool}".txt
##https://cryptsetup-team.pages.debian.net/cryptsetup/README.initramfs.html
sed -i 's,#KEYFILE_PATTERN=,KEYFILE_PATTERN="/etc/cryptsetup-keys.d/*.key",' /etc/cryptsetup-initramfs/conf-hook
EOH
case "${script_env}" in
chroot)
cp /tmp/diskid_check_"${pool}".txt "$mountpoint"/tmp
cp /tmp/update_crypttab_${pool}.sh "$mountpoint"/tmp
chroot "$mountpoint" /bin/bash -x /tmp/update_crypttab_$pool.sh
;;
base)
##Test for live environment.
if grep casper /proc/cmdline >/dev/null 2>&1;
then
echo "Live environment present. Reboot into new installation."
exit 1
else
/bin/bash /tmp/update_crypttab_$pool.sh
fi
;;
*)
exit 1
;;
esac
}
debootstrap_part1_Func(){
export DEBIAN_"${install_warning_level}"
##Error out script on apt update error such as network failure during package download.
##https://bugs.launchpad.net/ubuntu/+source/apt/+bug/1693900
cat > /etc/apt/apt.conf.d/30apt_error_on_transient <<-EOF
APT::Update::Error-Mode "any";
EOF
##Identify apt sources
identify_apt_data_sources
##Identify live iso default archive
#ubuntu_original="$(grep -v '^ *#\|security\|cdrom\|.*gpg' "${apt_data_sources_loc}" | sed '/^[[:space:]]*$/d' | awk '{ print $2 }' | sort -u | grep ubuntu)"
apt_sources "base" "${ubuntu_original}"
if [ -n "${mirror_archive}" ];
then
apt_mirror_source
else
true
fi
cat "${apt_data_sources_loc}"
#sed -i 's,deb http://security,#deb http://security,' "${apt_data_sources_loc}" ##Uncomment to resolve security pocket time out. Security packages are copied to the other pockets frequently, so should still be available for update. See https://wiki.ubuntu.com/SecurityTeam/FAQ
trap 'printf "%s\n%s" "The script has experienced an error during the first apt update. That may have been caused by a queried server not responding in time. Try running the script again." "If the issue is the security server not responding, then comment out the security server in the "${apt_data_sources_loc}". Alternatively, you can uncomment the command that does this in the install script. This affects the temporary live iso only. Not the permanent installation."' ERR
apt update
trap - ERR ##Resets the trap to doing nothing when the script experiences an error. The script will still exit on error if "set -e" is set.
ssh_Func(){
##Setup SSH to allow remote access in live environment
apt install --yes openssh-server
service sshd start
ip addr show scope global | grep inet
}
#ssh_Func
apt-get -yq install debootstrap software-properties-common gdisk zfs-initramfs
if service --status-all | grep -Fq 'zfs-zed'; then
systemctl stop zfs-zed
fi
##Clear partition table
clear_partition_table "root"
partprobe
sleep 2
##Partition disk
partitionsFunc(){
##gdisk hex codes:
##EF02 BIOS boot partitions
##EF00 EFI system
##BE00 Solaris boot
##BF00 Solaris root
##BF01 Solaris /usr & Mac Z
##8200 Linux swap
##8300 Linux file system
##8309 Linux LUKS
##FD00 Linux RAID
case "$topology_root" in
single|mirror)
swap_hex_code="8200"
;;
raid0|raidz*)
swap_hex_code="FD00"
;;
*)
echo "topology_root variable not recognised."
exit 1
;;
esac
if [ -n "$zfs_root_password" ];
then
case "$zfs_root_encrypt" in
native)
root_hex_code="BF00" ##ZFS native encryption
;;
luks)
root_hex_code="FD00" ##luks
;;
*)
echo "zfs_root_encrypt variable not recognised."
exit 1
;;
esac
else
root_hex_code="BF00" ##unencrypted ZFS
fi
while IFS= read -r diskidnum;
do
echo "Creating partitions on disk ${diskidnum}."
##2.3 create bootloader partition
sgdisk -n1:1M:+"${EFI_boot_size}"M -t1:EF00 /dev/disk/by-id/"${diskidnum}"
##2.4 create swap partition
##bug with swap on zfs zvol so use swap on partition:
##https://github.com/zfsonlinux/zfs/issues/7734
##hibernate needs swap at least same size as RAM
##hibernate only works with unencrypted installs
sgdisk -n2:0:+"${swap_size}"M -t2:"${swap_hex_code}" /dev/disk/by-id/"${diskidnum}"
##2.6 Create root pool partition
sgdisk -n3:0:0 -t3:"${root_hex_code}" /dev/disk/by-id/"${diskidnum}"
done < /tmp/diskid_check_"${pool}".txt
partprobe
sleep 2
}
partitionsFunc
}
debootstrap_createzfspools_Func(){
##Create root pool
create_zpool_Func root
##System installation
mountpointsFunc(){
##zfsbootmenu setup for no separate boot pool
##https://github.com/zbm-dev/zfsbootmenu/wiki/Debian-Buster-installation-with-ESP-on-the-zpool-disk
partprobe
sleep 2
##Create filesystem datasets to act as containers
zfs create -o canmount=off -o mountpoint=none "$RPOOL"/ROOT
##Create root filesystem dataset
rootzfs_full_name="ubuntu.$(date +%Y.%m.%d)"
zfs create -o canmount=noauto -o mountpoint=/ "$RPOOL"/ROOT/"$rootzfs_full_name" ##zfsbootmenu debian guide
##assigns canmount=noauto on any file systems with mountpoint=/ (that is, on any additional boot environments you create).
##With ZFS, it is not normally necessary to use a mount command (either mount or zfs mount).
##This situation is an exception because of canmount=noauto.
zfs mount "$RPOOL"/ROOT/"$rootzfs_full_name"
zpool set bootfs="$RPOOL"/ROOT/"$rootzfs_full_name" "$RPOOL"
##Create datasets
##Aim is to separate OS from user data.
##Allows root filesystem to be rolled back without rolling back user data such as logs.
##https://didrocks.fr/2020/06/16/zfs-focus-on-ubuntu-20.04-lts-zsys-dataset-layout/
##https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-3-system-installation
##"-o canmount=off" is for a system directory that should rollback with the rest of the system.
zfs create "$RPOOL"/srv ##server webserver content
zfs create -o canmount=off "$RPOOL"/usr
zfs create "$RPOOL"/usr/local ##locally compiled software
zfs create -o canmount=off "$RPOOL"/var
zfs create -o canmount=off "$RPOOL"/var/lib
zfs create "$RPOOL"/var/games ##game files
zfs create "$RPOOL"/var/log ##log files
zfs create "$RPOOL"/var/mail ##local mails
zfs create "$RPOOL"/var/snap ##snaps handle revisions themselves
zfs create "$RPOOL"/var/spool ##printing tasks
zfs create "$RPOOL"/var/www ##server webserver content
##USERDATA datasets
zfs create "$RPOOL"/home
zfs create -o mountpoint=/root "$RPOOL"/home/root
chmod 700 "$mountpoint"/root
##optional
##exclude from snapshots
zfs create -o com.sun:auto-snapshot=false "$RPOOL"/var/cache
zfs create -o com.sun:auto-snapshot=false "$RPOOL"/var/tmp
chmod 1777 "$mountpoint"/var/tmp
zfs create -o com.sun:auto-snapshot=false "$RPOOL"/var/lib/docker ##Docker manages its own datasets & snapshots
##Mount a tempfs at /run
mkdir "$mountpoint"/run
mount -t tmpfs tmpfs "$mountpoint"/run
}
mountpointsFunc
}
debootstrap_installminsys_Func(){
##Install minimum system
##drivesizecheck
FREE="$(df -k --output=avail "$mountpoint" | tail -n1)"
if [ "$FREE" -lt 5242880 ]; then # 15G = 15728640 = 15*1024*1024k
echo "Less than 5 GBs free!"
exit 1
fi
debootstrap "$ubuntuver" "$mountpoint"
}
zfsbootmenu_install_config_Func(){
zfsbootmenu_install_config_loc="/tmp/zfsbootmenu_install_config.sh"
cat <<-EOH >"${zfsbootmenu_install_config_loc}"
#!/bin/bash
set -euo pipefail
set -x
apt update
compile_zbm_git(){
##https://github.com/zbm-dev/zfsbootmenu/blob/master/testing/helpers/chroot-ubuntu.sh