Skip to content

Instantly share code, notes, and snippets.

@ncatallo
Last active May 9, 2025 16:50
Show Gist options
  • Save ncatallo/8b813493fc60f4cd28a50fc24e71ae0f to your computer and use it in GitHub Desktop.
Save ncatallo/8b813493fc60f4cd28a50fc24e71ae0f to your computer and use it in GitHub Desktop.
This script setup UFW on your server to allow only 80 and 443 ports / SSH port if specified
#!/bin/bash
# Default values
SSH_ENABLE=false
SSH_PORT=22
SSH_ALLOW_FROM=""
RESET=false
# Args parsing
while [[ "$#" -gt 0 ]]; do
case "$1" in
--ssh-enable)
SSH_ENABLE=true
;;
--ssh-port)
SSH_PORT="$2"
shift
;;
--ssh-allow-from)
SSH_ALLOW_FROM="$2"
shift
;;
--reset)
RESET=true
;;
*)
echo "Unknowned option : $1"
echo "Usage : $0 [--ssh-enable] [--ssh-port <port>] [--ssh-allow-from <ip>] [--reset]"
exit 1
;;
esac
shift
done
# Check ufw tool
if ! command -v ufw &> /dev/null; then
echo "UFW will be installed..."
sudo apt update && sudo apt install -y ufw
fi
# Check Fail2ban tool
if ! command -v fail2ban-client &>/dev/null; then
echo "📦 Installing Fail2ban..."
sudo apt install -y fail2ban
else
echo "✅ Fail2ban already installed."
fi
# Reset ufw
if [ "$RESET" = true ]; then
echo "Reset UFW's rules..."
sudo ufw --force reset
fi
# Default policy
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow HTTP/HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
echo "Ports HTTP (80) and HTTPS (443) authorized."
# SSH
if [ "$SSH_ENABLE" = true ]; then
if [[ -n "$SSH_ALLOW_FROM" ]]; then
echo "Authorizing SSH port $SSH_PORT from $SSH_ALLOW_FROM"
sudo ufw allow from "$SSH_ALLOW_FROM" to any port "$SSH_PORT"/tcp
else
echo "Authorizing SSH port $SSH_PORT for everyone"
sudo ufw allow "$SSH_PORT"/tcp
fi
fi
# Activate UFW
if sudo ufw status | grep -q "Status: inactive"; then
echo "Activating UFW..."
sudo ufw --force enable
else
echo "UFW already active."
fi
# Final ufw verbose print
echo "Current state of the firewall :"
sudo ufw status verbose
### Configuration of Fail2ban ###
echo "🚨 Fail2ban config..."
sudo tee /etc/fail2ban/jail.local > /dev/null <<EOF
[DEFAULT]
bantime = 2h
findtime = 15m
maxretry = 5
backend = systemd
[sshd]
enabled = true
port = ${SSH_PORT}
filter = sshd
logpath = /var/log/auth.log
EOF
systemctl restart fail2ban
systemctl enable fail2ban
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment