PortGate

Free tools

UFW and SSH hardening

A script for a host you already administer. Keep an existing SSH session open, and confirm key login works before you disable passwords.

Generated script

#!/bin/bash
set -euo pipefail
# Review on a host you administer. Keep the current SSH session open.
SSH_PORT=22
WAN_IFACE=eth0
ufw default deny incoming
ufw default allow outgoing
ufw allow "${SSH_PORT}/tcp" comment 'SSH'
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'
iptables -N DOCKER-USER 2>/dev/null || true
iptables -F DOCKER-USER
iptables -A DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
iptables -A DOCKER-USER -i "${WAN_IFACE}" -p tcp --dport "${SSH_PORT}" -j RETURN
iptables -A DOCKER-USER -i "${WAN_IFACE}" -p tcp -m multiport --dports 80,443 -j RETURN
iptables -A DOCKER-USER -i "${WAN_IFACE}" -j DROP
iptables -A DOCKER-USER -j RETURN
ufw --force enable
# SSH settings go in a drop-in read before cloud-init's 50-cloud-init.conf,
# because sshd keeps the first value it reads for each setting.
if [ -d /etc/ssh/sshd_config.d ] && grep -qE '^\s*Include\s+/etc/ssh/sshd_config\.d' /etc/ssh/sshd_config; then
  cat > /etc/ssh/sshd_config.d/00-portgate-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
EOF
else
  sed -i 's/^#\?PermitRootLogin .*/PermitRootLogin no/' /etc/ssh/sshd_config
  sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
fi
sshd -t
systemctl reload ssh || systemctl reload sshd
sshd -T | grep -E '^(permitrootlogin|passwordauthentication)'