🛡️ UFW Advanced Configuration
Configuration Files Explained
UFW rules are stored in several text files. Understanding them helps with troubleshooting:
bash
# UFW core configuration files
/etc/ufw/ufw.conf # Main config (enabled/disabled, default policy)
/etc/ufw/user.rules # IPv4 user-defined rules
/etc/ufw/user6.rules # IPv6 user-defined rules
/etc/ufw/ufw.before.rules # Loaded before user rules (advanced usage)
/etc/ufw/ufw.after.rules # Loaded after user rules
# View current rules (raw format)
cat /etc/ufw/user.rules
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
-A ufw-before-input -p tcp --dport 22 -j ACCEPT
-A ufw-before-input -p tcp --dport 80 -j ACCEPT
...
# Directly edit rule file (restart UFW after editing)
nano /etc/ufw/user.rules
ufw disable && ufw enable⚠️ Warning: ⚠️ Note: It is not recommended to simply use
ufw allow 22/tcpto open SSH to all IPs. In production, you should restrict the source IP:ufw allow from 10.0.0.0/8 to any port 22.
Rate Limiting Against Brute Force
bash
# UFW has a built-in rate limiting feature (much simpler than manual iptables config)
ufw limit 22/tcp
# Maximum 6 new connections from the same IP within 30 seconds, then reject
# Verify rate limiting is in effect
ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- ------ ----
22/tcp LIMIT Anywhere
# Set different limits for different services
ufw limit 22/tcp # SSH: 6 attempts in 30 seconds
ufw limit 3306/tcp # MySQL: same limit
# Combine with fail2ban for more granular protection
apt install fail2ban
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
EOF
systemctl restart fail2banLog Monitoring
bash
# UFW log levels: off, low, medium, high, full
ufw logging medium
# View UFW logs
tail -f /var/log/ufw.log
# Analyze rejected connections
grep "BLOCK" /var/log/ufw.log | \
awk '{print $NF}' | sort | uniq -c | sort -rn | head -10
# Clear logs (when logs are too large)
> /var/log/ufw.log
# Disable logging (not recommended, but reduces disk IO)
ufw logging off