Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
VGSources
Blog

How to Convert iptables Rules to UFW on Linux Safely

A step-by-step guide to converting iptables policies to UFW, including rule translation, SSH protection, routed traffic, NAT, unsupported matches, testing, and rollback.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There is no one-command importer for arbitrary iptables commands. A safe conversion is an inventory-and-rebuild exercise: save the active IPv4 and IPv6 rules, classify host filtering separately from forwarding and NAT, recreate simple rules with UFW, keep unsupported logic in UFW’s before.rules or after.rules files, and test before enabling the firewall. Protect SSH first because enabling UFW can flush chains and interrupt existing connections.

What conversion actually means

UFW (Uncomplicated Firewall) is a command-line frontend for common stateful host-firewall policies. It is not a universal translator for every iptables command, table, match, or custom chain. Ubuntu’s ufw(8) manual describes the boundary clearly: “ufw is not intended to provide complete firewall functionality via its command interface, but instead provides an easy way to add or remove simple rules.”

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

That makes UFW a good fit for ordinary server access rules such as “allow HTTPS,” “permit SSH from this management address,” or “deny an unused service.” It is a poor fit when the existing policy depends on granular packet matches, unusual tables, custom chains, packet-size or time-of-day conditions, or multi-layer inspection. In those cases, retain direct iptables or nftables management, or combine UFW’s normal rules with carefully maintained restore files.

The objective is behavioral equivalence, not a literal rewrite of every line. A single iptables ruleset can contain several different jobs:

  • Filtering traffic addressed to the machine itself (INPUT and usually OUTPUT).
  • Filtering traffic that passes through the machine (FORWARD).
  • Network address translation and masquerading (NAT).
  • Packet-processing changes in raw, mangle, or other tables.
  • Custom chains, counters, logging, or matches that have no direct UFW command.

Convert each category using the mechanism that can express it. Do not assume that a successful ufw enable means the old gateway or inspection behavior still exists.

Before changing anything: capture state and protect access

Record IPv4 and IPv6 rules

Save a complete snapshot before touching UFW. Capture both address families if IPv6 is enabled; converting only IPv4 can leave an exposed IPv6 service or create an unexpected outage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo iptables-save > ~/iptables-v4-before-ufw.rules
sudo ip6tables-save > ~/iptables-v6-before-ufw.rules
sudo iptables -L -n -v --line-numbers
sudo ip6tables -L -n -v --line-numbers

The save files are your rollback reference and let you compare policy after migration. Also note rules in tables that a filter-only review can miss. On systems using nftables through an iptables compatibility layer, verify which command and backend produced the active rules, and keep restore syntax compatible with that installation.

Identify how you are connected

If the machine is administered over SSH, treat the first enable as a change that can sever your session. UFW may flush chains while applying its policy, and an existing connection is not a guarantee that a new rule set will permit reconnection.

  • Open a second SSH session, console, or out-of-band management channel before enabling.
  • Determine the management source address and whether SSH listens on a non-default port.
  • Add and verify the SSH allow rule before enabling UFW.
  • Keep the second session open while testing a fresh connection from the expected client.

For a standard SSH service, the broad rule is:

sudo ufw allow 22/tcp

If administration must come from one address, narrow it instead:

sudo ufw allow proto tcp from 203.0.113.10 to any port 22

Use your real management address and port, not the documentation example. Add an equivalent IPv6 rule when IPv6 SSH access is required and UFW’s IPv6 support is enabled.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inventory and classify every iptables rule

Read the saved rules from top to bottom and make a conversion worksheet. For each rule, record its table, chain, direction, interface, protocol, source and destination, match conditions, target, logging behavior, and position. Classification prevents a common migration error: treating a forwarding or NAT rule as if it were a local service rule.

iptables location or behavior Meaning UFW approach
INPUT Traffic destined for the firewall host ufw allow, deny, reject, or limit
OUTPUT Traffic originating on the firewall host Directional out rules and an intentional outgoing default
FORWARD Traffic routed through the machine ufw route allow|deny|reject, plus forwarding settings
NAT (POSTROUTING, PREROUTING, DNAT, masquerade) Address or port translation Restore-file rules, commonly in /etc/ufw/before.rules
raw, mangle, custom chains, unusual matches Special packet processing or reusable logic Keep in before.rules/after.rules when compatible, or continue using direct nftables/iptables

Write down the intended default behavior as well as explicit rules. An iptables policy that ends with a drop in INPUT is not equivalent to a UFW installation left with an unintended “allow incoming” default. Decide incoming, outgoing, and routed defaults deliberately rather than inferring them from a few visible accept rules.

Translate ordinary host rules into UFW syntax

Ports and protocols

The simplest one-to-one conversions preserve the protocol and destination port:

iptables pattern UFW command
iptables -A INPUT -p tcp --dport 22 -j ACCEPT sudo ufw allow 22/tcp
A TCP denial for port 23 sudo ufw deny 23/tcp
A TCP rejection for port 23 sudo ufw reject 23/tcp
SSH connection-rate limiting sudo ufw limit ssh/tcp

deny silently drops matching traffic, while reject returns an explicit rejection. Preserve that distinction when applications or monitoring depend on it. Use a numeric port when the service name in /etc/services is ambiguous, and specify UDP separately when the original ruleset distinguishes TCP and UDP.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Source and destination restrictions

Attach the original source address, subnet, destination address, and port instead of broadening access:

sudo ufw allow proto tcp from 203.0.113.10 to any port 22

For a destination address on a multi-address host, replace any with the address that the original rule targeted. Check whether the iptables rule matched a source subnet, a single host, or an interface-generated address; those are different policies.

Interfaces, direction, logging, and comments

UFW can constrain a rule to an interface and direction:

sudo ufw allow in on eth0 to any port 80 proto tcp

Logging and an operator-facing comment can travel with a rule:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw allow log 443/tcp comment 'HTTPS'

Use out for traffic originating from the host when the iptables policy filtered OUTPUT. UFW also supports application profiles, but inspect the profile before using it: a profile may open more than the single port represented by an old iptables line.

Preserve order and manage changes safely

Rule order matters when an earlier match decides the result. Inspect the numbered list:

sudo ufw status numbered

Insert a rule at a specific position when order is significant, then delete by number only after rechecking the list because numbering changes after every deletion. UFW also supports prepending a rule for cases where it must be evaluated before existing entries. Use sudo ufw --dry-run with planned operations to see the generated changes without applying them.

Can UFW handle FORWARD traffic?

Yes, but routed traffic requires a different command family and kernel settings. An ordinary ufw allow rule describes traffic to the firewall host; it does not automatically authorize packets crossing between interfaces.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use ufw route for transit policy

Translate a forwarding accept, deny, or reject into the corresponding routed form and retain interface, protocol, address, and port constraints. For example, the shape of a routed allow is:

sudo ufw route allow in on eth0 out on eth1 proto tcp from 192.0.2.0/24 to 198.51.100.20 port 443

Use ufw route deny or ufw route reject when the original forwarding target was a drop or reject. Adapt the addresses and interfaces to the actual rule; the example is not a license to widen a subnet.

Enable forwarding in UFW and the kernel

Ubuntu’s server guidance calls for three coordinated settings when the host is a router or gateway:

  1. Set DEFAULT_FORWARD_POLICY="ACCEPT" in /etc/default/ufw when that is the intended baseline. A restrictive routed policy can instead use a different default and explicit ufw route permits.
  2. Enable net/ipv4/ip_forward=1 in /etc/ufw/sysctl.conf.
  3. Enable the IPv6 forwarding equivalent there when the machine routes IPv6.

Apply the settings using the system’s normal sysctl and UFW reload procedure, then test traffic through both interfaces. A route rule without kernel forwarding, or kernel forwarding without a matching UFW route policy, will not reproduce a working gateway.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to preserve NAT, masquerading, and unsupported logic

NAT and masquerading

UFW’s command interface is not a complete NAT editor. Ubuntu documents /etc/ufw/*.rules as iptables-restore-compatible files; before.rules and after.rules are intended places for legacy rules and gateway or bridge-related logic. Put the original NAT section there in the syntax accepted by the installed backend, alongside the required table declarations and chain flow.

Typical gateway migrations need to preserve both halves of the behavior: a forwarding policy that permits the flow and a NAT rule that rewrites the source or destination. Copying only masquerading while omitting the route permission, or vice versa, produces a gateway that appears partially configured but cannot pass the intended traffic.

Custom chains and special matches

Keep custom chains, unusual matches, packet marks, and table-specific rules in the restore files only when the host’s iptables-restore implementation supports them. Validate the syntax before a reload and document which file owns each chain so a later UFW edit does not silently remove it. If the policy depends on conditions UFW cannot represent—such as packet-size matching, time-of-day windows, or multi-layer inspection—direct nftables or iptables remains the more maintainable control plane.

Do not mix ad-hoc commands with file-managed rules without recording ownership. A manually inserted rule can disappear on reload, while a file rule can be applied in an order different from the one you tested interactively.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose defaults, test, and enable in a controlled sequence

Set policy intentionally

Choose the incoming, outgoing, and routed defaults to match the old policy and the machine’s role. A workstation, an Internet-facing server, and a two-interface gateway generally need different defaults. Add all required allows before selecting a restrictive incoming or routed policy. Include DNS, package mirrors, monitoring, time synchronization, and any outbound service the host must initiate when the outgoing policy is not open.

Preview generated changes

Use UFW’s dry-run mode for planned commands:

sudo ufw --dry-run allow 443/tcp

Review the resulting rules and compare them with the inventory. Dry-run output is a planning aid, not a connectivity test; it cannot prove that a remote client can complete a connection.

Enable only after local and remote checks

  1. Confirm the SSH rule and any console fallback.
  2. Add host and route rules, plus restore-file NAT or custom logic.
  3. Review sudo ufw status numbered and the intended defaults.
  4. From known clients, test every required service, denied service, and routed path. Test IPv4 and IPv6 separately when both are active.
  5. Enable or reload UFW while the second management session remains available.
  6. Retest after the reload, then inspect logs and counters for unexpected drops.

When a test fails, identify whether the packet is local or routed, which address family it uses, whether DNS resolved an unexpected address, and whether a NAT rewrite is present. Correct the narrowest rule or setting rather than opening an entire interface or subnet as a diagnostic shortcut.

Rollback and recovery

Keep the pre-migration iptables-save and ip6tables-save files accessible through the console or recovery environment. If enabling UFW cuts off remote access, use that channel to disable or reload UFW, restore the known-good rules with the system’s supported restore command, and investigate from a controlled session. Do not overwrite the only backup with a post-failure snapshot.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a planned rollback, first record the failed UFW status and restore-file versions, then return to the previous firewall control method consistently. Leaving UFW enabled while also restoring an independently managed iptables policy can create competing ownership and an unpredictable next reload.

UFW versus direct iptables or nftables

Decision axis UFW Direct iptables or nftables
Rule expressiveness Clear commands for common stateful host rules; limited for granular matches and specialized tables Full access to matches, tables, chains, sets, marks, and inspection logic supported by the backend
Host filtering Fast to read, add, insert, delete, and audit with numbered status More detailed but easier to make ordering and maintenance mistakes without tooling
Forwarding and gateways Supported through ufw route, forwarding policy, sysctl settings, and restore files Native control of forwarding and NAT in the chosen ruleset language
Migration risk Low for simple INPUT/OUTPUT policies after testing; higher when hidden NAT or custom chains are omitted Preserves the original model but requires expertise and disciplined change control
Operational readability Short, service-oriented commands and application profiles Exact packet-processing behavior is visible, but rulesets can be harder for general administrators to edit safely

nftables entered the mainline Linux kernel in version 3.13, released in 2014. Modern distributions may expose nftables through compatibility commands, so determine which backend is active before placing legacy restore syntax in UFW files. If your policy fundamentally depends on capabilities outside UFW’s interface, staying with direct nftables or iptables is safer than forcing an incomplete translation.

A practical conversion checklist

  • Save active IPv4 and IPv6 rules and record the backend.
  • Mark SSH or console access and prepare a second management path.
  • Separate INPUT/OUTPUT, FORWARD, NAT, and special-table rules.
  • Translate simple service rules with exact protocol, port, source, destination, interface, and action.
  • Use ufw route plus forwarding and sysctl settings for transit traffic.
  • Place NAT, custom chains, and unsupported matches in validated before.rules or after.rules files, or retain direct firewall management.
  • Choose incoming, outgoing, and routed defaults deliberately.
  • Preview changes with --dry-run, inspect numbered status, and test both address families.
  • Enable or reload only with a recovery path available, then keep the original saves for rollback.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.