Introduction to UFW
UFW (Uncomplicated Firewall) is a user-friendly interface for managing iptables firewall rules on Linux systems. It’s particularly well-suited for Debian and Ubuntu servers, providing a simplified way to configure your system’s firewall.
Installation
Install UFW using the following command:
sudo apt update
sudo apt install ufw
Basic UFW Commands
Check UFW Status
This command shows if UFW is active and lists all current rules.
For a more detailed view, use:
Enable and Disable UFW
Before enabling UFW, ensure you have configured rules to allow SSH access (port 22)
to prevent being locked out of your server.
To enable UFW:
To disable UFW:
Managing Basic Rules
Allow Incoming Connections
Allow specific ports:
sudo ufw allow 22 # Allow SSH
sudo ufw allow 80 # Allow HTTP
sudo ufw allow 443 # Allow HTTPS
Allow specific services by name:
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
Deny Incoming Connections
Deny specific ports:
sudo ufw deny 23 # Deny Telnet
Delete Rules
Delete rules by number:
- List rules with numbers:
- Delete a specific rule:
Delete rules by specification:
Advanced Configuration
Allow Specific IP Addresses
Allow a specific IP address:
sudo ufw allow from 203.0.113.4
Allow an IP address to access a specific port:
sudo ufw allow from 203.0.113.4 to any port 22
Set default policies for incoming and outgoing traffic:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Best Practices
-
Always Allow SSH First
Before enabling UFW, ensure SSH access is allowed:
-
Use Specific Rules
Instead of allowing all traffic to a port, specify the service and protocol:
-
Regular Audits
Regularly review your firewall rules:
-
Backup Rules
Backup your UFW rules periodically:
sudo cp /etc/ufw/user.rules /etc/ufw/user.rules.backup
Common Configuration Examples
Basic Web Server Setup
# Allow SSH, HTTP, and HTTPS
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
Database Server Setup
# Allow MySQL/MariaDB from specific IP
sudo ufw allow from 203.0.113.4 to any port 3306
Rate Limiting
Enable rate limiting for SSH to prevent brute force attacks:
Troubleshooting
If you encounter issues:
-
Check UFW Status
-
View UFW Logs
sudo tail -f /var/log/ufw.log
-
Reset UFW
If needed, reset UFW to default settings:
Conclusion
UFW provides a straightforward way to manage your firewall rules on Debian and Ubuntu systems. Remember to always configure SSH access before enabling the firewall, and regularly audit your rules to maintain security. For more advanced configurations, consult the UFW documentation.