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
sudo systemctl is-enabled nftables 2>/dev/null || true
sudo systemctl is-enabled firewalld 2>/dev/null || true
sudo iptables –version 2>/dev/null || true
sudo nft list ruleset

 

2. Safety Before Changing Remote Firewall Rules

  1. Keep a console, hypervisor console, serial console or cloud out-of-band session available.
  2. Confirm the SSH source address and allow it before enabling a default-deny policy.
  3. Back up the active rules and configuration files.
  4. Validate file-based nftables rules before applying them.
  5. Test from a second session before closing the existing administrative session.

Pre-change inventory and backup

sudo ss -lntup
sudo ip address show
sudo ip route show
sudo ufw status numbered
sudo sh -c ‘nft list ruleset > /root/nftables-before-$(date +%F-%H%M).nft’
sudo tar -czf /root/ufw-before-$(date +%F-%H%M).tgz /etc/ufw

 

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
sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw default deny routed
sudo ufw allow proto tcp from 192.0.2.0/24 to any port 22 comment ‘Admin SSH’
sudo ufw –dry-run enable
sudo ufw enable
sudo ufw status verbose

 

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
sudo ufw disable
sudo ufw reload
sudo ufw status
sudo ufw status verbose
sudo ufw status numbered
sudo ufw show added
sudo ufw show raw

 

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
dpkg-query -W -f=’${Status} ${Version}\n’ ufw
sudo systemctl status ufw
ufw version

 

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
sudo ufw allow http
sudo ufw allow https
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw deny 23/tcp comment ‘Block Telnet’
sudo ufw reject 25/tcp comment ‘Reject direct SMTP’

 

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’
sudo ufw allow 53/tcp comment ‘DNS TCP and large replies’
sudo ufw allow proto tcp to any port 80,443,8443 comment ‘Web services’
sudo ufw allow 14000:14500/tcp comment ‘PeopleSoft range 1’
sudo ufw allow 24000:24500/tcp comment ‘PeopleSoft range 2’

 

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’
sudo ufw allow proto udp from 198.51.100.20 to any port 161 comment ‘SNMP manager’
sudo ufw allow in on enp1s0 proto tcp from 203.0.113.0/24 to any port 443
sudo ufw deny out on enp1s0 proto tcp to any port 25 comment ‘Block outbound SMTP’
sudo ufw allow out proto udp to 198.51.100.53 port 53 comment ‘Approved DNS resolver’

 

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
sudo ufw status numbered
sudo ufw delete 3
sudo ufw delete allow 80/tcp
sudo ufw reset

 

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’
sudo ufw limit 22/tcp
sudo ufw status verbose

 

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
sudo ufw app info OpenSSH
sudo ufw allow OpenSSH
sudo ufw allow from 192.0.2.0/24 to any app OpenSSH
sudo ufw delete allow OpenSSH

 

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]
title=XCOM file transfer
description=TCP ports 8044 and 8045
ports=8044,8045/tcp

[PeopleSoft]
title=PeopleSoft application ports
description=TCP ranges 14000-14500 and 24000-24500
ports=14000:14500/tcp|24000:24500/tcp

[Application-Misc]
title=Application miscellaneous ports
description=TCP ports 8000 and 8443
ports=8000,8443/tcp

 

Load and permit the custom profiles

sudo chmod 0644 /etc/ufw/applications.d/business-applications
sudo ufw app update XCOM
sudo ufw app update PeopleSoft
sudo ufw app update Application-Misc
sudo ufw app info XCOM
sudo ufw allow from 10.37.33.0/24 to any app XCOM
sudo ufw allow from 10.37.33.0/24 to any app PeopleSoft
sudo ufw allow from 10.37.33.0/24 to any app Application-Misc
sudo ufw status verbose

 

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
sudo ufw status verbose
sudo journalctl -k –since today | grep ‘UFW’
sudo dmesg | grep ‘UFW’
sudo ufw logging off

 

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
sudo ufw status verbose
sudo ip -6 address show
sudo ip6tables –version 2>/dev/null || true

 

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’
net.ipv4.ip_forward = 1
EOF
sudo sysctl –system
sudo ufw default deny routed
sudo ufw route allow in on enp2s0 out on enp1s0 from 10.0.0.0/24

 

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
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.0.0.0/24 -o enp1s0 -j MASQUERADE
COMMIT

 

Apply and verify the UFW NAT configuration

sudo ufw reload
sudo ufw status verbose
sudo nft list ruleset

 

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
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -i enp1s0 -p tcp –dport 8080 \
  -j DNAT –to-destination 10.0.0.20:80
-A POSTROUTING -s 10.0.0.0/24 -o enp1s0 -j MASQUERADE
COMMIT

 

Permit the forwarded flow

sudo ufw route allow in on enp1s0 out on enp2s0 \
  proto tcp to 10.0.0.20 port 80
sudo ufw reload

 

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
sudo apt install nftables
sudo systemctl is-active ufw
sudo systemctl is-enabled nftables 2>/dev/null || true
sudo nft –version
sudo nft list ruleset

 

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 {
    chain input {
        type filter hook input priority filter; policy drop;

        iifname “lo” accept
        ct state invalid drop
        ct state established,related accept
        meta l4proto { icmp, ipv6-icmp } accept

        ip saddr 192.0.2.0/24 tcp dport 22 accept
        tcp dport { 80, 443 } accept

        limit rate 5/minute counter \
            log prefix “nft input drop: ” drop
    }

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

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

 

Validate and switch from UFW from a trusted console

sudo nft -c -f /etc/nftables.conf
sudo sh -c ‘nft list ruleset > /root/ufw-generated-before.nft’
sudo ufw disable
sudo systemctl disable –now ufw
sudo nft -f /etc/nftables.conf
sudo systemctl enable nftables
sudo nft list ruleset

 

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
sudo nft ‘add chain inet host_filter input { \
  type filter hook input priority filter; policy drop; }’
sudo nft ‘add rule inet host_filter input iifname “lo” accept’
sudo nft add rule inet host_filter input \
  ct state established,related accept
sudo nft add rule inet host_filter input \
  ip saddr 192.0.2.0/24 tcp dport 22 accept
sudo nft add rule inet host_filter input tcp dport 443 accept

 

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
sudo nft insert rule inet host_filter input position 7 \
  tcp dport 8443 accept
sudo nft delete rule inet host_filter input handle 9
sudo nft flush chain inet host_filter input
sudo nft delete table inet host_filter

 

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’
sudo nft -c -f /root/nftables-backup.nft
sudo nft -f /root/nftables-backup.nft
sudo nft monitor ruleset

 

11. nftables Sets and Common Application Rules

Use named sets for source and port groups

Persistent named-set example

table inet filter {
    set admin_hosts {
        type ipv4_addr
        flags interval
        elements = { 192.0.2.0/24, 198.51.100.10 }
    }

    set business_ports {
        type inet_service
        flags interval
        elements = { 8000, 8044, 8045, 8443, \
                     14000-14500, 24000-24500 }
    }

    chain input {
        type filter hook input priority filter; policy drop;
        iifname “lo” accept
        ct state established,related accept
        ip saddr @admin_hosts tcp dport @business_ports accept
    }
}

 

Update a named set at runtime

sudo nft ‘add element inet filter admin_hosts { 203.0.113.20 }’
sudo nft ‘delete element inet filter admin_hosts { 198.51.100.10 }’
sudo nft list set inet filter admin_hosts

 

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 \
  ip saddr 192.0.2.0/24 tcp dport 22 accept
sudo nft add rule inet filter input tcp dport { 80, 443 } accept
sudo nft add rule inet filter input \
  ip saddr 198.51.100.20 udp dport 161 accept
sudo nft add rule inet filter input \
  ip saddr 10.37.33.0/24 tcp dport { 8044, 8045 } accept
sudo nft add rule inet filter input \
  ip saddr 10.37.33.0/24 tcp dport 14000-14500 accept

 

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’
net.ipv4.ip_forward = 1
EOF
sudo sysctl –system

 

Forward-chain example

table inet filter {
    chain forward {
        type filter hook forward priority filter; policy drop;
        iifname “enp2s0” oifname “enp1s0” \
            ip saddr 10.0.0.0/24 ct state new,established,related accept
        iifname “enp1s0” oifname “enp2s0” \
            ip daddr 10.0.0.0/24 ct state established,related accept
        iifname “enp1s0” oifname “enp2s0” \
            ip daddr 10.0.0.20 tcp dport 80 accept
    }
}

 

Masquerade and destination NAT

nftables NAT table

table ip nat {
    chain prerouting {
        type nat hook prerouting priority dstnat; policy accept;
        iifname “enp1s0” tcp dport 8080 \
            dnat to 10.0.0.20:80
    }

    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        oifname “enp1s0” ip saddr 10.0.0.0/24 masquerade
    }
}

 

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
sudo ip6tables –version
sudo update-alternatives –display iptables 2>/dev/null || true
sudo iptables -L -n -v –line-numbers
sudo ip6tables -L -n -v –line-numbers
sudo iptables-save

 

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
sudo iptables -I INPUT 5 -p tcp -m conntrack \
  –ctstate NEW –dport 3872 -j ACCEPT
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
sudo netfilter-persistent save
sudo netfilter-persistent start
sudo ls -l /etc/iptables/rules.v4 /etc/iptables/rules.v6

 

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
sudo sh -c ‘iptables-save > /root/iptables-v4.dump’
sudo sh -c ‘iptables-restore-translate -f /root/iptables-v4.dump > /root/iptables-converted.nft’
sudo nft -c -f /root/iptables-converted.nft

 

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
sudo systemctl status SERVICE_NAME
sudo ip address show
sudo ip route get 198.51.100.10
sudo ufw status verbose
sudo nft -a list ruleset
sudo journalctl -k –since today | grep -E ‘UFW|nft input drop’

 

  • 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 \
  ip saddr 192.0.2.10 tcp dport 443 meta nftrace set 1
sudo nft monitor trace
sudo nft -a list chain 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
sudo ufw disable
sudo tar -xzf /root/ufw-before-DATE-TIME.tgz -C /
sudo ufw enable

 

nftables recovery

Restore a saved nftables ruleset

sudo sh -c ‘nft list ruleset > /root/nftables-broken.nft’
sudo nft -c -f /root/nftables-before-DATE-TIME.nft
sudo nft -f /root/nftables-before-DATE-TIME.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

 

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.