#!/bin/sh
# Second half of the SSH session handoff, shipped in the initramfs as
# /scripts/servury-boot-follow; servury-handoff runs it with the booted
# system's /bin/sh, chrooted into that root while the initramfs is still
# running. Once run-init has moved /run, /proc and /sys in and journald is up,
# it shows the whole boot (kernel lines first, then systemd) and follows it
# until the boot is finished, then turns the session into a root login shell,
# but only if this system's own sshd would let the same key log in as root from
# the same address. Otherwise it says so and ends, and the customer connects
# again as usual, exactly as before this existed.
#
# su -l, not login(1): login vhangup()s the terminal, which dropbear reads as
# the end of the session.
H=/run/servury-handoff
# Wait for the switch itself: PID 1's root becomes this root. Under dracut
# systemd and journald already run inside the initramfs, so "systemd is up" is
# not enough there; asking too early talks to the initramfs's systemd.
# Both sides must be read: at the switch systemd ends every process not named
# "@...", these stat calls included, and two empty strings compare equal.
switched() {
    a=$(stat -L -c %d:%i /proc/1/root/ 2>/dev/null)
    b=$(stat -L -c %d:%i / 2>/dev/null)
    [ -n "$a" ] && [ "$a" = "$b" ]
}
i=0
until switched && [ -d /run/systemd/system ] && [ -S /run/systemd/journal/socket ]; do
    sleep 0.2; i=$((i + 1)); [ $i -gt 900 ] && break
done
# SELinux (EL): this session was started in the initramfs before the policy
# was loaded and runs as kernel_t, and stricter policies (AlmaLinux 10) deny
# the programs it starts its own terminal and systemd's socket. Carry on in
# the context an SSH login gets, once, if the policy allows the switch.
# systemd loads the policy just after the switch, so wait for it where it will
# load: the kernel runs SELinux (selinuxfs registered) and the system does not
# turn it off. Elsewhere (Debian, Ubuntu, measured boot's AppArmor kernel)
# there is nothing to wait for.
if grep -qw selinuxfs /proc/filesystems 2>/dev/null && command -v selinuxenabled >/dev/null 2>&1 \
    && ! grep -qsE '^[[:space:]]*SELINUX=disabled' /etc/selinux/config && ! grep -qw 'selinux=0' /proc/cmdline; then
    i=0
    until selinuxenabled || [ $i -gt 150 ]; do sleep 0.2; i=$((i + 1)); done
fi
CTX=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
if [ -z "${SERVURY_CTX:-}" ] && [ -n "${FOLLOW:-}" ] && command -v selinuxenabled >/dev/null 2>&1 \
    && selinuxenabled && ! id -Z 2>/dev/null | grep -q ':unconfined_t:' \
    && runcon "$CTX" /bin/true 2>/dev/null; then
    export SERVURY_CTX=1
    exec runcon "$CTX" /bin/sh -c "$FOLLOW" boot-follow
fi
journalctl -b -f -n all -o short --no-hostname --no-pager 2>/dev/null &
J=$!
# Right after the switch systemd re-executes and does not answer for a moment
# ("unknown"); --wait gives up at once then, so wait for a real state first.
i=0
until case "$(systemctl is-system-running 2>/dev/null)" in
        initializing|starting|running|degraded|maintenance|stopping) true ;; *) false ;;
      esac || [ $i -gt 300 ]; do
    sleep 0.2; i=$((i + 1))
done
timeout 180 systemctl is-system-running --wait >/dev/null 2>&1
STATE=$(systemctl is-system-running 2>/dev/null)
sleep 0.5
kill $J 2>/dev/null

# "type base64" of each key in an authorized_keys file. With "plain", only
# lines without options count: a key the customer restricted (from=,
# command=, restrict, ...) is not handed a free shell here.
keys_of() {
    awk -v plain="$2" '
        /^[[:space:]]*(#|$)/ { next }
        {
            for (i = 1; i < NF; i++) if ($i ~ /^(ssh-|ecdsa-|sk-)/) break
            if (i >= NF) next
            if (plain != "" && i != 1) next
            print $i " " $(i + 1)
        }' "$1" 2>/dev/null
}

policy_ok() {
    addr=${SSH_CLIENT%% *}
    [ -n "$addr" ] || return 1
    # sshd -T refuses to run without its privilege-separation directory,
    # which a socket-activated sshd (Ubuntu 24.04) only creates on the first
    # connection; create it the way sshd itself would.
    [ -d /run/sshd ] || mkdir -m 0755 /run/sshd 2>/dev/null
    T=$(/usr/sbin/sshd -T -C "user=root,host=$addr,addr=$addr" 2>/dev/null) || return 1
    get() { printf '%s\n' "$T" | sed -n "s/^$1 //p" | head -n 1; }
    case "$(get permitrootlogin)" in yes|prohibit-password|without-password) ;; *) return 1 ;; esac
    [ "$(get pubkeyauthentication)" = yes ] || return 1
    case "$(get authenticationmethods)" in any|publickey) ;; *) return 1 ;; esac
    case "$(get authorizedkeyscommand)" in ""|none) ;; *) return 1 ;; esac
    # Any further restriction on who may log in or what they get (user or
    # group allow/deny lists, a forced command, a chroot) stays sshd's to
    # apply: no handoff, the customer logs in normally and sshd enforces it.
    for o in allowusers denyusers allowgroups denygroups; do
        [ -z "$(get $o)" ] || return 1
    done
    case "$(get forcecommand)" in ""|none) ;; *) return 1 ;; esac
    case "$(get chrootdirectory)" in ""|none) ;; *) return 1 ;; esac

    : > "$H/real"
    for f in $(get authorizedkeysfile); do
        f=$(printf '%s' "$f" | sed 's/%%/\x01/g; s#%h#/root#g; s/%u/root/g; s/\x01/%/g')
        case "$f" in /*) ;; *) f="/root/$f" ;; esac
        keys_of "$f" plain >> "$H/real"
    done

    # The key this session used, when its authorized_keys comment names exactly
    # one line (dropbear exports it as SSH_PUBKEYINFO); otherwise every key the
    # initramfs accepts must also be accepted here.
    need=""
    if [ -n "${SSH_PUBKEYINFO:-}" ]; then
        m=$(awk -v c="$SSH_PUBKEYINFO" '
            /^[[:space:]]*(#|$)/ { next }
            { for (i = 1; i < NF; i++) if ($i ~ /^(ssh-|ecdsa-|sk-)/) break
              if (i >= NF) next
              rest = ""; for (j = i + 2; j <= NF; j++) rest = rest (rest == "" ? "" : " ") $j
              if (rest == c) print $i " " $(i + 1) }' "$H/keys")
        [ "$(printf '%s\n' "$m" | grep -c .)" = 1 ] && need="$m"
    fi
    [ -n "$need" ] || need=$(keys_of "$H/keys")
    [ -n "$need" ] || return 1
    printf '%s\n' "$need" | while read -r k; do
        grep -qxF "$k" "$H/real" || exit 1
    done
}

if policy_ok; then
    rm -rf "$H"
    echo ""
    echo "  Boot finished ($STATE)."
    echo ""
    run-parts --lsbsysinit /etc/update-motd.d 2>/dev/null
    [ -s /etc/motd ] && cat /etc/motd
    # The session arrives from the initramfs with no locale. Give the shell the
    # system's, as an sshd login would: su -l keeps only variables it is told
    # to keep (-w, util-linux 2.32 and later).
    KEEP=""
    for f in /etc/default/locale /etc/locale.conf; do
        [ -r "$f" ] || continue
        for v in $(sed -n 's/^[[:space:]]*\(LANG\|LANGUAGE\|LC_[A-Z_]*\)=.*/\1/p' "$f"); do
            KEEP="$KEEP,$v"
        done
        set -a; . "$f"; set +a
    done
    if [ -n "$KEEP" ] && su --help 2>&1 | grep -q -- '--whitelist-environment'; then
        exec su -l -w "${KEEP#,}" root
    fi
    exec su -l root
fi
rm -rf "$H"
echo ""
echo "  Boot finished ($STATE). This server's SSH settings do not allow handing"
echo "  this session over, so connect again with SSH as usual."
echo ""
exit 0
