Part 3 · Networking and hardening · Lesson 03 · 50 minutes
Filter traffic with a firewall
- Write nftables rules that drop by default and allow by port and source
- Prove a rule by connecting to a test server before and after
- Use ufw as the simple front end and say how firewalld and iptables compare
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A test server runs a status page on port 8080. Your team lead says: "Only the office network may read it. Everyone else must get nothing. And do not lock yourself out of SSH." You write a firewall rule set that drops all incoming traffic that nothing allows, you prove each rule with a connection before and after, and you keep a way back at every step.
Recall
Which two settings must you give ip to add a second address to a dummy interface, and how do you remove it?
The address with its length and the interface name: ip addr add 198.51.100.11/24 dev krdummy0. Remove it with ip addr del and the same arguments.
Which command changes the host name so that it survives a reboot?
hostnamectl set-hostname NAME. It writes /etc/hostname.
The idea
A firewall looks at each packet and decides: accept, drop (throw it away, the sender hears nothing) or reject (throw it away and tell the sender). On Linux the kernel does the filtering, in a framework called netfilter. The tool nft writes its rules (the tool is part of nftables). A rule set has three levels: a table holds chains, and a chain holds rules. A chain that is hooked to the input of the machine sees every packet that arrives for it. Rules are read from the top. The first rule that matches decides. When no rule matches, the policy of the chain decides.
Default deny means the policy is drop and you add rules for what you allow. Stateful means the firewall remembers connections: a rule ct state established,related accept lets the answers of connections that you allowed come back, so you do not write a rule for every reply.
- Packet → Chain: arrives at the input hook
- Chain → Rule 1: part of a known connection?
- Rule 1 → Packet: yes, accept
- Chain → Rule 2: port 8080 from the office?
- Rule 2 → Packet: yes, accept
- Chain → Policy: no rule matched
- Policy → Packet: drop
The same job has several front ends:
| Tool | What it is |
|---|---|
nftables (nft) | The current kernel firewall and its language. Used in this lesson. |
ufw | "Uncomplicated firewall": short commands that write the rules for you. Default on Ubuntu. |
firewalld | Zones and services, managed by firewall-cmd. Default on Fedora, RHEL and CentOS. |
iptables | The older tool, with the same job. On a new system it is only a compatible front end to nftables. |
Worked example
The firewall changes need administrator rights, so each command has sudo. A wrong rule can cut you off. Every step below has a way back: you delete the table that you made.
1. Make a test server and two clients
- Office client → Firewall: from 198.51.100.10 to port 8080
- Firewall → Status page: matches the allow rule: 200
- Stranger → Firewall (blocked): from .99, no rule, policy drop
Make a dummy interface with two addresses (lesson 2): 198.51.100.10 is "the office", 198.51.100.99 is "a stranger". curl --interface ADDRESS makes a request that comes from that address. The server listens on 0.0.0.0, port 8080. The small function t prints the HTTP status and the exit code of curl. -m 2 stops the request after two seconds.
sudo ip link add krdummy0 type dummy
sudo ip link set krdummy0 up
sudo ip addr add 198.51.100.10/24 dev krdummy0
sudo ip addr add 198.51.100.99/24 dev krdummy0
mkdir -p ~/krlab/linux-advanced/fw/site && cd ~/krlab/linux-advanced/fw
echo "firewall test page" > site/index.html
python3 -m http.server 8080 --bind 0.0.0.0 --directory site > server.log 2>&1 &
SRV=$!
t() { curl -s -m 2 -o /dev/null -w "%{http_code}" "$@"; echo " exit=$?"; }2. Test before the rules
Ask for the page from the office, from the stranger and from the loopback.
t --interface 198.51.100.10 http://198.51.100.10:8080/
t --interface 198.51.100.99 http://198.51.100.10:8080/
t http://127.0.0.1:8080/200 exit=0
200 exit=0
200 exit=0Everyone gets the page. sudo nft list ruleset prints the rules that are active. On a new Ubuntu it prints nothing.
3. Add a table, a chain and rules
nft add table inet krlab makes a table for IPv4 and IPv6. nft add chain makes a chain: type filter hook input attaches it to the incoming packets, and priority 0 sets its order against other chains. The braces and the semicolons need quotes, so that the shell does not read them. Start with policy accept, add the rules, and only then switch to drop. A drop policy with no rules cuts off every connection, SSH included.
sudo nft add table inet krlab
sudo nft add chain inet krlab input '{ type filter hook input priority 0 ; policy accept ; }'
sudo nft add rule inet krlab input ct state established,related accept
sudo nft add rule inet krlab input tcp dport 22 accept
sudo nft add rule inet krlab input ip saddr 198.51.100.0/28 tcp dport 8080 accept
sudo nft chain inet krlab input '{ policy drop ; }'
sudo nft list rulesettable inet krlab {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
tcp dport 22 accept
ip saddr 198.51.100.0/28 tcp dport 8080 accept
}
}Read the rules in order. Known connections pass. SSH (port 22) passes from everywhere. The last rule has three parts:
The range holds the office but not the stranger. A real rule set also has iif lo accept, to let the machine talk to itself. This lab leaves it out, because traffic between two addresses of one machine travels over lo, and the rule would hide the test. The cost: while this table is loaded, the local resolver 127.0.0.53 is also blocked, so name lookups and apt fail. Delete the table when you have finished the test.
4. Test after the rules
t --interface 198.51.100.10 http://198.51.100.10:8080/
t --interface 198.51.100.99 http://198.51.100.10:8080/
t http://127.0.0.1:8080/200 exit=0
000 exit=28
000 exit=28The office still gets 200. The stranger and the loopback wait for two seconds and give up: exit code 28 means "timed out", which is what a drop looks like from outside. The policy dropped them.
5. Reject instead of drop
A reject rule answers the sender with an error, so the failure is at once. Add one at the end. nft -a list chain shows the handle of each rule, a number that names it, and nft delete rule ... handle N removes one rule.
sudo nft add rule inet krlab input tcp dport 8080 reject
t --interface 198.51.100.99 http://198.51.100.10:8080/
sudo nft -a list chain inet krlab input000 exit=7
table inet krlab {
chain input { # handle 1
type filter hook input priority filter; policy drop;
ct state established,related accept # handle 2
tcp dport 22 accept # handle 3
ip saddr 198.51.100.0/28 tcp dport 8080 accept # handle 4
tcp dport 8080 reject # handle 5
}
}Exit code 7 is "connection refused", and it comes at once. drop hides that a service exists and slows a scanner; reject is friendlier to your own users. Remove the last rule with sudo nft delete rule inet krlab input handle 5. Your handle number can differ: read it from the listing.
6. Save the rules and load them from a file
Rules that you type are lost at a reboot. A file holds them. Save this file as krlab.nft in the folder fw. The first two lines make the table krlab and delete it, so the file replaces an old copy of that table as one step and leaves the tables of other tools alone. nft -c -f FILE checks a file and loads nothing, and nft -f FILE loads it.
krlab.nft
#!/usr/sbin/nft -f
table inet krlab
delete table inet krlab
table inet krlab {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
tcp dport 22 accept
ip saddr 198.51.100.0/28 tcp dport 8080 accept
}
}sudo nft -c -f krlab.nft && echo check-ok
sudo nft -f krlab.nft
sudo nft list ruleset | head -4check-ok
table inet krlab {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related acceptsudo nft list ruleset > krlab.nft saves the live rules in the same form. A file with a mistake is refused with the line and column of the error, and the old rules stay. To load the rules at every boot on Ubuntu, copy the file to /etc/nftables.conf and run sudo systemctl enable --now nftables. First add iif lo accept as the first rule of the chain: this lab file leaves it out (step 3), and without it every boot would start with no name resolution. The copy was tested in the lab, with the original file put back afterwards.
7. Remove the table
Your table has done its job. Delete it before you try ufw: two firewall front ends in one lab can contradict each other (see the field notes). Keep the server and the dummy interface for ufw and for "Your turn", and stay in the same terminal: it holds the function t and the variable $SRV.
sudo nft delete table inet krlab8. Use ufw as the simple front end
ufw writes the rules from short commands. ufw default deny incoming sets the policy, ufw allow 22/tcp opens a port, and ufw allow from NETWORK to any port N proto tcp opens a port for one source. Allow SSH before you enable the firewall. --force skips the question "Command may disrupt existing ssh connections".
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow from 198.51.100.0/28 to any port 8080 proto tcp
sudo ufw --force enable
sudo ufw status numberedStatus: active
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 8080/tcp ALLOW IN 198.51.100.0/28
[ 3] 22/tcp (v6) ALLOW IN Anywhere (v6)sudo ufw delete 2 removes the second rule after a question. ufw puts a rule for lo at the top, so on one machine its rules can be listed here but not exercised by a connection: the nft test above proves the logic. Before "Your turn", switch ufw off and clear its rules, because it would block the new port:
sudo ufw --force resetYour turn
Protect a second page. There are no steps here: use the commands of the worked example. Use the terminal of the worked example, with the dummy interface, its two addresses and the function t of step 1. If you closed that terminal, open a new one, run the commands of step 1 again, and define the function t again.
- Serve the folder
siteon0.0.0.0, port8081, in the background. - Make the table
inet krtaskwith the chaininput(policydropat the end). Add a rule for known connections, and one rule that allows port8081only from the single address198.51.100.99. Add the rules before you set the policy. - Ask for the page from
198.51.100.99and from198.51.100.10, both to198.51.100.10:8081, with a time-out of two seconds.
Now add a last rule tcp dport 8081 reject, and repeat the request from 198.51.100.10.
Clean up: remove the table krtask, stop both servers (kill $SRV, and the one that you started), and delete the interface with sudo ip link del krdummy0.
Check yourself
Why do you add the rules first and switch the policy to drop last?
A chain with policy drop and no allow rules drops every packet, including your own SSH session. Rules first, policy last, so that the machine is reachable at every moment. A rule file loaded with nft -f avoids the gap, because it loads as one step.
The stranger waited two seconds and the office got a page at once. What did the stranger's packets meet?
No rule matched, so the policy drop threw the packets away. The sender gets no answer and must wait for a time-out.
What does "ct state established,related accept" make unnecessary?
A rule for every reply. Without it, the answer to a connection that you allowed would be a new packet that meets the policy and is dropped.
You switch on ufw over SSH and lose the session. What did you forget?
sudo ufw allow 22/tcp (or your SSH port) before ufw enable. Always allow the way in first, and keep a second session or a console open.
Field notes
- Filter output too on a server that holds secrets: a compromised program that cannot connect out cannot send data away. Start with a
logrule to learn what the server needs. iif lo acceptbelongs in every real input chain. So do rules for ICMP, the protocol ofpingand of error messages (icmp type echo-request,icmpv6) with a rate limit, because IPv6 needs ICMP to work.- Use a table of type
inet, so that one rule covers IPv4 and IPv6. A rule set for IPv4 only leaves the same port open on IPv6. - Use one firewall front end at a time. ufw, firewalld and a hand-written
nftfile each make their own table, and each table has its own input chain. A packet must pass all of them, so two tools can contradict each other. - A firewall reduces the attack surface, and a service that listens only on
127.0.0.1needs no firewall rule at all. Close the listener first, filter second. The CIS Benchmarks for Linux ask for a firewall with a default deny policy.