Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Firewalls and Segmentation

Writing Firewall Rules: iptables, nftables and Security Groups

Learn to write a default-deny firewall policy with nftables and iptables, read ufw and cloud security group rules, and check a ruleset with a Python audit script.

Knowing what a firewall is only helps once you can write rules for one. This lesson shows a complete, sensible server ruleset in the Linux firewall languages, nftables and iptables, then maps the same ideas to ufw and to cloud security groups. The Linux examples are read-only: the site cannot run a kernel firewall, and you should never paste firewall commands into a remote machine without a way back in. Practise them in a virtual machine you can reach from the console.

Afterwards you will write a rule auditor in Python that reads a ruleset and flags common mistakes, which is the kind of check that catches errors before they reach production.

Changing firewall rules over SSH can lock you out. Always keep a console session, schedule an automatic rollback (for example a timed iptables-restore or a cloud snapshot), and test in a lab first.

The shape of a good server ruleset

A host firewall for a web server should say, in words:

  1. Accept traffic on the loopback interface.
  2. Accept packets that belong to established connections, plus related ones.
  3. Drop invalid packets.
  4. Allow new connections only to the services you intend: SSH from the admin network, HTTP and HTTPS from anywhere.
  5. Allow a limited amount of ICMP (ping and path MTU discovery).
  6. Drop everything else. This is the default policy.

nftables

nftables is the modern Linux packet filtering framework, replacing iptables. Rules live in tables, which contain chains, which hold rules. A chain hooked into the input path filters traffic addressed to the host.

Terminal
# /etc/nftables.conf  (read-only example)
table inet filter {
  set admin_net { type ipv4_addr; flags interval; elements = { 192.0.2.0/24 } }

  chain input {
    type filter hook input priority 0; policy drop;

    iif "lo" accept
    ct state established,related accept
    ct state invalid drop

    ip protocol icmp icmp type { echo-request, destination-unreachable, time-exceeded } limit rate 5/second accept
    ip6 nexthdr icmpv6 accept

    tcp dport 22 ip saddr @admin_net accept
    tcp dport { 80, 443 } accept
  }

  chain forward {
    type filter hook forward priority 0; policy drop;
  }

  chain output {
    type filter hook output priority 0; policy accept;
  }
}

Points to notice:

  • policy drop on the chain is the default deny. Anything that matches no rule is dropped.
  • ct state established,related uses connection tracking (the state table from the last lesson).
  • A set (admin_net) keeps addresses in one place so you can update it without editing rules.
  • The forward chain also has policy drop; this host is not a router.
  • output accepts everything here for simplicity, but stricter servers filter outbound traffic too (see egress filtering).

Load and check with nft -f /etc/nftables.conf and nft list ruleset.

iptables

iptables is older but still everywhere. The same policy:

Terminal
# read-only example
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 5/second -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -s 192.0.2.0/24 -j ACCEPT
iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT

-A INPUT appends to the end of the chain; -I INPUT 1 inserts at the top. Because order matters, a mistaken -A after a broad accept never takes effect. Show the table with iptables -L -n -v --line-numbers.

ufw: a friendlier front end

On Ubuntu, ufw ("uncomplicated firewall") wraps the same engine:

Terminal
ufw default deny incoming
ufw default allow outgoing
ufw allow from 192.0.2.0/24 to any port 22 proto tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

Cloud platforms have the same concepts under different names. A security group is a stateful allow-list attached to an instance: you list inbound rules (source, protocol, port) and everything else is denied; replies are allowed automatically. A network ACL is usually stateless and applies to a whole subnet, with numbered rules evaluated in order.

Auditing a ruleset in Python

Reading a long ruleset by eye misses things. An auditor encodes your policy as checks. The program below parses a small rule list (in a simplified format) and warns about the classic mistakes: a missing default deny, SSH open to the world, databases exposed, and shadowed rules that can never match.

Python Audit a ruleset for common mistakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is the same idea behind commercial firewall audit tools: turn policy into code and run it on every change. You can extend the checks with your own rules, such as "no rule may allow a source range wider than /16 to a server subnet".

Reading the counters

Rule counters tell you whether a rule is ever used. With nft list ruleset or iptables -L -v, a rule with zero packets after months is a candidate for removal, and a drop rule with a high counter shows what you are blocking.

TEXT
Chain INPUT (policy DROP 1248 packets, 61420 bytes)
 pkts bytes target  prot opt in  out source          destination
 9012  420K ACCEPT  all  --  lo  *   0.0.0.0/0       0.0.0.0/0
88210   71M ACCEPT  all  --  *   *   0.0.0.0/0       0.0.0.0/0   ctstate ESTABLISHED,RELATED
   17   884 ACCEPT  tcp  --  *   *   192.0.2.0/24    0.0.0.0/0   tcp dpt:22
 3310  198K ACCEPT  tcp  --  *   *   0.0.0.0/0       0.0.0.0/0   multiport dports 80,443

Illustrative output. The policy line shows 1248 packets were dropped by default: that is the noise of the internet.

Logging without drowning

Logging every dropped packet on a public server fills the disk in hours. Log selectively and with rate limits: for example only new SSH attempts from outside the admin network, with a prefix you can search for.

Terminal
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m limit --limit 3/min -j LOG --log-prefix "ssh-new: "

Send firewall logs to a central system so an intruder who compromises the host cannot erase them.

Common mistakes

  • Locking yourself out by applying a default deny before adding the SSH allow rule.
  • Allowing "temporarily" and forgetting. Add an expiry date in a comment, and review.
  • IPv6 left open: if the host has IPv6, you need rules for it too (the inet family in nftables covers both).
  • Order mistakes, as in the shadowed rule above.
  • Rules nobody understands: use sets, comments and a version-controlled configuration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In nftables, what does 'policy drop' on an input chain do?

    The chain policy is what happens when no rule matches. 'drop' makes the chain default deny.
  2. 2. Why accept 'ct state established,related' early in the chain?

    Connection tracking lets the firewall allow packets belonging to existing connections without opening ports for replies.
  3. 3. A rule 'drop tcp port 3306 from anywhere' comes after 'accept tcp port 3306 from anywhere'. What is true?

    First match wins, so the earlier accept decides every packet and the later drop is dead.
  4. 4. What is the main danger of applying a default-deny policy over SSH?

    Add the allow rule for your own access before the default drop, and keep a console or rollback ready.

Summary

  • A good host ruleset: allow loopback, established/related, drop invalid, allow only intended new services, rate-limit ICMP, default drop.
  • nftables uses tables, chains, sets and policies; iptables uses -A/-I, order matters; ufw and cloud security groups express the same ideas.
  • Audit rules with code: missing default deny, world-open admin or database ports, shadowed rules.
  • Use counters to find unused rules, log selectively and ship logs off the host.
  • Avoid lock-outs, forgotten temporary rules, open IPv6 and unreadable rulesets.

Next: Stateful Inspection and Connection Tracking