Debian and Ubuntu Linux Firewall Management Cheat Sheet
Practical host-firewall guidance for supported Debian and Ubuntu systems, with UFW for straightforward host rules and nftables for native or advanced policies.
Commands are shown without shell prompt characters so they can be copied directly. Replace example interfaces, addresses, zones and ports with values appropriate to your environment.
The documentation uses RFC 5737 example IPv4 ranges such as 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24. These ranges are for documentation and should not be used as production addresses.
1. Choose the Correct Firewall Manager
Packet-filtering components
- Netfilter is the Linux kernel packet-filtering and network address translation subsystem.
- A user-space manager such as UFW, nftables, firewalld or iptables creates and maintains the rules used by Netfilter.
- Ubuntu documents UFW as its default firewall configuration tool. UFW is initially disabled on a standard installation until an administrator enables it.
- Debian uses nftables as its default and recommended firewall framework. The nft command manages the nf_tables kernel ruleset directly.
- Modern iptables commands may use the nftables kernel backend through the iptables-nft compatibility layer. This does not make direct mixing of managers safe.
|
Use case |
Recommended manager |
Reason |
|
Ubuntu host with common allow/deny requirements |
UFW |
Simple syntax, application profiles, IPv4/IPv6 handling and straightforward persistence. |
|
Debian host or complex gateway/router |
nftables |
Native framework, atomic ruleset loading, sets, maps, NAT and detailed packet control. |
|
Fleet standardized on firewalld |
firewalld (optional) |
Can be installed on Debian/Ubuntu, but use it instead of UFW or the nftables service. |
|
Existing legacy rules only |
iptables compatibility |
Retain temporarily for migration; prefer UFW or native nftables for new work. |
Best practice: Run one firewall management layer on a host. Do not have UFW, firewalld, the nftables service and an iptables persistence service all loading independent rules.
Identify the active tooling and backend
|
sudo ufw status verbose |
2. Safety Before Changing Remote Firewall Rules
- Keep a console, hypervisor console, serial console or cloud out-of-band session available.
- Confirm the SSH source address and allow it before enabling a default-deny policy.
- Back up the active rules and configuration files.
- Validate file-based nftables rules before applying them.
- Test from a second session before closing the existing administrative session.
Pre-change inventory and backup
|
sudo ss -lntup |
Remote-access warning: UFW may flush and rebuild its chains when first enabled or when default policies change. Add the SSH rule before enabling UFW. For nftables, use nft -c to validate the complete file before loading it.
3. Ubuntu UFW Quick Start
Install and establish a secure baseline
The following example denies unsolicited inbound traffic, allows normal outbound traffic, denies routed traffic and permits SSH only from an administration subnet.
Secure UFW baseline
|
sudo apt update |
Important: If the administrator location changes frequently, permit the required current source or use a controlled VPN/bastion before restricting SSH by source.
Enable, disable, reload and inspect UFW
Core UFW lifecycle and inspection commands
|
sudo ufw enable |
Use status numbered before deleting by rule number. The numbering changes after a deletion, so list the rules again before deleting another number.
4. UFW Packages, Service and Configuration Files
Check the package, unit and version
|
apt-cache policy ufw |
|
Path |
Purpose |
|
/etc/default/ufw |
Default policies, IPv6 setting and general framework options. |
|
/etc/ufw/ufw.conf |
Enablement state and UFW configuration. |
|
/etc/ufw/user.rules |
Generated IPv4 rules created through the UFW command interface. |
|
/etc/ufw/user6.rules |
Generated IPv6 rules created through the UFW command interface. |
|
/etc/ufw/before.rules and before6.rules |
Rules evaluated before user rules; commonly used for carefully reviewed framework customisation and NAT. |
|
/etc/ufw/after.rules and after6.rules |
Rules evaluated after user rules. |
|
/etc/ufw/applications.d/ |
Application profile definitions used by ufw app commands. |
Best practice: Use the ufw command for ordinary rules. Edit framework files only when UFW cannot express the requirement, and keep a tested backup of every manual change.
5. Add, Remove and Order UFW Rules
Named services and simple ports
Allow, deny or reject common services
|
sudo ufw allow OpenSSH |
deny silently drops matching traffic. reject returns an error to the sender. Use explicit protocols where practical. Port 53 is DNS and commonly needs both UDP and TCP; SMTP is normally TCP port 25.
TCP, UDP, multiple ports and ranges
Port and range examples
|
sudo ufw allow 53/udp comment ‘DNS UDP’ |
A UFW comma-separated multiport rule is managed as one rule. To remove one port from it, delete and recreate the complete rule.
Restrict by source, destination, interface and direction
Source-, interface- and direction-specific rules
|
sudo ufw allow proto tcp from 192.0.2.10 to any port 22 comment ‘Admin workstation’ |
Best practice: Restrict administrative, database and monitoring ports to known source ranges instead of exposing them to any address.
Insert, delete and reset rules
Rule ordering, deletion and full reset
|
sudo ufw insert 1 allow proto tcp from 192.0.2.10 to any port 22 |
Caution: ufw reset removes user rules and disables UFW. Back up /etc/ufw first and use the command only when rebuilding the policy intentionally.
Rate-limit SSH and add rule comments
Basic connection-rate limiting
|
sudo ufw limit OpenSSH comment ‘Rate-limit SSH attempts’ |
UFW limit is a lightweight safeguard against repeated connection attempts. It is not a replacement for key-based authentication, fail2ban, a VPN, a bastion host or identity-aware access controls.
6. UFW Application Profiles and Custom Services
List and use installed application profiles
Application profile commands
|
sudo ufw app list |
Create XCOM, PeopleSoft and miscellaneous application profiles
Create a file such as /etc/ufw/applications.d/business-applications with the following INI-format entries.
Example /etc/ufw/applications.d/business-applications
|
[XCOM] [PeopleSoft] [Application-Misc] |
Load and permit the custom profiles
|
sudo chmod 0644 /etc/ufw/applications.d/business-applications |
Best practice: Use separate profiles for unrelated applications so that each service can be reviewed, enabled and removed independently.
7. UFW Logging and IPv6
Enable and review logging
UFW logging
|
sudo ufw logging low |
Higher logging levels can generate substantial data. Start with low, reproduce the issue and turn logging down or off after troubleshooting. Log file locations depend on the system journal and rsyslog configuration.
Confirm IPv6 filtering
IPv6 checks
|
grep ‘^IPV6=’ /etc/default/ufw |
Best practice: Keep IPv6 enabled in the firewall when the host has IPv6 connectivity. Disabling IPv6 filtering while the protocol remains active can leave an unintended path around IPv4-only rules.
8. UFW Forwarding, Masquerading and Port Forwarding
Enable kernel forwarding and permit a routed flow
The example routes a private network on enp2s0 through an internet-facing interface enp1s0. Keep the routed default policy at deny and allow only the required path.
Enable and allow IPv4 forwarding
|
sudo tee /etc/sysctl.d/95-firewall-forwarding.conf >/dev/null <<‘EOF’ |
Add IPv4 masquerading to the UFW framework
Add the following NAT table before the first *filter section in /etc/ufw/before.rules. Do not add a second duplicate *nat section if one already exists.
Masquerading block for /etc/ufw/before.rules
|
*nat |
Apply and verify the UFW NAT configuration
|
sudo ufw reload |
Forward an external port to an internal server
The following combined NAT example forwards TCP port 8080 received on enp1s0 to 10.0.0.20:80. Merge it with any existing NAT section rather than creating conflicting sections.
DNAT and masquerading block
|
*nat |
Permit the forwarded flow
|
sudo ufw route allow in on enp1s0 out on enp2s0 \ |
Security note: NAT does not replace filtering. Add only the required forwarding rule, verify the internal service, and account for cloud security groups, hypervisor firewalls and upstream network access controls.
9. Native nftables Quick Start
Install and inspect nftables without switching managers
Install nftables without changing the active firewall
|
sudo apt update |
Caution: Keep UFW active until the replacement file below passes nft -c validation. Perform the final switch from a console or protected second session.
|
Path or object |
Purpose |
|
/etc/nftables.conf |
Primary persistent ruleset loaded by the nftables service on Debian and Ubuntu. |
|
include statements |
Split a large policy into files such as /etc/nftables.d/*.nft. Wildcard includes load in lexical order. |
|
nft list ruleset |
Displays the active in-kernel ruleset. |
|
nft -a list ruleset |
Displays rule handles used for precise deletion or replacement. |
|
nft -c -f FILE |
Checks syntax and semantics without applying the file. |
Example persistent host firewall
This example uses an inet table so one filter policy covers IPv4 and IPv6. It allows loopback traffic, established connections, ICMP/ICMPv6, SSH from an administration subnet, and public HTTP/HTTPS. All other inbound and forwarded traffic is dropped.
Example /etc/nftables.conf
|
#!/usr/sbin/nft -f flush ruleset table inet filter { iifname “lo” accept ip saddr 192.0.2.0/24 tcp dport 22 accept limit rate 5/minute counter \ chain forward { chain output { |
Validate and switch from UFW from a trusted console
|
sudo nft -c -f /etc/nftables.conf |
IPv6 note: ICMPv6 is required for essential IPv6 functions such as neighbour discovery and path MTU discovery. Do not block it indiscriminately.
10. nftables Live Rule Management
Create tables, chains and rules
Build a live test ruleset
|
sudo nft add table inet host_filter |
Live nft commands change the in-kernel ruleset immediately but do not automatically update /etc/nftables.conf. Record approved changes in the persistent file.
List with handles, insert and delete
Handle-based rule maintenance
|
sudo nft -a list chain inet host_filter input |
Caution: A handle is specific to the active ruleset and can change after reload. List the chain immediately before deleting or replacing a rule.
Back up, restore and monitor changes
Ruleset backup, restore and monitoring
|
sudo sh -c ‘nft list ruleset > /root/nftables-backup.nft’ |
11. nftables Sets and Common Application Rules
Use named sets for source and port groups
Persistent named-set example
|
table inet filter { set business_ports { chain input { |
Update a named set at runtime
|
sudo nft ‘add element inet filter admin_hosts { 203.0.113.20 }’ |
Representative service rules
|
Service |
Ports |
Notes |
|
SSH |
22/tcp |
Restrict to administration networks or a bastion. |
|
HTTP / HTTPS |
80/tcp, 443/tcp |
Expose only when a web service is intended to be public. |
|
DNS server |
53/udp and 53/tcp |
TCP is required for some large responses and zone transfers. |
|
SNMP polling / traps |
161/udp, 162/udp |
Restrict to known monitoring systems. Prefer SNMPv3. |
|
NFSv4 |
2049/tcp |
NFSv3 can require additional RPC services and ports. |
|
PostgreSQL |
5432/tcp |
Restrict to application subnets. |
|
MySQL / MariaDB |
3306/tcp |
Restrict to application subnets. |
|
XCOM |
8044/tcp, 8045/tcp |
Custom application using two TCP ports. |
|
PeopleSoft |
14000-14500/tcp, 24000-24500/tcp |
Use interval sets or two range rules. |
Live examples for common requests
|
sudo nft add rule inet filter input \ |
12. nftables Routing and NAT
Enable forwarding and add filter rules
Enable IPv4 forwarding
|
sudo tee /etc/sysctl.d/95-firewall-forwarding.conf >/dev/null <<‘EOF’ |
Forward-chain example
|
table inet filter { |
Masquerade and destination NAT
nftables NAT table
|
table ip nat { chain postrouting { |
Best practice: Keep NAT and forwarding rules in the same reviewed change. Confirm the route, reverse path, service listener and upstream network policy before troubleshooting the firewall alone.
13. Legacy iptables Compatibility and Migration
Identify the backend and display rules
Legacy/compatibility diagnostics
|
sudo iptables –version |
An iptables version string containing nf_tables means the iptables syntax is using the nftables kernel backend. It is still a separate management interface and should not be mixed casually with UFW or native nft rules.
Insert a rule before a final block rule
Open an application or agent port before a catch-all rule
|
sudo iptables -L INPUT -n -v –line-numbers |
Persist an iptables ruleset when legacy support is unavoidable
Save and reload legacy iptables rules
|
sudo apt install iptables-persistent netfilter-persistent |
Caution: Do not enable netfilter-persistent to load iptables rules if UFW, firewalld or a native nftables ruleset is already the authoritative manager.
Translate iptables syntax to nftables
Migration helpers
|
sudo iptables-translate -A INPUT -p tcp –dport 8443 -j ACCEPT |
Translation output must be reviewed. Some extensions do not translate, and a syntactically valid ruleset can still have incorrect ordering or policy behaviour.
14. Diagnostics and Troubleshooting
Check the service, listener, route and firewall separately
Layered troubleshooting checklist
|
sudo ss -lntup |
- A firewall rule does not start a service. Confirm the process is listening on the expected address and port.
- A listening service can still be unreachable because of routing, cloud security groups, upstream ACLs, load balancers or hypervisor firewalls.
- Test from another host. A local connection can bypass the same path and interface that remote traffic uses.
- Container runtimes can create or manage Netfilter rules. Review the full nft ruleset and the container platform documentation before assuming UFW has final control over a published container port.
- Verify IPv4 and IPv6 independently. A service may listen on one protocol family only, or a rule may protect only one family.
Trace nftables rule evaluation
Use tracing only for a bounded troubleshooting window because it can produce substantial output. Add nftrace to a narrowly matching rule, monitor the trace and remove the tracing rule afterwards.
Temporary nftables tracing
|
sudo nft add rule inet filter input \ |
15. Best-Practice Checklist
- Use a default-deny inbound policy and allow only documented services.
- Restrict SSH, databases, SNMP, management agents and application administration ports by source address or VPN.
- Keep established/related connection rules ahead of new-connection rules in nftables policies.
- Protect IPv4 and IPv6 consistently. Do not assume an IPv4 rule also covers IPv6 unless using an inet-family nftables table or a manager that creates both rules.
- Use rule comments, application profiles, named sets and version-controlled configuration files to make intent clear.
- Validate a complete nftables file with nft -c before applying it. Use a second session to test remote access.
- Prefer UFW profiles or nftables sets over long collections of nearly identical rules.
- Do not edit generated UFW user.rules or user6.rules directly for routine changes.
- Log with rate limits and for a defined troubleshooting or security purpose; avoid unbounded logging before a drop rule.
- Review rules periodically and remove temporary, duplicate, unused or overly broad entries.
- Coordinate host firewalls with cloud security groups, network firewalls, Kubernetes/container networking and service-level access controls.
- Automate repeatable policies with configuration management, but retain an out-of-band recovery path.
16. Quick Recovery
UFW recovery
Restore a saved UFW configuration from console
|
sudo ufw status verbose |
nftables recovery
Restore a saved nftables ruleset
|
sudo sh -c ‘nft list ruleset > /root/nftables-broken.nft’ |
Emergency note: nft flush ruleset removes all nftables filtering and can expose services. Use it only from a trusted console as part of a controlled recovery procedure.
17. Official References
- Ubuntu Server documentation – Firewall – UFW basics, application profiles, masquerading and logging.
- Ubuntu ufw(8) manual page – Rule syntax, routing, comments, logging and application integration.
- Ubuntu ufw-framework(8) manual page – Framework files, forwarding, NAT and custom rules.
- Debian nftables guidance – Debian status and migration overview.
- Debian nft(8) manual page – Authoritative nft command and ruleset syntax.
- Debian netfilter-persistent(8) manual page – Legacy persistence loader commands.
Check out our other Cheat Sheets and Blogs and if you would like us to write a cheat sheet for you, for FREE, (and we find it suitable) Contact Us.