Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

Security Tools

Like this article? We recommend


The iptables tool is the next generation of TCP/IP filtering and monitoring for the Linux environment. The tool is an interface to the netfilter module of the Linux kernel. Netfilter provides Network Address Translation (NAT) and a security mechanism for your network.

iptables was written by Rusty Russell, who is also the author of the ipchains tool. The work was sponsored by Watchguard, and the community is supported by Penguin Computing, the Samba Team and SGI, and Jim Pick. The Samba Team also maintains a mailing list (see lists.samba.org for more details).

An Overview of iptables and Netfilter

Netfilter is a kernel module for the 2.4 kernel series, and it is responsible for packet filtering. It looks at the headers of each packet moving through the gateway and makes a decision about what to do with them. Packets might be accepted (passed along to the routing process or the receiving protocol stack), dropped (not forwarded), or they might have some more complicated action taken. People choose to filter their traffic for many reasons. The most common reasons include segregating network traffic, securing an internal network, providing NAT for internal hosts, and controlling internal users' access to external services.

Netfilter starts with three sets of rules: INPUT, OUTPUT, and FORWARD. These rule sets are called chains (short for firewall chains). Traffic moves through these chains as shown in Figure 8.

Figure 8 IP traffic moving through the firewall chains.

Each chain represents a list of rules that are consulted sequentially for each packet. As traffic moves through a rule chain, it is examined to determine what to do with it. If it is accepted, it passes to the next point in the diagram. If it is dropped, the packet stops there. If a rule doesn't specify what to do with a packet, the packet is examined by the next rule.

Setting Up iptables

The first step in setting up iptables is to build the appropriate kernel modules. These can either be built as separate modules or included in the kernel. To build them into the kernel, answer 'Y' to the question CONFIG_NETFILTER during kernel configuration on any kernel of 2.3.15 or better. You might find that there are additional kernel modules you want to build and install (such as ip_conntrack_ftp).

With the necessary kernel modules available, you can build and install the userspace tools. You can download iptables from netfilter.kernelnotes.org or either of the other sites mentioned previously. After downloaded, iptables follows the normal configure, make, make install pattern.

You can use the set of rules shown in Listing 4 to test1 your newly installed iptables and netfilter.

Listing 4 A Test Script for iptables

# create a new table
iptables -N GATE

# set up rules for it
iptables -A GATE -m state --state ESTABLISHED, RELATED -j ACCEPT
iptables -A GATE -i eth0 -s -j LOG --log-prefix \
 "connection from test bad machine, dropping:"
iptables -A GATE -s -j DROP
iptables -A GATE -s -j LOG --log-prefix \
 "connection from test good machine, accepting:"
iptables -A GATE -J LOG --log-prefix "Accepting packet:"
iptables -A GATE -j DROP

# apply it to the INPUT and FORWARD chains.
iptables -A INPUT -j GATE

After you've installed these rules, you can test them by trying to connect from and The first connection should fail (with a log entry), and the second should succeed (also with a log entry). If this happens, everything is fine and you can flush the rules:

iptables -F GATE
iptables -X GATE
iptables -F INPUT

Now that the tools have been built, installed, and verified you can configure them for use at your site.

iptables at Work

Before you start writing iptables rules, it is important to sit down and think about three things: What policy are you trying to implement, how can you keep the rules and chains manageable, and how can you keep the rules as efficient as possible without making them unmanageable. If the rules you write don't implement the policy you're trying to enforce, they might as well not be there. If you (and your coworkers) can't read and maintain the rules, someone is going to break them. If they don't work efficiently, they will throttle your network.

As important as efficiency is, we tend to overlook a major component of it—human time. If your rules are hard to read and understand, they will take a great deal of human time to maintain. In addition, as they get hairy, your chances of making a mistake increase dramatically. I don't like working late into the weekend trying to figure out why a needlessly complex set of rules isn't working the way I want it to, and I'm sure you don't either.

Remember that each rule a packet must traverse takes time. When you have lots of packets going through your packet filter, the little chunks of time add up. Keeping this in mind, you should make sure that (as much as possible) the rules that will be used most often should be the first rules in the chain. In addition, the more bytes you check in the packet headers the more work you're going to do. This means that again, you want to ensure that each rule checks as few bytes as possible—without compromising your security.

In order to actually work with your chains, you'll need to use the switches in Table 3.

Table 3 iptables Chain Operations




Creates a new rule chain.


Lists the rules in a chain.


Changes the policy for a built-in chain.


Zeroes the byte and packet counters in a chain.


Flushes all the rules from a chain.


Deletes an empty chain (except the built-in chains).

In addition to operations on chains, you also need to perform operations on individual rules within a chain. Table 4 shows some of the major operations on rules within a chain and the switches needed to invoke them. (Notice that these rules actually operate on the chain itself, modifying the content of the chain on a rule-by-rule basis.)

Table 4 iptables Rule Operations




Adds this rule to the end of a chain.


Inserts this rule at the specified point in the chain.


Replaces a rule at the specified point in the chain.


Deletes a rule; can be specified by number or by matching content.

Using the rule and chains options from Table 4, you can start to modify the built-in chains or add your own. The additional information you'll need is in the following sections. Let's start by dissecting one of the rules from our GATE chain used in the preceding tests.

iptables -A GATE -s -j DROP

The -A GATE statement means that this is a new rule being added to the end of the GATE chain. The -s statement applies this rule to any packet with a source address of The -j DROP tells netfilter to drop this packet without further processing. Each rule that you build will follow this basic pattern.

Filtering by Address

In our example rule, we defined a source address with the -s option. This option can also be used to define a range of addresses using a network mask:


or a hostname:

-s crashtestdummy

In addition to source addresses, we can also filter by destination address with the -d switch. (--source, --src, --destination, and --dst are all legal forms of this switch as well.)

Filtering by Interface

Instead of filtering by address, you can also define filters by the interface. -i and --in-interface define inbound interfaces, while -o and --out-interface define outbound interfaces.

The INBOUND chain only matches inbound interfaces and the OUTBOUND chain only matches outbound interfaces. The FORWARD chain can match either. If you define a nonexistent interface, it will not match any packets until (or unless) that interface is brought up. There is also a special interface matching wildcard—the + indicates any interface matching the string preceding it:

-o eth+

That matches any packet destined to be sent out any Ethernet interface.

Filtering by Protocol

Protocols can be matched as well by using the -p switch. You can identify protocols either by the (IP) protocol number or (for the TCP, UDP, and ICMP) by its name. To specify all ICMP traffic, you could use


Inverting a Selection

Sometimes it is easier to say "anything that isn't foo" than it is to specify all the individual things you want to talk about. iptables allows for this with an inversion prefix. To invert a selection, you use !. Selecting anything that doesn't come from the network would look like this:

-s !

Creating Your Own Selection Criteria

iptables is designed to be extensible, so you can define your own criteria. Definitions can be based upon existing TCP, UDP, ICMP, State, or other extensions.

TCP extensions include examination of TCP Flags and TCP Source and Destination Ports. To look for the SYN and ACK flags being set without any other flags being turned on, you could do this:

-p tcp --tcp-flags ALL SYN, ACK

To look for connections to X servers, you could do this:

-p tcp --destination-port 6000-6010

A --source-port extension is also provided. Both of these extensions allow four kinds of port listings: a single port, a range of ports (as above), all ports at or above a listed port (1024-), or all ports at or below a listed port (-1024).

UDP extensions are similar, but include only the --destination-port and --source-port options from the TCP extensions.

ICMP extensions provide searching of the ICMP Type and Code with the --icmp-type switch. ICMP Type name, the numeric value of the Type, or the Type and Code separated by a "/" are all allowed. To search for an ICMP Redirect for Host, you could do this:

-p icmp --icmp-type 5/1

Inspection of a connection's state can determine whether a packet is requesting a new connection, related to an existing connection (such as an ICMP error message), part of an existing connection, or indeterminate. To search for packets that are requesting new connections, you could do this:

-m state --state NEW

Defining and Using Chains

In our testing example, we created a new chain called GATE and applied it to both the INPUT and FORWARD chains. The flow of traffic through the INPUT chain looks something like Figure 9 after we've added these rules.

Figure 9 Flow of traffic through a netfilter chain.

We created the chain and set it into motion with the following steps:

  1. Create the chain.

  2. Add rules to it.

  3. Apply the chain.

Creating the chain was done with the following command:

iptables -N GATE

The name is not required to be all uppercase, but cannot be the name of an existing rule chain.

Rules were added sequentially in our example, but we could have inserted them in any order using the -I switch instead. We could have also deleted or replaced existing rules had we so desired.

After the rules were written, we applied the rule with the following command:

iptables -A INPUT -j GATE

This command adds a rule to the INPUT chain that causes traffic to jump to the GATE chain for further processing. If you don't do this, no traffic will ever be checked by your rule chain!

Special Handling

At times you will want to log traffic that moves through your packet filter. This logging can take up a great deal of disk space, so it is normally done only on a reduced basis. Three switches are of special importance when logging. We used one of these options in the logging rules in our example.

iptables -A GATE -J LOG --log-prefix "Accepting packet:"

After declaring that packets matching this rule were to be logged, we gave the --log-prefix switch to prepend some text onto our log entries. The other switch used when logging is --log-level, which takes a syslog-style logging level as an argument, and directs the logging to that logging level. Because logging can take up so much disk space, it is most often used with the -m limit option as well. This command will limit the number of matches to a default of three matches per hour, with a burst of 5 matches.

When a packet is dropped, it is dropped silently. If you want to send an ICMP Port Unreachable message, you can specify that the packet be rejected with this:


If you want to use multiple chains in conjunction with each other, you don't want to end a chain by dropping all remaining packets. Instead, you can pass control of the packet back to the parent chain with this:


If this rule is hit and the chain is built-in, the default policy is executed. If the rule is hit in a user-defined chain, the packet begins to traverse the parent chain again at the point it jumped out to the current chain.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020