armbian_rootenc_setup.sh 45 KB

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