Notes on iptables

Notes on iptables

Loading the Kernel Module

Before you can use the iptables command, you must load the netfilter kernel module that provides support for it.

modprobe ip_tables

modprobe -- program to add and remove modules from the Linux Kernel

Using iptables

The iptables command is used to configure IP filtering and NAT (along with other packet-processing applications, including accounting, logging, and mangling). To facilitate this, there are two tables of rules called filter and nat.

The filter table is assumed if you do not specify the -t option to override it. Five built-in chains are also provided. The INPUT and FORWARD chains are available for the filter table, the PREROUTING and POSTROUTING chains are available for the nat table, and the OUTPUT chain is available for both tables.

The general syntax of most iptables commands is: # iptables command rule-specification extensions

iptables miscellaneous options

-c(--set-counters) packets bytes

When combined with the -A, -I, or -R subcommand, sets the packet counter to packets and the byte counter to bytes for the new or modified rule.


Displays information on iptables usage. If it appears after -m match or -j target, then any additional help related to the extension match or target (respectively) is also displayed.

-j(--jump) target [options]

Determines what to do with packets matching this rule. The target can be the name of a user-defined chain, one of the built-in targets, or an iptables extension (in which case there may be additional options).


When combined with the -L subcommand, displays numbers for the rules in each chain, so you can refer to the rules by index when inserting rules into (via -I) or deleting rules from (via -D) a chain.

-m(--match) match [options]

Invoke extended match, possibly with additional options.

-M cmd(--modprobe=cmd) Used to load an iptables module (with new targets or match extensions) when appending, inserting, or replacing rules.


Displays numeric addresses and ports instead of looking up and displaying domain names for the IP addresses and displaying service names for the port numbers. This can be especially useful if your DNS service is slow or down.

-t table(--table)

Performs the specified subcommand on table. If this option is not used, the subcommand operates on the filter table by default.

-v(--verbose) Produces verbose output.


Displays exact numbers for packet and byte counters, rather than the default abbreviated format with metric suffixes (K, M, or G).

Getting Help

iptables -h | --help; iptables -m match -h; iptables -j TARGET -h; man iptables

The iptables Subcommands

Each iptables command can contain one subcommand, which performs an operation on a particular table.

iptables subcommand options

-A(--append) chain rule Appends rule to chain.

-D(--delete) chain [index | rule] Deletes the rule at position index or matching rule from chain.

--delete-chain Synonym for -X. -E(--rename-chain) chain newchain Renames chain to newchain.

-F(--flush)[chain] Flushes (deletes) all rules from chain (or from all chains if no chain is given).

-I(--insert ) chain [index] rule

Inserts rule into chain, at the front of the chain, or in front of the rule at position index.

-L(--list) [chain] Lists the rules for chain (or for all chains if no chain is given).

-N(--new-chain or --new) chain Creates a new user-defined chain.

-P(--policy) chain target

Sets the default policy of the built-in chain to target. (applies to built-in chains and targets only).

-R(--replace ) chain index rule Replaces the rule at position index of chain with the new rule.

-V(--version) Displays the version of iptables.

-X [chain] Deletes the user-defined chain, or all user-defined chains if none is given.

-Z(--zero ) chain Zeros the packet and byte counters for chain (or for all chains if no chain is given).

Basic iptables Matches

iptables has a small number of built-in matches and targets and a set of extensions that are loaded if they are referenced. The matches for IP are considered built-in, and the others are considered match extensions (even though the icmp, tcp and udp match extensions are automatically loaded when the corresponding protocols are referenced with the -p built-in IP match option).

Internet Protocol (IPv4) Matches

These built-in matches are available without a preceding -m argument to iptables.

-d(--destination,--dst) [!] addr [/mask] Destination address addr (or range, if mask is given).

[!] -f(--fragments ) Second or further fragment of a packet that has undergone fragmentation.

-i(--in-interface) [!] in

Input interface in (if in ends with +, any interface having a name that starts with in will match).

-o(--out-interface) [!] out

Input interface out (if out ends with +,any interface having a name that starts with out will match).

-p(--protocol) [!] proto Protocol name or number proto.

-s(--source,--src) [!] addr [/mask] Source address addr (or range, if mask is given).

You can use the old-style dotted-quad notation for masks such as , or the newer Common Inter-Domain Routing (CIDR) notation such as

Common IP protocols: ALL, icmp, tcp, udp

Ethernet Media Access Controller (MAC) Match

--mac-source [!] mac Match when the Ethernet frame source MAC field matches mac.

To allow only a single Ethernet device to communicate over an interface:

iptables -A PREROUTING -i eth1 -m mac --mac-source ! 0d:bc:97:02:18:21 -j DROP

Internet Control Message Protocol Match

The Internet Control Message Protocol (ICMP) match extension is automatically loaded if

-p icmp is used.

--icmp-type [!] typename Matches ICMP type typename

--icmp-type [!] type[/code] Matches ICMP type and code given

User Datagram Protocol Match

The User Datagram Protocol (UDP) match extension is automatically loaded if -p udp is used.

--destination-port(--dport) [!] port[:port]

Match when the UDP destination port number is equal to port (if only one port is given) or in the inclusive range (if both ports are given).

--source-port(--sport) [!] port[:port]

Transmission Control Protocol Match

The Transmission Control Protocol (TCP) match extension is automatically loaded if -p tcp is used.

--dport(--destination-port) [!] port[:port]

--sport(--source-port) [!] port[:port]

[!] --syn

Synonym for --tcp-flags SYN,RST,ACK SYN. Packets matching this are called "SYN" packets. This option can be used to construct rules to block incoming connections while permitting outgoing connections.

--tcp-flags [!] mask comp

Check the mask flags, and match if only the comp flags are set. The mask and comp arguments are comma-separated lists of flag names, or one of the two special values ALL and NONE.


num Match if TCP option num is set.

To allow our users to be able to access WWW (HTTP on port 80 only, not HTTPS on port 443) servers on the Internet, but to allow no other traffic to be passed.

modprobe ip_tables

iptables -F FORWARD

iptables -P FORWARD DROP

iptables -A FORWARD -p tcp -s 0/0 --sport 80 -d --syn -j DROP

iptables -A FORWARD -p tcp -s --dport 80 -d 0/0 -j ACCEPT

iptables -A FORWARD -p tcp -d --sport 80 -s 0/0 -j ACCEPT

Lines 1-3 install iptables into the running kernel, flush the FORWARD chain of the filter table, and sets the default policy for the FORWARD chain of the filter table to DROP.

Line 4 prevents Internet hosts establishing connection from to the internal network by dropping SYN packets (but only if the source port is 80 since those are the only ones that would be let through by later rules)

Line 5 allows all packets heading from the internal network to port 80 on any host to get out.

Line 6 allows all packets heading from port 80 on any host to hosts on the internal network through.

IP Accounting

The general command syntax is: # iptables -A chain rule-specification

Any command that doesn't specify the -j option performs accounting only.

Accounting by Address

How much data travels between the two departments?

# iptables -A FORWARD -s -d

# iptables -A FORWARD -s -d

Accounting by Service Port

We might want to know how much of the link the FTP, SMTP, and World Wide Web (HTTP) services are consuming.

iptables -A FORWARD -i ppp0 -p tcp --sport 20:21

iptables -A FORWARD -o ppp0 -p tcp --dport 20:21(or smtp, www)

# iptables -A FORWARD -i ppp0 -p tcp -m multiport --sports ftp-data,ftp,smtp,www -j ACCEPT

# iptables -A FORWARD -j ACCEPT

The first rule would count our essential traffic while the second one would count everything else.

Accounting of ICMP Packets

ICMP doesn't use ports as TCP and UDP do. Instead ICMP has ICMP message types. We can build rules to account for each ICMP message type. We place the ICMP message and type number in place of the port field in the accounting


iptables -A FORWARD -m icmp -p icmp --sports echo-request(echo-reply)

iptables -A FORWARD -m icmp -p icmp -f

Accounting by Protocol

iptables -A FORWARD -i ppp0 -m tcp -p tcp(udp,icmp)

Using IP Accounting Results

Listing Accounting Data

To list our accounting data, we would use: iptables -L -v

you can also use the -x argument to show the output in expanded format with unit figures.

Resetting the Counters: iptables -Z

You can even combine the list and zeroing actions together to ensure that no accounting data is lost in between:

iptables -L -Z -v

This command will first list the accounting data and then immediately zero the counters and begin counting again.

Flushing the Rule Set

The iptables command supports the -F argument, which flushes all the rules of the type you specify: iptables -F

This flushes all of your configured rules (not just your accounting rules), removing them all and saving you having to remove each of them individually.

ifconfig eth1 promisc

Enabling promiscuous mode for an Ethernet device causes it to deliver all packets to the operating system rather than only those with its Ethernet address as the destination. This is only relevant if the device is connected to a broadcast medium (such as unswitched Ethernet).

IP Masquerade and Network Address Translation

Network Address Translation (NAT) describes the process of modifying the network addresses (and sometimes port numbers) contained with packet headers while they are in transit.

IP masquerading is the name

given to one type of network address translation that allows all of the hosts on a private network to use the Internet at the price of a single dynamic IP address.

When it receives a packet from a computer on the LAN, it takes note of the type of packet it is, (such as TCP, UDP or ICMP) and modifies the packet so that it looks like it was generated by the router host itself (and remembers that it has done so). It then transmits the packet onto the Internet with its single connection IP address. When the destination host receives this packet, it believes the packet has come from the routing host and sends any reply packets back to that address. When the Linux masquerade router receives a packet from its Internet connection, it looks in its table of established masqueraded connections to see if this packet actually belongs to a computer on the LAN, and if it does, it reverses the modification it did on the forward path and transmits the packet to the LAN computer.

you can use DNAT (Destination NAT) on the router to route inbound connections to certain ports to internal servers.

Configuring the Kernel for IP Masquerade

The netfilter package includes modules that help perform masquerading functions. To provide connection tracking of FTP sessions, you'd load and use the ip_conntrack_ftp and ip_nat_ftp.o modules. This connection tracking support is required for masquerading to work correctly with protocols that involve multiple connections for one logical session, since masquerading relies on connection tracking.

Configuring IP Masquerade

The iptables command uses -j

MASQUERADE to indicate that packets matching the rule specification should be masqueraded (this is for a dynamic IP address; if you have a static IP address, use -j SNAT instead).

# iptables -t nat -P POSTROUTING DROP

# iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE

To list the masquerade rules you have created, use the -L argument to the iptables command: iptables -t nat -L

More About Network Address Translation

Translating the source address of a packet is referred to as Source NAT, or SNAT, in iptables. Translating the destination address of a packet is known as Destination NAT, or DNAT.

Backward Compatibility with ipfwadm and ipchains

The two netfilter kernel modules called ipfwadm.o and ipchains.o provide backward compatibility for ipfwadm and ipchains. You may load only one of these modules at a time, and use one only if the ip_tables.o module is not loaded. When the appropriate module is loaded, netfilter works exactly like the former firewall implementation.

netfilter mimics the ipchains interface with the following commands:

# rmmod ip_tables

# modprobe ipchains

# ipchains options

netflter has a few tables, each containing a default set of rules, which are called chains. The default table loaded into the kernel is the flter table, which contains three chains: INPUT, FORWARD, OUTPUT.

By loading the NAT and mangle modules of netflter, nat and mangle tables are automatically loaded.

Iptables - Operations

The operations iptables can do with chains are:

List the rules in a chain (iptables -L CHAIN).

Change the policy of a chain (iptables -P CHAIN ACCEPT).

Create a new chain (iptables -N CHAIN).

Flush a chain; delete all rules (iptables -F CHAIN).

Delete a chain (iptables -D CHAIN), only if the chain is empty.

Zero counters in a chain (iptables -Z CHAIN). Every rule in every chain keeps a counter of the number of packets and bytes it matched. This command resets those counters.

For the -L, -F, -D, and -Z operations, if the chain name is not specifed, the operation is applied to the entire table, which if not specifed is by default the flter table.

Operations that iptables can execute on rules are: iptables -A|I|D|R

Filtering Specifcations

Filtering specifcations for Layer2: -i|--in-interface -o|--out-interface

+ can be used to specify only the beginning string of the interface: -i eth+ will match all interfaces beginning with the string eth.

The exclamation mark "!" represents a negation. e.g. -i ! eth1 will not match packets coming in on eth1.

Layer 3: -s|--src|--source, -d|--dst|--destination

Layer 4: -p|--protocol,--icmp-type, --sport,--dport

"--tcp-flags", "--syn" and "--tcp-option". TCP fags can be "SYN ACK FIN RST URG PSH ALL NONE".

"--syn" is used to identify the initiating connections and is equivalent to "--tcp-flags SYN,RST,ACK SYN". "--tcp-option" followed by a number atches TCP packets with the option set to that number.

Netfilter Extensions

Target Specifcations


An alternative to DROP is the REJECT target, which drops the packet but sends an ICMP packet to the source IP of the packet. By default, the REJECT target will send an ICMP 'port unreachable' message to the sender, but that can be overwritten using the "--reject-with" switch.

The target in an iptables rule can also be used to pass a packet to a user-defned chain. For example, if we create a new chain like iptables -N SSH, then:

iptables -A INPUT -p tcp --dport 22 -j SSH

Another useful target is LOG, which can be used to log packets matching a fltering specifcation in the kernel log, which can be read with dmesg or syslogd. LOG target options are:

--log-level level, --log-prefix prefix, --log-tcp-sequence, --log-tcp-options, --log-ip-options, --log-uid.


Only accept incoming SSH connections from and

iptables -N SSH

iptables -A SSH -s -j ACCEPT

iptables -A SSH -s -j ACCEPT

iptables -A SSH -m limit --limit 5/s -j LOG

iptables -A SSH -j DROP

iptables -L -n -v

--policy -P chain target Change policy on chain to target

Disable all connection from out world

#set policies on each chain

/sbin/iptables -P INPUT DROP

/sbin/iptables -P FORWARD DROP

/sbin/iptables -P OUTPUT ACCEPT #default, but set it anyway

#flush all rules in the filter table

/sbin/iptables -F

#Some applications use TCP/IP connections on the loopback interface; so it's

#safe to allow packets that come in on the interface "lo"

#allow traffic on the loopback interface

/sbin/iptables -A INPUT -i lo -j ACCEPT

#allow icmp traffic

/sbin/iptables -A INPUT -p icmp -j ACCEPT

#allow incoming DNS traffic

/sbin/iptables -A INPUT -p udp --sport 53 -j ACCEPT

#allow established TCP connections

/sbin/iptables -A INPUT -p tcp ! --syn -j ACCEPT

if the provider's DNS servers are and, it is safer to replace the earlier line with:

/sbin/iptablesT -A INPUT -s -p udp --sport 53 -j ACCEPT

/sbin/iptablesT -A INPUT -s -p udp --sport 53 -j ACCEPT

NAT - Network Address Translation

For NAT to work, the router needs to "know" which packets are for itself, and which packets are

for which hosts with private IP addresses. The router accomplishes this by keeping track of all TCP/IP connections that pass through it. This process is called connection tracking.

Connection tracking gives Linux the ability to hold state information about TCP and UDP connections in memory tables. Information about every connection is stored in /proc/net/ip_conntrack and includes IP addresses, port numbers, protocol types, connection state, and timeouts.

SNAT(Source Network Address Translation) and Masquerade

SNAT is called so because only the source IP address gets translated. The NAT box will overwrite the source address in IP headers of all packets sent by a box behind NAT to one or many IP addresses.

If one or many hosts behind NAT are translated into only one public IP address, the process is called static SNAT. If they are translated into several public IP addresses (usually a range of IP addresses), the process is called dynamic SNAT.

Masquerade or MASQ works exactly like static SNAT does, except that you cannot specify the public IP address to be used. It will automatically use the IP address of the outgoing interface of the NAT router.


DNAT or Destination Network Address Translations maps a public IP address to a private IP address. DNAT is the reverse of SNAT; so, if you SNAT to translate a private IP address into a public IP address and DNAT to translate the same public IP address into the same private IP address, the result will be full NAT.

DNAT is usually used when you have servers behind NAT, so the same public IP address is mapped to different private IP addresses depending on ports or protocols.

This process is also called port forwarding.


PAT stands for Port Address Translation and it is also called NAPT, which stands for Network Address and Port Translation. The idea behind PAT is to translate not only the IP address, but also the port number for specifc hosts and ports.

The netflter nat Table

The nat table contains three chains-PREROUTING, POSTROUTING, and OUTPUT.

iptables -t nat -L

The PREROUTING chain is analyzed by the kernel before any routing decision is made. Therefore, what we should do in the PREROUTING chain is to change the address of the destination IP and then leave it to the routing process to fnd the destination that we just changed (DNAT).

The POSTROUTING chain contains rules that the kernel analyzes after a routing decision is made. This means that we have a path to the destination, and so we can change the source IP address if that path is outside our network (SNAT).

To append, insert, or delete rules in the nat table: iptables -t nat -A|I|D|F <chain> <rule> where <chain> can be PREROUTING, POSTROUTING, or OUTPUT.

SNAT with iptables

iptables -t nat -A POSTROUTING -s -j SNAT --to

iptables -t nat -A POSTROUTING -s -j MASQUERADE

iptables -t nat -A POSTROUTING -s -j SNAT --to

Enable ip_conntrack_irc and ip_conntrack_ftp to allow irc and ftp

modprobe ip_conntrack_irc #or insmod ip_conntrack_irc

modprobe ip_conntrack_ftp #or insmod ip_conntrack_ftp

iptables -t nat -A POSTROUTING -s -j SNAT --to

iptables -t nat -A POSTROUTING -s -j SNAT --to --to

iptables -t nat -A POSTROUTING -s -j SNAT --to --to --to

iptables -t nat -A POSTROUTING -s -d ! -j SNAT --to --to

iptables -t nat -A POSTROUTING -s -o eth1 -j SNAT --to --to

On the other site, we have the network We need to let computers in our network access computers in the network without SNATing them:

iptables -t nat -I POSTROUTING -s -d -j ACCEPT

This command will insert the rule before the NAT rule; so if any packet from is destined to any IP in the network, this rule will match and the chain will not be analyzed further, so SNAT will not take place.

iptables -t nat -I POSTROUTING -s -p tcp --dport 6666:6669 -j DROP

iptables -t nat -I POSTROUTING -s -p tcp --dport ! 80 -j DROP

DNAT with iptables

iptables -t nat -A PREROUTING -d -j DNAT --to

iptables -t nat -A PREROUTING -s -d -p tcp --dport 80 -j DNAT --to

iptables -t nat -A PREROUTING -d -p tcp --dport 65521 -j DNAT --to

iptables -t nat -A PREROUTING -d -p tcp --dport 80 -j DNAT --to

Transparent Proxy

Transparent proxy is a way to force users to use a proxy server, even if their browsers are confgured not to.

Benefts of using a proxy server-bandwidth saving for cached pages and access control implementation (e.g. deny downloads of fles that have dangerous extensions).

On our Linux router, we installed a Squid proxy server to cache some content from the Web.

If the proxy server listens on port 3128 we will do the following:

iptables -t nat -A PREROUTING -s -p tcp --dport 80 -j REDIRECT --to-port 3128

iptables -t nat -I PREROUTING -s -p tcp --dport 80 -j ACCEPT

Setting Up the Script

/sbin/iptables -t nat -F

#Jane's special rule.

#Don't SNAT any TCP connections from her computer except www and all

#udp connections except DNS

/sbin/iptables -t nat -A POSTROUTING -s -p tcp --dport ! 80 -j DROP

/sbin/iptables -t nat -A POSTROUTING -s -p udp --dport ! 53 -j DROP

#Don't SNAT anything from to

/sbin/iptables -t nat -A POSTROUTING -s -d -j ACCEPT

#The boss needs DNAT but we should also SNAT her IP address to

/sbin/iptables -t nat -A POSTROUTING -s -j SNAT --to

#Snat Everyone

/sbin/iptables -t nat -A POSTROUTING -s -o eth1 -j SNAT --to --to

############ DNAT PART

#Dnat the boss so she can access her PC from home

/sbin/iptables -t nat -A PREROUTING -d -j DNAT --to

#DNAT the intranet server for the guy in the financial department

/sbin/iptables -t nat -A PREROUTING -s -d -p tcp --dport 80 -j DNAT –to

#DNAT for us to ssh into the intranet server

/sbin/iptables -t nat -A PREROUTING -d -p tcp --dport 65521 -j DNAT --to

#DNAT the web server

/sbin/iptables -t nat -A PREROUTING -d -p tcp --dport 80 -j DNAT --to

############ Transparent Proxy

#Allow the boss to bypass the proxy server

/sbin/iptables -t nat -A PREROUTING -s -p tcp --dport 80 -j ACCEPT

#Do transparent proxy for the rest of the people

/sbin/iptables -t nat -A PREROUTING -s -p tcp --dport 80 -j REDIRECT --to-port 3128

The private IP segments are described in RFC 1918, and are: - (10/8 prefx) - (172.16/12 prefx) - (192.168/16 prefx)


Block one specific host:
iptables -I INPUT -s -j DROP
Unblock that specific host:
iptables -D INPUT -s -j DROP


Linux Network Administrators Guide 3rd

Designing and Implementing Linux Firewalls with QoS using netfilter, iproute2, NAT and L7-filter

Post a Comment


Java (160) Lucene-Solr (112) Interview (64) All (58) J2SE (53) Algorithm (45) Soft Skills (39) Eclipse (33) Code Example (31) JavaScript (23) Linux (22) Spring (22) Windows (22) Tools (21) Web Development (20) Nutch2 (18) Bugs (17) Debug (16) Defects (14) Text Mining (14) Troubleshooting (14) J2EE (13) Network (13) PowerShell (11) Problem Solving (10) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Security (8) Tips (8) bat (8) blogger (8) Big Data (7) Database (7) Google (7) Guava (7) JSON (7) Shell (7) System Design (7) ANT (6) Coding Skills (6) Lesson Learned (6) Programmer Skills (6) Scala (6) css (6) Algorithm Series (5) Cache (5) Continuous Integration (5) IDE (5) adsense (5) xml (5) AIX (4) Become a Better You (4) Code Quality (4) Concurrency (4) Dynamic Languages (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Review (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Distributed (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Life (3) Python (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Fiddler (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Logging (2) Mac (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Firefox (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) Invest (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts