#!/usr/bin/env bash # privex-vps-encrypt.sh - convert a Privex VPS to full disk encryption (LUKS2) # with remote unlock over SSH (dropbear in the initramfs). # # Run it as root inside the SystemRescue live ISO, with the VPS disk NOT mounted. # Supported: the Privex Debian 12, Debian 13, Ubuntu 22.04 and Ubuntu 24.04 templates. # # bash privex-vps-encrypt.sh --dry-run # show what would be done, change nothing # bash privex-vps-encrypt.sh # convert (asks for YES and a passphrase) # bash privex-vps-encrypt.sh --grow # later, on the running VPS after a disk upgrade # # If the run is interrupted (power loss, closed console, Ctrl-C), boot SystemRescue # again and run the same command: it finds where it stopped and continues. # # There is no way to recover the data if the passphrase is lost. set -euo pipefail umask 077 export LC_ALL=C VERSION="1.0" MAPPER="cryptroot" MNT="/mnt/privex-encrypt" LOG="/root/privex-vps-encrypt.log" STATE_DIR_NAME=".privex-encrypt" BOOT_LABEL="boot" BOOT_PARTNAME="privex-boot" LUKS_RESERVE_MIB=32 TYPE_BIOS="21686148-6449-6e6f-744e-656564454649" TYPE_ESP="c12a7328-f81f-11d2-ba4b-00a0c93ec93b" TYPE_LINUX_FS="0fc63daf-8483-4772-8e79-3d69d8477de4" # ---------------------------------------------------------------- options DISK="" DRY_RUN=0 NET_MODE="auto" # auto: DHCP, then the static address; dhcp; static CONSOLE="serial" # main passphrase prompt: serial (dashboard default) or vga; the other one gets a second prompt KEYS_FILE="" PASS_FD="" RECONFIGURE=0 GROW=0 BOOT_MIB=1024 DHCP_TIMEOUT="" OPT_IPV4="" OPT_GW4="" OPT_IPV6="" OPT_GW6="" OPT_MAC="" OPT_NET_MODE="" OPT_DHCP_TIMEOUT="" OPT_CONSOLE="" usage() { cat <&2; exit 2 ;; esac shift done case "$CONSOLE" in vga|serial) ;; *) echo "--console must be vga or serial" >&2; exit 2 ;; esac case "$BOOT_MIB" in ''|*[!0-9]*) echo "--boot-size must be a number of MiB" >&2; exit 2 ;; esac [ "$BOOT_MIB" -ge 512 ] || { echo "--boot-size must be at least 512" >&2; exit 2; } if [ -n "$PASS_FD" ]; then case "$PASS_FD" in *[!0-9]*) echo "--passphrase-fd must be a number" >&2; exit 2 ;; esac fi if [ -z "$DHCP_TIMEOUT" ]; then if [ "$NET_MODE" = dhcp ]; then DHCP_TIMEOUT=60; else DHCP_TIMEOUT=20; fi fi case "$DHCP_TIMEOUT" in *[!0-9]*) echo "--dhcp-timeout must be a number" >&2; exit 2 ;; esac # ---------------------------------------------------------------- output if [ -t 1 ]; then C_B=$'\e[1m'; C_R=$'\e[31m'; C_Y=$'\e[33m'; C_G=$'\e[32m'; C_0=$'\e[0m' else C_B=""; C_R=""; C_Y=""; C_G=""; C_0=""; fi STEP_NO=0 step() { STEP_NO=$((STEP_NO + 1)); printf '\n%s==> [%d] %s%s\n' "$C_B" "$STEP_NO" "$*" "$C_0"; } info() { printf ' %s\n' "$*"; } warn() { printf '%sWARNING: %s%s\n' "$C_Y" "$*" "$C_0" >&2; } die() { trap - ERR; printf '\n%sERROR: %s%s\n' "$C_R" "$*" "$C_0" >&2; exit 1; } ok() { printf ' %sOK%s %s\n' "$C_G" "$C_0" "$*"; } # Prompts read from the terminal even when the script itself was piped into bash. if [ -t 0 ]; then exec 9<&0 elif { exec 9/dev/null; then : else exec 9<&0; fi ask() { # ask VAR "prompt" local __v printf '%s' "$2" IFS= read -r __v <&9 || __v="" printf -v "$1" '%s' "$__v" } # ---------------------------------------------------------------- state PASSPHRASE="" CHANGED=0 OPENED_MAPPER=0 CHROOT_DIR="" ROOT_MNT="$MNT/root" BOOT_MNT="$MNT/boot" cleanup() { local rc=$? set +e if [ -n "$CHROOT_DIR" ]; then chroot_teardown "$CHROOT_DIR"; fi if [ -d "$MNT" ]; then # unmount everything below $MNT, deepest first findmnt -rn -o TARGET | grep -E "^$MNT(/|$)" | sort -r | while read -r m; do umount "$m" 2>/dev/null || umount -l "$m" 2>/dev/null done fi if [ "$OPENED_MAPPER" = 1 ] && [ -e "/dev/mapper/$MAPPER" ]; then cryptsetup close "$MAPPER" 2>/dev/null fi PASSPHRASE="" if [ $rc -ne 0 ] && [ "$DRY_RUN" = 0 ] && [ "$GROW" = 0 ]; then printf '\n%sThe script stopped before finishing (exit %s).%s Log: %s\n' "$C_R" "$rc" "$C_0" "$LOG" >&2 if [ "$CHANGED" = 0 ]; then printf 'The VPS disk was not repartitioned or encrypted; it still boots as before.\n' >&2 else printf 'The VPS is probably NOT bootable right now. Fix the reported problem and run\n' >&2 printf 'this script again (same command): it continues where it stopped.\n' >&2 fi fi } trap cleanup EXIT # report where an unexpected failure happened (BASH_COMMAND is the unexpanded text, never the passphrase) trap 'printf "%sERROR: command failed (line %s): %s%s\n" "$C_R" "$LINENO" "$BASH_COMMAND" "$C_0" >&2' ERR set -E trap 'echo; die "Interrupted. Run the script again to continue."' INT TERM # ---------------------------------------------------------------- helpers need_cmds() { local c missing="" for c in "$@"; do command -v "$c" >/dev/null 2>&1 || missing="$missing $c"; done [ -z "$missing" ] || die "Missing commands:$missing. Run this from the SystemRescue ISO." } part_dev() { # part_dev /dev/sda 1 -> /dev/sda1 ; /dev/nvme0n1 1 -> /dev/nvme0n1p1 case "$1" in *[0-9]) printf '%sp%s' "$1" "$2" ;; *) printf '%s%s' "$1" "$2" ;; esac } sysblk() { basename "$(readlink -f "$1")"; } part_num() { cat "/sys/class/block/$(sysblk "$1")/partition"; } part_start() { cat "/sys/class/block/$(sysblk "$1")/start"; } # 512-byte sectors part_size() { cat "/sys/class/block/$(sysblk "$1")/size"; } # 512-byte sectors part_type() { lsblk -dno PARTTYPE "$1" | tr 'A-F' 'a-f' | tr -d ' '; } fs_type() { blkid -p -o value -s TYPE "$1" 2>/dev/null || true; } list_parts() { # all partitions of $1 lsblk -lnpo NAME,TYPE "$1" | awk '$2=="part"{print $1}' } settle() { udevadm settle 2>/dev/null || sleep 2; } settle_disk() { sleep 1; settle; } # after a whole-disk write: let udev see the close first flush_disk_caches() { # write back and drop the page caches of the disk and root sync blockdev --flushbufs "$ROOT_PART" 2>/dev/null || true blockdev --flushbufs "$DISK" 2>/dev/null || true } reread_parts() { settle # nothing on the disk is in use in SystemRescue, so a full re-read is possible; it is # needed when a partition's start moved (partx -u can only resize) if ! blockdev --rereadpt "$DISK" 2>/dev/null; then partx -d "$DISK" 2>/dev/null || true partx -a "$DISK" 2>/dev/null || partx -u "$DISK" 2>/dev/null || true fi settle } mib_align_up() { # sectors -> sectors rounded up to 1 MiB (2048 sectors) echo $(( ( $1 + 2047 ) / 2048 * 2048 )) } human() { # bytes -> human awk -v b="$1" 'BEGIN{ split("B KiB MiB GiB TiB",u," "); i=1; while (b>=1024 && i<5) {b/=1024; i++}; printf "%.1f %s", b, u[i] }' } # ext4 numbers fs_blocksize() { dumpe2fs -h "$1" 2>/dev/null | awk -F: '/^Block size:/{gsub(/ /,"",$2); print $2}'; } fs_blockcount() { dumpe2fs -h "$1" 2>/dev/null | awk -F: '/^Block count:/{gsub(/ /,"",$2); print $2}'; } fs_minblocks() { # resize2fs' estimate; if it refuses (needs a fresh e2fsck), used blocks + 10% local m m=$(resize2fs -P "$1" 2>/dev/null | awk -F: '/Estimated minimum size/{gsub(/ /,"",$2); print $2}' || true) if [ -z "$m" ]; then m=$(dumpe2fs -h "$1" 2>/dev/null | awk -F: '/^Block count:/{gsub(/ /,"",$2); b=$2} /^Free blocks:/{gsub(/ /,"",$2); f=$2} END{ if (b) printf "%d", (b - f) * 1.1 }' || true) fi echo "$m" } run_fsck() { # run_fsck DEV : full check, fix safe problems, stop on real ones local rc=0 info "Checking file system on $1 (e2fsck)" e2fsck -f -p "$1" || rc=$? if [ $rc -ge 4 ]; then die "e2fsck found problems on $1 that need manual repair (exit $rc). Run 'e2fsck -f $1' yourself, then rerun this script." fi } mask2prefix() { local IFS=. n=0 o # shellcheck disable=SC2086 set -- $1 for o in "$@"; do case "$o" in 255) n=$((n + 8)) ;; 254) n=$((n + 7)) ;; 252) n=$((n + 6)) ;; 248) n=$((n + 5)) ;; 240) n=$((n + 4)) ;; 224) n=$((n + 3)) ;; 192) n=$((n + 2)) ;; 128) n=$((n + 1)) ;; 0) ;; *) echo ""; return ;; esac done echo "$n" } # Flatten the small YAML subset netplan files use into path=value lines, e.g. # network.ethernets.eth0.addresses.#1=10.0.2.15/24 # network.ethernets.eth0.routes.#2.via=fec0::2 yaml_flatten() { awk ' function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s } function unq(s) { s = trim(s); if (s ~ /^".*"$/ || s ~ /^\047.*\047$/) s = substr(s, 2, length(s) - 2); return s } function path( p, i) { p = ""; for (i = 1; i <= n; i++) p = p (p == "" ? "" : ".") nm[i]; return p } function popto(ind, item) { while (n > 0 && (ki[n] > ind || (ki[n] == ind && (!item || it[n])))) n-- } function emitkv(s, ind, k, v, a, m, j) { k = s; sub(/:.*/, "", k); k = unq(k) v = s; sub(/^[^:]*:/, "", v); v = trim(v) if (v == "") { n++; ki[n] = ind; nm[n] = k; it[n] = 0; return } if (v ~ /^\[/) { gsub(/^\[|\]$/, "", v); m = split(v, a, ",") for (j = 1; j <= m; j++) if (trim(a[j]) != "") print path() (n ? "." : "") k ".#" j "=" unq(a[j]) return } print path() (n ? "." : "") k "=" unq(v) } { line = $0 if (line !~ /["\047]/) sub(/[ \t]+#.*/, "", line) if (line ~ /^[ \t]*#/ || line ~ /^[ \t]*$/) next match(line, /^ */); ind = RLENGTH; s = substr(line, ind + 1) if (s ~ /^-( |$)/) { popto(ind, 1) p = path(); cnt[p]++ n++; ki[n] = ind; nm[n] = "#" cnt[p]; it[n] = 1 s = trim(substr(s, 2)) if (s == "") next if (s ~ /^[^"\047 ][^:]*:( |$)/) emitkv(s, ind + 2) else print path() "=" unq(s) next } popto(ind, 0) if (s ~ /:( |$)/) emitkv(s, ind) }' } # ---------------------------------------------------------------- network config of the VPS NET_IF="" NET_MAC="" NET_IPV4="" NET_GW4="" NET_IPV6="" NET_GW6="" NET_SRC="" NET_DHCP4=0 read_netplan() { # $1 = root mount local files flat ifn pfx n to via files=$(find "$1/etc/netplan" -maxdepth 1 -name '*.yaml' 2>/dev/null | sort) [ -n "$files" ] || return 1 # shellcheck disable=SC2086 flat=$(cat $files | yaml_flatten) ifn=$(printf '%s\n' "$flat" | sed -n 's/^network\.ethernets\.\([^.=]*\)\..*/\1/p' | sed -n 1p) [ -n "$ifn" ] || return 1 if [ "$(printf '%s\n' "$flat" | sed -n 's/^network\.ethernets\.\([^.=]*\)\..*/\1/p' | sort -u | wc -l)" -gt 1 ]; then warn "The VPS has more than one network interface in netplan; using $ifn for the unlock network." fi pfx="network.ethernets.$ifn" NET_IF="$ifn"; NET_SRC="netplan ($(echo "$files" | tr '\n' ' '))" NET_MAC=$(printf '%s\n' "$flat" | grep -F "$pfx.match.macaddress=" | sed -n 1p | cut -d= -f2- || true) if grep -qE "^${pfx//./\\.}\.dhcp4=(true|yes)$" <<< "$flat"; then NET_DHCP4=1; fi while IFS= read -r a; do case "$a" in *:*) [ -n "$NET_IPV6" ] || NET_IPV6="$a" ;; *.*) [ -n "$NET_IPV4" ] || NET_IPV4="$a" ;; esac done < <(printf '%s\n' "$flat" | grep -E "^${pfx//./\\.}\.addresses\.#[0-9]+=" | cut -d= -f2- || true) NET_GW4=$(printf '%s\n' "$flat" | grep -F "$pfx.gateway4=" | sed -n 1p | cut -d= -f2- || true) NET_GW6=$(printf '%s\n' "$flat" | grep -F "$pfx.gateway6=" | sed -n 1p | cut -d= -f2- || true) for n in $(printf '%s\n' "$flat" | sed -n "s/^${pfx//./\\.}\.routes\.#\([0-9]*\)\..*/\1/p" | sort -un); do to=$(printf '%s\n' "$flat" | grep -F "$pfx.routes.#$n.to=" | sed -n 1p | cut -d= -f2- || true) via=$(printf '%s\n' "$flat" | grep -F "$pfx.routes.#$n.via=" | sed -n 1p | cut -d= -f2- || true) case "$to" in default|0.0.0.0/0|::/0) case "$via" in *:*) [ -n "$NET_GW6" ] || NET_GW6="$via" ;; *.*) [ -n "$NET_GW4" ] || NET_GW4="$via" ;; esac ;; esac done return 0 } read_ifupdown() { # $1 = root mount local files out files=$(ls "$1/etc/network/interfaces" "$1"/etc/network/interfaces.d/* 2>/dev/null || true) [ -n "$files" ] || return 1 # shellcheck disable=SC2086 out=$(cat $files | awk ' $1=="iface" && $2!="lo" { ifn=$2; fam=$3; meth=$4; if (!first) first=ifn if (ifn==first && fam=="inet" && meth=="dhcp") print "dhcp4=1" ; next } $1=="iface" { ifn=""; next } ifn!="" && ifn==first && $1=="address" { print fam "_address=" $2 } ifn!="" && ifn==first && $1=="netmask" { print fam "_netmask=" $2 } ifn!="" && ifn==first && $1=="gateway" { print fam "_gateway=" $2 } END { if (first) print "if=" first }') [ -n "$out" ] || return 1 NET_IF=$(printf '%s\n' "$out" | sed -n 's/^if=//p' | sed -n 1p) [ -n "$NET_IF" ] || return 1 NET_SRC="ifupdown" if grep -q '^dhcp4=1' <<< "$out"; then NET_DHCP4=1; fi local a4 m4 a6 m6 a4=$(printf '%s\n' "$out" | sed -n 's/^inet_address=//p' | sed -n 1p) m4=$(printf '%s\n' "$out" | sed -n 's/^inet_netmask=//p' | sed -n 1p) a6=$(printf '%s\n' "$out" | sed -n 's/^inet6_address=//p' | sed -n 1p) m6=$(printf '%s\n' "$out" | sed -n 's/^inet6_netmask=//p' | sed -n 1p) if [ -n "$a4" ]; then case "$a4" in */*) NET_IPV4="$a4" ;; *) [ -n "$m4" ] && NET_IPV4="$a4/$(mask2prefix "$m4")" ;; esac fi if [ -n "$a6" ]; then case "$a6" in */*) NET_IPV6="$a6" ;; *) NET_IPV6="$a6/${m6:-64}" ;; esac fi NET_GW4=$(printf '%s\n' "$out" | sed -n 's/^inet_gateway=//p' | sed -n 1p) NET_GW6=$(printf '%s\n' "$out" | sed -n 's/^inet6_gateway=//p' | sed -n 1p) return 0 } detect_network() { # $1 = root mount read_netplan "$1" || read_ifupdown "$1" || true [ -n "$OPT_IPV4" ] && NET_IPV4="$OPT_IPV4" && NET_SRC="command line" [ -n "$OPT_GW4" ] && NET_GW4="$OPT_GW4" [ -n "$OPT_IPV6" ] && NET_IPV6="$OPT_IPV6" && NET_SRC="command line" [ -n "$OPT_GW6" ] && NET_GW6="$OPT_GW6" [ -n "$OPT_MAC" ] && NET_MAC="$OPT_MAC" NET_MAC=$(printf '%s' "$NET_MAC" | tr 'A-F' 'a-f') case "$NET_IPV4" in ''|*/*) ;; *) die "IPv4 address '$NET_IPV4' has no prefix length (use ADDR/PREFIX)" ;; esac case "$NET_IPV6" in ''|*/*) ;; *) NET_IPV6="$NET_IPV6/64" ;; esac } # ---------------------------------------------------------------- SSH keys KEYS="" extract_keys() { # stdin: authorized_keys lines -> plain "type base64 comment" lines awk '{ for (i = 1; i <= NF; i++) if ($i ~ /^(ssh-(rsa|ed25519|dss)|ecdsa-sha2-nistp(256|384|521)|sk-(ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)$/) { line = $i " " $(i + 1); if (i + 2 <= NF) line = line " " $(i + 2); print line; break } }' } validate_keys() { # $1 = text with keys; prints valid unique keys local k tmp tmp=$(mktemp) while IFS= read -r k; do [ -n "$k" ] || continue printf '%s\n' "$k" > "$tmp" if ssh-keygen -l -f "$tmp" >/dev/null 2>&1; then printf '%s\n' "$k"; else warn "Ignoring invalid key: ${k:0:40}..."; fi done < <(printf '%s\n' "$1" | extract_keys | awk '!seen[$1" "$2]++') rm -f "$tmp" } collect_keys() { # $1 = root mount (may be empty when resuming) local raw="" f line if [ -n "$KEYS_FILE" ]; then [ -r "$KEYS_FILE" ] || die "Cannot read $KEYS_FILE" raw=$(cat "$KEYS_FILE") elif [ -n "$1" ]; then for f in "$1/root/.ssh/authorized_keys" "$1"/home/*/.ssh/authorized_keys; do [ -r "$f" ] && raw="$raw"$'\n'"$(cat "$f")" done fi KEYS=$(validate_keys "$raw") if [ -z "$KEYS" ] && [ "$DRY_RUN" = 0 ]; then echo echo "No SSH public key found for unlocking. Paste one public key per line" echo "(e.g. 'ssh-ed25519 AAAA... you@laptop'), then an empty line:" raw="" while true; do ask line "> " [ -n "$line" ] || break raw="$raw"$'\n'"$line" done KEYS=$(validate_keys "$raw") fi if [ -z "$KEYS" ]; then [ "$DRY_RUN" = 1 ] && { warn "No SSH public key found on the VPS; a real run will ask for one."; return 0; } die "At least one SSH public key is needed to unlock the VPS over SSH." fi } print_keys() { local k tmp tmp=$(mktemp) while IFS= read -r k; do printf '%s\n' "$k" > "$tmp" info " $(ssh-keygen -l -f "$tmp" 2>/dev/null)" done <<< "$KEYS" rm -f "$tmp" } # ---------------------------------------------------------------- passphrase read_passphrase() { # $1 = 1 to confirm local p1 p2 if [ -n "$PASS_FD" ]; then IFS= read -r p1 <&"$PASS_FD" || [ -n "$p1" ] || die "Could not read the passphrase from fd $PASS_FD" PASSPHRASE="$p1" else while true; do printf 'New disk passphrase: ' IFS= read -r -s p1 <&9 || die "Could not read the passphrase" echo if [ "$1" = 1 ]; then printf 'Repeat the passphrase: ' IFS= read -r -s p2 <&9 || die "Could not read the passphrase" echo if [ "$p1" != "$p2" ]; then echo "The passphrases differ, try again."; continue; fi fi if [ "$1" = 1 ] && ! check_passphrase "$p1"; then continue; fi break done PASSPHRASE="$p1" fi p1="" p2="" if [ "$1" = 1 ]; then check_passphrase "$PASSPHRASE" || die "Unusable passphrase"; fi } check_passphrase() { if [ "${#1}" -lt 8 ]; then echo "Use at least 8 characters."; return 1; fi if [[ "$1" == *[![:print:]]* ]] || [[ "$1" == *[^\ -~]* ]]; then echo "Use only plain ASCII letters, digits, spaces and punctuation: the boot console" echo "uses a US keyboard layout and cannot type other characters." return 1 fi return 0 } # feeds the passphrase to cryptsetup on stdin (never on a command line) cs_with_pass() { printf '%s\n' "$PASSPHRASE" | cryptsetup "$@"; } # ---------------------------------------------------------------- chroot chroot_setup() { # $1 = dir local d="$1" mount -t proc proc "$d/proc" mount --rbind /sys "$d/sys"; mount --make-rslave "$d/sys" mount --rbind /dev "$d/dev"; mount --make-rslave "$d/dev" mount -t tmpfs -o mode=755 tmpfs "$d/run" mkdir -p "$d/run/systemd/resolve" "$d/run/lock" # name resolution from SystemRescue; /etc/resolv.conf may be a symlink into /run cp -L /etc/resolv.conf "$d/run/systemd/resolve/stub-resolv.conf" cp -L /etc/resolv.conf "$d/run/systemd/resolve/resolv.conf" if [ -e "$d/etc/resolv.conf" ] || [ -L "$d/etc/resolv.conf" ]; then if [ ! -e "$d/etc/resolv.conf.privex-orig" ] && [ ! -L "$d/etc/resolv.conf.privex-orig" ]; then mv "$d/etc/resolv.conf" "$d/etc/resolv.conf.privex-orig" else rm -f "$d/etc/resolv.conf" fi fi cp -L /etc/resolv.conf "$d/etc/resolv.conf" chmod 644 "$d/etc/resolv.conf" "$d/run/systemd/resolve/stub-resolv.conf" "$d/run/systemd/resolve/resolv.conf" # no services may start inside the chroot printf '#!/bin/sh\nexit 101\n' > "$d/usr/sbin/policy-rc.d" chmod 755 "$d/usr/sbin/policy-rc.d" CHROOT_DIR="$d" } chroot_teardown() { local d="$1" rm -f "$d/usr/sbin/policy-rc.d" if [ -e "$d/etc/resolv.conf.privex-orig" ] || [ -L "$d/etc/resolv.conf.privex-orig" ]; then rm -f "$d/etc/resolv.conf" mv "$d/etc/resolv.conf.privex-orig" "$d/etc/resolv.conf" fi umount "$d/run" 2>/dev/null || umount -l "$d/run" 2>/dev/null || true umount -R "$d/dev" 2>/dev/null || umount -l "$d/dev" 2>/dev/null || true umount -R "$d/sys" 2>/dev/null || umount -l "$d/sys" 2>/dev/null || true umount "$d/proc" 2>/dev/null || umount -l "$d/proc" 2>/dev/null || true CHROOT_DIR="" } in_chroot() { chroot "$ROOT_MNT" /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root LANG=C.UTF-8 \ DEBIAN_FRONTEND=noninteractive /bin/sh -c 'umask 022; exec "$@"' sh "$@" } # ---------------------------------------------------------------- detection ROOT_PART="" ROOT_FS="" BOOT_PART="" ESP_PART="" BIOS_PART="" MODE="" OS_ID="" OS_VER="" OS_NAME="" STATE_FOUND="" STATE_STAGE="" detect_disk() { if [ -n "$DISK" ]; then [ -b "$DISK" ] || die "$DISK is not a block device" return fi local d t p found cands="" while read -r d t; do [ "$t" = disk ] || continue case "$d" in /dev/loop*|/dev/sr*|/dev/zram*|/dev/ram*|/dev/fd*) continue ;; esac # a VPS disk carries a GPT with an ext4 or LUKS partition found="" for p in $(list_parts "$d"); do case "$(fs_type "$p")" in ext4|crypto_LUKS) found=y ;; esac done [ -z "$found" ] || cands="$cands $d" done < <(lsblk -dnpo NAME,TYPE) # shellcheck disable=SC2086 set -- $cands [ $# -ge 1 ] || die "No VPS disk found (no disk with an ext4 or LUKS partition)." [ $# -eq 1 ] || die "More than one possible disk:$cands. Pick one with --disk." DISK="$1" } find_state() { # look for our state directory on ext4 partitions of the disk local p m STATE_FOUND="" STATE_STAGE="" mkdir -p "$MNT/probe" for p in $(list_parts "$DISK"); do [ "$(fs_type "$p")" = ext4 ] || continue [ "$p" = "$ROOT_PART" ] && continue m="$MNT/probe" mount -o ro,noload "$p" "$m" 2>/dev/null || continue if [ -r "$m/$STATE_DIR_NAME/state" ]; then STATE_FOUND="$p" STATE_STAGE=$(sed -n 's/^STAGE=//p' "$m/$STATE_DIR_NAME/state" | sed -n '$p') fi umount "$m" [ -z "$STATE_FOUND" ] || return 0 done return 0 } state_get() { # state_get KEY (state partition mounted at $BOOT_MNT) sed -n "s/^$1=//p" "$BOOT_MNT/$STATE_DIR_NAME/state" 2>/dev/null | sed -n '$p' } state_set_stage() { [ "$DRY_RUN" = 0 ] || return 0 echo "STAGE=$1" >> "$BOOT_MNT/$STATE_DIR_NAME/state" sync } check_not_mounted() { local p for p in "$DISK" $(list_parts "$DISK"); do if findmnt -rn -S "$p" >/dev/null 2>&1; then die "$p is mounted ($(findmnt -rn -o TARGET -S "$p" | sed -n 1p)). Unmount the VPS disk first." fi done if [ -e "/dev/mapper/$MAPPER" ]; then die "/dev/mapper/$MAPPER is already open. Close it first: umount it, then 'cryptsetup close $MAPPER'." fi } detect_layout() { local p t last_start=-1 s ROOT_PART="" BIOS_PART="" ESP_PART="" for p in $(list_parts "$DISK"); do t=$(part_type "$p") case "$t" in "$TYPE_BIOS") BIOS_PART="$p" ;; "$TYPE_ESP") ESP_PART="$p" ;; esac # the root partition is the one numbered 1 on Privex templates if [ "$(part_num "$p")" = 1 ]; then ROOT_PART="$p"; fi s=$(part_start "$p") [ "$s" -gt "$last_start" ] && last_start=$s && LAST_PART="$p" done [ "$(blkid -p -o value -s PTTYPE "$DISK" 2>/dev/null)" = gpt ] || die "$DISK has no GPT partition table; this is not a Privex VPS template layout." [ -n "$ROOT_PART" ] || die "No partition 1 (root) on $DISK." [ -n "$BIOS_PART" ] || die "No BIOS boot partition on $DISK; unexpected layout." ROOT_FS=$(fs_type "$ROOT_PART") } inspect_os() { # root ext4 mounted read-only at $ROOT_MNT local f="$ROOT_MNT/etc/os-release" [ -r "$f" ] || f="$ROOT_MNT/usr/lib/os-release" [ -r "$f" ] || die "No /etc/os-release on $ROOT_PART; not a supported system." OS_ID=$(sed -n 's/^ID=//p' "$f" | tr -d '"') OS_VER=$(sed -n 's/^VERSION_ID=//p' "$f" | tr -d '"') OS_NAME=$(sed -n 's/^PRETTY_NAME=//p' "$f" | tr -d '"') case "$OS_ID $OS_VER" in "debian 12"|"debian 13"|"ubuntu 22.04"|"ubuntu 24.04") ;; *) die "Unsupported system: ${OS_NAME:-$OS_ID $OS_VER}. Supported: Debian 12, Debian 13, Ubuntu 22.04, Ubuntu 24.04." ;; esac # (an interrupted run may already have moved /boot to the privex-boot partition) ls "$ROOT_MNT"/boot/vmlinuz-* >/dev/null 2>&1 || [ "$(fstab_field /boot 1)" != "" ] \ || lsblk -lno PARTLABEL "$DISK" | grep -qx "$BOOT_PARTNAME" || die "No kernel found in /boot." } fstab_field() { # fstab_field MOUNTPOINT FIELDNO (from $ROOT_MNT/etc/fstab) awk -v mp="$1" -v f="$2" '$1 !~ /^#/ && $2==mp { print $f; exit }' "$ROOT_MNT/etc/fstab" } resolve_spec() { # UUID=/LABEL=/PARTUUID=/path -> device case "$1" in UUID=*|LABEL=*|PARTUUID=*|PARTLABEL=*) blkid -l -o device -t "$1" 2>/dev/null || true ;; /dev/*) readlink -f "$1" ;; *) echo "" ;; esac } decide_mode() { local bspec bdev rspec rdev rspec=$(fstab_field / 1) rdev=$(resolve_spec "$rspec") if [ -n "$rdev" ] && [ "$(readlink -f "$rdev")" != "$(readlink -f "$ROOT_PART")" ]; then die "/etc/fstab mounts / from $rspec ($rdev), not $ROOT_PART; unexpected layout." fi [ "$(fstab_field / 3)" = ext4 ] || die "The root file system in /etc/fstab is not ext4." bspec=$(fstab_field /boot 1) if [ -n "$bspec" ]; then bdev=$(resolve_spec "$bspec") if [ -z "$bdev" ] || [ ! -b "$bdev" ]; then die "/etc/fstab has /boot on $bspec but that partition was not found."; fi [ "$(fs_type "$bdev")" = ext4 ] || die "/boot ($bdev) is not ext4." [ "$(readlink -f "$bdev")" != "$(readlink -f "$ROOT_PART")" ] || die "/boot points at the root partition." MODE="existing"; BOOT_PART=$(readlink -f "$bdev") else MODE="carve" BOOT_PART="" # root must stay the last partition (so it can grow after a disk upgrade) [ "$LAST_PART" = "$ROOT_PART" ] || die "The root partition is not the last partition on the disk; unexpected layout." # an earlier, interrupted run may already have created the /boot partition in front of root local p for p in $(list_parts "$DISK"); do if [ "$(lsblk -dno PARTLABEL "$p")" = "$BOOT_PARTNAME" ]; then BOOT_PART="$p"; fi done fi } # ---------------------------------------------------------------- size planning SECTOR=512 MOVE_CHUNK=$((64 * 1048576)) # bytes copied per step while moving the root fs forward RAW_STATE_BYTES=1048576 # state kept in the last MiB of the root partition during the move plan_sizes() { # carve: sets PS PZ DS FS_BYTES TARGET_FS_BLOCKS; always: ROOT_BS ROOT_BLOCKS ROOT_MIN_BLOCKS local bs blocks minb max_bytes bs=$(fs_blocksize "$ROOT_PART"); blocks=$(fs_blockcount "$ROOT_PART") if [ -z "$bs" ] || [ -z "$blocks" ]; then die "Cannot read the root file system size (dumpe2fs)."; fi ROOT_BS=$bs; ROOT_BLOCKS=$blocks minb=$(fs_minblocks "$ROOT_PART") [ -n "$minb" ] || die "resize2fs could not estimate the minimum size of $ROOT_PART." ROOT_MIN_BLOCKS=$minb PS=$(part_start "$ROOT_PART"); PZ=$(part_size "$ROOT_PART") if [ "$MODE" = carve ] && [ -z "$BOOT_PART" ]; then DS=$((BOOT_MIB * 2048)) # new layout: [ /boot: DS sectors ][ root: the rest, up to the old end ] # the moved fs must leave room for the LUKS header and the state area at the end max_bytes=$(( (PZ - DS) * SECTOR - (LUKS_RESERVE_MIB + 4) * 1048576 - RAW_STATE_BYTES )) max_bytes=$(( max_bytes / 1048576 * 1048576 )) TARGET_FS_BLOCKS=$(( max_bytes / bs )) [ "$TARGET_FS_BLOCKS" -le "$blocks" ] || TARGET_FS_BLOCKS=$blocks FS_BYTES=$(( TARGET_FS_BLOCKS * bs )) else TARGET_FS_BLOCKS=$(( (PZ * SECTOR - (LUKS_RESERVE_MIB + 4) * 1048576) / bs )) [ "$TARGET_FS_BLOCKS" -le "$blocks" ] || TARGET_FS_BLOCKS=$blocks fi # keep at least 300 MiB free after shrinking (packages, logs) if [ $(( (TARGET_FS_BLOCKS - minb) * bs )) -lt $((300 * 1048576)) ]; then die "Not enough free space on the root file system. It must shrink to $(human $((TARGET_FS_BLOCKS * bs))) but needs about $(human $((minb * bs))) plus 300 MiB headroom. Free some space (or upgrade the disk) and try again." fi } # ---------------------------------------------------------------- raw state (during the move) # While the root fs is being moved there is no safe file system to keep state in, so # it lives in the last MiB of the root partition (whose end never changes). RAW_MAGIC="PRIVEX-ENCRYPT-MOVE-STATE v1" RAW_STAGE="" MOVE_NEXT="" # Writing to the whole disk makes udev re-read the partition table when the device is # closed, so partition devices and their sysfs entries vanish for a moment afterwards: # the offset is computed once (the end of root never changes) and every whole-disk # write is followed by "udevadm settle". RAW_OFF="" raw_state_offset() { # in 512-byte sectors from the start of the disk [ -n "$RAW_OFF" ] || RAW_OFF=$(( $(part_start "$ROOT_PART") + $(part_size "$ROOT_PART") - RAW_STATE_BYTES / SECTOR )) echo "$RAW_OFF" } raw_state_read() { # sets RAW_STAGE and the saved plan if our marker is there local f="$MNT/raw-state" v RAW_STAGE="" dd if="$DISK" of="$f" bs=512 iflag=direct skip="$(raw_state_offset)" count=$((RAW_STATE_BYTES / SECTOR)) status=none 2>/dev/null || return 0 tr -d '\000' < "$f" > "$f.txt" [ "$(sed -n 1p "$f.txt")" = "$RAW_MAGIC" ] || return 0 rv() { sed -n "s/^$1=//p" "$f.txt" | sed -n '$p'; } RAW_STAGE=$(rv STAGE); OS_ID=$(rv OS_ID); OS_VER=$(rv OS_VER); OS_NAME=$(rv OS_NAME) PS=$(rv PS); PZ=$(rv PZ); DS=$(rv DS); FS_BYTES=$(rv FS_BYTES); MOVE_NEXT=$(rv NEXT) [ -n "$OPT_NET_MODE" ] || NET_MODE=$(rv NET_MODE) [ -n "$OPT_DHCP_TIMEOUT" ] || DHCP_TIMEOUT=$(rv DHCP_TIMEOUT) [ -n "$OPT_CONSOLE" ] || CONSOLE=$(rv CONSOLE) NET_MAC=$(rv NET_MAC); NET_IPV4=$(rv NET_IPV4); NET_GW4=$(rv NET_GW4); NET_IPV6=$(rv NET_IPV6); NET_GW6=$(rv NET_GW6) KEYS=$(sed -n 's/^KEY=//p' "$f.txt") for v in PS PZ DS FS_BYTES; do case "${!v}" in ''|*[!0-9]*) die "The saved move state on $ROOT_PART is damaged ($v). Do not reboot into the VPS; contact Privex support." ;; esac done } raw_state_write() { # $1 = stage [ "$DRY_RUN" = 0 ] || return 0 local f="$MNT/raw-state.new" { echo "$RAW_MAGIC" echo "# privex-vps-encrypt.sh: the root file system is being moved; rerun the script to continue." echo "STAGE=$1"; echo "NEXT=$MOVE_NEXT" echo "OS_ID=$OS_ID"; echo "OS_VER=$OS_VER"; echo "OS_NAME=$OS_NAME" echo "PS=$PS"; echo "PZ=$PZ"; echo "DS=$DS"; echo "FS_BYTES=$FS_BYTES" echo "NET_MODE=$NET_MODE"; echo "DHCP_TIMEOUT=$DHCP_TIMEOUT"; echo "CONSOLE=$CONSOLE" echo "NET_MAC=$NET_MAC"; echo "NET_IPV4=$NET_IPV4"; echo "NET_GW4=$NET_GW4" echo "NET_IPV6=$NET_IPV6"; echo "NET_GW6=$NET_GW6" printf '%s\n' "$KEYS" | sed 's/^/KEY=/' } > "$f" [ "$(stat -c %s "$f")" -lt "$RAW_STATE_BYTES" ] || die "Internal error: state too large." truncate -s "$RAW_STATE_BYTES" "$f" dd if="$f" of="$DISK" bs=512 oflag=direct seek="$(raw_state_offset)" count=$((RAW_STATE_BYTES / SECTOR)) conv=notrunc,fsync status=none \ || die "Could not write the move state to $DISK." settle RAW_STAGE="$1" } raw_state_wipe() { dd if=/dev/zero of="$DISK" bs=512 seek="$(raw_state_offset)" count=$((RAW_STATE_BYTES / SECTOR)) conv=notrunc,fsync status=none || true settle_disk RAW_STAGE="" } # ---------------------------------------------------------------- unlock environment config (written inside the chroot) write_unlock_config() { # $1 = root dir; uses KEYS, NET_*, NET_MODE local d="$1" dbdir conf if [ -d "$d/etc/dropbear/initramfs" ]; then dbdir="$d/etc/dropbear/initramfs"; conf="$dbdir/dropbear.conf" elif [ -d "$d/etc/dropbear-initramfs" ]; then dbdir="$d/etc/dropbear-initramfs"; conf="$dbdir/config" else die "dropbear-initramfs configuration directory not found after installation." fi [ -e "$conf.privex-orig" ] || { [ -e "$conf" ] && cp -p "$conf" "$conf.privex-orig"; } || true { echo "# Written by privex-vps-encrypt.sh: SSH server used to unlock the disk at boot." echo "# -p 2222: port; -s: no passwords; -j -k: no port forwarding; -I 300: idle timeout" echo 'DROPBEAR_OPTIONS="-p 2222 -s -j -k -I 300"' } > "$conf" printf '%s\n' "$KEYS" > "$dbdir/authorized_keys" chmod 600 "$dbdir/authorized_keys" DROPBEAR_DIR="${dbdir#"$d"}" mkdir -p "$d/etc/initramfs-tools/conf.d" "$d/etc/initramfs-tools/hooks" \ "$d/etc/initramfs-tools/scripts/init-premount" "$d/etc/initramfs-tools/scripts/init-bottom" cat > "$d/etc/initramfs-tools/conf.d/privex-encrypt" <<'EOF' # Written by privex-vps-encrypt.sh. # The network for SSH unlocking is set up by scripts/init-premount/privex-net # (DHCP and/or the VPS's static address, see /etc/initramfs-tools/privex-net.conf), # so initramfs-tools' own ip= handling stays off. IP=none EOF { echo "# Written by privex-vps-encrypt.sh: network used while the disk waits for its passphrase." echo "# NET_MODE: auto = DHCP first, then the static address; dhcp; static." echo "# Run update-initramfs -u after changing this file." echo "NET_MODE=$NET_MODE" echo "DHCP_TIMEOUT=$DHCP_TIMEOUT" echo "MAC=$NET_MAC" echo "ADDR4=$NET_IPV4" echo "GW4=$NET_GW4" echo "ADDR6=$NET_IPV6" echo "GW6=$NET_GW6" } > "$d/etc/initramfs-tools/privex-net.conf" chmod 644 "$d/etc/initramfs-tools/privex-net.conf" cat > "$d/etc/initramfs-tools/hooks/privex-net" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh: copies the unlock network config and tools into the initramfs. PREREQ="" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac . /usr/share/initramfs-tools/hook-functions mkdir -p "$DESTDIR/conf" cp /etc/initramfs-tools/privex-net.conf "$DESTDIR/conf/privex-net.conf" # the real iproute2 binary (not a symlink: in the initramfs "ip" may be busybox) for ipbin in /usr/sbin/ip /sbin/ip /usr/bin/ip /bin/ip; do if [ -x "$ipbin" ]; then copy_exec "$(readlink -f "$ipbin")" /sbin/privex-ip; break; fi done if [ ! -e "$DESTDIR/bin/ipconfig" ] && [ -x /usr/lib/klibc/bin/ipconfig ]; then copy_exec /usr/lib/klibc/bin/ipconfig /bin/ipconfig fi EOF cat > "$d/etc/initramfs-tools/scripts/init-premount/privex-net" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh: network for SSH unlocking (dropbear on port 2222). PREREQ="udev" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac [ -r /conf/privex-net.conf ] || exit 0 . /conf/privex-net.conf IPB=/sbin/privex-ip [ -x "$IPB" ] || IPB=ip find_dev() { for n in /sys/class/net/*; do [ -e "$n/device" ] || continue if [ -n "$MAC" ]; then [ "$(cat "$n/address")" = "$MAC" ] && { echo "${n##*/}"; return 0; } else echo "${n##*/}"; return 0 fi done # MAC not found: fall back to the first network card for n in /sys/class/net/*; do [ -e "$n/device" ] && { echo "${n##*/}"; return 0; } done return 1 } privex_net() { i=0; dev="" while [ $i -lt 60 ]; do dev=$(find_dev) && [ -n "$dev" ] && break sleep 1; i=$((i + 1)) done [ -n "$dev" ] || { echo "privex-net: no network card found"; return 0; } echo "$dev" > /run/privex-net.dev $IPB link set dev "$dev" up # static IPv6 first: it needs no DHCP and makes IPv6-only VPSes reachable at once if [ "$NET_MODE" != dhcp ] && [ -n "$ADDR6" ]; then $IPB -6 addr add "$ADDR6" dev "$dev" nodad [ -z "$GW6" ] || $IPB -6 route add default via "$GW6" dev "$dev" onlink fi got4="" if [ "$NET_MODE" != static ]; then if ipconfig -t "${DHCP_TIMEOUT:-20}" -c dhcp -d "$dev" >/run/privex-net.log 2>&1; then got4=1 fi fi if [ -z "$got4" ] && [ "$NET_MODE" != dhcp ] && [ -n "$ADDR4" ]; then $IPB addr add "$ADDR4" dev "$dev" [ -z "$GW4" ] || $IPB route add default via "$GW4" dev "$dev" onlink fi addrs=$($IPB -o addr show dev "$dev" | while read -r _ _ _ addr _ scope _; do [ "$scope" = link ] || printf ' %s' "$addr"; done) printf '\n[SSH unlock: port 2222 on %s:%s]\n' "$dev" "${addrs:- no address}" } privex_net & echo $! > /run/privex-net.pid exit 0 EOF cat > "$d/etc/initramfs-tools/scripts/init-premount/privex-console" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh. cryptsetup's own prompt only appears on the LAST # console= of the kernel command line. This asks for the passphrase on the other # console (VGA tty1 or serial ttyS0) too, by running cryptroot-unlock there; the first # correct answer from either console (or from SSH) unlocks the disk. PREREQ="" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac [ -x /bin/cryptroot-unlock ] || exit 0 primary=tty1 for x in $(cat /proc/cmdline); do case "$x" in console=*) primary=${x#console=}; primary=${primary%%,*} ;; esac done [ "$primary" = tty0 ] && primary=tty1 second_prompt() { while [ ! -e /run/privex-console.stop ]; do # cryptroot-unlock gives up after 10 s without askpass, so wait for askpass's fifo if [ -p /lib/cryptsetup/passfifo ]; then /bin/cryptroot-unlock <"/dev/$1" >"/dev/$1" 2>&1 fi sleep 1 done } for t in tty1 ttyS0; do [ "$t" = "$primary" ] && continue [ -c "/dev/$t" ] || continue if [ "$t" = ttyS0 ]; then # only if the VM really has a serial port grep -q '^0: uart:[0-9]' /proc/tty/driver/serial 2>/dev/null || continue fi second_prompt "$t" & echo $! >> /run/privex-console.pids done exit 0 EOF cat > "$d/etc/initramfs-tools/scripts/init-bottom/privex-console" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh: stop the second passphrase prompt (see init-premount/privex-console). PREREQ="" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac [ -r /run/privex-console.pids ] || exit 0 : > /run/privex-console.stop for pid in $(cat /run/privex-console.pids); do # children first (cryptroot-unlock), then the loop itself sed -nr "s/^([0-9]+) \(.*\) \S $pid .*/\1/p" /proc/[0-9]*/stat 2>/dev/null | while read -r c; do kill -TERM "$c" 2>/dev/null; done kill -TERM "$pid" 2>/dev/null done rm -f /run/privex-console.pids /run/privex-console.stop exit 0 EOF chmod 755 "$d/etc/initramfs-tools/scripts/init-premount/privex-console" \ "$d/etc/initramfs-tools/scripts/init-bottom/privex-console" mkdir -p "$d/etc/initramfs-tools/scripts/init-top" cat > "$d/etc/initramfs-tools/scripts/init-top/privex-net" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh. With IP=none, Debian 12's configure_networking() # (run by dropbear's init-premount script) still sources /run/net-*.conf unconditionally # and dies if there is none, so dropbear never starts. Give it an empty file to source. PREREQ="" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac if grep -qE '^[[:space:]]*\. /run/net-\*\.conf[[:space:]]*$' /scripts/functions 2>/dev/null; then mkdir -p /run echo "# placeholder from privex-net (see /scripts/init-top/privex-net)" > /run/net-privex-placeholder.conf fi exit 0 EOF chmod 755 "$d/etc/initramfs-tools/scripts/init-top/privex-net" cat > "$d/etc/initramfs-tools/scripts/init-bottom/privex-net" <<'EOF' #!/bin/sh # Written by privex-vps-encrypt.sh: remove the unlock network before the real system starts, # so the system's own network configuration (netplan/cloud-init) is not disturbed. PREREQ="" prereqs() { echo "$PREREQ"; } case "$1" in prereqs) prereqs; exit 0 ;; esac IPB=/sbin/privex-ip [ -x "$IPB" ] || IPB=ip if [ -r /run/privex-net.pid ]; then pid=$(cat /run/privex-net.pid) t=0 while [ -d "/proc/$pid" ] && [ $t -lt 90 ]; do sleep 1; t=$((t + 1)); done fi if [ -r /run/privex-net.dev ]; then dev=$(cat /run/privex-net.dev) $IPB route flush dev "$dev" 2>/dev/null $IPB -6 route flush dev "$dev" 2>/dev/null $IPB addr flush dev "$dev" 2>/dev/null $IPB link set dev "$dev" down 2>/dev/null # Ubuntu's configure_networking may have turned a DHCP lease into /run/netplan/.yaml rm -f "/run/netplan/$dev.yaml" fi rm -f /run/net-*.conf /run/net6-*.conf /run/privex-net.pid /run/privex-net.dev exit 0 EOF chmod 755 "$d/etc/initramfs-tools/hooks/privex-net" \ "$d/etc/initramfs-tools/scripts/init-premount/privex-net" \ "$d/etc/initramfs-tools/scripts/init-bottom/privex-net" # cloud-init: never try to grow the (now encrypted) root partition if [ -d "$d/etc/cloud/cloud.cfg.d" ]; then cat > "$d/etc/cloud/cloud.cfg.d/99-privex-encrypt.cfg" <<'EOF' # Written by privex-vps-encrypt.sh: the root file system is inside LUKS (cryptroot). # growpart cannot grow it without the passphrase, so growing after a disk upgrade # is a manual step (growpart, cryptsetup resize cryptroot, resize2fs). growpart: mode: 'off' resize_rootfs: false EOF chmod 644 "$d/etc/cloud/cloud.cfg.d/99-privex-encrypt.cfg" fi # GRUB: the passphrase prompt goes to the last console= on the kernel command line mkdir -p "$d/etc/default/grub.d" if [ "$CONSOLE" = vga ]; then cat > "$d/etc/default/grub.d/99-privex-encrypt.cfg" <<'EOF' # Written by privex-vps-encrypt.sh: the disk passphrase prompt is shown on the LAST # console= of the kernel command line, so put the VGA console (the dashboard console) last. GRUB_CMDLINE_LINUX="$(printf '%s' "$GRUB_CMDLINE_LINUX" | sed -E 's/(^| )console=tty[0-9]+( |$)/ /g; s/ +/ /g; s/^ //; s/ $//') console=tty1" GRUB_CMDLINE_LINUX_DEFAULT="$(printf '%s' "$GRUB_CMDLINE_LINUX_DEFAULT" | sed -E 's/(^| )console=tty[0-9]+( |$)/ /g; s/ +/ /g; s/^ //; s/ $//') console=tty1" EOF else cat > "$d/etc/default/grub.d/99-privex-encrypt.cfg" <<'EOF' # Written by privex-vps-encrypt.sh: the disk passphrase prompt is shown on the LAST # console= of the kernel command line, so put the serial console last. GRUB_CMDLINE_LINUX="$(printf '%s' "$GRUB_CMDLINE_LINUX" | sed -E 's/(^| )console=ttyS[0-9][^ ]*( |$)/ /g; s/ +/ /g; s/^ //; s/ $//') console=ttyS0,115200" GRUB_CMDLINE_LINUX_DEFAULT="$(printf '%s' "$GRUB_CMDLINE_LINUX_DEFAULT" | sed -E 's/(^| )console=ttyS[0-9][^ ]*( |$)/ /g; s/ +/ /g; s/^ //; s/ $//') console=ttyS0,115200" EOF fi cat >> "$d/etc/default/grub.d/99-privex-encrypt.cfg" <<'EOF' # root is /dev/mapper/cryptroot: a device-mapper device has no PARTUUID, so do not use one GRUB_DISABLE_LINUX_PARTUUID=true EOF chmod 644 "$d/etc/default/grub.d/99-privex-encrypt.cfg" } # ---------------------------------------------------------------- phases phase_prepare() { # root ext4 mounted rw at $ROOT_MNT (and /boot if separate) step "Installing cryptsetup-initramfs and dropbear-initramfs in the VPS (apt)" chroot_setup "$ROOT_MNT" info "(dropbear may warn about an invalid authorized_keys file: the keys are added in the next step)" in_chroot apt-get update || die "apt-get update failed inside the VPS. Check the network in SystemRescue (see the instructions) and run the script again; nothing has been encrypted yet." in_chroot apt-get install -y --no-install-recommends -o Dpkg::Options::=--force-confold \ cryptsetup cryptsetup-initramfs dropbear-initramfs \ || die "Package installation failed. Nothing has been encrypted yet; fix the problem and run the script again." step "Writing the unlock configuration (dropbear, network, cloud-init, GRUB console)" write_unlock_config "$ROOT_MNT" info "dropbear config: $DROPBEAR_DIR (port 2222, keys only)" info "unlock network: /etc/initramfs-tools/privex-net.conf" chroot_teardown "$ROOT_MNT" } # Debian 12/13, Ubuntu 22.04: make room for /boot at the START of the root partition, so # root stays the last partition and can grow later: # 1. shrink the root fs (resize2fs) # 2. move it forward by DS sectors, in 64 MiB chunks from the end backwards; each chunk # is copied before its source can be overwritten, and the next chunk number is saved # in the raw state after every chunk, so an interrupted move is simply continued # 3. check the moved fs (e2fsck -fn through a read-only loop device) # 4. partition table: root = old start + DS .. old end (same number/type/PARTUUID), # /boot = the freed DS sectors in front of it # 5. mkfs /boot, copy /boot into it, save the state there, wipe the raw state phase_carve() { if [ -z "$BOOT_PART" ] && [ -z "$RAW_STAGE" ]; then step "Shrinking the root file system" run_fsck "$ROOT_PART" if [ "$(fs_blockcount "$ROOT_PART")" -gt "$TARGET_FS_BLOCKS" ]; then info "resize2fs $ROOT_PART to $(human "$FS_BYTES")" resize2fs "$ROOT_PART" "$TARGET_FS_BLOCKS" || die "resize2fs failed; nothing else was changed. Run 'e2fsck -f $ROOT_PART', then the script again." fi [ $(( $(fs_blockcount "$ROOT_PART") * ROOT_BS )) -le "$FS_BYTES" ] || die "Internal check failed: file system larger than planned." MOVE_NEXT=$(( (FS_BYTES + MOVE_CHUNK - 1) / MOVE_CHUNK - 1 )) disable_old_boot raw_state_write moving fi if [ "$RAW_STAGE" = moving ]; then disable_old_boot move_root_fs raw_state_write moved fi settle_disk if [ "$RAW_STAGE" = moved ]; then step "Rewriting the partition table: /boot in front, root behind it up to the old end" flush_disk_caches if [ "$(part_start "$ROOT_PART")" = "$PS" ]; then echo "start=$((PS + DS)), size=$((PZ - DS))" \ | sfdisk --no-reread --no-tell-kernel -N "$(part_num "$ROOT_PART")" "$DISK" >/dev/null \ || die "sfdisk could not move the root partition. Run the script again." reread_parts fi [ "$(part_start "$ROOT_PART")" = $((PS + DS)) ] || die "The kernel still sees the old root partition; reboot SystemRescue and rerun." BOOT_PART="" local p for p in $(list_parts "$DISK"); do [ "$(lsblk -dno PARTLABEL "$p")" = "$BOOT_PARTNAME" ] && BOOT_PART="$p" done if [ -z "$BOOT_PART" ]; then printf 'start=%s, size=%s, type=%s, name="%s"\n' "$PS" "$DS" "$TYPE_LINUX_FS" "$BOOT_PARTNAME" \ | sfdisk --no-reread --no-tell-kernel --append "$DISK" >/dev/null || die "sfdisk could not create the /boot partition." reread_parts for p in $(list_parts "$DISK"); do [ "$(part_start "$p")" = "$PS" ] && BOOT_PART="$p" done fi [ -n "$BOOT_PART" ] || die "The new /boot partition did not appear." info "/boot: $BOOT_PART ($(human $(( $(part_size "$BOOT_PART") * SECTOR )))), root: $ROOT_PART ($(human $(( $(part_size "$ROOT_PART") * SECTOR ))))" [ "$(fs_type "$ROOT_PART")" = ext4 ] || die "No ext4 file system at the start of the moved root partition." ROOT_BS=$(fs_blocksize "$ROOT_PART") fi # BOOT_PART exists here; (re)make it unless our state directory is already on it if ! boot_has_state "$BOOT_PART"; then step "Copying /boot to $BOOT_PART" run_fsck "$ROOT_PART" mkfs.ext4 -q -F -L "$BOOT_LABEL" "$BOOT_PART" || die "mkfs.ext4 failed on $BOOT_PART" mount "$ROOT_PART" "$ROOT_MNT" mount "$BOOT_PART" "$BOOT_MNT" cp -a "$ROOT_MNT/boot/." "$BOOT_MNT/" || die "Copying /boot failed." diff -r --no-dereference -x lost+found "$ROOT_MNT/boot" "$BOOT_MNT" >/dev/null \ || die "The copy of /boot differs from the original; nothing was encrypted. Run the script again." write_state_file sync # the old /boot files in the root file system are hidden under the mount point from now on find "$ROOT_MNT/boot" -mindepth 1 -maxdepth 1 ! -name efi -exec rm -rf {} + umount "$BOOT_MNT"; umount "$ROOT_MNT" ok "/boot copied; state saved on $BOOT_PART" fi raw_state_wipe } # While the fs is moved, the old system must not boot: GRUB would still find the old # copy at the start of the partition, and Linux would mount it read-write and write # into data that is being moved. Wiping the MBR boot code (bytes 0-439; the partition # table is untouched) stops SeaBIOS from booting the disk; grub-install puts it back # at the end of the conversion. disable_old_boot() { dd if=/dev/zero of="$DISK" bs=440 count=1 conv=notrunc,fsync status=none || die "Could not disable booting from $DISK." settle_disk } move_root_fs() { local base=$((PS * SECTOR)) shift=$((DS * SECTOR)) i off len n loop total n=$(( (FS_BYTES + MOVE_CHUNK - 1) / MOVE_CHUNK )) i=$MOVE_NEXT step "Moving the root file system forward by $(human "$shift") ($(human "$FS_BYTES"), $n chunks)" [ "$i" -lt $((n - 1)) ] && info "Continuing an interrupted move at chunk $((i + 1)) of $n" info "If this is interrupted, boot SystemRescue again and rerun the script: the move continues." [ $((MOVE_CHUNK)) -le "$shift" ] || die "Internal error: chunk larger than the shift." # resize2fs/e2fsck wrote through the partition device; its page cache is separate from the # whole disk's, so write everything back and drop both caches, and copy with direct I/O flush_disk_caches total=$n while [ "$i" -ge 0 ]; do off=$((i * MOVE_CHUNK)); len=$MOVE_CHUNK [ $((off + len)) -le "$FS_BYTES" ] || len=$((FS_BYTES - off)) dd if="$DISK" of="$DISK" bs=4M iflag=direct,skip_bytes,count_bytes oflag=direct,seek_bytes conv=notrunc,fsync \ skip=$((base + off)) seek=$((base + off + shift)) count="$len" status=none \ || die "Copying chunk $i failed. Run the script again to continue the move." MOVE_NEXT=$((i - 1)) raw_state_write moving if [ $(( (total - i) % 32 )) = 0 ]; then info " $(( (total - i) * 100 / total ))% moved"; fi i=$((i - 1)) done flush_disk_caches settle_disk info "Checking the moved file system (e2fsck -fn)" loop=$(losetup -r -f --show -o $((base + shift)) --sizelimit "$FS_BYTES" "$DISK") || die "losetup failed." if ! e2fsck -f -n "$loop"; then losetup -d "$loop" die "The moved file system has errors. Do not reboot into the VPS; contact Privex support (the data was not encrypted yet)." fi losetup -d "$loop" ok "root file system moved" } boot_has_state() { local r=1 [ "$(fs_type "$1")" = ext4 ] || return 1 mount -o ro,noload "$1" "$MNT/probe" 2>/dev/null || return 1 [ -r "$MNT/probe/$STATE_DIR_NAME/state" ] && r=0 umount "$MNT/probe" return $r } write_state_file() { # boot fs mounted at $BOOT_MNT mkdir -p "$BOOT_MNT/$STATE_DIR_NAME" { echo "# privex-vps-encrypt.sh state (no secrets). Delete this directory only after a successful conversion." echo "VERSION=$VERSION" echo "OS_ID=$OS_ID" echo "OS_VER=$OS_VER" echo "MODE=$MODE" echo "ROOT_PARTUUID=$(blkid -p -o value -s PART_ENTRY_UUID "$ROOT_PART")" echo "NET_MODE=$NET_MODE" echo "DHCP_TIMEOUT=$DHCP_TIMEOUT" echo "CONSOLE=$CONSOLE" echo "NET_MAC=$NET_MAC" echo "NET_IPV4=$NET_IPV4" echo "NET_GW4=$NET_GW4" echo "NET_IPV6=$NET_IPV6" echo "NET_GW6=$NET_GW6" echo "STAGE=boot-ready" } > "$BOOT_MNT/$STATE_DIR_NAME/state" printf '%s\n' "$KEYS" > "$BOOT_MNT/$STATE_DIR_NAME/authorized_keys" } pbkdf_memory_kib() { local mem mem=$(awk '/^MemTotal:/{print $2}' /proc/meminfo) mem=$((mem / 4)) [ "$mem" -le 1048576 ] || mem=1048576 [ "$mem" -ge 65536 ] || mem=65536 echo "$mem" } phase_encrypt() { local fsb step "Encrypting $ROOT_PART in place (LUKS2)" if [ "$(fs_type "$ROOT_PART")" = ext4 ]; then run_fsck "$ROOT_PART" ROOT_BS=$(fs_blocksize "$ROOT_PART") fsb=$(( $(fs_blockcount "$ROOT_PART") * ROOT_BS )) if [ "$fsb" -gt $(( $(part_size "$ROOT_PART") * SECTOR - LUKS_RESERVE_MIB * 1048576 )) ]; then local target=$(( ( $(part_size "$ROOT_PART") * SECTOR - (LUKS_RESERVE_MIB + 4) * 1048576 ) / ROOT_BS )) info "Shrinking the file system by $((LUKS_RESERVE_MIB + 4)) MiB to make room for the LUKS header" resize2fs "$ROOT_PART" "$target" || die "resize2fs failed." fi fsb=$(( $(fs_blockcount "$ROOT_PART") * ROOT_BS )) [ "$fsb" -le $(( $(part_size "$ROOT_PART") * SECTOR - LUKS_RESERVE_MIB * 1048576 )) ] \ || die "Internal check failed: no room for the LUKS header." disable_old_boot mount "$STATE_FOUND" "$BOOT_MNT"; state_set_stage encrypting; umount "$BOOT_MNT" info "This rewrites the whole partition ($(human $(( $(part_size "$ROOT_PART") * SECTOR )))) and can take a while." info "If it is interrupted, boot SystemRescue again and rerun this script to resume." cs_with_pass reencrypt --batch-mode --encrypt --type luks2 --reduce-device-size "${LUKS_RESERVE_MIB}M" \ --pbkdf argon2id --pbkdf-memory "$(pbkdf_memory_kib)" --progress-frequency 10 "$ROOT_PART" \ || die "cryptsetup reencrypt failed or was interrupted. Run the script again to resume." elif reencrypt_pending; then info "Resuming the interrupted encryption of $ROOT_PART" cs_with_pass open --test-passphrase "$ROOT_PART" 2>/dev/null \ || die "Wrong passphrase for $ROOT_PART. Run the script again with the passphrase you chose at the start." # after a crash in the middle of a block the reencryption metadata must be # recovered first ("Device requires reencryption recovery"); repair does that info "Recovering the reencryption metadata (cryptsetup repair)" cs_with_pass repair --batch-mode "$ROOT_PART" || die "cryptsetup repair failed. Do not reboot into the VPS; ask Privex support." cs_with_pass reencrypt --batch-mode --resume-only --progress-frequency 10 "$ROOT_PART" \ || die "Resuming the encryption failed. Run the script again." fi reencrypt_pending && die "Encryption is still not complete; run the script again." mount "$STATE_FOUND" "$BOOT_MNT"; state_set_stage encrypted; umount "$BOOT_MNT" ok "$ROOT_PART is LUKS2 encrypted" } reencrypt_pending() { local dump dump=$(cryptsetup luksDump "$ROOT_PART" 2>/dev/null || true) grep -q 'online-reencrypt' <<< "$dump" } phase_finalize() { local luks_uuid boot_uuid k kernels step "Opening the encrypted root and growing the file system into it" cs_with_pass open --allow-discards "$ROOT_PART" "$MAPPER" || die "Could not open $ROOT_PART (wrong passphrase?)." OPENED_MAPPER=1 run_fsck "/dev/mapper/$MAPPER" resize2fs "/dev/mapper/$MAPPER" >/dev/null 2>&1 || die "resize2fs on /dev/mapper/$MAPPER failed." mount "/dev/mapper/$MAPPER" "$ROOT_MNT" mount "$BOOT_PART" "$ROOT_MNT/boot" BOOT_MNT_SAVE="$BOOT_MNT"; BOOT_MNT="$ROOT_MNT/boot" if [ -n "$ESP_PART" ] && [ -d "$ROOT_MNT/boot/efi" ]; then mount "$ESP_PART" "$ROOT_MNT/boot/efi" 2>/dev/null || true; fi luks_uuid=$(cryptsetup luksUUID "$ROOT_PART") boot_uuid=$(blkid -p -o value -s UUID "$BOOT_PART") step "Updating /etc/fstab and /etc/crypttab" [ -e "$ROOT_MNT/etc/fstab.privex-orig" ] || cp -p "$ROOT_MNT/etc/fstab" "$ROOT_MNT/etc/fstab.privex-orig" awk -v boot="UUID=$boot_uuid" -v carve="$MODE" ' $1 !~ /^#/ && $2 == "/" { $1 = "/dev/mapper/cryptroot"; gsub(/,?x-systemd\.growfs/, "", $4); sub(/^,/, "", $4); print; next } $1 !~ /^#/ && $2 == "/boot" && carve == "carve" { next } { print } END { if (carve == "carve") print boot "\t/boot\text4\tdefaults\t0\t2" }' \ "$ROOT_MNT/etc/fstab.privex-orig" > "$ROOT_MNT/etc/fstab.new" chmod 644 "$ROOT_MNT/etc/fstab.new"; mv "$ROOT_MNT/etc/fstab.new" "$ROOT_MNT/etc/fstab" if [ -s "$ROOT_MNT/etc/crypttab" ] && [ ! -e "$ROOT_MNT/etc/crypttab.privex-orig" ]; then cp -p "$ROOT_MNT/etc/crypttab" "$ROOT_MNT/etc/crypttab.privex-orig" fi { grep -v -E '^[[:space:]]*cryptroot[[:space:]]' "$ROOT_MNT/etc/crypttab" 2>/dev/null || true echo "cryptroot UUID=$luks_uuid none luks,discard,initramfs,tries=0"; } > "$ROOT_MNT/etc/crypttab.new" chmod 644 "$ROOT_MNT/etc/crypttab.new"; mv "$ROOT_MNT/etc/crypttab.new" "$ROOT_MNT/etc/crypttab" info "fstab: / on /dev/mapper/cryptroot$([ "$MODE" = carve ] && echo ", /boot on UUID=$boot_uuid")" info "crypttab: cryptroot UUID=$luks_uuid none luks,discard,initramfs,tries=0" # make sure the unlock config is current (resume after a changed option, or keys from the state dir) if [ -z "$KEYS" ]; then KEYS=$(cat "$ROOT_MNT/etc/dropbear/initramfs/authorized_keys" "$ROOT_MNT/etc/dropbear-initramfs/authorized_keys" 2>/dev/null || true) fi [ -n "$KEYS" ] || die "No unlock SSH keys known; pass --authorized-keys FILE." write_unlock_config "$ROOT_MNT" chroot_setup "$ROOT_MNT" step "Rebuilding the initramfs (update-initramfs -u -k all)" in_chroot update-initramfs -u -k all || die "update-initramfs failed." step "Checking the initramfs" kernels=$(find "$ROOT_MNT/boot" -maxdepth 1 -name 'initrd.img-*' -printf '%f\n' | sed 's/^initrd.img-//' | sort) [ -n "$kernels" ] || die "No initramfs found in /boot." for k in $kernels; do verify_initramfs "$k" "$luks_uuid"; done step "Updating GRUB (update-grub, grub-install --target=i386-pc $DISK)" in_chroot update-grub || die "update-grub failed." in_chroot grub-install --target=i386-pc "$DISK" || die "grub-install failed." verify_grub "$boot_uuid" update_efi_stub "$boot_uuid" step "Host key of the unlock SSH server (port 2222)" show_dropbear_fingerprints chroot_teardown "$ROOT_MNT" rm -f "$BOOT_MNT/$STATE_DIR_NAME/authorized_keys" state_set_stage "done" cp -f "$LOG" "$ROOT_MNT/var/log/privex-vps-encrypt.log" 2>/dev/null || true sync BOOT_MNT="$BOOT_MNT_SAVE" } verify_initramfs() { # $1 kernel version, $2 luks uuid local list miss="" list=$(in_chroot lsinitramfs "/boot/initrd.img-$1") || die "lsinitramfs failed for $1" grep -qE '(^|/)sbin/dropbear$' <<< "$list" || miss="$miss dropbear" grep -qE '(^|/)bin/cryptroot-unlock$' <<< "$list" || miss="$miss cryptroot-unlock" grep -qE '(^|/)cryptroot/crypttab$' <<< "$list" || miss="$miss crypttab" grep -qE '(^|/)conf/privex-net.conf$' <<< "$list" || miss="$miss privex-net.conf" grep -qE 'scripts/init-premount/privex-console$' <<< "$list" || miss="$miss privex-console" grep -qE '/\.ssh/authorized_keys$' <<< "$list" || miss="$miss authorized_keys" grep -qE 'dm-crypt\.ko' <<< "$list" || miss="$miss dm-crypt.ko" [ -z "$miss" ] || die "initramfs for $1 is missing:$miss" in_chroot unmkinitramfs "/boot/initrd.img-$1" "/run/privex-initrd" >/dev/null 2>&1 || die "unmkinitramfs failed for $1" if [ -z "$(find "$ROOT_MNT/run/privex-initrd" -path '*sbin/privex-ip' -type f -size +20k)" ]; then rm -rf "$ROOT_MNT/run/privex-initrd" die "initramfs for $1 has no usable /sbin/privex-ip (iproute2) for the static unlock network" fi if ! grep -rqs "^cryptroot UUID=$2 " "$ROOT_MNT/run/privex-initrd" --include=crypttab; then rm -rf "$ROOT_MNT/run/privex-initrd" die "initramfs for $1 has no crypttab entry for cryptroot" fi rm -rf "$ROOT_MNT/run/privex-initrd" ok "initrd.img-$1: dropbear, cryptroot-unlock, crypttab (cryptroot UUID=$2), unlock network, keys" } verify_grub() { local cfg="$ROOT_MNT/boot/grub/grub.cfg" fsuuid fslabel r bad="" [ -r "$cfg" ] || die "No /boot/grub/grub.cfg after update-grub." grep -q "$1" "$cfg" || die "grub.cfg does not search the new /boot ($1)." grep -qE '^[[:space:]]*linux[[:space:]]' "$cfg" || die "grub.cfg has no kernel entries." fsuuid=$(blkid -p -o value -s UUID "/dev/mapper/$MAPPER") fslabel=$(blkid -p -o value -s LABEL "/dev/mapper/$MAPPER" || true) # every kernel line must find root inside the LUKS container # shellcheck disable=SC2013 # root=... values never contain spaces for r in $(grep -E '^[[:space:]]*linux[[:space:]]' "$cfg" | grep -oE ' root=[^ ]*' | sort -u); do r="${r#root=}" case "$r" in "/dev/mapper/$MAPPER"|"UUID=$fsuuid") ;; LABEL=*) { [ -n "$fslabel" ] && [ "$r" = "LABEL=$fslabel" ]; } || bad="$bad '$r'" ;; *) bad="$bad '$r'" ;; esac done [ -z "$bad" ] || die "grub.cfg boots with a wrong root device:$bad" ok "grub.cfg: kernel and initramfs from /boot ($1); root=$(grep -m1 -E '^[[:space:]]*linux[[:space:]]' "$cfg" | grep -oE ' root=[^ ]*' | cut -d= -f2-)" } update_efi_stub() { # point the EFI GRUB stub at the /boot file system (only used if the VPS is switched to UEFI) local f mountpoint -q "$ROOT_MNT/boot/efi" || return 0 for f in "$ROOT_MNT"/boot/efi/EFI/*/grub.cfg; do [ -f "$f" ] || continue grep -q 'search' "$f" || continue if ! grep -q "$1" "$f"; then cp -p "$f" "$f.privex-orig" 2>/dev/null || true printf "search.fs_uuid %s root\nset prefix=(\$root)'/grub'\nconfigfile \$prefix/grub.cfg\n" "$1" > "$f" info "EFI stub ${f#"$ROOT_MNT"} now loads GRUB from /boot ($1)" fi done } show_dropbear_fingerprints() { local f pub for f in "$ROOT_MNT$DROPBEAR_DIR"/dropbear_*_host_key; do [ -f "$f" ] || continue pub=$(in_chroot dropbearkey -y -f "${f#"$ROOT_MNT"}" 2>/dev/null | grep -E '^(ssh-|ecdsa-)' || true) [ -n "$pub" ] || continue printf '%s\n' "$pub" > "$MNT/hostkey.pub" info "$(ssh-keygen -l -f "$MNT/hostkey.pub" 2>/dev/null)" done rm -f "$MNT/hostkey.pub" } check_network() { local host case "$OS_ID" in debian) host=deb.debian.org ;; *) host=archive.ubuntu.com ;; esac if ! getent ahosts "$host" >/dev/null 2>&1; then die "SystemRescue cannot resolve $host. Its network normally comes up by DHCP; if it did not, set it up by hand (see the instructions), then run the script again. Nothing was changed." fi if command -v curl >/dev/null 2>&1 && ! curl -sS -m 20 -o /dev/null "http://$host/" 2>/dev/null; then die "SystemRescue cannot reach http://$host/. Set up the network first. Nothing was changed." fi ok "network: $host reachable" } print_result() { local addr="" [ -n "$NET_IPV4" ] && addr="${NET_IPV4%/*}" [ -z "$addr" ] && [ -n "$NET_IPV6" ] && addr="${NET_IPV6%/*}" [ -n "$addr" ] || addr="" cat < >(tee -a "$LOG") 2>&1; fi echo "${C_B}privex-vps-encrypt.sh $VERSION --grow$([ "$DRY_RUN" = 1 ] && echo " (dry run)")${C_0}" need_cmds lsblk sfdisk partx blockdev cryptsetup resize2fs findmnt awk step "Checking the encrypted root" src=$(findmnt -no SOURCE /) [ "$src" = "/dev/mapper/$MAPPER" ] || die "/ is on $src, not /dev/mapper/$MAPPER. Run --grow on the running, unlocked VPS (not in SystemRescue)." dev=$(cryptsetup status "$MAPPER" | awk '$1 == "device:" {print $2}') [ -b "$dev" ] || die "Cannot find the partition under $MAPPER." disk="/dev/$(lsblk -dno PKNAME "$dev")" [ -b "$disk" ] || die "Cannot find the disk of $dev." num=$(part_num "$dev"); start=$(part_start "$dev"); size=$(part_size "$dev") local p for p in $(list_parts "$disk"); do [ "$(part_start "$p")" -gt "$start" ] && die "$dev is not the last partition on $disk ($p follows it); cannot grow it in place." done dsz=$(blockdev --getsz "$disk"); last_usable=$((dsz - 34)) free=$((last_usable - (start + size) + 1)) before=$(df -h --output=size / | sed -n 2p | tr -d ' ') info "Disk $disk $(human $((dsz * SECTOR))); root partition $dev $(human $((size * SECTOR))); root fs $before" if [ "$free" -lt 2048 ]; then ok "Nothing to grow: the root partition already ends at the end of the disk." exit 0 fi step "Plan" info "1. grow partition $num of $disk by $(human $((free * SECTOR))) to the end of the disk" info "2. cryptsetup resize $MAPPER (may ask for the disk passphrase)" info "3. resize2fs /dev/mapper/$MAPPER (online)" if [ "$DRY_RUN" = 1 ]; then echo; echo "Dry run: nothing was changed."; exit 0; fi ask yes "Type YES to continue: " [ "$yes" = YES ] || die "Not confirmed; nothing was changed." step "Growing partition $num" if command -v growpart >/dev/null 2>&1; then growpart "$disk" "$num" || die "growpart failed." else echo ", +" | sfdisk --no-reread -N "$num" "$disk" >/dev/null || die "sfdisk failed." partx -u --nr "$num" "$disk" || die "partx could not tell the kernel about the new size; reboot, unlock and run --grow again." fi [ "$(part_size "$dev")" -gt "$size" ] || die "The kernel still sees the old partition size; reboot, unlock and run --grow again." ok "$dev is now $(human $(( $(part_size "$dev") * SECTOR )))" step "Resizing the LUKS mapping" if [ -n "$PASS_FD" ]; then read_passphrase 0 cs_with_pass resize "$MAPPER" || die "cryptsetup resize failed (wrong passphrase?). Run --grow again." else echo "If cryptsetup asks, enter the disk passphrase." cryptsetup resize "$MAPPER" <&9 || die "cryptsetup resize failed (wrong passphrase?). Run --grow again." fi step "Growing the file system (online)" resize2fs "/dev/mapper/$MAPPER" || die "resize2fs failed." after=$(df -h --output=size / | sed -n 2p | tr -d ' ') echo echo "${C_G}${C_B}Done: root file system $before -> $after.${C_0}" } # ================================================================ main main() { if [ "$GROW" = 1 ]; then [ "$(id -u)" = 0 ] || die "Run this script as root." grow_main exit 0 fi [ "$(id -u)" = 0 ] || die "Run this script as root." need_cmds lsblk blkid sfdisk partx blockdev udevadm e2fsck resize2fs dumpe2fs mkfs.ext4 \ cryptsetup findmnt mount umount chroot ssh-keygen awk sed grep diff dd losetup truncate local csv csv=$(cryptsetup --version | awk '{print $2}') case "$csv" in 1.*|2.0.*|2.1.*|2.2.*|2.3.*) die "cryptsetup $csv is too old; use SystemRescue 10.x." ;; esac if [ "$DRY_RUN" = 0 ]; then exec > >(tee -a "$LOG") 2>&1 fi echo "${C_B}privex-vps-encrypt.sh $VERSION$([ "$DRY_RUN" = 1 ] && echo " (dry run: nothing will be changed)")${C_0}" if ! grep -qi sysrescue /etc/os-release 2>/dev/null; then warn "This does not look like SystemRescue. Only run this from the SystemRescue ISO." fi step "Finding the VPS disk" detect_disk check_not_mounted detect_layout # a private tmpfs for all our mounts, so they never propagate into the mount namespaces # of SystemRescue's services (that would keep the VPS file systems busy after unmounting) mkdir -p "$MNT" mountpoint -q "$MNT" || mount -t tmpfs -o mode=700,size=16m privex-encrypt "$MNT" mount --make-rprivate "$MNT" mkdir -p "$ROOT_MNT" "$BOOT_MNT" "$MNT/probe" info "Disk $DISK ($(human $(( $(blockdev --getsz "$DISK") * SECTOR )))), root partition $ROOT_PART ($ROOT_FS)" raw_state_offset >/dev/null local resume=0 case "$ROOT_FS" in ext4) raw_state_read if [ -n "$RAW_STAGE" ]; then # interrupted while moving the root fs: the fs at the old place may be half # overwritten, so everything comes from the saved state, nothing is mounted resume=1; MODE=carve; BOOT_PART="" info "Found an interrupted move of the root file system (stage: $RAW_STAGE); continuing it." [ -n "$KEYS" ] || die "The saved unlock keys are missing from the move state." else mount -o ro,noload "$ROOT_PART" "$ROOT_MNT" || die "Cannot mount $ROOT_PART read-only." inspect_os decide_mode detect_network "$ROOT_MNT" collect_keys "$ROOT_MNT" umount "$ROOT_MNT" find_state if [ -n "$STATE_FOUND" ]; then resume=1 info "Found an unfinished conversion (stage: $STATE_STAGE) on $STATE_FOUND; continuing it." if [ "$MODE" = carve ]; then BOOT_PART="$STATE_FOUND"; fi elif [ -n "$BOOT_PART" ]; then resume=1 info "Found the /boot partition of an unfinished conversion ($BOOT_PART); continuing it." fi fi ;; crypto_LUKS) find_state if [ -z "$STATE_FOUND" ]; then die "$ROOT_PART is already LUKS encrypted (not by this script). Nothing to do." fi if [ "$STATE_STAGE" = "done" ] && [ "$RECONFIGURE" = 0 ]; then die "$ROOT_PART is already encrypted; this script finished converting it earlier. Nothing to do. (--reconfigure redoes the boot setup.)" fi resume=1 BOOT_PART="$STATE_FOUND" mount -o ro "$STATE_FOUND" "$BOOT_MNT" OS_ID=$(state_get OS_ID); OS_VER=$(state_get OS_VER); MODE=$(state_get MODE) # options given on this command line win over the saved ones [ -n "$OPT_NET_MODE" ] || NET_MODE=$(state_get NET_MODE) [ -n "$OPT_DHCP_TIMEOUT" ] || DHCP_TIMEOUT=$(state_get DHCP_TIMEOUT) [ -n "$OPT_CONSOLE" ] || CONSOLE=$(state_get CONSOLE) NET_MAC=${OPT_MAC:-$(state_get NET_MAC)} NET_IPV4=${OPT_IPV4:-$(state_get NET_IPV4)}; NET_GW4=${OPT_GW4:-$(state_get NET_GW4)} NET_IPV6=${OPT_IPV6:-$(state_get NET_IPV6)}; NET_GW6=${OPT_GW6:-$(state_get NET_GW6)} if [ -n "$KEYS_FILE" ]; then collect_keys "" else KEYS=$(cat "$BOOT_MNT/$STATE_DIR_NAME/authorized_keys" 2>/dev/null || true); fi umount "$BOOT_MNT" OS_NAME="$OS_ID $OS_VER" if [ "$STATE_STAGE" = "done" ]; then info "Reconfiguring $OS_NAME (converted earlier); the unlock keys stay as they are unless --authorized-keys is given." else info "Found an unfinished conversion of $OS_NAME (stage: $STATE_STAGE) on $STATE_FOUND; continuing it." [ -n "$KEYS" ] || die "The saved unlock keys are missing from $STATE_FOUND/$STATE_DIR_NAME." fi ;; *) die "The root partition $ROOT_PART has file system '${ROOT_FS:-none}'; expected ext4." ;; esac if [ "$ROOT_FS" = ext4 ] && [ -z "$RAW_STAGE" ]; then plan_sizes fi if [ "$NET_MODE" = dhcp ] && [ -z "$NET_IPV4" ] && [ -n "$NET_IPV6" ]; then die "This VPS has no IPv4 address; DHCP (IPv4) unlock would not work. Use the default (--auto) or --static." fi if [ "$NET_MODE" = static ] && [ -z "$NET_IPV4$NET_IPV6" ]; then die "No static address found in the VPS's network config. Pass --ipv4/--gateway4 (or --ipv6/--gateway6)." fi if [ "$NET_MODE" = auto ] && [ -z "$NET_IPV4$NET_IPV6" ]; then if [ "$NET_DHCP4" = 1 ]; then info "The VPS itself uses DHCP; the unlock network will use DHCP too." else warn "No static address found in the VPS's network config; the unlock network will rely on DHCP only." fi fi # ------------------------------------------------ plan step "Plan" info "System: ${OS_NAME} on $DISK" info "Root partition: $ROOT_PART -> LUKS2 'cryptroot' (in-place, --reduce-device-size ${LUKS_RESERVE_MIB}M)" if [ -n "$RAW_STAGE" ]; then info "Move: continue moving the root fs ($(human "$FS_BYTES")) forward by $(human $((DS * SECTOR)))" info "New /boot: $(human $((DS * SECTOR))) in front of root" elif [ "$ROOT_FS" = ext4 ]; then info "Root fs: $(human $((ROOT_BLOCKS * ROOT_BS))), at least $(human $((ROOT_MIN_BLOCKS * ROOT_BS))) needed" if [ "$MODE" = carve ] && [ -z "$BOOT_PART" ]; then info "Shrink + move: root fs to $(human "$FS_BYTES"), moved forward by $(human $((DS * SECTOR))) inside the partition" info "New /boot: $(human $((DS * SECTOR))) ext4 partition at the start of the old root partition;" info " root keeps its number and end, stays the last partition (can grow later)" elif [ "$MODE" = carve ]; then info "/boot: $BOOT_PART (created by an earlier run)" else info "/boot: existing partition $BOOT_PART (kept, not encrypted)" fi else info "/boot: $BOOT_PART" fi info "Unlock SSH: dropbear on port 2222, key login only, keys:" if [ -n "$KEYS" ]; then print_keys; else info " (none yet)"; fi info "Unlock network: mode $NET_MODE$([ "$NET_MODE" != static ] && echo " (DHCP timeout ${DHCP_TIMEOUT}s)"); interface ${NET_IF:-first NIC}${NET_MAC:+ ($NET_MAC)}" info " IPv4 ${NET_IPV4:-none}${NET_GW4:+ gw $NET_GW4}; IPv6 ${NET_IPV6:-none}${NET_GW6:+ gw $NET_GW6}${NET_SRC:+ [from $NET_SRC]}" info "Boot console: passphrase prompt on the $CONSOLE console (main) and on the $([ "$CONSOLE" = serial ] && echo VGA || echo serial) console" info "Packages: cryptsetup-initramfs, dropbear-initramfs (apt, inside the VPS)" if [ -z "$NET_IPV4" ] && [ -n "$NET_IPV6" ]; then info "Note: IPv6-only VPS: the unlock SSH server listens on $NET_IPV6 (static)." fi if [ "$DRY_RUN" = 1 ]; then [ "$ROOT_FS" = ext4 ] && check_network_dry echo echo "Dry run: nothing was changed. Run without --dry-run to convert." exit 0 fi if [ "$ROOT_FS" = ext4 ] && [ "$resume" = 0 ]; then check_network; fi echo echo "${C_R}${C_B}This encrypts the VPS disk. Make sure you have a backup.${C_0}" echo "If you lose the passphrase, the data cannot be recovered by anyone." local yes ask yes "Type YES to continue: " [ "$yes" = YES ] || die "Not confirmed; nothing was changed." echo if [ "$resume" = 1 ] && [ "$ROOT_FS" = crypto_LUKS ]; then echo "Enter the passphrase you chose when the conversion started." read_passphrase 0 else echo "Choose the disk passphrase. It is asked at every boot. Use only ASCII characters." read_passphrase 1 fi # ------------------------------------------------ work if [ "$ROOT_FS" = ext4 ]; then if [ -z "$RAW_STAGE" ] && { [ "$resume" = 0 ] || [ "$STATE_STAGE" = "boot-ready" ] || { [ -n "$BOOT_PART" ] && [ -z "$STATE_FOUND" ]; }; }; then run_fsck "$ROOT_PART" mount "$ROOT_PART" "$ROOT_MNT" if [ "$MODE" = existing ]; then mount "$BOOT_PART" "$ROOT_MNT/boot"; fi if [ "$resume" = 1 ]; then check_network; fi phase_prepare umount -R "$ROOT_MNT" run_fsck "$ROOT_PART" plan_sizes # packages changed the used space fi CHANGED=1 if [ "$MODE" = carve ]; then phase_carve elif ! boot_has_state "$BOOT_PART"; then mount "$BOOT_PART" "$BOOT_MNT"; write_state_file; umount "$BOOT_MNT" fi if ! boot_has_state "$BOOT_PART"; then mount -o ro "$BOOT_PART" "$MNT/probe" || true ls -la "$MNT/probe" "$MNT/probe/$STATE_DIR_NAME" || true umount "$MNT/probe" 2>/dev/null || true die "Internal error: state directory missing on the /boot partition $BOOT_PART." fi STATE_FOUND="$BOOT_PART" fi CHANGED=1 phase_encrypt phase_finalize print_result } check_network_dry() { local host case "$OS_ID" in debian) host=deb.debian.org ;; *) host=archive.ubuntu.com ;; esac if getent ahosts "$host" >/dev/null 2>&1; then info "Network: $host resolves (apt will work)" else warn "SystemRescue cannot resolve $host; set up the network before the real run."; fi } main "$@"