401 lines
14 KiB
Bash
401 lines
14 KiB
Bash
#!/usr/bin/env bash
|
|
#
|
|
# harden-jumphost.sh
|
|
#
|
|
# Hardens an Alpine box for use as an SSH jump host (bastion). Run on a fresh
|
|
# box. Layered on the same PQ-hybrid posture as harden-ssh.sh, plus jump-host
|
|
# specifics.
|
|
#
|
|
# Two groups, two privilege levels:
|
|
# ssh-admins -- full TTY shell on the jump host (for maintenance only).
|
|
# No forwarding. This is for fixing the box, not for
|
|
# reaching anywhere else.
|
|
# ssh-jumpers -- ProxyJump ONLY. No TTY, no shell, no SFTP, no agent
|
|
# forwarding. Only direct-tcpip to whitelisted targets.
|
|
# These users cannot get a prompt on the jump host even if
|
|
# their key works.
|
|
#
|
|
# How the restriction works:
|
|
# - Global default: DisableForwarding yes, PermitTTY no, ForceCommand
|
|
# /sbin/nologin. So a user with no group membership cannot do anything.
|
|
# - Match Group ssh-admins: re-enables PermitTTY and clears ForceCommand
|
|
# so admins get a normal shell. Forwarding stays off.
|
|
# - Match Group ssh-jumpers: enables AllowTcpForwarding + PermitOpen
|
|
# whitelist. Keeps PermitTTY no and ForceCommand /sbin/nologin so any
|
|
# attempt at an interactive session fails -- but ProxyJump (direct-tcpip)
|
|
# still works because it doesn't open a session channel.
|
|
#
|
|
# A note on ProxyJump and ForceCommand:
|
|
# `ssh -J jumphost target` opens a direct-tcpip channel on the jump host;
|
|
# it is NOT a session/exec request, so ForceCommand never fires. That's
|
|
# why this pattern works: jumpers literally cannot run anything on the
|
|
# jump host, but their tunnels go through.
|
|
#
|
|
# Usage:
|
|
# bash harden-jumphost.sh
|
|
# SSH_PORT=2222 bash harden-jumphost.sh
|
|
# JUMP_TARGETS="10.0.0.5:22 10.0.0.6:22" bash harden-jumphost.sh
|
|
# ALLOWED_IP=1.2.3.4 bash harden-jumphost.sh
|
|
# FORCE=1 bash harden-jumphost.sh
|
|
|
|
set -euo pipefail
|
|
|
|
# ============================================================================
|
|
# CONFIG
|
|
# ============================================================================
|
|
: "${SSH_PORT:=22}"
|
|
: "${ALLOWED_IP:=}"
|
|
: "${FORCE:=0}"
|
|
# Space-separated host:port list jumpers can reach via ProxyJump.
|
|
# Empty means jumpers can ProxyJump nowhere (deny-all). Set this to your
|
|
# internal targets, e.g. "10.0.0.5:22 10.0.0.6:22".
|
|
: "${JUMP_TARGETS:=}"
|
|
: "${KEY_COMMENT:=root@$(hostname)-$(date +%Y%m%d)}"
|
|
|
|
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
|
|
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
|
|
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
|
|
|
|
[[ $EUID -eq 0 ]] || die "Run as root."
|
|
[[ -f /etc/alpine-release ]] || die "This script targets Alpine Linux."
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 1. Packages
|
|
# ----------------------------------------------------------------------------
|
|
log "Installing openssh + PAM + sshguard + iptables + gum..."
|
|
if apk info -e openssh-server >/dev/null 2>&1 && \
|
|
! apk info -e openssh-server-pam >/dev/null 2>&1; then
|
|
apk del -q openssh-server || true
|
|
fi
|
|
apk add -q openssh openssh-server-pam linux-pam sshguard iptables ip6tables openrc gum shadow
|
|
|
|
# Install sshuser tool alongside this script if present.
|
|
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
|
if [[ -f "$SCRIPT_DIR/sshuser.sh" ]]; then
|
|
install -m 0755 "$SCRIPT_DIR/sshuser.sh" /usr/local/bin/sshuser
|
|
log "Installed /usr/local/bin/sshuser"
|
|
fi
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 2. PQ KEX detection (same as harden-ssh.sh)
|
|
# ----------------------------------------------------------------------------
|
|
log "Checking OpenSSH version supports PQ KEX..."
|
|
SSH_VER=$(ssh -V 2>&1 | grep -oE 'OpenSSH_[0-9]+\.[0-9]+' | head -1 | sed 's/OpenSSH_//')
|
|
SSH_MAJOR=${SSH_VER%%.*}
|
|
SSH_MINOR=${SSH_VER##*.}
|
|
|
|
HAS_MLKEM=0
|
|
HAS_SNTRUP=0
|
|
[[ $SSH_MAJOR -gt 9 || ( $SSH_MAJOR -eq 9 && $SSH_MINOR -ge 0 ) ]] && HAS_SNTRUP=1
|
|
[[ $SSH_MAJOR -gt 9 || ( $SSH_MAJOR -eq 9 && $SSH_MINOR -ge 9 ) ]] && HAS_MLKEM=1
|
|
[[ $HAS_SNTRUP -eq 1 || $HAS_MLKEM -eq 1 ]] \
|
|
|| die "OpenSSH ${SSH_VER} has no PQ KEX. Need >= 9.0."
|
|
log "OpenSSH ${SSH_VER}: ML-KEM=${HAS_MLKEM} sntrup761=${HAS_SNTRUP}"
|
|
|
|
KEX_LIST=""
|
|
[[ $HAS_MLKEM -eq 1 ]] && KEX_LIST="mlkem768x25519-sha256"
|
|
[[ $HAS_SNTRUP -eq 1 ]] && KEX_LIST="${KEX_LIST:+$KEX_LIST,}sntrup761x25519-sha512"
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 3. Host keys (Ed25519 only)
|
|
# ----------------------------------------------------------------------------
|
|
log "Regenerating host keys (Ed25519 only)..."
|
|
rm -f /etc/ssh/ssh_host_rsa_key* /etc/ssh/ssh_host_ecdsa_key* /etc/ssh/ssh_host_dsa_key*
|
|
if [[ ! -f /etc/ssh/ssh_host_ed25519_key ]]; then
|
|
ssh-keygen -q -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N "" \
|
|
-C "host@$(hostname)-$(date +%Y%m%d)"
|
|
fi
|
|
chmod 600 /etc/ssh/ssh_host_ed25519_key
|
|
chmod 644 /etc/ssh/ssh_host_ed25519_key.pub
|
|
|
|
log "Host key fingerprint:"
|
|
ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub | sed 's/^/ /'
|
|
|
|
# Stop Alpine's sshd init from regenerating RSA/ECDSA keys.
|
|
if [[ -f /etc/conf.d/sshd ]]; then
|
|
if ! grep -q '^sshd_disable_keygen=' /etc/conf.d/sshd; then
|
|
echo 'sshd_disable_keygen="yes"' >> /etc/conf.d/sshd
|
|
else
|
|
sed -i 's/^sshd_disable_keygen=.*/sshd_disable_keygen="yes"/' /etc/conf.d/sshd
|
|
fi
|
|
fi
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 4. Groups -- create if missing
|
|
# ----------------------------------------------------------------------------
|
|
log "Ensuring groups ssh-admins and ssh-jumpers exist..."
|
|
getent group ssh-admins >/dev/null || addgroup -S ssh-admins
|
|
getent group ssh-jumpers >/dev/null || addgroup -S ssh-jumpers
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 5. Root keypair (for ssh-admins maintenance access)
|
|
# ----------------------------------------------------------------------------
|
|
log "Generating Ed25519 keypair for root..."
|
|
mkdir -p /root/.ssh
|
|
chmod 700 /root/.ssh
|
|
touch /root/.ssh/authorized_keys
|
|
chmod 600 /root/.ssh/authorized_keys
|
|
|
|
# Add root to ssh-admins so the Match block applies.
|
|
adduser root ssh-admins 2>/dev/null || true
|
|
|
|
TMP_KEY=$(mktemp -u /tmp/root_ed25519.XXXXXX)
|
|
ssh-keygen -q -t ed25519 -f "$TMP_KEY" -N "" -C "$KEY_COMMENT"
|
|
ROOT_PUB=$(cat "${TMP_KEY}.pub")
|
|
ROOT_PRIV=$(cat "$TMP_KEY")
|
|
if ! grep -qxF "$ROOT_PUB" /root/.ssh/authorized_keys; then
|
|
echo "$ROOT_PUB" >> /root/.ssh/authorized_keys
|
|
fi
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 6. Build PermitOpen line from JUMP_TARGETS
|
|
# ----------------------------------------------------------------------------
|
|
# JUMP_TARGETS is space-separated; PermitOpen wants comma-separated.
|
|
# Empty => "none" (deny all). sshd_config doesn't accept a literal empty list.
|
|
PERMIT_OPEN_LINE="none"
|
|
if [[ -n "$JUMP_TARGETS" ]]; then
|
|
PERMIT_OPEN_LINE=$(echo "$JUMP_TARGETS" | tr -s ' ' ',' | sed 's/^,//;s/,$//')
|
|
fi
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 7. sshd_config
|
|
# ----------------------------------------------------------------------------
|
|
log "Writing /etc/ssh/sshd_config..."
|
|
[[ -f /etc/ssh/sshd_config.orig ]] || cp /etc/ssh/sshd_config /etc/ssh/sshd_config.orig
|
|
|
|
cat > /etc/ssh/sshd_config <<EOF
|
|
# Generated by harden-jumphost.sh -- $(date -u +%FT%TZ)
|
|
# Original config preserved at /etc/ssh/sshd_config.orig
|
|
|
|
Port ${SSH_PORT}
|
|
AddressFamily any
|
|
ListenAddress 0.0.0.0
|
|
ListenAddress ::
|
|
|
|
# --- Host key: Ed25519 only ---
|
|
HostKey /etc/ssh/ssh_host_ed25519_key
|
|
|
|
# --- Post-quantum hybrid KEX only ---
|
|
KexAlgorithms ${KEX_LIST}
|
|
|
|
# --- Modern ciphers and MACs ---
|
|
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
|
|
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
|
|
|
|
# --- Algorithms for host and client signatures ---
|
|
HostKeyAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com
|
|
PubkeyAcceptedAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256,rsa-sha2-256-cert-v01@openssh.com
|
|
RequiredRSASize 4096
|
|
|
|
# --- Authentication ---
|
|
PermitRootLogin prohibit-password
|
|
PubkeyAuthentication yes
|
|
PasswordAuthentication no
|
|
PermitEmptyPasswords no
|
|
ChallengeResponseAuthentication no
|
|
KbdInteractiveAuthentication no
|
|
UsePAM yes
|
|
AuthenticationMethods publickey
|
|
MaxAuthTries 3
|
|
MaxSessions 10
|
|
LoginGraceTime 30s
|
|
|
|
# --- Default posture: deny everything ---
|
|
# Anyone not in ssh-admins or ssh-jumpers gets nothing. Matches below
|
|
# selectively re-enable what each group needs.
|
|
DisableForwarding yes
|
|
PermitTTY no
|
|
ForceCommand /sbin/nologin
|
|
X11Forwarding no
|
|
GatewayPorts no
|
|
PermitTunnel no
|
|
PermitUserRC no
|
|
PermitListen none
|
|
PermitOpen none
|
|
AllowAgentForwarding no
|
|
AllowTcpForwarding no
|
|
AllowStreamLocalForwarding no
|
|
PrintMotd no
|
|
TCPKeepAlive no
|
|
ClientAliveInterval 300
|
|
ClientAliveCountMax 2
|
|
|
|
# --- Misc ---
|
|
StrictModes yes
|
|
IgnoreRhosts yes
|
|
HostbasedAuthentication no
|
|
Compression no
|
|
Banner none
|
|
|
|
# --- Subsystems ---
|
|
# SFTP off by default. Admins who need it can be added to a separate
|
|
# Match block; jumpers must never have it.
|
|
# Subsystem sftp internal-sftp
|
|
|
|
# --- Allowlist ---
|
|
# Only members of these groups can authenticate at all. AllowGroups
|
|
# enforces this BEFORE the per-group Match blocks run.
|
|
AllowGroups ssh-admins ssh-jumpers
|
|
|
|
# ============================================================================
|
|
# Match blocks
|
|
# ============================================================================
|
|
|
|
# --- Admins: full shell, no forwarding, no SFTP ---
|
|
Match Group ssh-admins
|
|
PermitTTY yes
|
|
ForceCommand none
|
|
DisableForwarding yes
|
|
AllowTcpForwarding no
|
|
AllowAgentForwarding no
|
|
AllowStreamLocalForwarding no
|
|
X11Forwarding no
|
|
PermitOpen none
|
|
|
|
# --- Jumpers: ProxyJump only, no shell, no SFTP, whitelisted destinations ---
|
|
# direct-tcpip channels are controlled by AllowTcpForwarding + PermitOpen.
|
|
# Session channels (shell/exec/subsystem) hit ForceCommand=/sbin/nologin
|
|
# and PermitTTY=no, so any interactive attempt fails immediately.
|
|
Match Group ssh-jumpers
|
|
PermitTTY no
|
|
ForceCommand /sbin/nologin
|
|
AllowTcpForwarding yes
|
|
PermitOpen ${PERMIT_OPEN_LINE}
|
|
AllowAgentForwarding no
|
|
AllowStreamLocalForwarding no
|
|
DisableForwarding no
|
|
X11Forwarding no
|
|
GatewayPorts no
|
|
PermitTunnel no
|
|
EOF
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 8. Validate config
|
|
# ----------------------------------------------------------------------------
|
|
log "Validating sshd config..."
|
|
if ! sshd -t 2>/tmp/sshd-test.err; then
|
|
cat /tmp/sshd-test.err >&2
|
|
cp /etc/ssh/sshd_config.orig /etc/ssh/sshd_config
|
|
die "sshd config invalid; restored original. NOT reloading."
|
|
fi
|
|
rm -f /tmp/sshd-test.err
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 9. sshguard
|
|
# ----------------------------------------------------------------------------
|
|
log "Configuring sshguard..."
|
|
mkdir -p /etc/sshguard
|
|
WHITELIST=/etc/sshguard/whitelist
|
|
{
|
|
echo "127.0.0.1"
|
|
echo "::1"
|
|
[[ -n "$ALLOWED_IP" ]] && echo "$ALLOWED_IP"
|
|
} > "$WHITELIST"
|
|
|
|
cat > /etc/sshguard/sshguard.conf <<EOF
|
|
BACKEND="/usr/libexec/sshg-fw-iptables"
|
|
LOGREADER="LANG=C journalctl -afb -p info -n1 -u sshd -o cat"
|
|
THRESHOLD=30
|
|
BLOCK_TIME=300
|
|
DETECTION_TIME=1800
|
|
PID_FILE=/run/sshguard.pid
|
|
WHITELIST_FILE=${WHITELIST}
|
|
EOF
|
|
|
|
cat > /etc/local.d/sshguard-iptables.start <<'EOF'
|
|
#!/bin/sh
|
|
SSH_PORT=$(awk '/^Port / {print $2; exit}' /etc/ssh/sshd_config)
|
|
SSH_PORT=${SSH_PORT:-22}
|
|
for ipt in iptables ip6tables; do
|
|
$ipt -N sshguard 2>/dev/null || true
|
|
$ipt -C INPUT -p tcp --dport "$SSH_PORT" -j sshguard 2>/dev/null \
|
|
|| $ipt -I INPUT -p tcp --dport "$SSH_PORT" -j sshguard
|
|
done
|
|
EOF
|
|
chmod +x /etc/local.d/sshguard-iptables.start
|
|
rc-update add local default 2>/dev/null || true
|
|
/etc/local.d/sshguard-iptables.start
|
|
|
|
rc-update add sshguard default
|
|
rc-service sshguard restart || rc-service sshguard start
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# 10. Enable sshd
|
|
# ----------------------------------------------------------------------------
|
|
log "Enabling sshd at boot..."
|
|
rc-update add sshd default
|
|
|
|
cat <<EOF
|
|
|
|
================================================================
|
|
JUMP HOST SETUP COMPLETE
|
|
|
|
Groups created:
|
|
ssh-admins -- full shell on the jump host (root added)
|
|
ssh-jumpers -- ProxyJump only, no shell
|
|
|
|
Add a jumper user:
|
|
adduser -D -s /sbin/nologin alice
|
|
addgroup alice ssh-jumpers
|
|
mkdir -p /home/alice/.ssh && chmod 700 /home/alice/.ssh
|
|
echo 'ssh-ed25519 AAA...' > /home/alice/.ssh/authorized_keys
|
|
chmod 600 /home/alice/.ssh/authorized_keys
|
|
chown -R alice:alice /home/alice/.ssh
|
|
|
|
Note the user's shell can be /sbin/nologin -- ProxyJump still works
|
|
because it never opens a session channel.
|
|
|
|
Allowed jump targets (PermitOpen):
|
|
${PERMIT_OPEN_LINE}
|
|
|
|
To change targets: edit JUMP_TARGETS and re-run, or edit the Match
|
|
block in /etc/ssh/sshd_config directly.
|
|
|
|
COPY THIS PRIVATE KEY TO YOUR CLIENT *NOW* (admin/root key):
|
|
|
|
ssh -i ~/.ssh/id_ed25519_jump -p ${SSH_PORT} root@<host>
|
|
|
|
----- BEGIN ROOT PRIVATE KEY (Ed25519) -----
|
|
${ROOT_PRIV}
|
|
----- END ROOT PRIVATE KEY -----
|
|
|
|
Public key (already in /root/.ssh/authorized_keys):
|
|
${ROOT_PUB}
|
|
|
|
Host fingerprint:
|
|
$(ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub)
|
|
|
|
Client usage examples:
|
|
|
|
# Admin shell on the jump host:
|
|
ssh -i ~/.ssh/id_ed25519_jump -p ${SSH_PORT} root@<jumphost>
|
|
|
|
# ProxyJump through to an internal target:
|
|
ssh -J root@<jumphost>:${SSH_PORT} -i ~/.ssh/id_ed25519_target user@<target>
|
|
|
|
================================================================
|
|
EOF
|
|
|
|
shred -u "$TMP_KEY" "${TMP_KEY}.pub" 2>/dev/null || rm -f "$TMP_KEY" "${TMP_KEY}.pub"
|
|
|
|
if [[ "$FORCE" != "1" ]]; then
|
|
cat <<EOF
|
|
sshd config has passed validation. Ready to reload sshd.
|
|
|
|
Open a SECOND terminal and verify the new key/port/KEX work BEFORE
|
|
answering yes:
|
|
ssh -i ~/.ssh/<saved key> -p ${SSH_PORT} root@<host>
|
|
|
|
Reload sshd now? [y/N]
|
|
EOF
|
|
read -r ans
|
|
if [[ "${ans,,}" != "y" && "${ans,,}" != "yes" ]]; then
|
|
warn "Skipping reload. Run 'rc-service sshd reload' manually when ready."
|
|
exit 0
|
|
fi
|
|
fi
|
|
|
|
log "Reloading sshd..."
|
|
rc-service sshd reload || rc-service sshd restart
|
|
log "Done."
|