iptables / Firewall commands

Options, match forms and targets of iptables 1.8.13, drawn from the iptables(8), iptables-extensions(8), iptables-save(8) and iptables-restore(8) manual pages and grouped by task. Most rows are bare options to combine on one command line; rows that begin with iptables are whole commands the manuals print. Rules go to the filter table unless -t TABLE names another, and ip6tables shares the command syntax. Rarely used extensions are left out, as are ufw, firewalld and nft commands.

136 commands in 10 sections. Checked row by row against iptables(8) manual page, iptables 1.8.13 (Netfilter upstream Git, rendered by man7.org) on . Edited by Jay.

Listing rules 9

CommandWhat it does
-L [CHAIN]List rules in a chainLong form --list; with no chain named, every chain of the selected table is shown.
iptables -L -vList rules with full detailThe manual's command for seeing the exact rules, which a plain listing leaves out.
iptables -t nat -n -LList NAT rules numericallyReads the nat table in place of the default filter table and skips reverse DNS lookups.
-S [CHAIN]Print rules in iptables-save formLong form --list-rules; covers every chain of the selected table when no chain is named.
-nNumeric addresses and portsLong form --numeric; stops the listing from resolving host, network and service names.
-vVerbose listingLong form --verbose; a listing gains interface names, rule options and packet and byte counters.
-xExact counter valuesLong form --exact; with -L, prints full packet and byte counts instead of figures rounded to K, M or G.
--line-numbersNumber each listed ruleThe number is the rule's place in its chain, the rulenum that -D, -I and -R take.
-Z [CHAIN [RULENUM]]Reset packet and byte countersLong form --zero; clears all chains, one chain or one rule, and may be combined with -L to list first.

Adding and deleting rules 9

CommandWhat it does
-A CHAIN RULE-SPECIFICATIONAppend a ruleLong form --append; the rule goes to the end of the chain, once per address when a name resolves to several.
-I CHAIN [RULENUM] RULE-SPECIFICATIONInsert a rule at a positionLong form --insert; with no rule number the rule becomes the first one in the chain.
-D CHAIN RULE-SPECIFICATIONDelete a matching ruleLong form --delete; removes the rule whose specification equals the one given.
-D CHAIN RULENUMDelete a rule by numberPositions count from 1 at the top of the chain; --line-numbers shows them in a listing.
-R CHAIN RULENUM RULE-SPECIFICATIONReplace a rule in placeLong form --replace; fails if a source or destination name resolves to more than one address.
-C CHAIN RULE-SPECIFICATIONTest whether a rule existsLong form --check; changes nothing and reports the result through its exit code.
-F [CHAIN]Flush all rulesLong form --flush; empties the named chain, or every chain of the table when none is named.
--comment COMMENTAttach a comment to a ruleOption of -m comment; the text may be 256 characters long at most.
iptables -A INPUT -i eth1 -m comment --comment "my local LAN"Add a commented ruleThe manual's example: a rule for packets arriving on eth1 that carries a quoted comment.

Chains and policies 7

The default filter table has three built-in chains: INPUT for packets addressed to the host, FORWARD for routed packets and OUTPUT for locally generated ones.

CommandWhat it does
-t TABLESelect the tableLong form --table; the tables are filter (the default), nat, mangle, raw and security.
-N CHAINCreate a user-defined chainLong form --new-chain; the name must not already belong to a target.
-X [CHAIN]Delete a user-defined chainLong form --delete-chain; the chain must be empty and unreferenced, and with no name every empty chain goes.
-P CHAIN TARGETSet a chain's default policyLong form --policy; built-in chains only, and the policy has to be ACCEPT or DROP.
-E OLD-CHAIN NEW-CHAINRename a user chainLong form --rename-chain; purely cosmetic, the structure of the table stays as it was.
iptables -t raw -N RPFILTERCreate a chain in the raw tableOpens the manual's reverse-path example by adding a chain called RPFILTER for later rules to use.
iptables -t raw -A PREROUTING -j RPFILTERSend packets through a user chainMakes every packet in the raw table's PREROUTING chain traverse the RPFILTER chain.

Matching packets 28

A "!" in front of -p, -s, -d, -i or -o, or of any match option the manual prints with [!], inverts that test.

CommandWhat it does
-p PROTOCOLMatch a protocolLong form --protocol; a name such as tcp, udp, icmp or sctp, a number, or all, which is the default.
-s ADDRESS[/MASK]Match source addressLong form --source or --src; a host, a network with mask, or a comma-separated list that expands to several rules.
-d ADDRESS[/MASK]Match destination addressLong form --destination or --dst; address syntax is the same as for -s.
-i NAMEMatch the incoming interfaceLong form --in-interface; for INPUT, FORWARD and PREROUTING, and a name ending in + matches every interface with that prefix.
-o NAMEMatch the outgoing interfaceLong form --out-interface; for FORWARD, OUTPUT and POSTROUTING, with the same + wildcard as -i.
-fMatch later fragmentsLong form --fragment; IPv4 only, covering the second and following fragments, which carry no port or ICMP type to match.
-m MATCHLoad a match extensionLong form --match; several can be given, tested in command-line order until one fails.
--sport PORT[:PORT]Match source portOption of -p tcp and -p udp, long form --source-port; a service name, a number or a first:last range.
--dport PORT[:PORT]Match destination portOption of -p tcp and -p udp, long form --destination-port; takes the same values as --sport.
--dports PORT[,PORT|,PORT:PORT]...Match several destination portsOption of -m multiport, long form --destination-ports; at most 15 ports, and a range counts as two.
--sports PORT[,PORT|,PORT:PORT]...Match several source portsOption of -m multiport, long form --source-ports; commas separate entries and a colon marks a range, as in 53,1024:65535.
--ports PORT[,PORT|,PORT:PORT]...Match ports in either directionOption of -m multiport; true when the source port or the destination port is on the list.
--tcp-flags MASK COMPMatch TCP flag combinationsOption of -p tcp; the first list names the flags to examine, the second those that must be set.
iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYNMatch SYN-only packetsMatches forwarded TCP packets that have SYN set while ACK, FIN and RST are clear; the manual gives it no target.
--synMatch connection requestsOption of -p tcp, equal to --tcp-flags SYN,RST,ACK,FIN SYN; blocking these on input stops incoming connections only.
--icmp-type {TYPE[/CODE]|TYPENAME}Match an ICMP typeOption of -p icmp; accepts a number, a type/code pair or a type name.
iptables -p icmp -hList ICMP type namesPrints the type names that the --icmp-type option accepts.
--src-range FROM[-TO]Match a source address rangeOption of -m iprange; the range is two addresses joined by a hyphen, and the second is optional.
--dst-range FROM[-TO]Match a destination address rangeOption of -m iprange; the destination counterpart of --src-range, with the same syntax.
--mac-source ADDRESSMatch source MAC addressOption of -m mac; written XX:XX:XX:XX:XX:XX, and useful only for Ethernet packets in PREROUTING, FORWARD or INPUT.
--uid-owner USERNAMEMatch the sending userOption of -m owner; locally generated packets in OUTPUT and POSTROUTING only, and a numeric UID or range also works.
--mark VALUE[/MASK]Match the packet markOption of -m mark; compares the mark that the MARK target sets, after ANDing with the mask when one is given.
--match-set SETNAME FLAG[,FLAG]...Match an IP setOption of -m set, for sets made with ipset; each flag is src or dst and at most six are allowed.
iptables -A FORWARD -m set --match-set test src,dstMatch forwarded packets against a setLooks packets up in the set named test, by a source field first and a destination field second.
-m time --weekdays Sa,SuMatch on weekendsDay names may be given in two-character form, and times are read as UTC unless told otherwise.
-m time --timestart 12:30 --timestop 13:30Match a daily time windowTrue between the two clock times every day, which are taken as UTC by default.
iptables -A INPUT -p sctp --dport 80 -j DROPDrop SCTP packets for port 80Shows that --dport also works after -p sctp, here discarding incoming packets for one port.
iptables -t raw -A RPFILTER -m rpfilter --invert -j DROPDrop packets failing reverse-path checkWith --invert the rpfilter match selects packets whose reply would leave by a different interface.

Connection state 15

CommandWhat it does
--ctstate STATELISTMatch connection tracking statesOption of -m conntrack; a comma-separated list from INVALID, NEW, ESTABLISHED, RELATED, UNTRACKED, SNAT and DNAT.
--ctstate NEWMatch new connectionsAlso true while the connection has carried traffic in only one direction.
--ctstate ESTABLISHEDMatch established connectionsTrue once the connection has carried packets both ways.
--ctstate RELATEDMatch related connectionsA new connection tied to an existing one, for example FTP data channels and ICMP errors.
--ctstate INVALIDMatch packets of no known connectionThe REJECT section of the manual advises dropping these packets instead of rejecting them.
--ctstate UNTRACKEDMatch untracked packetsApplies to packets exempted from tracking in the raw table with -j CT --notrack.
--ctstatus STATELISTMatch connection statusOption of -m conntrack; the statuses are NONE, EXPECTED, SEEN_REPLY, ASSURED and CONFIRMED.
--ctdir {ORIGINAL|REPLY}Match one flow directionOption of -m conntrack; when it is left out, packets of both directions match.
--ctorigdst ADDRESS[/MASK]Match the original destinationOption of -m conntrack; tests the destination address of the connection's original direction, not of the reply.
--ctorigdstport PORT[:PORT]Match the original destination portOption of -m conntrack; port ranges need a kernel newer than 2.6.38.
--state STATEMatch states with the state moduleOption of -m state, a subset of conntrack that knows INVALID, ESTABLISHED, NEW, RELATED and UNTRACKED.
-A INPUT ... -m conntrack --ctstate INVALID -j DROPDrop invalid packets before rejectingSchematic rule the manual places ahead of a REJECT rule so late stray packets are dropped silently; the dots stand for your own matches.
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state INVALID -j DROPDrop invalid packets for one portClosing rule of the SYNPROXY example: discards out-of-flow TCP packets for port 80 that arrive on eth0.
-j CT --notrackExempt packets from trackingRaw table only; the NOTRACK target is an equivalent shorthand.
iptables -t raw -A PREROUTING -i eth0 -p tcp --dport 80 --syn -j CT --notrackLeave SYN packets untrackedFirst rule of the SYNPROXY example: connection requests for port 80 on eth0 bypass connection tracking.

Targets 12

CommandWhat it does
-j TARGETJump to a targetLong form --jump; the target is a user-defined chain, a built-in verdict or an extension, and without it only counters change.
-g CHAINContinue in another chainLong form --goto; unlike a jump, a later RETURN goes back to the chain that called the current one.
ACCEPTAccept the packetBuilt-in verdict that lets the packet pass; also one of the two values a chain policy can take.
DROPDiscard the packetBuilt-in verdict that discards the packet; no error goes back to the sender, unlike REJECT.
RETURNReturn to the calling chainIn a built-in chain, or at its end, the chain policy decides the packet's fate.
REJECTRefuse with an error replyEnds rule traversal like DROP but answers the sender; valid in INPUT, FORWARD, OUTPUT and chains called from them.
--reject-with TYPEChoose the rejection replyOption of REJECT; icmp-port-unreachable is the default, and other ICMP unreachable or prohibited types can be named.
--reject-with tcp-resetReject with a TCP resetOnly for rules that match TCP; the sender gets a RST packet back.
--set-mark VALUE[/MASK]Set the packet markOption of the MARK target; for mark-based routing set it in PREROUTING or OUTPUT of the mangle table.
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtuClamp MSS to the path MTUThe manual's workaround when ICMP fragmentation-needed messages are blocked: forwarded SYN packets get their MSS lowered.
--clamp-mss-to-pmtuClamp MSS automaticallyOption of the TCPMSS target; sets the MSS to the path MTU minus 40 for IPv4 or 60 for IPv6.
--set-mss VALUESet a fixed MSSOption of the TCPMSS target; cannot be combined with --clamp-mss-to-pmtu.

NAT 12

CommandWhat it does
DNATRewrite the destination addressValid in the nat table's PREROUTING and OUTPUT chains; later packets of the same connection are rewritten alike.
--to-destination [IPADDR[-IPADDR]][:PORT[-PORT[/BASEPORT]]]Set the new destinationOption of DNAT; an address or range, plus ports when the rule names tcp, udp, dccp or sctp.
SNATRewrite the source addressValid in the nat table's POSTROUTING and INPUT chains; meant for static addresses, MASQUERADE being for dynamic ones.
--to-source [IPADDR[-IPADDR]][:PORT[-PORT]]Set the new sourceOption of SNAT; one address or an inclusive range, with an optional port range for tcp, udp, dccp or sctp.
MASQUERADEMasquerade behind the outgoing interfacePOSTROUTING of the nat table only; uses the outgoing interface's address and suits dynamically assigned addresses.
--to-ports PORT[-PORT]Set masquerade source portsOption of MASQUERADE; overrides the default source port selection, for tcp, udp, dccp or sctp rules.
REDIRECTRedirect to the local machineValid in the nat table's PREROUTING and OUTPUT chains; packets go to this host itself, locally generated ones to 127.0.0.1.
--to-ports PORT[-PORT]Set the redirect portOption of REDIRECT; without it the destination port stays as it was.
iptables -t nat -A PREROUTING -p tcp --dport 80 -m cpu --cpu 0 -j REDIRECT --to-ports 8080Redirect port 80 to port 8080From the cpu match example: web traffic handled by CPU 0 is redirected to port 8080 on the firewall itself.
--randomRandomise NAT source portsAccepted by SNAT, DNAT, MASQUERADE and REDIRECT.
--random-fullyFully randomise source portsOption of SNAT and MASQUERADE that draws ports from a PRNG; SNAT needs kernel 3.14 for it.
--persistentKeep one mapping per clientOption of SNAT and DNAT; each client keeps the same translated address across connections.

Logging and rate limits 28

The limit match cannot be negated; for a negated rate test the manual points to -m hashlimit.

CommandWhat it does
LOGLog matching packetsWrites packet headers to the kernel log and does not end traversal, so a second rule must drop or reject.
--log-prefix PREFIXPrefix log linesOption of LOG; the prefix can be 29 letters at most and tells messages apart in the log.
--log-level LEVELSet the logging levelOption of LOG; a number or a name from emerg, alert, crit, error, warning, notice, info and debug.
--log-uidLog the sending user IDOption of LOG; records which user's process produced the packet.
--log-tcp-sequenceInclude TCP sequence numbersOption of LOG; the manual calls it a security risk when users can read the log.
--log-tcp-optionsInclude TCP header options
--log-ip-optionsInclude IP header options
NFLOGLog through a netlink backendHands the packet to the loaded logging backend, usually nfnetlink_log, and like LOG does not end traversal.
--nflog-prefix PREFIXPrefix NFLOG messagesOption of NFLOG; the string can be 64 characters long at most.
--nflog-group NLGROUPChoose the netlink groupOption of NFLOG; group 0 is used when the option is absent.
--limit RATE[/SECOND|/MINUTE|/HOUR|/DAY]Limit the average match rateOption of -m limit; the rule matches until the rate is reached, and 3/hour applies when none is given.
--limit-burst NUMBERSet the initial burstOption of -m limit; packets let through before the rate applies, 5 by default, regained one at a time.
iptables -t raw -A RPFILTER -m limit --limit 10/minute -j NFLOG --nflog-prefix "rpfilter drop"Log at a limited rateFrom the reverse-path example: about ten packets a minute reach NFLOG, tagged with a prefix.
iptables -A INPUT -p tcp --dport 80 -m string --algo bm --string 'GET /index.html' -j LOGLog packets containing a stringSearches TCP port 80 packets for the quoted text with the Boyer-Moore algorithm and logs each hit.
--name NAMEName the address listOption of -m recent; the list called DEFAULT is used when no name is given.
--setAdd the source to the listOption of -m recent; an address already listed has its entry refreshed, and the test always succeeds.
--rcheckTest for a listed sourceOption of -m recent; true when the packet's source address is on the list.
--updateTest and refresh the entryOption of -m recent; works like --rcheck and also renews the last-seen timestamp on a match.
--removeRemove a listed sourceOption of -m recent; true when the address was on the list, which then loses that entry.
--seconds SECONDSLimit to recent sightingsOption of -m recent, with --rcheck or --update; the address must have been seen within that many seconds.
--hitcount HITSRequire a number of hitsOption of -m recent, with --rcheck or --update; add --seconds to demand the hits within a time frame.
iptables -A FORWARD -m recent --name badguy --rcheck --seconds 60 -j DROPDrop recently listed sourcesDiscards forwarded packets from addresses put on the badguy list during the last 60 seconds.
iptables -A FORWARD -p tcp -i eth0 --dport 139 -m recent --name badguy --set -j DROPList and drop port probersPuts the source of each TCP packet for port 139 on eth0 onto the badguy list, then drops it.
--connlimit-above NMatch above a connection countOption of -m connlimit; true when the client already holds more than N connections.
--connlimit-upto NMatch up to a connection countOption of -m connlimit; true while the client holds N connections or fewer.
--connlimit-mask PREFIX_LENGTHCount connections per networkOption of -m connlimit; groups clients by prefix length, 0 to 32 for IPv4 and 0 to 128 for IPv6.
iptables -A INPUT -p tcp --syn --dport 23 -m connlimit --connlimit-above 2 -j REJECTCap telnet connections per clientRejects a new connection to port 23 once the client address already has more than two.
iptables -A INPUT -p tcp --syn --dport 23 -m connlimit --connlimit-upto 2 -j ACCEPTAccept up to two per clientThe same telnet limit written the other way round: connections are accepted while the count stays at two or below.

Saving and restoring 11

The manuals print no redirection example: iptables-save writes to standard output unless -f names a file, and iptables-restore reads standard input or a file argument.

CommandWhat it does
iptables-saveDump the current rulesetPrints every available table in a parseable format on standard output unless a file is named.
iptables-save -cDump rules with countersLong form --counters; iptables-save then writes each rule's current packet and byte counts into the dump.
iptables-save -t TABLEDump one tableLong form --table; without it the output holds every table whose kernel module is already loaded.
iptables-save -f FILENAMEWrite the dump to a fileLong form --file; replaces the default of printing to standard output.
iptables-restore FILELoad rules from a fileReads the ruleset from the named file, or from standard input, and flushes each table it restores first.
--noflushRestore without flushingiptables-restore option, short form -n; existing rules stay, though user-defined chains declared in the input are still flushed.
--testParse a ruleset without applyingiptables-restore option, short form -t; the ruleset is built but never committed.
--countersRestore packet and byte countersiptables-restore option, short form -c; loads the counts that a dump made with iptables-save -c contains.
--table NAMERestore one table onlyiptables-restore option, short form -T; other tables present in the input are skipped.
-4Mark a rule as IPv4-onlyLong form --ipv4; ip6tables-restore silently skips such a rule, so one file can serve both restore commands.
-6Mark a rule as IPv6-onlyLong form --ipv6; iptables-restore silently skips such a rule, and any other use is an error.

Other options 5

CommandWhat it does
-w [SECONDS]Wait for the lockLong form --wait; without it the program exits when another instance holds the xtables lock, and seconds cap the wait.
-c PACKETS BYTESSet a rule's countersLong form --set-counters; gives the rule starting packet and byte counts when it is inserted, appended or replaced.
-hShow brief helpPrints a short summary of the syntax; placed after a -m module it adds help for that module.
-VShow the versionLong form --version; also reports which kernel API the program uses.
--modprobe=COMMANDSet the module loader commandNames the program that loads targets, match extensions and other modules needed while rules are added or inserted.

Notes

Reading and writing rules

-L [CHAIN] with -n and -v lists the rules with packet and byte counters and numeric addresses, without DNS lookups; add --line-numbers to see the positions that -D CHAIN RULENUM deletes by. A packet is tested against the rules of a chain from the top, and the first rule whose target decides its fate ends the walk, so -A CHAIN RULE-SPECIFICATION, which appends to the end, takes effect only if nothing above it dropped the packet; -I CHAIN [RULENUM] RULE-SPECIFICATION inserts at the top instead. A rule that blocks one host with -s ADDRESS[/MASK] and DROP therefore belongs above any broad ACCEPT. -F [CHAIN] deletes the rules but leaves the chain policy alone — on a remote server whose policy is DROP this locks you out, so set the policy to ACCEPT with -P CHAIN TARGET first or run it inside a scheduled rollback.

Making it survive a reboot

iptables rules live in the kernel and vanish on reboot. iptables-save prints the current ruleset to standard output, or to a file with iptables-save -f FILENAME, and iptables-restore FILE loads it back, flushing each table it restores unless --noflush is given; --test parses a file without committing it. Debian and Ubuntu package the boot-time restore as iptables-persistent, and RHEL-family systems use the iptables-services unit with /etc/sysconfig/iptables. Whichever you use, edit the live rules, test, then save — editing the file directly and forgetting to load it is the usual cause of "the rule is there but not working".

ufw

ufw is Ubuntu's front end to the same kernel firewall; its commands are not rows on this page. Per ufw(8), ufw enable loads the firewall and enables it at boot, and a fresh install denies incoming and allows outgoing traffic by default. ufw allow takes a port (53), a port with protocol (25/tcp) or a service name (smtp). Allow SSH before enabling on a remote box, because enabling flushes ufw's chains and can drop existing connections. ufw status verbose shows the rules ufw manages with extra detail, and ufw show raw prints the complete tables in iptables format. Mixing hand-written iptables rules with ufw quickly becomes hard to reason about; pick one.

Questions

Why does a rule added with -A not take effect?

-A CHAIN RULE-SPECIFICATION appends to the end of the chain, and an earlier rule that already accepted, dropped or rejected the packet wins. Check the order with -L [CHAIN] and --line-numbers, then place the rule higher with -I CHAIN [RULENUM] RULE-SPECIFICATION.

How do I delete one iptables rule?

List the chain with --line-numbers and delete by position with -D CHAIN RULENUM, or repeat the rule exactly after -D CHAIN RULE-SPECIFICATION. -C CHAIN RULE-SPECIFICATION tests whether a rule exists without changing anything.

What is the difference between DROP and REJECT?

DROP discards the packet and sends nothing back. REJECT also ends rule traversal but returns an error: icmp-port-unreachable by default, or a TCP reset with --reject-with tcp-reset. The manual advises dropping packets in the INVALID state instead of rejecting them.

Should I match connection state with -m state or -m conntrack?

Both work. The manual describes state as a subset of conntrack: --state STATE knows INVALID, ESTABLISHED, NEW, RELATED and UNTRACKED, while --ctstate STATELIST adds the virtual SNAT and DNAT states and comes with further options such as --ctstatus STATELIST and --ctdir {ORIGINAL|REPLY}.

Which table and chains do NAT rules go in?

The nat table, selected with -t TABLE. DNAT and REDIRECT are valid in PREROUTING and OUTPUT, SNAT in POSTROUTING and INPUT, and MASQUERADE only in POSTROUTING. iptables -t nat -n -L lists them.

How do I keep iptables rules after a reboot?

Dump them with iptables-save (to a file with iptables-save -f FILENAME) and load the file at boot with iptables-restore FILE. Debian and Ubuntu ship this as the iptables-persistent package, RHEL-family systems as iptables-services.

Sources and checks

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.