UFW is a user-friendly front-end for managing iptables. It is the standard way to secure Ubuntu servers. By default, UFW is often disabled or set to allow all traffic; configuring it to allow only specific IPs is a vital security step.
Prerequisites:
- SSH Access with
sudoor root privileges. - The Port Number you want to secure (e.g., 3306 for MySQL).
- The Trusted IP Address you want to permit.
Steps to Restrict Access:
- Check UFW Status: Run the following command to see if UFW is active:
sudo ufw status - IMPORTANT: Allow SSH First: Before enabling the firewall, ensure you don't lock yourself out by allowing SSH (Port 22):
sudo ufw allow 22/tcp - Allow a Specific IP to a Specific Port: To allow a trusted IP (e.g., 1.2.3.4) to access a specific port (e.g., 3306), use this syntax:
sudo ufw allow from 1.2.3.4 to any port 3306 - Enable the Firewall: If the status was “inactive,” enable it now:
sudo ufw enable(Type ‘y' and press Enter when prompted). - Verify the Rules: Check the status again to confirm the rule is applied:
sudo ufw status numbered
How to Remove a Rule:
If you need to delete a rule later, find its number using the command above and run: sudo ufw delete [number]
Pro-Tip: Always use sudo ufw status numbered before deleting rules. It prevents mistakes by showing you exactly which line index you are modifying.
Verification:
Test the connection from the allowed IP. If you configured it correctly, the connection will go through, while all other IPs will be blocked by the default “Deny” policy of the firewall.