October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Convert iptables Rules to UFW on Linux Without Locking Yourself Out

There is no universal iptables importer for UFW. Learn how to inventory and classify rules, translate common host policies, preserve forwarding and NAT logic, protect SSH, test both address families, and roll back safely.

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.

There is no one-command importer for an arbitrary iptables ruleset. A safe conversion is an inventory-and-rebuild process: save the active IPv4 and IPv6 rules, classify each rule, translate ordinary host filtering into UFW commands, keep forwarding/NAT and unsupported matches in UFW’s iptables-restore-compatible files, then test before enabling.

Protect your management path first. Enabling UFW can flush chains and interrupt existing connections, so add and verify the SSH rule from a second session before you turn the firewall on.

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.

What converting iptables to UFW actually involves

UFW (Uncomplicated Firewall) is a command-line frontend for common stateful host-firewall policies. It gives you readable commands, numbered rules, insertion and deletion, application profiles, comments, and per-rule logging. It is not a universal parser for every rule that can be written for iptables or nftables.

The UFW manual describes its scope directly: “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.” That distinction determines the migration plan. A web server with a few inbound ports is a good UFW candidate. A router using several tables, custom chains, packet-size tests, time-of-day matches, or multi-layer inspection may need direct iptables or nftables instead.

nftables entered the mainline Linux kernel in version 3.13, released in 2014. On current distributions, UFW may ultimately program an iptables-compatible backend backed by nftables or a legacy backend. Rules retained in files must use syntax accepted by the backend installed on that machine; do not assume that a file copied from another host will behave identically.

1. Capture the current state and your access path

Do this while the existing firewall is still working. Keep the saved files outside any temporary directory that may be cleared during maintenance, and record which account and network path you use for administration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Save IPv4 rules. Run sudo iptables-save > ~/iptables-v4-before-ufw.rules.
  2. Save IPv6 rules. Run sudo ip6tables-save > ~/iptables-v6-before-ufw.rules. IPv6 policy is separate; an IPv4-only migration leaves IPv6 exposed or unreachable if you do not review it.
  3. Record the active state. Capture sudo iptables -L -n -v --line-numbers, sudo ip6tables -L -n -v --line-numbers, and the NAT table with sudo iptables -t nat -L -n -v --line-numbers. The byte and packet counters help you identify rules that are actually used.
  4. Identify every management route. Note whether you connect over SSH, a console, a VPN, a private interface, or an out-of-band service. A rule that allows SSH only from one source address must match the address you will really use after the change.
  5. Open a second session. Leave the current SSH connection open and establish another one before enabling UFW. If the new policy blocks the first session, the second gives you a way to correct it.

Do not enable UFW merely to inspect its syntax. Use sudo ufw --dry-run ... for planned changes, and inspect the resulting policy before applying it. If you have no console or recovery channel and cannot open a second management session, schedule the migration for a maintenance window with an out-of-band fallback.

2. Classify each rule before translating anything

Read the complete ruleset, not just the visible INPUT chain. The destination determines whether a rule belongs in the UFW command interface or in a file.

iptables area What it usually does UFW treatment
INPUT Filters packets addressed to the machine itself Usually an ordinary ufw allow, deny, reject, or limit rule
OUTPUT Controls traffic generated by the machine Use UFW rules with the out direction and choose an explicit outgoing default
FORWARD Filters packets traversing the machine between interfaces Use ufw route allow|deny|reject, plus forwarding and sysctl settings
NAT Masquerading, destination translation, and port translation Keep gateway rules in /etc/ufw/before.rules or another appropriate UFW rules file
raw, mangle, and other tables Connection tracking exceptions, packet marking, alteration, or specialized matches Preserve in file-based rules when UFW’s command syntax cannot represent them
Custom chains Reusable or application-specific processing paths Retain with iptables-restore syntax; do not flatten them into unrelated UFW commands

Also record rule order and policy defaults. A rule that appears to allow traffic may never be reached if an earlier rule drops it. UFW’s numbered list is convenient for maintaining a new policy, but it is not a faithful visual copy of every chain and table in the old configuration.

3. Translate ordinary host rules into UFW syntax

The following conversions cover the common INPUT-style patterns. Replace example ports, addresses, and interfaces with the values from your inventory.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
iptables pattern UFW command Important qualification
iptables -A INPUT -p tcp --dport 22 -j ACCEPT sudo ufw allow 22/tcp Allows TCP/22 from any source permitted by the surrounding policy.
Source-restricted SSH sudo ufw allow proto tcp from 203.0.113.10 to any port 22 Use the actual fixed administration address or network; a changing address will lock you out.
TCP port denial sudo ufw deny 23/tcp Silently drops matching traffic according to UFW’s generated rules.
TCP port rejection sudo ufw reject 23/tcp Sends a rejection instead of silently dropping; choose deliberately because it reveals that a host is reachable.
SSH rate limiting sudo ufw limit ssh/tcp UFW applies its built-in rate-limit behavior to repeated SSH connections.
Interface-specific HTTP sudo ufw allow in on eth0 to any port 80 proto tcp Traffic arriving on another interface is not covered by this rule.
Logged, documented HTTPS sudo ufw allow log 443/tcp comment 'HTTPS' Logging volume depends on traffic; monitor it rather than enabling broad logging blindly.

Direction, protocol, source, destination, and port can be combined. For example, an outbound DNS rule can be expressed as sudo ufw allow out 53/udp. Do not add an outbound allow simply because the old ruleset had one: first decide whether your outgoing default is permissive or restrictive and preserve the old intent.

Preserve ordering, insertion, and deletion

UFW evaluates its generated rules in an order that matters. Review the result with sudo ufw status numbered. To place a new rule ahead of an existing rule, use the insertion form, such as sudo ufw insert 1 allow 443/tcp. To remove a rule, use its displayed number: sudo ufw delete NUM, replacing NUM with the current number. Recheck the list after every deletion because the remaining numbers shift.

Use comments for purpose and owner information when a rule will outlive the migration. A comment does not change matching behavior, but it prevents a later administrator from deleting a required exception merely because its reason is unclear.

4. Convert FORWARD rules with ufw route

A packet crossing the host is not an ordinary inbound connection to that host. Translate those policies with the routed form, for example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • sudo ufw route allow in on lan0 out on wan0 from 192.0.2.0/24 to any permits forwarding from a LAN interface to a WAN interface.
  • sudo ufw route deny in on wan0 out on lan0 to 192.0.2.0/24 blocks the reverse direction.
  • Add protocol and port constraints when the original FORWARD rule is service-specific, such as proto tcp to any port 443.

These commands are only one part of a routed configuration. Ubuntu’s server guidance requires the forwarding policy and kernel forwarding settings to agree:

  1. Edit /etc/default/ufw and set DEFAULT_FORWARD_POLICY='ACCEPT' when your design requires forwarding by default. If your policy is deny-by-default, use the corresponding restrictive value and allow only the required routes.
  2. In /etc/ufw/sysctl.conf, enable net/ipv4/ip_forward=1. Enable the IPv6 forwarding setting there as well when IPv6 traffic must traverse the host.
  3. Reload the settings and verify the effective kernel values before testing a client behind the gateway.

Do not treat a successful local connection as proof that forwarding works. Test from a client on each source interface to a destination on each permitted interface, then test a deliberately denied path.

5. Keep NAT and masquerading in UFW rules files

UFW’s command interface is not a NAT editor. Keep destination NAT, port forwarding, and masquerading in /etc/ufw/before.rules (or the appropriate IPv6 rules file when applicable), using the iptables-restore format expected by the installed backend. Ubuntu documents these files for legacy iptables rules and for network-gateway or bridge-related logic.

A typical masquerade block has a *nat table, a POSTROUTING rule, and a terminating COMMIT. For example, a gateway serving the documentation subnet 192.0.2.0/24 through eth0 might use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 192.0.2.0/24 -o eth0 -j MASQUERADE
COMMIT

This is a pattern, not a drop-in value: substitute your real internal subnet and egress interface, preserve any existing NAT chains, and ensure the address family matches the rule. Back up the file before editing. A malformed table block can prevent UFW from loading, while a syntactically valid but overly broad masquerade can hide traffic that should have remained identifiable.

Port forwarding also needs two coordinated pieces: the NAT translation and a routed filter rule that permits the forwarded flow. Adding only one commonly produces a connection that reaches the gateway but is dropped before it reaches the destination.

6. Preserve matches and chains that UFW cannot express

Keep granular logic in /etc/ufw/before.rules or /etc/ufw/after.rules when it cannot be represented by a UFW command. Ubuntu loads these files with iptables-restore. They are appropriate for custom chains, unusual matches, bridge handling, packet marking, and other table-specific behavior.

  • Copy the relevant chain definitions and their jump relationships, not just individual rules.
  • Keep table declarations and COMMIT boundaries intact.
  • Separate IPv4 and IPv6 syntax; an IPv4 match is not automatically valid in an IPv6 file.
  • Validate the syntax with the restore tooling available on the host before enabling UFW.
  • Document why each retained block exists and which original chain or service it replaces.

Do not duplicate a rule in both the UFW command interface and a before/after file unless you intentionally want two independently maintained copies. Duplicate rules make deletion confusing and can change logging or counter behavior.

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

7. Set defaults, test with a dry run, and enable

Choose incoming, outgoing, and routed defaults based on the policy you actually need. A common host baseline is:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Set a routed default separately when the machine forwards traffic. A gateway policy should not inherit assumptions from a workstation policy. Before applying each change, preview it with the dry-run form, then inspect the numbered rules:

sudo ufw --dry-run allow 22/tcp
sudo ufw status numbered

Add the SSH rule before enabling:

sudo ufw allow proto tcp from 203.0.113.10 to any port 22
sudo ufw limit ssh/tcp

Use either a broad SSH allow or a source-restricted rule as appropriate; do not add both without understanding the resulting order. From the second management session, confirm that the new rule matches the source address you expect.

Enable only after the policy, files, and access test are ready:

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

Then run sudo ufw status verbose and sudo ufw status numbered. Test every required service from a known client, test an intentionally blocked service, and repeat the checks over IPv6 when IPv6 is enabled. If you changed forwarding or NAT, test traffic from behind the gateway rather than only from the gateway itself.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

8. Verify behavior and prepare a rollback

A clean status listing proves that UFW accepted its configuration; it does not prove that an application is reachable. Verification should cover policy, path, and application layers:

  • Confirm the expected listening service and port on the destination host.
  • Connect from each allowed source and interface.
  • Attempt the same connection from a source that should be denied.
  • For SSH, keep the original session open until the second session has completed authentication and a command.
  • For IPv6, test an IPv6 client separately; an IPv4 success says nothing about the IPv6 policy.
  • Review UFW logs only for rules where logging is enabled, and correlate timestamps with the client test.

If the migration fails, use the console or your still-open session to disable UFW, correct the policy, and reload:

sudo ufw disable
sudo ufw reload

For an emergency return to the previous firewall, restore the saved address-family rules with the matching restore command after UFW is disabled, then investigate why the translation differed. Restoring the old rules is a recovery action, not a reason to delete the saved files; keep them until the new policy has passed normal operating checks.

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

What UFW can and cannot replace

Decision axis UFW Direct iptables or nftables
Common host filtering Readable commands for ports, protocols, addresses, interfaces, logging, comments, and SSH limiting More verbose, but capable of every supported match and chain arrangement
Custom chains and unusual matches Possible through before/after files, not through the simple command interface Native control over chains, tables, matches, counters, and priorities
FORWARD traffic Requires ufw route plus forwarding policy and sysctl configuration Direct control of the FORWARD chain and routing-related tables
NAT and gateway use Rules live in iptables-restore-compatible files; operationally less obvious to newcomers Direct NAT-table configuration and granular ordering
Insertion and deletion status numbered, insertion, deletion, comments, and dry runs make routine edits approachable Powerful but easier to misorder or remove without a change-management convention
Migration risk Enabling can flush chains and interrupt connections; unsupported rules must be preserved manually Keeping the existing rules avoids translation, but maintenance remains more complex

Ubuntu recommends direct iptables or nftables when a policy depends on granular conditions, custom chains, packet-size or time-of-day matching, or multi-layer inspection. UFW is the better operational interface when the policy is primarily straightforward host access and the team values quick, auditable edits.

Troubleshooting common migration failures

SSH stopped working immediately after enabling UFW

The allow rule was missing, too broad or too narrow, attached to the wrong interface, or shadowed by an earlier rule. Use the second session or console, run sudo ufw status numbered, and add the precise SSH rule before re-enabling. If the host is reachable only through a bastion, allow the bastion’s actual source address, not the address of your workstation hidden behind it.

A forwarded connection reaches the gateway but not the destination

Check all three layers: kernel forwarding, UFW’s routed rule, and NAT or destination translation. Confirm the relevant ip_forward setting, use ufw route allow rather than a host-only allow, and verify that the NAT block is in the correct before-rules file with a valid COMMIT.

The rule appears in UFW but traffic is still blocked

Check address family, interface, direction, source address, and rule order. An IPv4 rule does not permit IPv6. An in on eth0 rule does not match traffic arriving on another interface. A deny or reject earlier in the numbered list can prevent a later allow from being reached.

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

UFW refuses to reload after editing a rules file

Inspect the edited table declaration, chain definition, match syntax, and COMMIT line. Restore the previous file from your backup if necessary, validate with the host’s restore tooling, and confirm that the syntax matches the active iptables/nftables backend. Do not troubleshoot by repeatedly enabling and disabling a production firewall without console access.

Rules work for IPv4 but not IPv6

Review the saved IPv6 rules, UFW’s IPv6 setting, IPv6 forwarding requirements, and any separate NAT or filtering file. Test with an IPv6 client and inspect IPv6 counters; an apparently correct IPv4 translation can leave the other protocol family with a different default policy.

A practical go/no-go checklist

  • Both IPv4 and IPv6 rules are saved and readable.
  • INPUT, OUTPUT, FORWARD, NAT, raw, mangle, and custom chains are classified.
  • The SSH or console access rule is written and tested from a second session.
  • Every simple host rule has a reviewed UFW equivalent.
  • Forwarded traffic uses ufw route and the required forwarding/sysctl settings.
  • NAT and unsupported matches are preserved in the correct UFW rules files.
  • Defaults for incoming, outgoing, and routed traffic are intentional.
  • Dry-run output and ufw status numbered match the planned order.
  • Allowed, denied, IPv6, and gateway paths have been tested from real clients.
  • A console or other rollback path remains available until the migration has operated normally.

The decision in one sentence

Convert ordinary host-filtering rules to UFW for clearer day-to-day administration, but do not force a translation of forwarding, NAT, custom-chain, or granular table logic: keep those rules in UFW’s restore-compatible files or remain on direct iptables/nftables when that is the only way to preserve the policy.

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.

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

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.