Firewalls, netfilter/iptables

an article added by: Philip A Clare at 04092007


In: Categories » Computers and technology » Linux » Firewalls, netfilter/iptables

The two things needed to build firewalls and Quality of Service (QoS) with Linux are two packages named netfilter and iproute. While netfilter is a packet filtering framework included in the Linux kernels 2.4 and 2.6, iproute is a package containing a few utilities that allow Linux users to do advanced routing and traffic shaping.
This article is intended to introduce the tools we will use throughout this article. However, netfilter and iproute are very large subjects; so what I'll try to do in this article is to introduce readers who are not familiar with the subject, along with building a nice overview for readers who already know the subject. There are two websites with a lot of documentation on both projects for netfilter, http://www.netfilter.org, and for iproute, http://www.lartc.org.

netfilter/iptables

netfilter is a very important part of the Linux kernel in terms of security, packet mangling, and manipulation. The front end for netfilter is iptables, which "tells" the kernel what the user wants to do with the IP packets arriving into, passing through, or leaving the Linux box.
The most used features of netfilter are packet filtering and network address translation, but there are a lot of other things that we can do with netfilter, such as packet mangling Layer 7 filtering.
A rough explanation on how netfilter works is like this:

  • The user instructs the kernel about what it needs to do with the IP packets that flow through the Linux box using the iptables tool.
  • The Linux box then analyzes the IP headers on all packets flowing through it.
  • If, when looking at the IP headers, the kernel finds matching rules, then the packet is manipulated according to the matching rule.

It might look very simple at the beginning, but actually is a lot more complicated process. netfilter has a few tables, each containing a default set of rules, which are called chains. The default table loaded into the kernel is the filter table, which contains three chains:

  • INPUT: Contains rules for packets destined to the Linux machine itself.
  • FORWARD: Contains rules for packets that the Linux machine routes to another IP address.
  • OUTPUT: Contains rules for packets generated by the Linux machine.

Next, the packets flow through the pre-routing chain of the nat table, where we can do DNAT, port redirection, etc.
It is only logical to be able to perform destination network address translation before the routing process occurs. As you will see in Article 4, where we discuss DNAT in more detail, DNAT is the process of translating one (usually public) IP address into another (usually private). This is done by modifying the destination IP address in the IP packet's header. netfilter must do that before the kernel makes a routing decision so that the kernel will look for the new destination IP address in the IP packet.
After passing through the two chains, the Linux kernel makes a routing decision. This is not the netfilter's job. By analyzing the destination IP address from the IP packet header, the Linux box knows if the packet needs to be routed elsewhere or it was destined for it.
If the Linux box is the destination for the IP packet, the packet goes through the mangle table's INPUT chain for packet mangling. Afterwards, the packet is passed to the filter table INPUT chain, where it can be accepted, rejected, or dropped. If the packet is accepted (e.g. a request to a web server running on our Linux box), the Linux box generates a response to that packet, which goes through the mangle table OUPUT chain first.
Next, the packet is passed through the nat table OUTPUT chain and the filter table OUTPUT chain. At this point, the mangle table POSTROUTING chain and the nat table POSTROUTING chain are analyzed and the packet is ready to be sent out on the corresponding interface.
The chains presented here are the predefined chains of each table (filter, nat, and mangle). However, users can set up custom chains with custom names, and pass packets to those chains from the corresponding predefined chain. For example, if we want to create some rules for SSH access into the Linux box, we can create a custom chain named SSH, and insert one rule in the INPUT chain that instructs the kernel to analyze the SSH chain for incoming packets on port 22/TCP.
The predefined chains cannot be deleted or renamed.

Iptables — Operations

iptables has a syntax somewhat similar to the old ipchains (netfilter for 2.2 kernels). However, the concepts of netfilter for 2.4+ kernels are totally different from netfilters' concepts for 2.2 kernels.
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 specified, the operation is applied to the entire table, which if not specified is by default the filter table.
To specify the table on which we do operations, we must use the –t switch like so iptables –t filter …

Operations that iptables can execute on rules are:

  • Append rules to a chain (iptables –A)
  • Insert rules in a chain (iptables –I)
  • Replace a rule from a chain (iptables –R)
  • Delete a rule from a chain (iptables –D)

The most used switches are –A and –D (append and delete rules). Usually, when designing firewalls, the rules are appended to chains.
During run time, users use –I more than –A because often they need to insert temporary rules in the chain.
iptables –A places the rule at the end of the chain, while iptables –I places the rule on the top of the other rules in the chain. However, you can insert a rule anywhere in the chain by specifying the position where you want the rule to be in the chain with the –I switch: iptables –I CHAIN 4 will insert a rule at the fourth position of the specified chain.

The syntax for adding a rule to a chain is:

iptables –A <CHAIN_NAME> …<filtering specifications>… -j <TARGET>

Filtering specifications is a part of an iptables rule that is used by the kernel to identify IP packets for which the kernel does the action specified by TARGET.

Filtering Specifications

IP packets can be identified in a large number of ways by specifying interfaces, protocols, ports, etc., to iptables rules. The beauty of it is that we can mix any of those specifications, having a high flexibility and a wide range of selectors. I'm not planning to cover all those selectors in depth, but keep in mind that if you think about something logical about IP packets, you have every chance to identify those packets using iptables rules.
Filtering specifications for Layer2: Interfaces can be specified as selectors with –i and –o switches.
-i stands for "--in-interface", and -o for "--out-interface". + can be used to specify only the beginning string of the interface—for example -i eth+ will match all interfaces beginning with the string eth; so we've specified all Ethernet interfaces as input interfaces for one rule.
Short version switches (e.g -i) and long version switches (e.g. "--in-interface") have absolutely the same effect. Some people prefer using short switches for command lines and long switches for scripts as they can offer better readability, but we will use only short switches in this article even in the scripts to get used to the command lines better.
The exclamation mark "!" represents a negation and can be used to specify on which interface(s) not to apply this filter (e.g. -i ! eth1 will not match packets coming in on eth1).

Packets analyzed in the OUTPUT and POSTROUTING chains don't have input interfaces, and so it is not allowed to use the -i switch on those chains.
Also, INPUT and PREROUTING chains don't have output interfaces, and so you can't use the -o switch for rules in those chains.

Layer 3: Source IP address(es) can be specified using -s, --src, or --source, and destination IP address(es) with -d,--dst, or --destination. Sources or destinations can be IP addresses, subnets, or canonical names (e.g, "-s 217.207.125.58", "-s www.packtpub.com", or "-s 217.207.125.58/32" have the same effect). Specifying canonical names for hosts that have multiple IP addresses will result in adding the same number of rules as the number of IP addresses the DNS server resolves for that host at the time the rules are added.

Don't use canonical names on rules with high risk. For example, don't allow SSH access from ahost.anotherisp.com, as this will easily allow a man-in-the-middle attack.

Layer 4: Protocol can be specified using the -p switch, which stands for "--protocol". Protocols can be specified by their corresponding numbers or by their names—tcp, udp, or icmp (case insensitive).
For the ICMP protocol, you can specify ICMP message types using "--icmp-type". The list of ICMP messages can be found by using the command "iptables -p icmp --help".
For the UDP protocol, you can specify source or destination ports with "--source-port" or "--sport" and "--destination-port" and "--dport".
TCP, being the most complete Layer 4 protocol, has more options. You can specify, besides source or destination ports as for the UDP protocol, "--tcp-flags", "--syn" and "--tcp-option". TCP flags 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 matches TCP packets with the option set to that number.

Filtering specifications can combine all of the features just mentioned; so we can have a combination of Layers 2, 3, and 4 specifications in the same rule.

Another beautiful thing about netfilter/iptables is that matching extensions can be developed separately and added later. On the netfilter site, there is a large repository of matching extensions called "patch-o-matic", at http://www.netfilter.org/projects/patch-o-matic/index.html.

A new and "daring" extension to iptables plans to extend its capabilities from the lower layers to the upper layer of the OSI model, Layer 7—application.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Public and Private IP Addresses
The Internet is a public network, and therefore a device connected directly to the Internet has a public IP address. Those IP addresses must be administered by someone in such way that two devices connected to the public network don't use the same IP address or that two networks don't have the same network address. This job was done by InterNIC (Internet Network Information Center), which has been succeeded by IANA (Internet Assigned Numbers Authority). IANA makes sure to provide unique IP network addresses to Internet Service Provide...

2. IP Supernetting or CIDR
CIDR stands for "Classless Inter-Domain Routing". It is a new addressing scheme for the Internet, intended to replace the old classful (Class A, B, C) address scheme. CIDR allows a more efficient allocation of IP addresses and uses routing aggregation for minimizing the routing table entries, and is also called supernetting. A recapitulation of classful IP addressing shows us the following: Address ...

3. Linux Security Threats
Creating firewalls may block some malicious attempts on your network, but this step is far from running an entirely secure network. As a network administrator or security consultant, to design a proper firewall for your network you need to know what you defend your network from. We cannot fully discuss this topic, even in 1000 pages, but we want to explain some principles that you should consider in running a safe network. As hard as it may seem to protect your network from the outside world, the most dangerous threats always come f...

4. IP Spoofing
An attacker might spoof a trusted IP address when communicating to a host in order to gain unauthorized access on that host. There are a variety of tools that can be found on the Internet to do IP spoofing. Using IP spoofing, attackers can also initiate Denial of Service by sending data with the source IP spoofed to the attacked IP address. The receiver then sends back replies that can contain large amounts of data to the attacked IP address resulting in...

5. BIND Domain Name System DNS
BIND (Berkley Internet Name Domain) is the most used DNS server on the Internet. Nowadays, every Linux distribution has a BIND package for DNS services. The problem with BIND and any DNS server is that in order to be able to translate names into IP addresses it has to communicate with a whole lot of other DNS servers, and so, filtering DNS packets is not possible. DNS services are vital for internet connection; so in order to disrupt services to victims, attackers have a great interest in bringing down DNS servers. Although BIN...

6. Simple Network Management Protocol SNMP
These days, most network devices use SNMP for remote monitoring and configuration. SNMP is a simple protocol used usually to create monitoring software that can retrieve information such as network traffic, CPU load, disk load, etc., and also to modify configuration of devices such as wireless equipment, broadband routers, etc. Most SNMP implementations on those kinds of network devices use version 1 or version 2, which have a very weak authentication method. SNMP version 1 contains a set of bugs in the way SNMP traps and reques...

7. Iptables Target Specifications in Linux
For the filter table, the most used targets for firewall rules are DROP and ACCEPT. If a rule matches the filtering specifications and has a DROP target, the packet will simply be discarded. If a packet matches a rule with a DROP target, the Linux kernel will drop the packet without consulting other rules in the firewall. If the target is ACCEPT, then the packet is accepted without further consultation of other firewall rules. An alternative to DROP is the REJECT target, which drops the packet but sends an ICMP packet to the sou...

8. A Basic Firewall Script, Linux as a Workstation
So far, we've learned mostly about the usage of iptables filtering options. I will now build up a small firewall script that I think should be default when installing any Linux distribution. By default, all Linux distributions have the default policy ACCEPT on all filter chains. Also, on a default installation, most Linux distributions leave a lot of services running. If you install an old Linux distribution and decide to go for lunch after you have just booted up without any firewall and with a public IP address, good chances a...