armbian_rootenc_setup.sh 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. #!/bin/bash
  2. PATH="$PATH:/usr/sbin:/sbin"
  3. RED="\e[31;1m" GREEN="\e[32;1m" YELLOW="\e[33;1m" BLUE="\e[34;1m" PURPLE="\e[35;1m" RESET="\e[0m"
  4. PROGNAME=$(basename $0)
  5. TITLE='Armbian Encrypted Root Filesystem Setup'
  6. CONFIG_VARS='
  7. ARMBIAN_IMAGE
  8. BOOTPART_LABEL
  9. ROOTFS_NAME
  10. DISK_PASSWD
  11. UNLOCKING_USERHOST
  12. SERIAL_CONSOLE
  13. IP_ADDRESS
  14. NETMASK
  15. ADD_ALL_MODS
  16. ADD_MODS
  17. USE_LOCAL_AUTHORIZED_KEYS
  18. USB_GADGET
  19. ETH_DEV
  20. '
  21. STATES='
  22. card_partitioned
  23. bootpart_copied
  24. bootpart_label_created
  25. rootpart_copied
  26. target_configured
  27. '
  28. USER_OPTS_INFO="
  29. NO_CLEANUP - no cleanup of mounts after program run
  30. FORCE_REBUILD - force full rebuild
  31. FORCE_RECONFIGURE - force reconfiguration
  32. FORCE_REFORMAT_ROOT - force reformat of encrypted root partition
  33. ADD_ALL_MODS - add all currently loaded modules to initramfs
  34. ADD_MODS y add specified modules to initramfs
  35. USE_LOCAL_AUTHORIZED_KEYS - use local 'authorized_keys' file if available
  36. PARTITION_ONLY - partition and create filesystems only
  37. ERASE - zero boot sector, boot partition and beginning of root partition
  38. ROOTENC_REUSE_FS - reuse existing filesystems (for development only)
  39. ROOTENC_TESTING - developer tweaks
  40. ROOTENC_PAUSE - pause along the way
  41. ROOTENC_IGNORE_APT_ERRORS - continue even if apt update fails
  42. SERIAL_CONSOLE - enable disk unlocking via serial console
  43. USB_GADGET - enable disk unlocking via SSH over USB (g_ether)
  44. ETH_DEV - select the network device manually (default: auto)
  45. VERBOSE - produce verbose output
  46. "
  47. RSYNC_VERBOSITY='--info=progress2'
  48. print_help() {
  49. echo " ${PROGNAME^^}: Create an Armbian image with encrypted root filesystem
  50. USAGE: $PROGNAME [options] <target device name (e.g. SD card)>
  51. OPTIONS: '-h' Print this help message
  52. '-C' Don't perform unmounts or clean up build directory at exit
  53. '-d' Produce tons of debugging output
  54. '-f' Force reconfiguration of target system
  55. '-F' Force a complete rebuild of target system
  56. '-m' Add all currently loaded modules to the initramfs (may help
  57. fix blank screen on bootup issues)
  58. '-o' Add specified modules to the initramfs (comma-separated list)
  59. '-M' Mount source and target systems and exit
  60. '-U' Unmount source and target systems and exit
  61. '-p' Partition and create filesystems only. Do not copy data
  62. '-R' Force reformat of encrypted root partition
  63. '-s' Use 'authorized_keys' file from working directory, if available
  64. (see below)
  65. '-v' Be more verbose
  66. '-u' Perform an 'apt upgrade' after each 'apt update'
  67. '-z' Erase boot sector and first partition of SD card before partitioning
  68. (an extra paranoia step, but it can’t hurt)
  69. For non-interactive operation, set the following variables in your environment
  70. or on the command line:
  71. ARMBIAN_IMAGE - Armbian image file
  72. ROOTFS_NAME - device mapper name of target root filesystem
  73. IP_ADDRESS - IP address of target (set to 'dhcp' for dynamic IP
  74. or 'none' to disable remote SSH unlocking support)
  75. NETMASK - Netmask of target. Defaults to 255.255.255.0
  76. BOOTPART_LABEL - Boot partition label of target
  77. DISK_PASSWD - Disk password of target root filesystem
  78. UNLOCKING_USERHOST - USER@HOST of remote unlocking host
  79. SERIAL_CONSOLE - Set this to 'y' to enable disk unlocking from the
  80. serial console, or 'n' to disable
  81. USB_GADGET - Set this to 'y' to enable disk unlocking via SSH over
  82. USB (g_ether), or 'n' to disable
  83. ETH_DEV - Select the network device manually (default: auto)
  84. INSTRUCTIONS FOR USE
  85. This script must be invoked as superuser on a running Armbian system.
  86. Packages will be installed using APT, so the system must be Internet-
  87. connected and its clock correctly set.
  88. If remote unlocking via SSH is desired, the unlocking host must be reachable.
  89. Alternatively, SSH public keys for the unlocking host or hosts may be
  90. provided in the file 'authorized_keys' in the current directory. This file
  91. has the same format as a standard SSH 'authorized_keys' file.
  92. Architecture of host and target (e.g. 64-bit or 32-bit ARM) must be the same.
  93. For best results, the host and target hardware should also be identical or
  94. similar. Building on a host with more memory than the target, for example,
  95. may lead to disk unlocking failure on the target. For most users, who’ll be
  96. building for the currently-running board, this point is a non-issue.
  97. 1. Place an Armbian boot image file for the target system in the current
  98. directory. For best results, the image file should match the Debian
  99. or Ubuntu release of the host system.
  100. 2. Insert a USB card reader with a blank micro-SD card for the target
  101. system into the host’s USB port.
  102. 3. Determine the SD card’s device name using 'dmesg' or 'lsblk'.
  103. 4. Invoke the script with the device name as argument. If any options
  104. are desired, they must precede the device name.
  105. If the board has an eMMC, it may be used as the target device instead of
  106. an SD card. Depending on your platform, you may need to run ‘armbian-config’
  107. and select ‘Install to internal storage’ -> ‘Install/Update the bootloader
  108. on eMMC’ to enable booting from the eMMC." | less
  109. }
  110. pause() {
  111. echo -ne $GREEN'(Press any key to continue)'$RESET >&$stderr_dup
  112. read
  113. no_fmsg=1
  114. }
  115. _debug_pause() { [ "$ROOTENC_PAUSE" ] && pause; true; }
  116. imsg() { echo -e "$1" >&$stdout_dup; no_fmsg=1; }
  117. imsg_nonl() { echo -ne "$1" >&$stdout_dup; no_fmsg=1; }
  118. tmsg() {
  119. no_fmsg=1
  120. [ "$ROOTENC_TESTING" ] || return 0
  121. echo -e "$1" >&$stdout_dup
  122. }
  123. warn() { echo -e "$YELLOW$1$RESET" >&$stdout_dup; no_fmsg=1; }
  124. warn_nonl() { echo -ne "$YELLOW$1$RESET" >&$stdout_dup; no_fmsg=1; }
  125. rmsg() { echo -e "$RED$1$RESET" >&$stdout_dup; no_fmsg=1; }
  126. gmsg() { echo -e "$GREEN$1$RESET" >&$stdout_dup; no_fmsg=1; }
  127. pu_msg() { echo -e "$PURPLE$1$RESET" >&$stdout_dup; no_fmsg=1; }
  128. do_partprobe() {
  129. if [ "$VERBOSE" ]; then
  130. partprobe
  131. else
  132. partprobe 2>/dev/null
  133. fi
  134. no_fmsg=1
  135. }
  136. _show_output() { [ "$VERBOSE" ] || exec 1>&$stdout_dup 2>&$stderr_dup; }
  137. _hide_output() { [ "$VERBOSE" ] || exec &>'/dev/null'; }
  138. bailout() { exit; }
  139. die() {
  140. echo -e "$RED$1$RESET" >&$stdout_dup
  141. no_fmsg=1
  142. exit 1
  143. }
  144. _return_handler() {
  145. local funcname=${FUNCNAME[1]} exitval=$? res
  146. if [ "${funcname:0:1}" == '_' -o "$no_fmsg" ]; then
  147. no_fmsg=
  148. return 0
  149. fi
  150. if [ "$exitval" -eq 0 ]; then res='OK'; else res="False ($exitval)"; fi
  151. printf "$BLUE%-32s $res$RESET\n" "$funcname" >&$stdout_dup
  152. }
  153. _sigint_handler() {
  154. warn "\nExiting at user request"
  155. exit 1
  156. }
  157. _error_handler() {
  158. local exitval=$?
  159. warn "$(basename ${BASH_SOURCE[1]}):${BASH_LINENO[0]}: ${FUNCNAME[1]}() failed at command '$BASH_COMMAND'"
  160. rmsg "$SCRIPT_DESC exiting with error ($exitval)"
  161. }
  162. _do_header() {
  163. echo
  164. local reply
  165. if banner=$(toilet --filter=border --filter=gay --width=80 --font=term "*** $TITLE ***" 2>/dev/null); then
  166. while read reply; do
  167. echo -e " $reply"
  168. done <<-EOF
  169. $banner
  170. EOF
  171. else
  172. echo -n ' '
  173. echo $TITLE
  174. echo
  175. fi
  176. echo " For detailed usage information,"
  177. echo " invoke with the '-h' switch"
  178. echo
  179. }
  180. _warn_user_opts() {
  181. local out opt have_optarg text
  182. while read opt have_optarg text; do
  183. [ "$opt" ] || continue
  184. if [ "${!opt}" ]; then
  185. if [ $have_optarg == 'y' ]; then
  186. out+=" + $text (${!opt})\n"
  187. else
  188. out+=" + $text\n"
  189. fi
  190. fi
  191. done <<<$USER_OPTS_INFO
  192. if [ "$out" ]; then
  193. warn "\n The following user options are in effect:"
  194. warn_nonl "${out}"
  195. fi
  196. }
  197. _set_host_vars() {
  198. BUILD_DIR='armbian_rootenc_build'
  199. SRC_ROOT="$BUILD_DIR/src"
  200. BOOT_ROOT="$BUILD_DIR/boot"
  201. TARGET_ROOT="$BUILD_DIR/target"
  202. CONFIG_VARS_FILE="$BOOT_ROOT/.rootenc_config_vars"
  203. host_distro=$(lsb_release --short --codename)
  204. host_kernel=$(ls '/boot' | egrep '^vmlinu[xz]') # allow 'vmlinux' or 'vmlinuz'
  205. }
  206. check_sdcard_name_and_params() {
  207. local dev chk
  208. dev=$1
  209. [ "$dev" ] || die "You must supply a device name"
  210. [ "${dev:0:5}" == '/dev/' ] || dev="/dev/$dev"
  211. [ -e "$dev" ] || die "$dev does not exist"
  212. chk="$(lsblk --noheadings --nodeps --list --output=TYPE $dev 2>/dev/null)"
  213. [ "$chk" != 'disk' -a "$chk" != 'loop' ] && {
  214. [ "$chk" == 'part' ] && die "$dev is a partition, not a block device!"
  215. die "$dev is not a block device!"
  216. }
  217. local pttype size oversize removable non_removable part_sep
  218. pttype=$(blkid --output=udev $dev | grep TYPE | cut -d '=' -f2)
  219. size="$(lsblk --noheadings --nodeps --list --output=SIZE --bytes $dev 2>/dev/null)"
  220. removable="$(lsblk --noheadings --nodeps --list --output=RM $dev 2>/dev/null)"
  221. oversize=$([ $size -gt 137438953472 ] && echo 'Size is > 128GiB') || true
  222. non_removable=$([ $removable -ne 0 ] || echo 'Device is non-removable')
  223. SD_INFO="$(lsblk --noheadings --nodeps --list --output=VENDOR,MODEL,SIZE $dev 2>/dev/null)"
  224. SD_INFO=${SD_INFO// / }
  225. if [ "$oversize" -o "$non_removable" ]; then
  226. warn " $dev ($SD_INFO) doesn’t appear to be an SD card"
  227. warn " for the following reasons:"
  228. if [ "$non_removable" ]; then warn " $non_removable"; fi
  229. if [ "$oversize" ]; then warn " $oversize"; fi
  230. _user_confirm ' Are you sure this is the device you want to install on?' 'no'
  231. fi
  232. SDCARD_DEVNAME=${dev:5}
  233. [ "${SDCARD_DEVNAME%[0-9]}" == $SDCARD_DEVNAME ] || part_sep='p'
  234. BOOT_DEVNAME=$SDCARD_DEVNAME${part_sep}1
  235. ROOT_DEVNAME=$SDCARD_DEVNAME${part_sep}2
  236. [ "$SDCARD_DEVNAME" ] || die 'You must supply a device name for the SD card!'
  237. pu_msg "Will write to target $dev ($SD_INFO)"
  238. }
  239. _get_user_var() {
  240. local var desc dfl prompt pat pat_errmsg vtest cprompt seen_prompt reply redo
  241. var=$1 desc=$2 dfl=$3 prompt=$4 pat=$5 pat_errmsg=$6 vtest=$7
  242. [ "$MOUNT_TARGET_ONLY" ] && [[ ! $var =~ ^(DISK_PASSWD|ROOTFS_NAME)$ ]] && {
  243. eval "$var=$dfl"
  244. return 0
  245. }
  246. if [ "$pat" == 'bool' ]; then READOPTS='-n1' READNL="\n"; else READOPTS='' READNL=''; fi
  247. while true; do
  248. if [ -z "${!var}" -o "$seen_prompt" -o "$redo" ]; then
  249. if [ "$seen_prompt" ]; then
  250. echo -n " Enter $desc: "
  251. else
  252. cprompt=
  253. while read reply; do
  254. cprompt+=" ${reply## }\n"
  255. done <<-EOF
  256. $prompt
  257. EOF
  258. echo
  259. if [ "$dfl" ]; then
  260. printf "${cprompt:0:-2} " "$dfl"
  261. else
  262. echo -ne "${cprompt:0:-2} "
  263. fi
  264. seen_prompt=1
  265. fi
  266. eval "read $READOPTS $var"; echo -ne "$READNL"
  267. fi
  268. redo=1
  269. if [ -z "${!var}" -a "$dfl" ]; then eval "$var=$dfl"; fi
  270. [ "${!var}" ] || {
  271. rmsg " $desc must not be empty"
  272. continue
  273. }
  274. if [ "$pat" ]; then
  275. local rpat=$pat
  276. if [ "$pat" == 'bool' ]; then
  277. rpat='^[ynYN]*$'
  278. pat_errmsg="You must type 'y' or 'n'"
  279. fi
  280. echo "${!var}" | egrep -qi "$rpat" || {
  281. rmsg " ${!var}: $pat_errmsg"
  282. continue
  283. }
  284. if [ "$pat" == 'bool' ]; then
  285. if [[ ${!var} =~ ^[Yy]$ ]]; then eval "$var=yes"; else eval "$var="; fi
  286. fi
  287. fi
  288. if [ "$vtest" ]; then
  289. $vtest || continue
  290. fi
  291. break
  292. done
  293. }
  294. _check_eth_dev() {
  295. if [ "$ETH_DEV" ]; then
  296. ip link show $ETH_DEV || {
  297. warn "User-selected network device '$ETH_DEV' could not be found"
  298. _user_confirm "Are you sure you want to continue?" "no"
  299. }
  300. fi
  301. }
  302. _get_user_vars() {
  303. local dq='[0-9]{1,3}'
  304. _get_user_var 'IP_ADDRESS' 'IP address' '' \
  305. "Enter the IP address of the target machine.
  306. Enter 'dhcp' for a dynamic IP or 'none' for no remote SSH unlocking support
  307. IP address:" \
  308. "^(dhcp|none|$dq\.$dq\.$dq\.$dq)$" \
  309. 'malformed IP address'
  310. IP_ADDRESS=${IP_ADDRESS,,}
  311. [[ $IP_ADDRESS =~ ^(dhcp|none)$ ]] || {
  312. _get_user_var 'NETMASK' 'netmask' '255.255.255.0' \
  313. "Enter the netmask of the target machine,
  314. or hit ENTER for the default (%s): " \
  315. "^($dq\.$dq\.$dq\.$dq)$" \
  316. 'malformed netmask'
  317. }
  318. _get_user_var 'BOOTPART_LABEL' 'boot partition label' 'ARMBIAN_BOOT' \
  319. "Enter a boot partition label for the target machine,
  320. or hit ENTER for the default (%s): " \
  321. '^[A-Za-z0-9_]{1,16}$' \
  322. "Label must contain no more than 16 characters in the set 'A-Za-z0-9_'"
  323. _get_user_var 'ROOTFS_NAME' 'root filesystem device name' 'rootfs' \
  324. "Enter a device name for the encrypted root filesystem,
  325. or hit ENTER for the default (%s):" \
  326. '^[a-z0-9_]{1,48}$' \
  327. "Name must contain no more than 48 characters in the set 'a-z0-9_'" \
  328. '_test_rootfs_mounted'
  329. if [ "$MOUNT_TARGET_ONLY" ]; then
  330. local pw_prompt="Enter disk password:"
  331. else
  332. local pw_prompt="Choose a simple disk password for the installation process.
  333. Once your encrypted system is up and running, you can change
  334. the password using the 'cryptsetup' command.
  335. Enter password:"
  336. fi
  337. _get_user_var 'DISK_PASSWD' 'disk password' '' "$pw_prompt" \
  338. '^[A-Za-z0-9_ ]{1,10}$' \
  339. "Temporary disk password must contain no more than 10 characters in the set 'A-Za-z0-9_ '"
  340. if [ "$IP_ADDRESS" == 'none' ]; then
  341. UNLOCKING_USERHOST=
  342. elif [ -e 'authorized_keys' -a "$USE_LOCAL_AUTHORIZED_KEYS" ]; then
  343. UNLOCKING_USERHOST=
  344. else
  345. _get_user_var 'UNLOCKING_USERHOST' 'USER@HOST' '' \
  346. "Enter the user@host of the machine you'll be unlocking from:" \
  347. '\S+@\S+' \
  348. 'malformed USER@HOST' \
  349. '_test_unlocking_host_available'
  350. fi
  351. _get_user_var 'SERIAL_CONSOLE' 'serial console unlocking' '' \
  352. "Unlock the disk from the serial console. WARNING: enabling this will
  353. make it impossible to unlock the disk using the keyboard and monitor,
  354. though unlocking via SSH will still work.
  355. Enable unlocking via serial console? (y/n):" \
  356. 'bool'
  357. _get_user_var 'USB_GADGET' 'disk unlocking via SSH over USB (g_ether)' '' \
  358. "Unlock the disk via SSH over USB (g_ether). Enable this only if your board
  359. supports USB gadget mode, i.e. if it has a USB OTG port. WARNING: enabling this
  360. will make it impossible to unlock the disk over the Ethernet interface (eth0).
  361. Enable unlocking via SSH over USB? (y/n):" \
  362. 'bool'
  363. true
  364. }
  365. _test_rootfs_mounted() {
  366. [ -e "/dev/mapper/$ROOTFS_NAME" ] && {
  367. local mnt=$(lsblk --list --noheadings --output=MOUNTPOINT /dev/mapper/$ROOTFS_NAME)
  368. [ "$mnt" ] && {
  369. rmsg " Device '$ROOTFS_NAME' is in use and mounted on $mnt"
  370. return 1
  371. }
  372. }
  373. return 0
  374. }
  375. _test_unlocking_host_available() {
  376. local ul_host=${UNLOCKING_USERHOST#*@}
  377. ping -c1 $ul_host &>/dev/null || {
  378. rmsg " Unable to ping host '$ul_host'"
  379. return 1
  380. }
  381. }
  382. _test_sdcard_mounted() {
  383. local chk="$(lsblk --noheadings --list --output=MOUNTPOINT /dev/$SDCARD_DEVNAME)"
  384. [ -z "$chk" ] || {
  385. lsblk --output=NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT /dev/$SDCARD_DEVNAME
  386. die "Device /dev/$SDCARD_DEVNAME has mounted partitions!"
  387. }
  388. }
  389. get_authorized_keys() {
  390. if [ -f 'authorized_keys' ]; then
  391. rm -rf /tmp/armbian_rootenc_build-authorized_keys_file
  392. mv 'authorized_keys' /tmp/armbian_rootenc_build-authorized_keys_file
  393. mkdir 'authorized_keys'
  394. mv /tmp/armbian_rootenc_build-authorized_keys_file 'authorized_keys'
  395. fi
  396. [ -e 'authorized_keys' -a "$USE_LOCAL_AUTHORIZED_KEYS" ] || {
  397. mkdir -p 'authorized_keys'
  398. rsync "$UNLOCKING_USERHOST:.ssh/id_*.pub" 'authorized_keys'
  399. }
  400. }
  401. _apt_update() {
  402. [ "$ROOTENC_IGNORE_APT_ERRORS" ] && set +e
  403. apt --yes update
  404. [ "$APT_UPGRADE" ] && apt --yes upgrade
  405. [ "$ROOTENC_IGNORE_APT_ERRORS" ] && set -e
  406. true
  407. }
  408. _print_pkgs_to_install() {
  409. local pkgs pkgs_ssh
  410. case $1 in
  411. 'host')
  412. case "$host_distro" in
  413. bionic|buster|focal|bullseye|jammy|bookworm|noble|trixie)
  414. pkgs='cryptsetup ed' ;;
  415. *)
  416. pkgs='cryptsetup ed'
  417. warn "Warning: unrecognized host distribution '$host_distro'" ;;
  418. esac ;;
  419. 'target')
  420. case "$target_distro" in
  421. buster|focal|bullseye|jammy|bookworm|noble|trixie)
  422. pkgs='cryptsetup-initramfs' pkgs_ssh='dropbear-initramfs' ;;
  423. bionic)
  424. pkgs='cryptsetup' pkgs_ssh='dropbear-initramfs' ;;
  425. *)
  426. pkgs='cryptsetup-initramfs' pkgs_ssh='dropbear-initramfs'
  427. warn "Warning: unrecognized target distribution '$target_distro'" ;;
  428. esac
  429. [ "$IP_ADDRESS" != 'none' ] && pkgs+=" $pkgs_ssh" ;;
  430. esac
  431. for i in $pkgs; do
  432. dpkg -l $i 2>/dev/null | grep -q ^ii || echo $i
  433. done
  434. }
  435. apt_install_host_pkgs() {
  436. local pkgs=$(_print_pkgs_to_install 'host')
  437. [ "$pkgs" ] && {
  438. _apt_update
  439. apt --yes install $pkgs
  440. }
  441. true
  442. }
  443. create_build_dir() {
  444. mkdir -p $BUILD_DIR
  445. mkdir -p $SRC_ROOT
  446. mkdir -p $BOOT_ROOT
  447. mkdir -p $TARGET_ROOT
  448. }
  449. umount_target() {
  450. for i in $BOOT_ROOT $TARGET_ROOT; do
  451. while mountpoint -q $i; do
  452. umount -Rl $i
  453. done
  454. done
  455. }
  456. remove_build_dir() {
  457. [ -d $TARGET_ROOT ] && rmdir $TARGET_ROOT
  458. [ -d $BOOT_ROOT ] && rmdir $BOOT_ROOT
  459. [ -d $SRC_ROOT ] && rmdir $SRC_ROOT
  460. [ -d $BUILD_DIR ] && rmdir $BUILD_DIR
  461. true
  462. }
  463. _get_device_maps() {
  464. local dm_type=$1 varname="device_maps_$1" dm_name ls mp
  465. eval "$varname="
  466. while read dm_name; do
  467. [ "$dm_name" == 'No devices found' ] && break
  468. fstype="$(lsblk --noheadings --nodeps -o fstype "/dev/mapper/$dm_name")"
  469. [ "$fstype" == 'ext4' ] || continue
  470. ls=$(findmnt -n --source "/dev/mapper/$dm_name" | cut -f 1 -d ' ')
  471. if [ "$ls" -a "$dm_type" == 'mounted_on_target' ]; then
  472. while read mp; do
  473. if [ "${mp: -${#TARGET_ROOT}}" == "$TARGET_ROOT" ]; then
  474. eval "$varname+='$dm_name '"
  475. fi
  476. done <<<"$ls"
  477. elif [ -z "$ls" -a "$dm_type" == 'unmounted' ]; then
  478. eval "$varname+='$dm_name '"
  479. fi
  480. done <<<$(dmsetup ls | cut -f 1)
  481. tmsg "$varname=[${!varname}]"
  482. }
  483. _close_device_maps() {
  484. local dm_type=$1
  485. local varname="device_maps_${dm_type}"
  486. for i in ${!varname}; do
  487. tmsg "closing $i"
  488. cryptsetup status $i > '/dev/null' && cryptsetup luksClose $i
  489. done
  490. true
  491. }
  492. _preclean() {
  493. close_loopmount
  494. _get_device_maps 'unmounted'
  495. _close_device_maps 'unmounted'
  496. _get_device_maps 'mounted_on_target'
  497. umount_target
  498. _close_device_maps 'mounted_on_target'
  499. remove_build_dir
  500. }
  501. _clean() {
  502. pu_msg "Cleaning up, please wait..."
  503. _show_output
  504. close_loopmount
  505. _get_device_maps 'mounted_on_target'
  506. umount_target
  507. update_config_vars_file
  508. _close_device_maps 'mounted_on_target'
  509. [ -e 'authorized_keys' -a -z "$USE_LOCAL_AUTHORIZED_KEYS" ] && shred -u 'authorized_keys'
  510. remove_build_dir
  511. }
  512. get_armbian_image() {
  513. ARMBIAN_IMAGE="$(echo *.img)"
  514. [ "$ARMBIAN_IMAGE" != '*.img' ] || {
  515. die 'No image file found: You must place an Armbian image in the current directory!'
  516. }
  517. local count=$(echo "$ARMBIAN_IMAGE" | wc -w)
  518. [ "$count" == 1 ] || die "More than one image file present!:\n$ARMBIAN_IMAGE"
  519. }
  520. get_partition_info() {
  521. local cmdout
  522. cmdout=$(fdisk --list --output='Start' $ARMBIAN_IMAGE)
  523. partition_table_type=$(echo "$cmdout" | grep '^Disklabel' | cut --delimiter=' ' --fields=3)
  524. case $partition_table_type in
  525. 'gpt')
  526. cmdout=$(fdisk --list-details --output='Start,Type-UUID' $ARMBIAN_IMAGE)
  527. read start_sector partition_type_uuid <<<$(echo "$cmdout" | tail --lines=1)
  528. ;;
  529. 'dos')
  530. read start_sector <<<$(echo "$cmdout" | tail --lines=1)
  531. ;;
  532. *) die "$partition_table_type: unrecognized partition table type!" ;;
  533. esac
  534. [ $((start_sector % 8)) -eq 0 ] || die "start sector: $start_sector: first partition misaligned!"
  535. boot_partition_sectors=409600 # 200MB
  536. pu_msg "Image partition table type: ${partition_table_type^^}"
  537. }
  538. _confirm_user_vars() {
  539. echo
  540. echo " Armbian image: $ARMBIAN_IMAGE"
  541. echo " Target device: /dev/$SDCARD_DEVNAME ($SD_INFO)"
  542. echo " Root filesystem device name: /dev/mapper/$ROOTFS_NAME"
  543. echo " Target IP address: $IP_ADDRESS"
  544. [ "$NETMASK" ] && echo " Target netmask: $NETMASK"
  545. echo " Boot partition label: $BOOTPART_LABEL"
  546. echo " Disk password: $DISK_PASSWD"
  547. [ "$UNLOCKING_USERHOST" ] && echo " user@host of unlocking host: $UNLOCKING_USERHOST"
  548. echo " Serial console unlocking: ${SERIAL_CONSOLE:-no}"
  549. echo " SSH over USB unlocking: ${USB_GADGET:-no}"
  550. echo " Ethernet device: ${ETH_DEV:-auto}"
  551. echo
  552. _user_confirm ' Are these settings correct?' 'yes'
  553. }
  554. setup_loopmount() {
  555. LOOP_DEV=$(losetup -f)
  556. losetup -P $LOOP_DEV $ARMBIAN_IMAGE
  557. mount ${LOOP_DEV}p1 $SRC_ROOT
  558. }
  559. _umount_with_check() {
  560. mountpoint -q $1 && umount $1
  561. }
  562. update_config_vars_file() {
  563. mount "/dev/$BOOT_DEVNAME" $BOOT_ROOT
  564. _print_config_vars $CONFIG_VARS_FILE
  565. umount $BOOT_ROOT
  566. }
  567. _print_states() {
  568. for i in $STATES; do
  569. echo $i: ${!i}
  570. done
  571. }
  572. _update_state_from_config_vars() {
  573. [ -e $CONFIG_VARS_FILE ] || return 0
  574. local reply
  575. while read reply; do
  576. eval "c$reply"
  577. done <<<$(cat $CONFIG_VARS_FILE)
  578. local saved_states cfgvar_changed
  579. saved_states="$(_print_states)"
  580. cfgvar_changed=
  581. [ $cARMBIAN_IMAGE != $ARMBIAN_IMAGE ] && cfgvar_changed+=' ARMBIAN_IMAGE' card_partitioned='n'
  582. [ $cBOOTPART_LABEL != $BOOTPART_LABEL ] && cfgvar_changed+=' BOOTPART_LABEL' bootpart_label_created='n'
  583. [ $cROOTFS_NAME != $ROOTFS_NAME ] && cfgvar_changed+=' ROOTFS_NAME' target_configured='n'
  584. [ $cDISK_PASSWD != $DISK_PASSWD ] && cfgvar_changed+=' DISK_PASSWD' rootpart_copied='n'
  585. [ "$UNLOCKING_USERHOST" -a "$cUNLOCKING_USERHOST" != "$UNLOCKING_USERHOST" ] && {
  586. cfgvar_changed+=' UNLOCKING_USERHOST' target_configured='n'
  587. }
  588. [ "$cSERIAL_CONSOLE" != "$SERIAL_CONSOLE" ] && {
  589. cfgvar_changed+=' SERIAL_CONSOLE' target_configured='n'
  590. }
  591. [ $cIP_ADDRESS != $IP_ADDRESS ] && cfgvar_changed+=' IP_ADDRESS' target_configured='n'
  592. [ "$cNETMASK" != "$NETMASK" ] && cfgvar_changed+=' NETMASK' target_configured='n'
  593. [ "$cADD_ALL_MODS" != "$ADD_ALL_MODS" ] && cfgvar_changed+=' ADD_ALL_MODS' target_configured='n'
  594. [ "$cADD_MODS" != "$ADD_MODS" ] && cfgvar_changed+=' ADD_MODS' target_configured='n'
  595. [ "$cUSB_GADGET" != "$USB_GADGET" ] && cfgvar_changed+=' USB_GADGET' target_configured='n'
  596. [ "$cETH_DEV" != "$ETH_DEV" ] && cfgvar_changed+=' ETH_DEV' target_configured='n'
  597. [ "$IP_ADDRESS" -a "$cUSE_LOCAL_AUTHORIZED_KEYS" != "$USE_LOCAL_AUTHORIZED_KEYS" ] && {
  598. cfgvar_changed+=' USE_LOCAL_AUTHORIZED_KEYS' target_configured='n'
  599. }
  600. [ $card_partitioned == 'n' ] && {
  601. bootpart_copied='n'
  602. bootpart_label_created='n'
  603. rootpart_copied='n'
  604. target_configured='n'
  605. }
  606. [ $bootpart_copied == 'n' ] && bootpart_label_created='n'
  607. [ $rootpart_copied == 'n' ] && target_configured='n'
  608. [ "$saved_states" != "$(_print_states)" ] && {
  609. warn "Install state altered due to changed config vars:$cfgvar_changed"
  610. for i in $STATES; do
  611. if [ "${!i}" == 'n' ]; then
  612. imsg " $i: ${RED}no$RESET"
  613. else
  614. imsg " $i: ${GREEN}yes$RESET"
  615. fi
  616. done
  617. _delete_state_files
  618. }
  619. true
  620. }
  621. _add_state_file() {
  622. local state=$1 cmd=$2
  623. if [ "$cmd" == 'target' ]; then
  624. touch "$TARGET_ROOT/boot/.rootenc_install_state/$state"
  625. else
  626. [ "$cmd" == 'mount' ] && mount "/dev/$BOOT_DEVNAME" $BOOT_ROOT
  627. mkdir -p "$BOOT_ROOT/.rootenc_install_state"
  628. touch "$BOOT_ROOT/.rootenc_install_state/$state"
  629. [ "$cmd" == 'mount' ] && umount $BOOT_ROOT
  630. fi
  631. eval "$state='y'"
  632. tmsg "added state file '$state'"
  633. }
  634. _delete_state_files() {
  635. for i in $STATES; do
  636. local fn="$BOOT_ROOT/.rootenc_install_state/$i"
  637. [ ${!i} == 'n' -a -e $fn ] && /bin/rm $fn
  638. done
  639. true
  640. }
  641. _get_state_from_state_files() {
  642. for i in $STATES; do
  643. if [ -e "$BOOT_ROOT/.rootenc_install_state/$i" ]; then
  644. eval "$i=y"
  645. else
  646. eval "$i=n"
  647. fi
  648. done
  649. }
  650. _print_state_from_state_files() {
  651. imsg 'Install state:'
  652. for i in $STATES; do
  653. if [ -e "$BOOT_ROOT/.rootenc_install_state/$i" ]; then
  654. imsg " $i: ${GREEN}yes$RESET"
  655. else
  656. imsg " $i: ${RED}no$RESET"
  657. fi
  658. done
  659. }
  660. check_install_state() {
  661. for i in $STATES; do eval "$i=n"; done
  662. if [ "$FORCE_REBUILD" ]; then
  663. return
  664. else
  665. do_partprobe
  666. lsblk --noheadings --list /dev/$SDCARD_DEVNAME -o 'NAME' | grep -q $BOOT_DEVNAME || return 0
  667. lsblk --noheadings --list /dev/$BOOT_DEVNAME -o 'FSTYPE' | grep -q 'ext4' || return 0
  668. mount "/dev/$BOOT_DEVNAME" $BOOT_ROOT
  669. _get_state_from_state_files
  670. if [ "$target_configured" == 'y' -a "$FORCE_RECONFIGURE" ]; then
  671. target_configured='n'
  672. _delete_state_files
  673. fi
  674. _print_state_from_state_files
  675. _update_state_from_config_vars
  676. _umount_with_check $BOOT_ROOT
  677. fi
  678. }
  679. close_loopmount() {
  680. while mountpoint -q $SRC_ROOT; do
  681. umount $SRC_ROOT
  682. done
  683. for i in $(losetup --noheadings --raw --list -j $ARMBIAN_IMAGE | awk '{print $1}'); do
  684. losetup -d $i
  685. done
  686. }
  687. _user_confirm() {
  688. local prompt1 prompt2 dfl_action reply
  689. prompt1=$1 dfl_action=$2
  690. if [ "$dfl_action" == 'yes' ]; then
  691. prompt2='(Y/n)'
  692. else
  693. prompt2='(y/N)'
  694. fi
  695. imsg_nonl "$prompt1 $prompt2 "
  696. read -n1 reply
  697. [ "$reply" ] && imsg ''
  698. [ "$dfl_action" == 'yes' -a -z "$reply" ] && return
  699. [ "$reply" == 'y' -o "$reply" == 'Y' ] && return
  700. warn "Exiting at user request"
  701. exit 1
  702. }
  703. erase_boot_sector_and_first_partition() {
  704. local sectors count
  705. sectors=$((start_sector + boot_partition_sectors + 100))
  706. count=$((sectors / 8192 + 1))
  707. pu_msg "Erasing up to beginning of second partition ($sectors sectors, ${count}M):"
  708. _show_output
  709. dd if=/dev/zero \
  710. of=/dev/$SDCARD_DEVNAME \
  711. status=progress \
  712. bs=$((512*8192)) \
  713. count=$count
  714. _hide_output
  715. }
  716. create_partition_label() {
  717. local label_code
  718. pu_msg "Creating new partition label on /dev/$SDCARD_DEVNAME"
  719. case $partition_table_type in 'dos') label_code='o';; 'gpt') label_code='g';; esac
  720. set +e
  721. echo -e "$label_code\nw\n" | fdisk "/dev/$SDCARD_DEVNAME"
  722. set -e
  723. do_partprobe
  724. }
  725. copy_boot_loader() {
  726. local bs=4096 skip count
  727. case $partition_table_type in 'dos') skip=0;; 'gpt') skip=8;; esac # LBA8 (0x8000): boot loader magic string
  728. count=$((start_sector / 8 - $skip))
  729. pu_msg "Copying boot loader ($count 4K blocks [$((count*8)) sectors], starting at $skip blocks [$((skip*8)) sectors]):"
  730. _show_output
  731. dd if=$ARMBIAN_IMAGE of="/dev/$SDCARD_DEVNAME" status='progress' bs=$bs count=$count skip=$skip seek=$skip
  732. _hide_output
  733. do_partprobe
  734. }
  735. _print_config_vars() {
  736. local outfile=$1
  737. local data="$(for i in $CONFIG_VARS; do echo "$i='${!i}'"; done)"
  738. if [ "$outfile" ]; then echo "$data" > $outfile; else echo "$data"; fi
  739. }
  740. create_partitions() {
  741. local p1_end p2_start cmds1 cmds2 bname rname fstype
  742. p1_end=$((start_sector + boot_partition_sectors - 1))
  743. p2_start=$((p1_end + 1))
  744. case $partition_table_type in
  745. 'gpt')
  746. cmds1="g\nn\n1\n$start_sector\n$p1_end\nn\n2\n$p2_start\n\n"
  747. cmds2="t\n1\n$partition_type_uuid\nt\n2\n$partition_type_uuid\n"
  748. ;;
  749. 'dos')
  750. cmds1="o\nn\np\n1\n$start_sector\n$p1_end\nn\np\n2\n$p2_start\n\n"
  751. cmds2=""
  752. ;;
  753. esac
  754. set +e; trap - ERR # fdisk exits with error if partition table cannot be re-read
  755. echo -e "${cmds1}${cmds2}w\n" | fdisk "/dev/$SDCARD_DEVNAME"
  756. set -e; trap '_error_handler' ERR
  757. do_partprobe
  758. [ "$VERBOSE" ] && {
  759. pu_msg 'Done partitioning:'
  760. fdisk --list "/dev/$SDCARD_DEVNAME"
  761. imsg ""
  762. }
  763. bname="$(lsblk --noheadings --list --output=NAME /dev/$BOOT_DEVNAME)"
  764. [ "$bname" == $BOOT_DEVNAME ] || die 'Partitioning failed!'
  765. rname="$(lsblk --noheadings --list --output=NAME /dev/$ROOT_DEVNAME)"
  766. [ "$rname" == $ROOT_DEVNAME ] || die 'Partitioning failed!'
  767. # filesystem is required by call to _add_state_file(), so we must create it here
  768. fstype=$(lsblk --noheadings --list --output=FSTYPE "/dev/$BOOT_DEVNAME")
  769. [ "$fstype" == 'ext4' -a "$ROOTENC_REUSE_FS" ] || mkfs.ext4 -F "/dev/$BOOT_DEVNAME"
  770. do_partprobe
  771. _add_state_file 'card_partitioned' 'mount'
  772. }
  773. _do_partition() {
  774. imsg "All data on /dev/$SDCARD_DEVNAME ($SD_INFO) will be destroyed!!!"
  775. _user_confirm 'Are you sure you want to continue?' 'no'
  776. [ "$ERASE" ] && erase_boot_sector_and_first_partition
  777. create_partition_label
  778. copy_boot_loader
  779. create_partitions
  780. }
  781. copy_system_boot() {
  782. [ "$PARTITION_ONLY" ] && {
  783. _add_state_file 'bootpart_copied' 'mount'
  784. return
  785. }
  786. mount "/dev/$BOOT_DEVNAME" $BOOT_ROOT
  787. pu_msg "Copying files to boot partition:"
  788. _show_output
  789. rsync $RSYNC_VERBOSITY --archive $SRC_ROOT/boot/* $BOOT_ROOT
  790. _hide_output
  791. [ -e "$BOOT_ROOT/boot" ] || (cd $BOOT_ROOT && ln -s . 'boot')
  792. _add_state_file 'bootpart_copied'
  793. umount $BOOT_ROOT
  794. }
  795. create_bootpart_label() {
  796. e2label "/dev/$BOOT_DEVNAME" "$BOOTPART_LABEL"
  797. do_partprobe
  798. _add_state_file 'bootpart_label_created' 'mount'
  799. }
  800. copy_system_root() {
  801. if [ "$FORCE_REFORMAT_ROOT" ] || ! cryptsetup isLuks "/dev/$ROOT_DEVNAME"; then
  802. pu_msg "Formatting encrypted root partition:"
  803. echo -n $DISK_PASSWD | cryptsetup luksFormat "/dev/$ROOT_DEVNAME" '-'
  804. fi
  805. echo $DISK_PASSWD | cryptsetup luksOpen "/dev/$ROOT_DEVNAME" $ROOTFS_NAME
  806. local fstype=$(lsblk --noheadings --list --output=FSTYPE "/dev/mapper/$ROOTFS_NAME")
  807. [ "$fstype" == 'ext4' -a "$ROOTENC_REUSE_FS" ] || mkfs.ext4 -F "/dev/mapper/$ROOTFS_NAME"
  808. [ "$PARTITION_ONLY" ] || {
  809. mount "/dev/mapper/$ROOTFS_NAME" $TARGET_ROOT
  810. pu_msg "Copying system to encrypted root partition:"
  811. _show_output
  812. rsync $RSYNC_VERBOSITY --archive --exclude=boot $SRC_ROOT/* $TARGET_ROOT
  813. _hide_output
  814. sync
  815. mkdir -p "$TARGET_ROOT/boot"
  816. touch "$TARGET_ROOT/root/.no_rootfs_resize"
  817. umount $TARGET_ROOT
  818. }
  819. cryptsetup luksClose $ROOTFS_NAME
  820. do_partprobe
  821. _add_state_file 'rootpart_copied' 'mount'
  822. }
  823. mount_target() {
  824. echo $DISK_PASSWD | cryptsetup luksOpen "/dev/$ROOT_DEVNAME" $ROOTFS_NAME
  825. mount "/dev/mapper/$ROOTFS_NAME" $TARGET_ROOT
  826. mount "/dev/$BOOT_DEVNAME" "$TARGET_ROOT/boot"
  827. local src dest args
  828. while read src dest args; do
  829. mount $args $src $TARGET_ROOT/$dest
  830. done <<-EOF
  831. udev dev -t devtmpfs -o rw,relatime,nosuid,mode=0755
  832. devpts dev/pts -t devpts
  833. tmpfs dev/shm -t tmpfs -o rw,nosuid,nodev,relatime
  834. proc proc -t proc
  835. sys sys -t sysfs
  836. EOF
  837. }
  838. _copy_to_target() {
  839. local fn=$1
  840. if [ -e $fn ]; then
  841. echo "Copying '$fn'"
  842. rm -rf $TARGET_ROOT/$fn
  843. cat $fn > $TARGET_ROOT/$fn
  844. else
  845. imsg "Unable to copy '$fn' to target (file does not exist)"
  846. false
  847. fi
  848. }
  849. create_etc_crypttab() {
  850. local root_uuid="$(lsblk --noheadings --list --nodeps --output=UUID /dev/$ROOT_DEVNAME)"
  851. echo "$ROOTFS_NAME UUID=$root_uuid none initramfs,luks" > "$TARGET_ROOT/etc/crypttab"
  852. _display_file "$TARGET_ROOT/etc/crypttab"
  853. }
  854. copy_etc_files() {
  855. _copy_to_target '/etc/resolv.conf'
  856. _copy_to_target '/etc/hosts'
  857. set +e
  858. _copy_to_target /etc/apt/apt.conf.d/*proxy
  859. set -e
  860. }
  861. _print_net_dev() {
  862. local text net_pfx
  863. text="$(ip --brief link)"
  864. for net_pfx in eth enp end eno enP enD enO en; do
  865. grepout="$(echo "$text" | grep ^$net_pfx)" || true
  866. if [ "$grepout" ]; then
  867. echo "$grepout" | head --lines=1 | cut --delimiter=' ' --field=1
  868. return 0
  869. fi
  870. done
  871. }
  872. _set_target_vars() {
  873. target_distro=$(chroot $TARGET_ROOT 'lsb_release' '--short' '--codename')
  874. target_kernel=$(chroot $TARGET_ROOT 'ls' '/boot' | egrep '^vmlinu[xz]')
  875. target_armbian_keyring_signed=
  876. local dfl_eth_dev
  877. case $target_distro in
  878. bionic|buster|focal)
  879. dfl_eth_dev='eth0'
  880. dropbear_dir='/etc/dropbear-initramfs'
  881. dropbear_conf='config' ;;
  882. bullseye|jammy)
  883. dfl_eth_dev='eth0'
  884. dropbear_dir='/etc/dropbear/initramfs'
  885. dropbear_conf='config' ;;
  886. bookworm|noble|trixie|*)
  887. dfl_eth_dev='end0'
  888. dropbear_dir='/etc/dropbear/initramfs'
  889. dropbear_conf='dropbear.conf'
  890. target_armbian_keyring_signed='y' ;;
  891. esac
  892. host_eth_dev=$(_print_net_dev)
  893. [ "$host_eth_dev" ] || die 'Unable to find default wired network device'
  894. if [ "$ETH_DEV" ]; then
  895. eth_dev=$ETH_DEV
  896. elif _distros_match; then
  897. eth_dev=$host_eth_dev
  898. else
  899. eth_dev=$dfl_eth_dev
  900. fi
  901. imsg "$(printf '%-8s %-28s %s' '' 'Host' 'Target')"
  902. imsg "$(printf '%-8s %-28s %s' '' '----' '------')"
  903. imsg "$(printf '%-8s %-28s %s' 'distro:' $host_distro $target_distro)"
  904. imsg "$(printf '%-8s %-28s %s' 'kernel:' $host_kernel $target_kernel)"
  905. imsg "network device: $YELLOW$eth_dev$RESET"
  906. }
  907. _distros_match() {
  908. [ $host_distro == $target_distro ]
  909. }
  910. _kernels_match() {
  911. [ ${host_kernel%.*} == ${target_kernel%.*} ] || return 1
  912. [ ${host_kernel##*-} == ${target_kernel##*-} ]
  913. }
  914. copy_etc_files_distro_specific() {
  915. local files='/etc/apt/sources.list /etc/apt/sources.list.d/armbian.list'
  916. if _distros_match; then
  917. for i in $files; do _copy_to_target $i; done
  918. else
  919. warn 'Warning: host and target distros do not match, attempting to rewrite files:'
  920. for i in $files; do
  921. imsg " rewriting $i"
  922. if [ "$target_armbian_keyring_signed" -a $(basename $i) == 'armbian.list' ]; then
  923. repl='deb [signed-by=\/usr\/share\/keyrings\/armbian.gpg] http'
  924. sed "s/$host_distro/$target_distro/g;s/deb http/$repl/" <$i >$TARGET_ROOT/$i
  925. else
  926. sed "s/$host_distro/$target_distro/g" <$i >$TARGET_ROOT/$i
  927. fi
  928. _display_file $TARGET_ROOT$i
  929. done
  930. fi
  931. }
  932. _display_file() {
  933. local name text reply
  934. if [ "$2" ]; then
  935. name="$1"
  936. text="$2"
  937. else
  938. name=${1#$TARGET_ROOT}
  939. text="$(cat $1)"
  940. fi
  941. hl='────────────────────────────────────────'
  942. hl="$hl$hl$hl"
  943. hls=${hl:0:${#name}+1}
  944. echo "┌─$hls─┐"
  945. echo "│ $name: │"
  946. echo "├─$hls─┘"
  947. echo "$text" | sed 's/^/│ /'
  948. }
  949. edit_armbianEnv() {
  950. local file=$TARGET_ROOT/$1 text console_arg
  951. ed $file <<-'EOF'
  952. g/^\s*rootdev=/d
  953. g/^\s*console=/d
  954. g/^\s*bootlogo=/d
  955. wq
  956. EOF
  957. case $SERIAL_CONSOLE in
  958. 'yes') console_arg='serial' ;;
  959. *) console_arg='display' ;;
  960. esac
  961. text="rootdev=/dev/mapper/$ROOTFS_NAME
  962. console=$console_arg
  963. bootlogo=false"
  964. echo "$text" >> $file
  965. _display_file $file
  966. }
  967. edit_extlinux_conf() {
  968. local file=$TARGET_ROOT/$1 text console_arg
  969. /bin/cp $SRC_ROOT/$1 $TARGET_ROOT/$1
  970. case $SERIAL_CONSOLE in
  971. 'yes') console_pat='console=tty1' ;;
  972. *) console_pat='console=ttyS\S+' ;;
  973. esac
  974. ed --extended-regexp $file <<-EOF
  975. s/root=\S+/root=\/dev\/mapper\/$ROOTFS_NAME/
  976. s/$console_pat *//
  977. wq
  978. EOF
  979. if grep -q 'splash plymouth' $file; then
  980. ed --extended-regexp $file <<-EOF
  981. s/splash plymouth\S+/splash=verbose/
  982. wq
  983. EOF
  984. fi
  985. _display_file $file
  986. }
  987. # Add the following lines to '/etc/initramfs-tools/initramfs.conf'. If
  988. # your board’s IP address will be statically configured, substitute the
  989. # correct static IP address after 'IP='. If it will be configured via
  990. # DHCP, omit the IP line entirely:
  991. edit_initramfs_conf() {
  992. local file="$TARGET_ROOT/etc/initramfs-tools/initramfs.conf" dev=$eth_dev
  993. [ "$USB_GADGET" ] && dev='usb0'
  994. ed $file <<-'EOF'
  995. g/^\s*IP=/s/^/# /
  996. g/^\s*DEVICE=/d
  997. wq
  998. EOF
  999. [ "$IP_ADDRESS" == 'dhcp' -o "$IP_ADDRESS" == 'none' ] || {
  1000. echo "IP=$IP_ADDRESS:::$NETMASK::$dev:off" >> $file
  1001. }
  1002. [ "$IP_ADDRESS" == 'none' ] || echo "DEVICE=$dev" >> $file
  1003. _display_file $file
  1004. }
  1005. edit_initramfs_modules() {
  1006. local modlist file hdr
  1007. [ "$ADD_ALL_MODS" -o "$ADD_MODS" -o "$USB_GADGET" ] && {
  1008. if ! _kernels_match; then
  1009. warn 'Host and target kernels do not match. Not adding modules to initramfs'
  1010. elif ! _distros_match; then
  1011. warn 'Host and target distros do not match. Not adding modules to initramfs'
  1012. else
  1013. local g_mods='libcomposite u_ether usb_f_rndis g_ether usb_f_eem'
  1014. [ "$ADD_ALL_MODS" ] && modlist=$(lsmod | cut -d ' ' -f1 | tail -n+2)
  1015. [ "$ADD_MODS" ] && modlist+=$(echo; for m in ${ADD_MODS//,/ }; do echo $m; done)
  1016. [ "$USB_GADGET" ] && modlist+=$(echo; for m in $g_mods; do echo $m; done)
  1017. fi
  1018. }
  1019. file="$TARGET_ROOT/etc/initramfs-tools/modules"
  1020. hdr="# List of modules that you want to include in your initramfs.
  1021. # They will be loaded at boot time in the order below.
  1022. #
  1023. # Syntax: module_name [args ...]
  1024. #
  1025. # You must run update-initramfs(8) to effect this change.
  1026. #
  1027. "
  1028. echo "$hdr$modlist" > $file
  1029. _display_file $file
  1030. }
  1031. copy_authorized_keys() {
  1032. local dest="$TARGET_ROOT$dropbear_dir"
  1033. mkdir -p $dest
  1034. /bin/cat authorized_keys/* > "$dest/authorized_keys"
  1035. chmod 644 "$dest/authorized_keys"
  1036. _display_file "$dest/authorized_keys"
  1037. }
  1038. create_fstab() {
  1039. local boot_uuid file text
  1040. boot_uuid="$(lsblk --noheadings --list --output=UUID /dev/$BOOT_DEVNAME)"
  1041. file="$TARGET_ROOT/etc/fstab"
  1042. text="/dev/mapper/$ROOTFS_NAME / ext4 defaults,noatime,nodiratime,commit=600,errors=remount-ro 0 1
  1043. UUID=$boot_uuid /boot ext4 defaults,noatime,nodiratime,commit=600,errors=remount-ro 0 2
  1044. tmpfs /tmp tmpfs defaults,nosuid 0 0"
  1045. echo "$text" > $file
  1046. _display_file $file
  1047. }
  1048. edit_dropbear_cfg() {
  1049. local dest file text
  1050. dest="$TARGET_ROOT$dropbear_dir"
  1051. file="$dest/$dropbear_conf"
  1052. text='DROPBEAR_OPTIONS="-p 2222"
  1053. DROPBEAR=y'
  1054. if [ "$IP_ADDRESS" == 'none' ]; then
  1055. [ -e $file ] && rm -v $file
  1056. true
  1057. else
  1058. mkdir -p $dest
  1059. [ -e $file ] && grep -q '^DROPBEAR_OPTIONS="-p 2222"' $file || echo "$text" >> $file
  1060. _display_file $file
  1061. fi
  1062. }
  1063. netman_manage_usb0() {
  1064. local file bu_file text
  1065. file="$TARGET_ROOT/etc/NetworkManager/NetworkManager.conf"
  1066. bu_file="$file.rootenc.orig"
  1067. text='
  1068. [device]
  1069. match-device=interface-name:$eth_dev
  1070. managed=0
  1071. match-device=interface-name:usb0
  1072. managed=1'
  1073. if [ -e $file ]; then
  1074. if [ "$USB_GADGET" ]; then
  1075. grep -q '^match-device=interface-name:usb0' $file || {
  1076. /bin/cp $file $bu_file
  1077. echo "$text" >> $file
  1078. }
  1079. else
  1080. [ -e $bu_file ] && /bin/mv $bu_file $file
  1081. fi
  1082. _display_file $file
  1083. elif [ "$USB_GADGET" ]; then
  1084. warn "$file does not exist, not enabling managed usb0"
  1085. fi
  1086. }
  1087. ifupdown_config_usb0() {
  1088. local file bu_file text
  1089. file="$TARGET_ROOT/etc/network/interfaces"
  1090. bu_file="$file.rootenc.orig"
  1091. text="
  1092. auto usb0
  1093. iface usb0 inet static
  1094. address $IP_ADDRESS
  1095. netmask $NETMASK
  1096. "
  1097. if [ -e $file ]; then
  1098. if [ "$USB_GADGET" -a "$IP_ADDRESS" != 'dhcp' ]; then
  1099. grep -q '^auto usb0' $file || {
  1100. /bin/cp $file $bu_file
  1101. echo "$text" >> $file
  1102. }
  1103. systemctl mask network-manager
  1104. else
  1105. [ -e $bu_file ] && /bin/mv $bu_file $file
  1106. systemctl unmask network-manager
  1107. fi
  1108. _display_file $file
  1109. elif [ "$USB_GADGET" ]; then
  1110. warn "$file does not exist, not configuring static usb0"
  1111. fi
  1112. }
  1113. create_cryptroot_unlock_sh() {
  1114. local dest file text
  1115. dest="$TARGET_ROOT/etc/initramfs-tools/hooks"
  1116. file="$dest/cryptroot-unlock.sh"
  1117. text='#!/bin/sh
  1118. if [ "$1" = "prereqs" ]; then echo "dropbear-initramfs"; exit 0; fi
  1119. . /usr/share/initramfs-tools/hook-functions
  1120. source="/tmp/cryptroot-unlock-profile"
  1121. root_home=$(echo $DESTDIR/root-*)
  1122. root_home=${root_home#$DESTDIR}
  1123. echo "if [ \"\$SSH_CLIENT\" ]; then /usr/bin/cryptroot-unlock; fi" > $source
  1124. copy_file ssh_login_profile $source $root_home/.profile
  1125. exit 0'
  1126. mkdir -p $dest
  1127. echo "$text" > $file
  1128. chmod 755 $file
  1129. _display_file $file
  1130. }
  1131. # begin chroot functions:
  1132. apt_remove_target_pkgs() {
  1133. if [ "$IP_ADDRESS" == 'none' ]; then
  1134. apt --yes purge 'dropbear-initramfs' || :
  1135. fi
  1136. apt --yes purge 'bash-completion' 'command-not-found' || :
  1137. }
  1138. apt_install_target_pkgs() {
  1139. local pkgs=$(_print_pkgs_to_install 'target')
  1140. [ "$pkgs" ] && {
  1141. echo "target packages to install: $pkgs"
  1142. local ls1 ls2
  1143. _show_output
  1144. ls1=$(ls -l /boot/initrd.img-*)
  1145. # DEBUG:
  1146. # dpkg-reconfigure $pkgs # doesn't work in chroot
  1147. # apt --yes purge $pkgs
  1148. # apt-get --yes --purge autoremove
  1149. dpkg --configure --pending --force-confdef
  1150. _apt_update
  1151. echo 'force-confdef' > /root/.dpkg.cfg
  1152. apt --yes install $pkgs
  1153. rm /root/.dpkg.cfg
  1154. apt --yes autoremove
  1155. ls2=$(ls -l /boot/initrd.img-*)
  1156. [ "$ls1" != "$ls2" ] && initramfs_updated='y'
  1157. _hide_output
  1158. }
  1159. true
  1160. }
  1161. update_initramfs() {
  1162. [ "$ROOTENC_TESTING" ] && return 0
  1163. _show_output
  1164. local ver=$(echo /boot/vmlinu?-* | sed 's/.boot.vmlinu.-//')
  1165. update-initramfs -k $ver -c
  1166. _hide_output
  1167. }
  1168. gen_target_ssh_host_keys() {
  1169. ssh-keygen -A
  1170. }
  1171. check_initramfs() {
  1172. local text chk count
  1173. text="$(lsinitramfs /boot/initrd.img-*)"
  1174. set +e
  1175. chk=$(echo "$text" | grep 'cryptsetup')
  1176. count=$(echo "$chk" | wc -l)
  1177. _display_file "lsinitramfs /boot/initrd.img* | grep 'cryptsetup'" "$chk"
  1178. [ "$count" -gt 5 ] || { echo "$text"; die 'Cryptsetup scripts missing in initramfs image'; }
  1179. [ "$IP_ADDRESS" == 'none' ] || {
  1180. chk=$(echo "$text" | grep 'dropbear')
  1181. count=$(echo "$chk" | wc -l)
  1182. _display_file "lsinitramfs /boot/initrd.img* | grep 'dropbear'" "$chk"
  1183. [ "$count" -gt 5 ] || { echo "$text"; die 'Dropbear scripts missing in initramfs image'; }
  1184. chk=$(echo "$text" | grep 'authorized_keys')
  1185. count=$(echo "$chk" | wc -l)
  1186. _display_file "lsinitramfs /boot/initrd.img* | grep 'authorized_keys'" "$chk"
  1187. [ "$count" -eq 1 ] || { echo "$text"; die 'authorized_keys missing in initramfs image'; }
  1188. }
  1189. set -e
  1190. }
  1191. configure_target() {
  1192. [ "$PARTITION_ONLY" ] && return
  1193. mount_target
  1194. _set_target_vars
  1195. copy_etc_files
  1196. copy_etc_files_distro_specific
  1197. edit_initramfs_conf
  1198. edit_initramfs_modules
  1199. [ "$IP_ADDRESS" == 'none' ] || copy_authorized_keys
  1200. create_etc_crypttab
  1201. create_fstab
  1202. edit_dropbear_cfg
  1203. netman_manage_usb0
  1204. ifupdown_config_usb0
  1205. [ "$IP_ADDRESS" == 'none' ] || create_cryptroot_unlock_sh
  1206. armbian_env="boot/armbianEnv.txt"
  1207. extlinux_conf="boot/extlinux/extlinux.conf"
  1208. if [ -e $SRC_ROOT/$armbian_env ]; then
  1209. edit_armbianEnv $armbian_env
  1210. elif [ -e $SRC_ROOT/$extlinux_conf ]; then
  1211. edit_extlinux_conf $extlinux_conf
  1212. else
  1213. die "could not find $SRC_ROOT/$armbian_env or $SRC_ROOT/$extlinux_conf"
  1214. fi
  1215. _debug_pause
  1216. _show_output # this must be done before entering chroot
  1217. /bin/cp $0 $TARGET_ROOT
  1218. export 'ROOTFS_NAME' 'IP_ADDRESS' 'target_distro' 'ROOTENC_TESTING' 'ROOTENC_PAUSE' 'ROOTENC_IGNORE_APT_ERRORS' 'APT_UPGRADE'
  1219. chroot $TARGET_ROOT "./$PROGNAME" $ORIG_OPTS 'in_target'
  1220. /bin/cp -a '/etc/resolv.conf' "$TARGET_ROOT/etc" # this could be a symlink
  1221. /bin/rm "$TARGET_ROOT/$PROGNAME"
  1222. _add_state_file 'target_configured' 'target'
  1223. }
  1224. _set_env_vars() {
  1225. shopt -s extglob
  1226. local name val
  1227. while [ $# -gt 0 ]; do
  1228. name=${1%=?*} val=${1#+([A-Z_])=}
  1229. [ "$name" == "$1" -o "$val" == "$1" ] && die "$1: illegal argument (must be in format 'NAME=value')"
  1230. eval "$name=$val"
  1231. shift
  1232. done
  1233. shopt -u extglob
  1234. }
  1235. _mount_target_and_exit() {
  1236. setup_loopmount
  1237. mount_target
  1238. _set_target_vars
  1239. rmdir $BOOT_ROOT
  1240. exit
  1241. }
  1242. # begin execution
  1243. set -e
  1244. while getopts hCfFmo:MUpRsudvz OPT
  1245. do
  1246. case "$OPT" in
  1247. h) print_help; exit ;;
  1248. C) NO_CLEANUP='y' ;;
  1249. f) FORCE_RECONFIGURE='y' ;;
  1250. F) FORCE_REBUILD='y' ;;
  1251. m) ADD_ALL_MODS='y' ;;
  1252. o) ADD_MODS=$OPTARG ;;
  1253. M) MOUNT_TARGET_ONLY='y' ;;
  1254. U) UMOUNT_TARGET_ONLY='y' ;;
  1255. p) PARTITION_ONLY='y' ;;
  1256. R) FORCE_REFORMAT_ROOT='y' ;;
  1257. s) USE_LOCAL_AUTHORIZED_KEYS='y' ;;
  1258. u) APT_UPGRADE='y' ;;
  1259. d) DEBUG='y' ;&
  1260. v) VERBOSE='y' RSYNC_VERBOSITY='--verbose' ;;
  1261. z) ERASE='y' ;;
  1262. *) exit ;;
  1263. esac
  1264. ORIG_OPTS+="-$OPT $OPTARG "
  1265. done
  1266. shift $((OPTIND-1))
  1267. trap '_return_handler' RETURN
  1268. trap '_sigint_handler' INT
  1269. trap '_error_handler' ERR
  1270. set -o functrace
  1271. set -o errtrace
  1272. exec {stdout_dup}>&1
  1273. exec {stderr_dup}>&2
  1274. [ $UID == 0 -o $EUID == 0 ] || die 'This program must be run as root!'
  1275. export HOME='/root'
  1276. [ "$DEBUG" ] && set -x
  1277. ARG1=$1
  1278. [ "$ARG1" ] || die 'You must supply a target device name'
  1279. shift
  1280. _set_env_vars $@
  1281. if [ "$ARG1" == 'in_target' ]; then
  1282. SCRIPT_DESC='Target script'
  1283. _hide_output
  1284. [ "$target_distro" == 'bionic' ] && {
  1285. echo 'export CRYPTSETUP=y' > '/etc/initramfs-tools/conf.d/cryptsetup'
  1286. }
  1287. apt_remove_target_pkgs
  1288. apt_install_target_pkgs
  1289. [ "$initramfs_updated" ] || update_initramfs
  1290. gen_target_ssh_host_keys
  1291. check_initramfs
  1292. else
  1293. SCRIPT_DESC='Host script'
  1294. _check_eth_dev
  1295. _do_header
  1296. _set_host_vars
  1297. [ "$ARMBIAN_IMAGE" ] || get_armbian_image
  1298. get_partition_info
  1299. apt_install_host_pkgs # _preclean requires cryptsetup
  1300. _preclean
  1301. [ "$UMOUNT_TARGET_ONLY" ] && exit
  1302. check_sdcard_name_and_params $ARG1
  1303. create_build_dir
  1304. [ "$MOUNT_TARGET_ONLY" ] && warn 'Mounting source and target and exiting at user request'
  1305. _get_user_vars
  1306. _test_sdcard_mounted
  1307. [ "$MOUNT_TARGET_ONLY" ] && _mount_target_and_exit
  1308. _warn_user_opts
  1309. _confirm_user_vars
  1310. [ "$IP_ADDRESS" == 'none' ] || get_authorized_keys
  1311. [ "$NO_CLEANUP" ] || trap '_clean' EXIT
  1312. setup_loopmount
  1313. _debug_pause
  1314. check_install_state
  1315. _hide_output
  1316. [ "$card_partitioned" == 'n' ] && _do_partition
  1317. _debug_pause
  1318. [ "$bootpart_copied" == 'n' ] && copy_system_boot
  1319. [ "$bootpart_label_created" == 'n' ] && create_bootpart_label
  1320. [ "$rootpart_copied" == 'n' ] && copy_system_root
  1321. [ "$target_configured" == 'n' ] && configure_target
  1322. sync
  1323. gmsg 'All done!'
  1324. if [ "$IP_ADDRESS" != 'none' ]; then
  1325. imsg "To unlock the target disk, execute the following from the unlocking host:"
  1326. imsg " ssh -p 2222 root@${IP_ADDRESS/dhcp/TARGET_IP}"
  1327. fi
  1328. fi