armbian_rootenc_setup.sh 40 KB

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