← Dokumentace

Ufw Firewall

Zdroj: ~/projects/ufw-firewall/

🔥 UFW Firewall — Configuration & Server Hardening

Uncomplicated Firewall (UFW) is a user-friendly frontend for iptables on Linux. This guide covers setup, hardening rules, and best practices for securing a Linux server.


🚀 Quick Deploy (Script)

Automate the setup below with one command — idempotent, with automatic backup of existing rules.

# 1. Edit your settings first: config/ufw.conf
#    (SSH port, management IP, allowed/denied ports, Docker fix, ...)

# 2. Run the deployment (as root):
sudo bash scripts/deploy-ufw.sh

# Useful options:
sudo bash scripts/deploy-ufw.sh --dry-run     # preview without changing anything
sudo bash scripts/deploy-ufw.sh --status      # show current status
sudo bash scripts/deploy-ufw.sh --docker-fix  # apply Docker+UFW fix now

⚠️ Always keep a second session open so you don't lock yourself out!


� Smart Checkpoints (ufw-checkpoint.sh)

Like Check Point SmartConsole — save, compare, and restore UFW snapshots.

# Save a named checkpoint (auto-runs before deploy-ufw if CHECKPOINT_AUTO=yes)
sudo bash scripts/ufw-checkpoint.sh save --tag "before-nginx"

# List all checkpoints
sudo bash scripts/ufw-checkpoint.sh list

# Show a checkpoint (by ID or number — 1 = newest)
sudo bash scripts/ufw-checkpoint.sh show ckpt-20260801-120000
sudo bash scripts/ufw-checkpoint.sh show 1

# Diff: checkpoint vs current live state
sudo bash scripts/ufw-checkpoint.sh diff ckpt-20260801-120000 CURRENT

# Diff: two checkpoints
sudo bash scripts/ufw-checkpoint.sh diff 1 2

# Restore a checkpoint (auto-saves pre-restore snapshot first!)
sudo bash scripts/ufw-checkpoint.sh restore ckpt-20260801-120000

# Delete a checkpoint
sudo bash scripts/ufw-checkpoint.sh delete 3

# Auto-purge old checkpoints (keep last N)
sudo bash scripts/ufw-checkpoint.sh purge --keep 10

Checkpoint storage: /root/ufw-checkpoints/<id>/

Each checkpoint contains: user.rules, user6.rules, before.rules, after.rules, ufw.conf, status.txt, iptables.v4, iptables.v6, and metadata.


�📋 Table of Contents


🔍 What is UFW?

UFW (Uncomplicated Firewall) provides a simplified interface to manage netfilter (iptables/nftables) rules on Ubuntu, Debian, and other Linux distributions.

Key features: - Simple CLI for managing firewall rules - IPv4 and IPv6 support - Application profiles (/etc/ufw/applications.d/) - Persistent across reboots - Logging integration


📦 Installation

# Ubuntu / Debian
sudo apt update && sudo apt install ufw -y

# Check version
sudo ufw version

# Check current status
sudo ufw status verbose

⚙️ Basic Commands

Command Description
sudo ufw enable Enable the firewall
sudo ufw disable Disable the firewall
sudo ufw reset Reset all rules to defaults
sudo ufw reload Reload rules
sudo ufw status Show current status & rules
sudo ufw status verbose Detailed status
sudo ufw status numbered Rules with line numbers

🚧 Default Policies

Always set default policies BEFORE enabling UFW to avoid locking yourself out!

# Deny all incoming traffic by default
sudo ufw default deny incoming

# Allow all outgoing traffic by default
sudo ufw default allow outgoing

# Deny all forwarded traffic (for non-router servers)
sudo ufw default deny forward

📝 Common Rules

Allow by Port

# Allow SSH (critical — do this before enabling!)
sudo ufw allow 22/tcp

# Allow HTTP
sudo ufw allow 80/tcp

# Allow HTTPS
sudo ufw allow 443/tcp

# Allow a custom port
sudo ufw allow 8080/tcp

Allow by Service Name (Application Profiles)

# List available app profiles
sudo ufw app list

# Allow by app name
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw allow 'Apache Full'

Allow from Specific IP

# Allow a specific IP to access all ports
sudo ufw allow from 192.168.1.100

# Allow a specific IP to a specific port
sudo ufw allow from 192.168.1.100 to any port 22

# Allow an entire subnet
sudo ufw allow from 192.168.1.0/24

# Allow a subnet to a specific port
sudo ufw allow from 10.0.0.0/8 to any port 5432

Deny Rules

# Deny a specific port
sudo ufw deny 23/tcp

# Deny from a specific IP
sudo ufw deny from 203.0.113.100

# Delete a rule by number
sudo ufw status numbered
sudo ufw delete 3

🔐 SSH Hardening Rules

Protect SSH from brute-force attacks.

# Allow SSH only from a trusted management IP or subnet
sudo ufw allow from 10.0.0.0/8 to any port 22 proto tcp

# If using a non-standard SSH port (e.g., 2222)
sudo ufw allow 2222/tcp

# IMPORTANT: Delete the default SSH rule if using a custom port
sudo ufw delete allow 22/tcp

⏱️ Rate Limiting

UFW has built-in rate limiting (blocks IPs that attempt >6 connections in 30 seconds):

# Enable rate limiting on SSH (brute-force protection)
sudo ufw limit ssh

# Enable rate limiting on a custom port
sudo ufw limit 2222/tcp

# Custom rate limit (via iptables directly)
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
  -m recent --set --name SSH
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
  -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP

🔧 Advanced Rules

Allow Specific Port Range

# Allow a port range (e.g., passive FTP)
sudo ufw allow 49152:65535/tcp
sudo ufw allow 49152:65535/udp

Allow Specific Interface

# Allow traffic only on eth0
sudo ufw allow in on eth0 to any port 80

Block ICMP (Ping) Flooding

Edit /etc/ufw/before.rules and find the ICMP section, then limit it:

# In /etc/ufw/before.rules, replace ACCEPT with limit:
-A ufw-before-input -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

Reject vs. Drop

# DROP — silently discard packets (attacker gets no response)
sudo ufw deny from 1.2.3.4

# REJECT — send back a "connection refused" (faster for legit timeout scenarios)
sudo ufw reject from 1.2.3.4

📊 Logging

# Enable logging
sudo ufw logging on

# Set log level (off | low | medium | high | full)
sudo ufw logging medium

# View UFW logs
sudo tail -f /var/log/ufw.log

# Filter blocked connections
sudo grep "BLOCK" /var/log/ufw.log | tail -20

🔍 Status & Debugging

# Show all rules with details
sudo ufw status verbose

# Show numbered rules for easy deletion
sudo ufw status numbered

# Check if UFW is running as a systemd service
sudo systemctl status ufw

# Test rules without applying (dry run)
sudo ufw --dry-run enable

# View raw iptables rules that UFW generates
sudo iptables -L -v -n
sudo ip6tables -L -v -n

✅ Server Hardening Checklist

Phase 1 — UFW Baseline

  • [ ] Set default deny incoming / allow outgoing
  • [ ] Allow SSH before enabling UFW
  • [ ] Enable rate limiting on SSH
  • [ ] Enable UFW
  • [ ] Verify rules with ufw status verbose

Phase 2 — SSH Hardening

  • [ ] Change SSH port from default 22
  • [ ] Disable root SSH login (PermitRootLogin no)
  • [ ] Disable password authentication (use SSH keys only)
  • [ ] Restrict SSH to management network/IP

Phase 3 — System Hardening

  • [ ] Disable unused network services
  • [ ] Enable automatic security updates
  • [ ] Configure fail2ban alongside UFW
  • [ ] Disable IPv6 if not needed
  • [ ] Set kernel sysctl hardening parameters
  • [ ] Enable process accounting (auditd)

Phase 4 — Ongoing

  • [ ] Regularly review UFW logs
  • [ ] Monitor with ufw status after changes
  • [ ] Test firewall rules with nmap from an external host

🐳 UFW + Docker Integration

⚠️ Warning: Docker bypasses UFW by default and directly modifies iptables!

Fix Docker + UFW Conflict

Method 1: Restrict Docker to localhost only (recommended for single-server setups)

# In /etc/docker/daemon.json
{
  "iptables": false
}

Then bind containers to localhost:

docker run -p 127.0.0.1:8080:80 nginx

Method 2: Use ufw-docker (community tool)

# Install ufw-docker
sudo wget -O /usr/local/bin/ufw-docker \
  https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker
sudo chmod +x /usr/local/bin/ufw-docker
sudo ufw-docker install

# Allow a Docker container port through UFW
sudo ufw-docker allow my_container 80

💾 Backup & Restore Rules

# Backup current rules
sudo cp /etc/ufw/user.rules ~/ufw-user.rules.bak
sudo cp /etc/ufw/user6.rules ~/ufw-user6.rules.bak
sudo cp /etc/ufw/before.rules ~/ufw-before.rules.bak
sudo cp /etc/ufw/after.rules ~/ufw-after.rules.bak

# Or export via iptables
sudo iptables-save > ~/iptables-backup.rules

# Restore
sudo iptables-restore < ~/iptables-backup.rules
sudo ufw reload

📁 Important UFW Files

File Purpose
/etc/ufw/ufw.conf Main config (enable/disable, logging)
/etc/ufw/user.rules IPv4 user-defined rules
/etc/ufw/user6.rules IPv6 user-defined rules
/etc/ufw/before.rules Rules applied before user rules
/etc/ufw/after.rules Rules applied after user rules
/etc/ufw/applications.d/ App profile definitions
/var/log/ufw.log UFW log file

🔗 Related Projects


💡 Pro Tip: Always test firewall changes from a second terminal session before closing your current one. If you lock yourself out, you'll need console/physical access to recover.