Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Linux firewalls: understand before you configure

By updated

Improve this page

A Linux firewall is a packet filter implemented in the kernel, driven by one or more user commands. It decides, packet by packet, what enters or leaves the machine according to a set of rules. It is the first layer of defence of an exposed server, and the cheapest: no extra service, just a configuration of a kernel already in place. This page lays out the concepts to master before opening UFW or Firewalld: default policy, inbound and outbound traffic, ports, connection state, and where the host firewall stops.

What you will learn

  • What a Linux firewall is, and what it is not
  • Reason in default policy: deny-by-default vs allow-by-default
  • Tell apart inbound, outbound and routed traffic
  • Understand stateful filtering (connection tracking) and why it simplifies rules
  • Place the tools: nftables (kernel), UFW and Firewalld (frontends)
  • Know when a host firewall is enough and when a network firewall must complement it

What is a firewall?

A firewall is a packet filter: it examines every network packet that crosses the machine and decides, according to rules, to let it through, block it, or redirect it.

On Linux, this filtering is done in the kernel by Netfilter, the historical subsystem, driven today by nftables (and still by iptables on older systems). The tools you use every day, UFW, Firewalld, firewall-cmd, ufw, nft, are interfaces that translate your rules into instructions for Netfilter.

What a firewall does:

  • allows or refuses traffic by source, destination, port, protocol, connection state
  • can redirect a port to another machine (NAT, forwarding)
  • can log packets for auditing

What a firewall does not do:

  • it does not inspect the content of encrypted packets: TLS passes intact, it only sees "port 443"
  • it does not replace authentication: if you leave SSH open without a strong key, the firewall changes nothing
  • it does not fix an application vulnerability: an unpatched Apache behind a firewall stays vulnerable

Why a firewall even behind a router?

The question comes up often: "My router / my cloud provider already has a firewall, why add one on the machine?". Three answers:

  • Defence in depth: a misconfigured rule at the network level must not directly expose an internal service.
  • Lateral traffic: two machines in the same cloud subnet can talk without going through the security group. Only the host firewall filters between them.
  • Controlled egress: a network firewall mostly filters what comes in; controlling what goes out (exfiltration) is more natural on the host side.

Key concepts

Default policy

It is the rule applied when no other rule matched. Two possible postures:

  • Deny-by-default: everything is blocked except what you explicitly allow. Recommended posture for a server.
  • Allow-by-default: everything passes except what you explicitly block. Acceptable on an isolated dev workstation, rarely elsewhere.

UFW and Firewalld both apply deny-by-default to inbound traffic as soon as they are enabled, and allow-by-default to outbound traffic. It is the most useful baseline.

Inbound, outbound and routed traffic

Netfilter distinguishes three paths a packet can take, and each one has its own chain of rules. Knowing which path a packet follows tells you where to write the rule:

PathDescriptionExample
INPUT (inbound)Packet addressed to the machine itselfSomeone hits your IP on port 443
OUTPUT (outbound)Packet sent by the machineYour server contacts the apt repository
FORWARD (routed)Packet crossing the machine without being addressed to itLinux router, VPN, NAT

Most servers route nothing: only INPUT and OUTPUT matter. FORWARD becomes relevant for a router, a KVM hypervisor or Kubernetes pod networking.

Stateful: connection tracking

Modern firewalls are stateful: they remember connections already open and automatically let the replies through.

In practice: you do not need to write a rule to allow the return of a packet you initiated. When your server runs apt update, the firewall records that an outbound connection to deb.debian.org:443 was established, and it accepts the return packets without an explicit rule.

The typical states (visible with conntrack -L) are the vocabulary of every stateful ruleset:

  • NEW: first time the packet is seen (this is where the authorisation decision is made)
  • ESTABLISHED: packet belonging to an already validated connection
  • RELATED: packet linked to an existing connection (passive FTP, ICMP in reply)
  • INVALID: inconsistent packet, to block

Golden rule: only filter NEW. Let ESTABLISHED and RELATED through; block INVALID. UFW and Firewalld do it for you by default.

Ports, services, protocols

A TCP or UDP packet carries a source port and a destination port (0-65535). Low ports (< 1024) are reserved by default to root, or to a process holding the CAP_NET_BIND_SERVICE capability.

A few well-known ports come up in almost every ruleset, and recognising them saves a lookup when reading a rule:

PortProtocolService
22TCPSSH
25TCPSMTP (often filtered outbound by the hosting provider)
53UDP + TCPDNS
80TCPHTTP
443TCPHTTPS
587TCPSMTP submission (encrypted)
993TCPIMAPS
5432TCPPostgreSQL
6443TCPKubernetes API

The Firewalld and UFW frontends offer service names (http, ssh, postgresql…) that resolve to port/protocol through /etc/services. Preferring these names makes your rules readable and portable.

How does it work on Linux?

The filtering is split into two layers: the kernel, which applies the rules to each packet, and a frontend, which you use to write them. Knowing which layer you are touching avoids most mix-ups.

The kernel layer: nftables or iptables

All filtering happens in the kernel through Netfilter. Two mechanisms coexist:

  • nftables: the modern standard (since Linux 3.13, 2014). More expressive, faster, unified syntax. Default backend on RHEL 8+, Debian 10+ and Ubuntu 22.04+ (Ubuntu 20.04 still used iptables-legacy).
  • iptables: the ancestor. Still there for compatibility, often as a wrapper that translates to nftables internally (iptables-nft): iptables -V then prints (nf_tables).

You can write nft rules by hand, as the nftables guide explains; it is less common, almost every administrator uses a frontend, but it is the right choice for a minimalist server or a versioned ruleset.

Frontends: UFW, Firewalld, direct

Each distribution family ships its own frontend, and the choice mostly follows the distribution rather than taste. The table sums up where UFW, Firewalld and direct nft fit:

ToolTypical distributionStrengths
UFWDebian, UbuntuReadable syntax, immediate setup, no zones
FirewalldRHEL, Fedora, CentOS Stream, Rocky, AlmaLinuxDynamic zones, hot reload, predefined services
Direct nftAllFull control, but more verbose syntax, needed for edge cases

Pragmatic rule: stick to your distribution's default frontend. Do not mix UFW and Firewalld on the same machine: both write into Netfilter and contradict each other silently.

Host firewall vs network firewall

Two possible locations, two complementary roles: the host firewall protects one machine, the network firewall guards the perimeter:

TypeWhereExamplesRole
HostOn each machineUFW, Firewalld, nftablesFilters what enters/leaves the machine itself
NetworkOn the path between several machinesRouter, cloud firewall (AWS, GCP, Azure security group), OPNsense, pfSenseFilters at the perimeter entry

In serious production, you have both. In a homelab or on an isolated cloud VM, the host firewall alone is already considerable progress over a server without any firewall.

Next-generation firewalls (NGFW), IDS/IPS and WAFs add application-level analysis layers (HTTP content inspection, attack signature detection): it is a separate field, outside the scope of this page.

Common pitfalls

Firewall mistakes share a common point: the rule looks right, but it cuts what had to stay, lets through what had to be closed, or disappears on reboot. Here are the most frequent ones.

  • Enabling the firewall without allowing SSH: guaranteed lockout if you work remotely. Always allow the administration port before enabling.
  • Forgetting --permanent (Firewalld): the rule disappears at the next reload or reboot.
  • Allow rule too broad: allow from any on an application port exposes to the Internet a service that should stay on the LAN. Scope it to 192.168.0.0/16 or to the VPN CIDR.
  • Mixing UFW and Firewalld: unpredictable behaviour, strange silences. Pick one and disable the other.
  • Mixing UFW/Firewalld with hand-written iptables rules: frontends manage their own chains, a manual change can be overwritten.
  • Relying on the firewall to hide a vulnerable service: an unpatched Nextcloud exposed on the LAN can still be compromised.
  • Not logging: without logging, a blocked packet you have been chasing for 3 hours stays invisible. Temporarily enable ufw logging medium or firewall-cmd --set-log-denied=unicast during diagnosis.

Key points

  • A Linux firewall is a packet filter in the kernel (Netfilter), driven by a frontend (UFW, Firewalld, nft).
  • Recommended default policy: deny inbound, allow outbound.
  • Modern firewalls are stateful: filter NEW, let ESTABLISHED / RELATED through, block INVALID.
  • Three paths to know: INPUT (to the machine), OUTPUT (from the machine), FORWARD (through the machine).
  • UFW on Debian/Ubuntu, Firewalld on RHEL/Fedora/Rocky, never both.
  • Prefer service names (ssh, http) over port numbers for readability.
  • Host firewall ≠ network firewall: they complement each other, neither replaces the other nor fixes application bugs.
  • Always allow SSH before enabling and keep a fallback console access.

Knowledge check

Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

Is this project useful to you?

The guides, courses, quizzes and labs stay free. If you use them regularly, you can contribute to their upkeep and development.

Become a supporting member (new tab) One-time support (new tab) Learn more

Follow the project on LinkedIn