Chapter 10 · Lesson 3 of 10
Server security

Advanced ufw firewall rules (limit, allow from IP, delete, insert)

Advanced ufw rules restrict ports to specific source addresses, rate limit SSH, and rely on rule order, so you control exactly who reaches each service.

By the end you will

Write ordered ufw rules that limit SSH, restrict ports to chosen IPs, delete rules by number and turn on logging safely.

Time
20 min
Level
Intermediate
Check
4 questions
You need
  • Ubuntu or Debian server with ufw installed
  • A second SSH session open

The basic ufw allow and ufw deny commands cover a simple server. Real servers need a bit more: SSH open only to known addresses, brute-force limits, rules in the right order, and a way to remove rules cleanly. This lesson covers those, building on set up a firewall with ufw.

Firewall mistakes lock people out of their own servers. Before changing rules, open a second SSH session and keep it open, and know where your provider’s web console is.

How it works#

ufw is a front end for the kernel’s packet filter. You describe rules, and ufw writes them into its chains. For incoming traffic it works down the rule list and applies the first rule that matches. Rules that match nothing fall through to the default policy, usually deny incoming and allow outgoing.

Because of this, order is part of the meaning. allow 22 followed by deny from 198.51.100.7 never blocks that address, since the first rule matches it. Rules you add go to the end of the list unless you use ufw insert. ufw also keeps separate IPv4 and IPv6 versions of most rules, which is why you see (v6) lines.

Step 1: Check the state before changing anything#

bash
sudo ufw status verbose
sudo ufw status numbered

verbose shows the default policies and logging level. numbered shows rule numbers. If ufw says Status: inactive, nothing is enforced yet. Add your rules first and only then enable it.

Step 2: Allow from one address to one port#

Restrict a service to a known source:

bash
sudo ufw allow from 192.0.2.25 to any port 22 proto tcp
sudo ufw allow from 192.0.2.0/24 to any port 5432 proto tcp

The first limits SSH to a single address, the second opens a database port to a private range. This is much safer than opening the port to everyone. The risk is your own address changing, so keep a fallback such as the provider console, and consider the hardened SSH settings as your main defense instead of an address list.

Step 3: Rate limit with ufw limit#

bash
sudo ufw limit 22/tcp

limit allows the port but denies an address that opens too many new connections in a short window. The exact threshold is built into ufw, so check the man page if you need it. It is a simple companion to fail2ban, but fail2ban gives you finer control over ban lengths. You can use both.

Step 4: Use application profiles#

Packages can register named profiles:

bash
sudo ufw app list
sudo ufw app info 'Nginx Full'
sudo ufw allow 'Nginx Full'

A profile bundles the ports a package needs, for example 80 and 443 for a web server. The names depend on installed packages, so read app list rather than guessing. Quote names that contain spaces.

Step 5: Control order with insert and delete#

Put a deny in front of a broader allow:

bash
sudo ufw insert 1 deny from 198.51.100.7

Remove rules by number:

bash
sudo ufw status numbered
sudo ufw delete 3

Numbers shift after each delete, so list again before the next. You can also delete by repeating the rule with delete in front: sudo ufw delete allow 80/tcp. That is safer in scripts because it does not depend on position.

Step 6: Turn on logging#

bash
sudo ufw logging low

Levels are off, low, medium, high and full. Blocked packets are written to the kernel log, usually /var/log/ufw.log on Ubuntu, with lines marked [UFW BLOCK]. Start with low. Higher levels can fill a disk on a busy server, so check the size now and then. See read logs with journalctl for reading them.

Step 7: Enable carefully, and mind Docker#

If ufw is not yet enabled, add the SSH allow rule first, keep your second session open, then:

bash
sudo ufw enable

ufw warns that it may disrupt existing SSH connections. With the allow rule in place, it will not. Then open a new terminal and log in to prove access before you close anything.

Docker needs a separate warning. A published container port is wired in by Docker’s own rules, which are checked before ufw’s. A ufw deny 8080 often does not stop traffic to a container published on 0.0.0.0:8080. The reliable fix is to publish internal services on 127.0.0.1 only. See publish container ports safely.

Check it worked#

bash
sudo ufw status verbose
sudo ss -tulpn

From another machine, test the ports you meant to open and the ones you meant to close, for example with nc -vz 203.0.113.10 22. A rule that exists but has never been tested is a guess.

Edge cases and gotchas#

  • First match wins. A broad allow above a specific deny makes the deny useless. Use insert.
  • v6 rules. If IPv6 is enabled, rules are added for both families. If IPV6=no in /etc/default/ufw, v6 traffic is not filtered by these rules.
  • Existing connections. Enabling ufw does not drop established SSH sessions, but a restart of networking can. Do not rely on this.
  • Deleting by number in a loop. Numbers change after each delete, so deleting 3, 4, 5 in turn removes the wrong rules. Delete from the highest number down.
  • Docker bypass. Published ports skip ufw’s input rules. Test from outside, not by reading ufw status.
  • Outgoing rules. The default allows all outgoing traffic. Restricting it breaks updates and DNS unless you add rules for them.

Troubleshooting#

SymptomLikely causeFix
ERROR: Could not find a profile matching 'nginx'Profile name is differentRun sudo ufw app list and use the exact name
Locked out after enableNo SSH allow ruleUse the provider console, sudo ufw allow 22/tcp
ERROR: Invalid position '5'Fewer rules than the positionCheck ufw status numbered, use a lower number
Deny rule does not blockAn allow rule sits above itufw insert 1 deny from ...
Container port still reachableDocker’s rules skip ufwBind to 127.0.0.1 or filter in DOCKER-USER
Skipping adding existing ruleSame rule already presentCheck ufw status numbered
No entries in ufw.logLogging is offsudo ufw logging low

Quick reference#

bash
sudo ufw status numbered
sudo ufw allow from 192.0.2.25 to any port 22 proto tcp
sudo ufw limit 22/tcp
sudo ufw insert 1 deny from 198.51.100.7
sudo ufw delete 3
sudo ufw app list
sudo ufw logging low

Next#

Continue with Unattended security updates and reboots.

Try it: Write ordered ufw rules

Practise on a test server with a second SSH session open. Never enable the firewall without an SSH allow rule.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which command shows rules with numbers you can delete by?
2You allow 22 from anywhere, then deny 22 from 198.51.100.7. Is that address blocked?
3What must you do before running ufw enable on a remote server?
4A container publishes 0.0.0.0:8080. Does ufw deny 8080 stop traffic to it?

Frequently asked questions

What does ufw limit do?

ufw limit allows a port but denies an address that makes too many new connections in a short time. It is meant for services like SSH that attract brute-force attempts.

How do I delete a ufw rule?

Run sudo ufw status numbered, then sudo ufw delete 3 to remove rule number 3. Numbers shift after each delete, so list again before the next one.

Does rule order matter in ufw?

Yes. ufw checks rules from the top and uses the first one that matches. Put specific rules before general ones, or use ufw insert to place a rule at a chosen position.

Why does ufw not block my Docker container ports?

Docker adds its own firewall rules for published ports, and they are evaluated before ufw's rules. Bind published ports to 127.0.0.1 or use the DOCKER-USER chain.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios