Skip to content

Commit

Permalink
Merge pull request #212 from arighi/sshd-config
Browse files Browse the repository at this point in the history
sshd: generate a custom sshd_config
  • Loading branch information
arighi authored Jan 1, 2025
2 parents f53c692 + 8f1788f commit 0695128
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions virtme/guest/virtme-sshd-script
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,43 @@ if [ -z "${virtme_ssh_user}" ]; then
exit 1
fi

mkdir -p /run/sshd
rm -f /var/run/nologin

SSH_HOME=$(getent passwd "${virtme_ssh_user}" | cut -d: -f6)
if [ ! -e "${SSH_HOME}" ]; then
# Setup an arbitrary ssh location, just to be able to start sshd.
SSH_HOME=/run/ssh
SSH_HOME=/run/sshd
fi

# Update authorized_keys by adding the user's public keys, but only if the
# changes are confined to the guest (no modifications made to the host).
#
# Overwriting authorized_keys is considered safe only when the guest rootfs
# is mounted as read-only, with an overlayfs on top to handle writes within
# the guest environment (e.g. `--rw` or `--rwdir` not specified as argument).
OVERLAYFS="794c7630" # OVERLAYFS_SUPER_MAGIC in include/uapi/linux/magic.h
SSH_AUTH_KEYS="${SSH_HOME}/.ssh/authorized_keys"
if [ "$(stat -f -c "%t" "${SSH_AUTH_KEYS}")" = "${OVERLAYFS}" ]; then
cat "${SSH_HOME}"/.ssh/id_*.pub >> "${SSH_AUTH_KEYS}" 2>/dev/null
chown "${virtme_ssh_user}" "${SSH_AUTH_KEYS}" 2>/dev/null
fi
# Generate authorized_keys in the virtme-ng cache directory and add all
# user's public keys.
CACHE_DIR=${SSH_HOME}/.cache/virtme-ng/.ssh
SSH_AUTH_KEYS="${CACHE_DIR}/authorized_keys"
cat "${SSH_HOME}"/.ssh/id_*.pub >> "${SSH_AUTH_KEYS}" 2>/dev/null
chown "${virtme_ssh_user}" "${SSH_AUTH_KEYS}" 2>/dev/null
chmod 600 "${SSH_AUTH_KEYS}" 2>/dev/null

# Generate ssh host keys (if they don't exist already).
CACHE_DIR=${SSH_HOME}/.cache/virtme-ng/.ssh
mkdir -p "${CACHE_DIR}/etc/ssh"
ssh-keygen -A -f "${CACHE_DIR}"
ARGS=()

# Generate a minimal sshd config.
SSH_CONFIG=/run/sshd/sshd_config
cat << EOF > "${SSH_CONFIG}"
# This file is automatically generated by virtme-ng.
Port 22
PermitRootLogin yes
AuthorizedKeysFile ${SSH_AUTH_KEYS}
PubkeyAuthentication yes
UsePAM yes
PrintMotd no
EOF

# Start sshd.
ARGS=(-f "${SSH_CONFIG}")
for key in "${CACHE_DIR}"/etc/ssh/ssh_host_*_key; do
ARGS+=(-h "${key}")
done

# Start sshd.
mkdir -p /run/sshd
rm -f /var/run/nologin
/usr/sbin/sshd "${ARGS[@]}"
/usr/sbin/sshd -f "${SSH_CONFIG}" "${ARGS[@]}"

0 comments on commit 0695128

Please sign in to comment.