Netfilter/iptables Getting Started

Source: Internet
Author: User
Tags log log syslog ftp protocol

Netfilter/iptables Getting Started

The Linux kernel is developed and maintained by the www.kernel.org organization, and the netfilter/iptables that we are going to discuss here is the www.netfilter.org organization's firewall software for Linux development. Because Linux is very modular, many functions are loaded with modules to expand the system functions, NetFilter also in this way exist in Linux. If you understand the Linux module loading, you will be able to understand how the NetFilter module is loaded. Everyone in the/lib/modules/kernel_version/kernel/net/ipv4/netfilter/directory can see a lot of ". Ko" as the extension of the file, where to store the compiled module files.

Learning Iptables first requires the learner to have the basic concept of TCP/IP, how packets are routed in the network, what limitations, especially the TCP and IP header structure, and what TCP, UDP, and sockets are related to, and understanding these is the basis of this chapter.

1. Function of NetFilter

If you go to the NetFilter module directory and look closely at the modules that will discover the various functions, these modules only provide some filtering functions, if you want to make netfilter for me, but also to give it the "rules" to execute, set the rules, NetFilter know which packets pass, Which packets are blocked and which packets are replaced. According to the function division, the NetFilter is divided into filter, NAT, mangle and raw four functions, the four functions also derive four tables, the main functions are as follows:

L Filter: The main function is to filter the packet.

L NAT (Network address translation): IP addresses translation, mainly to solve the internet problem.

L Mangle: Its main function is to modify the firewall packets.

L RAW: Its function is to speed up the data packets passing through the firewall to improve firewall performance.

Note: These four tables are ranked in the same way as the number of use levels, but the priority for processing by table is this: Raw > Mangle > Nat > Filter.

1. 1 Understanding the filter mechanism

First, let's take a look at the following example, on the client through Firefox access, the remote Apache server on the Web page, like such a common operation for NetFilter there are three types of packet, and this is the key mechanism of filter.

Package Type

input type

When the client accesses the Web server's httpd process, for the Web server, the inbound package, in other words, the other hosts on the network to the native httpd process of the packet, which is defined as the input type packet (red arrow in the figure).

Output type

In contrast to input, the httpd process that is linked to the client by the Web server belongs to the output type (the green arrow in the figure), which is the packet generated by the native httpd process.

Forward type

In the diagram, the packets passing through the Web server belong to the forward type. Under what circumstances will this type of encapsulation be generated? When we use Linux as a router, we have forward type packets.

With the above basic concept, the following start to discuss the filter table, filter tables have three chains (Chain), so-called chain can be image of the understanding of the chain, it is interlocking, the packet is transmitted over the network.

Filter table Structure

The system is the structure of the filter table, you will find this is not the three kinds of packet type? Here is a detailed analysis:

input chain : In order to understand this problem, we still take an example to analyze, for example, we want to protect the Web server httpd process, in three kinds of packet types, should pay attention to which kind of? Must be an input type packet, then you need to write the packet to filter the input type into the rules of the input chain. This will serve the purpose of protecting the httpd process. Broadly speaking, the input chain is used to store the rules of the filter input type packet, which is commonly used to protect the native.

output chain : or follow the example above to visit the site, if you want to limit the client cannot browse www.website.com website, we should limit that kind of packet? You can guess that's the output type packet, yes. We can write in the output chain "if the packet was generated by the httpd process and went wrong!" The hyperlink reference is not valid. , the packet is discarded "This pseudo-code, so as to limit the network link behavior." So the OUTPU chain is used to store the rules for filtering input type packets, which are often used to restrict the network links of native processes.

forward chain : In the Linux server as a router used to protect a remote Web server, then you should limit that type of packet? This is definitely the forward type, which means that the forward chain is used to protect the server behind the firewall.

Because the filter mechanism is very complex, for everyone easy to understand, with a simple expression of the filter principle, note that the chart, although the table is drawn two, but actually only one, that is, we in the system with "route–n" to see the content, the routing table determines the packet transmission path, Especially in the multi-network card system is particularly important. The local process is the Web server process described above and can be understood as the httpd process.

Figure Filter Schematic diagram

Next, the process of network packets being processed in the filter mechanism is illustrated in three different scenarios.

1) When surfing the Internet, the client connects to the server, that is, the destination of the network packet is the HTTPD process of the Web server, the packet is sent to the routing table first, and the content of the routing table determines the transmission path. Since the client is accessing the page on the Web server, that is, the packet is sent to the local process httpd, so the packet is fed into the input chain, if the input chain is allowed, the packet is sent to the local process and is discarded (dropped).

2) When the server returns the result, need to link the client process, which is the local process httpd outgoing packets, the first packet will be routed into the routing table, the contents of this decision packet transmission path, and then be fed into the output chain, if allowed to outbound, if not allow the monument will be discarded (drop off).

3) when the Linux system as a firewall deployment, as a gateway-style firewall used, when the packet to pass through the firewall, first inbound into the routing table, determined by the routing table, the packet is to be sent by another NIC Port, the packet will be fed into the forward chain, if the rules in the forward chain is not allowed to pass the packet, Then discard directly. Instead, the packet outbound leaves the firewall.

2. Rule matching Process

The concept of how to match the packet in each chain after describing how filter works is also very important. It is also explained that the number of rules contained in each chain in the actual application is different, regardless of the filter table whose matching principle is "first match", that is, priority execution. When we add new rules to the firewall, they are added to the input chain, numbered sequentially, such as Rules1, Rules2, and so on. When the packet enters the input chain, the filter mechanism will match the feature of the packet from the first rule in the input chain one at a time, and if the packet encounters the first rule allowing passage, then the packet will go to the local process httpd, regardless of the following rule2, The rule of rule3 is nothing; Conversely, if the first rule says to be discarded, even if the Rule2 rule allows it to pass, it is "first match" principle.

In the use of rules is to pay attention to a principle, as far as possible to reduce unnecessary rules, because when the packet into the firewall will be in a particular chain to be compared, the more the number of rules, the packet is stuck in the firewall longer time, firewall performance will be reduced.

The firewall rule order also affects its productivity, such as client charging of extranet mail through the Linux firewall, and the client using the program as Outlook, using the POP3 protocol. The firewall rules are as follows:

1. Iptables-a input-p TCP--syn-m State--state NEW--dport 22-j ACCEPT

2. Iptables-a input-p tcp--sync-m State--state NEW--dport 25-j ACCEPT

3. Iptables-a input-p TCP--sync-m State--state NEW--dport 80-j ACCEPT

4. Iptables-a input-p TCP--sync-m State--state NEW--dport 110-j ACCEPT

5.iptables-a input-p all-m State--state established,related-j ACCEPT

When the first packet of the customer segment takes 4 matching actions, if a message requires 1000 packets, and the packet with the TCP three handshake is matched to tens of thousands of times, if the fourth rule is moved to the first one, then the number of matches is only 1000 times. This shows that the order of the rules has a great impact on firewall performance. So as long as the use of the highest rules of flatness written in the first, and so on and so on.

So, how do you determine which rule is used at a high or low frequency? You can use the following command to view:

There are special cases, packets from the input chain came in from the first rule to match to the last one did not match success, how to do? System has been considered, at the end of each chain has a default policy, and this default policy is always the last to be matched, and the state of the default policy is only one (accept or drop), we assume that the default policy is accept, then the packet is allowed to enter the local process, If the drop is dropped, it is discarded by the default policy. Finally, it is emphasized that the default policy preset for NetFilter is accept, which can also be modified.

3.Iptables Combat

Iptables principle difficult to understand, the operation of the command parameters, in the use of more complex, we first regardless of complex syntax and a wide range of parameters, first look at the following simple example application:

1) List all the contents of the filter table

#iptables –t Filter-l

2) Clear all contents of the filter table

#iptables –t filter–f

3) Adding rules to the input chain

#iptables –t filter–a input–p udp-j ACCEPT

4) Insert the new rule in the position of the second row in the input chain

#iptables –t filter–i INPUT 2–p tcp–j ACCEPT

Note: 2 represents the position inserted into the second rule,-P tcp–j accept is the rule for this secondary insertion, and the-l parameter is followed by-line-number to indicate that the line number can be displayed before the rule.

5) Delete the second rule

#iptables –t filter–d INPUT 2

6) Change the default policy in the input chain to drop

#iptables –t filter–p INPUT DROP \\* Note Here the letter P is uppercase \ \

After reading the above demonstration, careless is not the introduction, divert the above command on the other table can still oh. Let's continue with the explanation below.

7) Disable 192.168.11.100 host ping me

You need to discard 192.168.11.100 ICMP packets sent to this machine, as follows:

#iptables –A input–p icmp–s 192.168.11.100–j DROP

Analysis:

Because the object is protected by this machine, the input chain is selected.

-P ICMP note is lowercase. Here is the matching ICMP protocol packet, extending the "–p TCP" matching TCP packet, the-p UDP matching UDP packet and "-p all" matching all protocol packets.

-S 192.168.11.100 the source IP address is 192.168.11.100, then if the destination address is "-D", if it is a URL "-D www.website.com", if it is a network segment it "-D 192.168.11.0/24 "is expressed in CIDR form.

-j drop falls in line with the previous two conditions

8) allow the 192.168.11.100 host to SSH in to the machine

#iptables –A input–p tcp s0 192.168.11.100–dport 22–j ACCEPT

--dport 22 matches packet with destination Port 22, TCPPort 22 is SSH service port

-j ACCEPT: Packages that meet the first three conditions can be entered

9) Allow 192.168.11.0/24 network segment all hosts to access native 192.168.12.1 any service request

#iptables –A input–p all–s 192.168.11.0/24–d 192.168.12.1–j ACCEPT

10) Prohibit enterprise internal host access to the external network

#iptables –A forward–i eth1–o eth0–p tcp–dport 80–j DROP

Here is the Linux installed on the dual-NIC server as a firewall to use, so definitely use forward chain, eth0 network, eth1 connected enterprise intranet.

-I eth1: Match Packet Entry interface

-O eth0: Match packet left interface, combined with-i,-o two parameters to match the purpose of packet transmission direction.

-P TCP: Packets matching TCP protocol

--dport 80: Match the packet with the destination port of 80 and add a little bit to it! "To represent the reverse, such as"-sport! 80 "represents a packet that is not sent from the web.

-j drop a packet drop that meets the above 4 conditions

4 iptables syntax

The following has to explain the grammar, read the above 10 examples believe that we have a basic concept below I summarize:

Iptables command format

Iptables [-t table] command [chain] [rules] [-j target]

You see this format is not a bit familiar, in fact, many of the above commands are written in this format.

Table: Specifies the name of the tables, such as the filter table, raw table, mangle table, Nat table

Command: Operations on the chain, such as-A for append rule,-I for Insert rule

Chain: Chain name, such as input chain, output chain, forward chain, prerouting chain, postouting chain

Rules: Rule

Target: How the action is performed, that is, how the condition in the current polygon rule is handled, whether it is accept (pass), or drop (discard) REJECT (discards and responds to the sending side a Destination unreachable ICMP packet)

Nat principle of NetFilter

NAT is the abbreviation of network address translation (translation), and its main function is not so much the use of public IP as to hide the intranet IP address. This technique can be used both on the server side and on the client side. A wide variety of NAT mainly has this book mainly describes one-to-many NAT use.

Figure Nat Principle

NAT working process:

The following through the NAT way, all the hosts in the enterprise intranet through a public IP network, as shown in the figure. In the diagram, the device parameters are described as follows:

? Client IP 192.168.11.10

? The NAT server is implemented by Linux Iptables, and the Linux server has a dual NIC installed.

? Eth1 connected intranet, Private IP is 192.168.11.1

? eth0 Connection Network, public IP is 10.0.0.1

? Public network Webserverip for 202.202.202.202

First, 192.168.11.10 this client in the browser input http://202.202.202.202/, through the following six steps to complete the process of displaying the Web page.

The first step , 192.168.11.10 send out packets to 202.202.202.202 server;

The second step , the packet to the Nat gateway processing, and then the NAT host to the received packet source address changed to the NAT host Publicip;

In the third step , the NAT host logs down the packet and sends the packet to the 202.202.202.202 host immediately;

The Fourth step , the remote host 202.202.202.202 corresponding to this host response packet, but this response to the destination host is 10.0.0.1 this public IP, not the client's IP;

Fifth Step , this package is sent back to the NAT host;

Sixth step , when the NAT host receives this packet, From the information previously recorded, the original NAT host converted the 192.168.11.10 to 10.0.0.1, and finally the NAT host changed the destination IP in the packet to 192.168.11.10, the client received a response from the Web server. That is, the intranet host with NAT to access the external network resources.

Note: In the first step to the second step of the process, the source address of the packet changed, the process of changing the source address is called Snat, and in steps fifth through sixth, the destination address Bai changed, the same is called Dnat, basically each kind of NAT is Snat and Dnat together.

Then the above example analysis, the packet is entered by the Eth1 interface, after the replacement by Eth0 left, the packet generated in turn postrouting (source address translation), Routing table and prerouting (destination address translation) Three different mechanisms of change. The order is reversed if the packet is fed by eth0 and has eth1 sent out. So the position of postrouting and prerouting is related to the packet flow.

The relationship between the flow of the package and the Snat and Dnat

The View NAT table Structure command is as follows:

#iptables –t Nat–l

Summary, postrouting is the source address conversion, to your intranet address into a public address to allow you to surf the Internet. Prerouting is the destination address conversion, to the other people's public network IP to your internal IP, so that access to your internal firewall protection of the machine. Describes the complete structure of NAT.

Figure NAT Structure

1) prerouting

When you want to change the packet destination IP, place the rule within prerouting chain, because prerouting chain's function is to perform dnat.

2) postrouting

The function of postrouting China is to change the source IP of the packet, that is, it mainly performs the Snat task. It is important to note that it is at the very end of the entire NAT mechanism, so we execute snat, and the source IP change is finally executed.

One-to-many NAT examples

A one-to-many NAT application is usually the most commonly used, below we see the actual application, topology and configuration or look.

When setting up this NAT, we consider the packet to enter and go out in two directions, first of all to consider the case of sending packets to the outside network by the enterprise, if 192.168.11.0/ 24 network segment of the host to access the external network 202.202.202.202 this host, its server request packets within the source IP can be timed private IP, it is certainly not possible to directly delivery outside the network, it must be the NAT host on the snat mechanism of the external packet of the source IP into the NAT host on the PUBLICIP, in order to let the external network host ring The packet that should be returned can return to the NAT host on Publicip, and this Snat rule is written as follows:

#iptables –t nat–a postrouting–o eth0–s 192.168.11.0/24-j snat–-to 10.0.0.1

Note that the system behind the NAT host is not secure, for example, for one-off NAT, when hackers attack Nat's public IP address from the extranet, the packet is forwarded to the host behind the NAT. To improve security, you need to combine with the filter mechanism.

Iptables Rule Base Management

We know that iptables's rules are stored in a variety of different chains, which is equivalent to a rule base, which can be stored when we modify the rules using the Iptables-save command. For Ossim systems, iptables rules are stored in/etc/ossim_firewall files, and/etc/ossim_firewall files are called into memory by Iptables-restore each time the system is booted. If the Redhat system is stored with the service iptables Save command, the default rule path is within the/etc/sysconfig/iptables file. But this management may not be good, such as the rule base has 100 rules, there are 80 rules contain address 192.168.11.10, then if you need to change the original 192.168.11.10 to 192.168.12.10, do you want to re-enter all the addresses? That's too inefficient. It is recommended that you use script management, which is to write rules to shell scripts so that the IP address can be stored in variables

Mangle mechanism

The mangle table is primarily used to modify the packet's TOS (type of service, services type), TTL (Time to Live, lifetime) to refer to, and set the mark tag for the packet to implement QoS (quality of service, quality of services) Applications such as adjustment and Policy routing, the kernel module corresponding to the Mangle table is iptable_mangle. Because of the need for the appropriate routing device support, the application is not extensive. Note that mark does not really change the packet, it simply sets a tag for the package in kernel space, and the mangle application order is higher than NAT, filter.

Iptables-f-T Mangle # Clears the rules in the Mangle table, all rule chains

Iptables-t Mangle-x # Clears the rules in the Mangle table, user-defined chains

Raw mechanism

Raw tables are used only on prerouting chains and output chains, because the highest priority is available, allowing the packets received to be processed before connection tracking. Once the user uses the raw table, on a chain, after the raw table is processed, the NAT table and the Ip_conntrack processing are skipped, i.e. the address translation and the link tracking of the packet are not processed.

Raw tables can be applied in situations where there is no need to do NAT to improve performance. such as a large number of access to the Web server, you can let the 80 port no longer let iptables do the packet tracking processing to improve the user's access speed.

How to execute instructions

Iptables-t raw-a prerouting-p TCP--dport 80-j notrack

Iptables-t raw-a prerouting-p TCP--sport 80-j notrack

Iptables-a forward-m State--state untracked-j ACCEPT

NetFilter Module Application Example

Packet matching is the basic way of netfilter filtering packets, the more matching methods, the more detailed the packets are extracted, so the protection scope of the firewall is greater.

Example:

1) Prohibit intranet users from accessing http://www.website.com

#iptables –A forward–p tcp–i eth1–o eth0–d www.website.com–j DROP

2) Matching Destination port

Disable access to the extranet FTP service for all hosts in the 192.168.11.0/24 network segment, as follows:

#iptables –A forward–i eth1–o eth0–p tcp–s 192.168.11.0/24--dport 21:22–j REJECT

What if the source port is matched? Just change "--dport" to "-sport".

3) tcp-flags Matching

In order to prevent some non-normal packets we can use NetFilter filter tcp-flags status, we can use-syn to determine that the packet contains a SYN flag. For example:

#iptables –A input–p tcp--tcp-flags all syn,fin–j DROP

4) MAC address matching

Some companies are DHCP-assigned client IPs, but sometimes you need to make a specific IP to access the database server, how to handle it? We can filter based on the MAC address of these specified machines. Assuming that the MS SQL Server uses a port of 1433, the specified host Nic MAC address is 00:0c:29:53:ab:60, as follows:

#iptables –A input–p TCP--dport 1433–m mac--mac-source 00:0c:29:53:ab:60–j ACCEPT

Where-M Mac represents the call to the Xt_mac.ki module, and its function is to match the MAC address.

5. IP address range Matching

When you want to block an IP address segment will not go to a line of IP address input, netfiletre in the Ipt_iprange.ko module can use a statement to solve the problem, the rules are as follows:

#iptables –A input–m iprange--src-range 192.168.11.110-192.168.11.150–j DROP

In the same way, if you need to limit the destination address, then you need to replace "--src-range" with "--dst-range".

6. Matching of TTL values

The time to Live (time-to-live) specifies the number of network segments that the packet is allowed to pass before it is dropped by the router. It is a value in the IP (Chinese full Name: Network protocol) Protocol package that tells the network whether the time of the packet is too long in the network and should be discarded, typically linuxttl a value of 64 or 255,windows 2000/xp TTL value of 128.

The matching of TTL values is implemented by the Ipt_ttl.ko module of NetFilter. For example, we want to discard packets with a TTL value of 128, with the following rules:

#iptables –A input–m ttl--ttl-sq 128–j REJECT

7. Match the MTU value

This is related to the packet length, the MTU is the maximum transmission unit, it refers to a communication protocol of a layer above the maximum packet size (in bytes), the following is an example of an ICMP packet to tell a special scenario.

Ping is a common command, and in Linux under the Ping–f–s 16384 1.2.3.4 will produce a large number of large ICMP packets not only occupy the machine CPU and occupy the network bandwidth, "-s 16386" will be generated by the ICMP packet data size is 16KB, If you use the Ping–f–s 0 1.2.3.4 Instruction, more ICMP request packets will be generated. This will slowly form a Dos attack.

Some friends think of a ban on ping and use the following command

Echo 1 >; /proc/sys/net/ipv4/icmp_echo_ignore_all

Sometimes it's not easy to ping yourself, or you can use Iptables's Xt_length.ko module.

#iptables –A input–p ICMP--icmp-type 8–m length--length 1:99–j ACCEPT

#iptables –A input–p ICMP--icmp-type 8–m length--length 1000:16386–j DROP

Note: We have filtered out the non-compliant ICMP type 8 packet to prevent the host from being attacked by a large number of ICMP packets. --length 1000:16,386 indicates a packet matching the MTU value between 1000~16386 bytes

8. Matching of the specified packet repetition rate

The flexibility to use limit is stronger than the rule above, not beat him. Let's say I want to have 10 ICMP packets per minute, and if it's more than that, we'll limit the 6 ICMP that can come in every minute. The implementation rules are as follows:

#iptables –A input–p ICMP--icmp-type 8–m limit--limit 6/m--limit-burst 10–j ACCEPT

#iptables –A input–p ICMP--icmp-type 8–j DROP

Note: 6/m, where the m represents minutes, and the back of-limit-burst 10 means that every minute into 10 packets, do not forget the second rule, only two are input to function.

9. Match the contents of the package inside

Suppose an extranet attacker attacks an intranet IIS server by sending "./winnt/system32/cmd.exe?/c+dir", and we can try to exploit xt_ on the Linux gateway Firewall before the server vulnerability is fully repaired The matching function of the String.ko module temporarily prevents attackers from attacking again. The rules are as follows:

#iptables –A forward–i eth0–o eth1–p tcp–d 10.0.0.1--dport 80–m string--algo BM--string "System32" –j DROP

Meaning: If the packet is to be sent to IIS server port 80, it is matched with the string module, BM represents (Boyer-morre) algorithm, if the packet contains system32 word a is discarded. But be aware that this is an interim approach rather than a lifeline.

10. Processing of logs

NetFilter default does not generate a log, if you need to log the need to use the Ipt_log.ko module, the following example, we want to record the FTP service request to the local IP address, you can use the following command:

#iptables –A input–p TCP--dport 21–j LOG

#iptables –A input–p TCP--dport 21–j ACCEPT

Log will only record the packet information, not the packet, log is a special processing method, the packet will continue to match other rules within the input chain, and log logs will be stored in the/var/log/messages, to view the method:

#tail –f/var/log/messages

When you use it, you will find that the log log volume is growing fast because log logs the information for each FTP protocol packet. Let's revise it to record only the first sub-package for each connection so that the size of the log is greatly reduced.

#iptables –A input–p tcp--syn--dport 21–j LOG

The next question is how to extract the log from/var/log/messages, and we can use the--log-level parameter to improve the method as follows:

#iptables –A input–p tcp--syn--dport 21-j LOG--log-level Alert

Don't worry, you need to add the following line configuration in the/etc/syslog.conf file

Kern.=alert/var/log/netfilter

This means that if log is generated by kernel, and the log level is alert, it is stored in the/var/log/netfilter file.

Finally, the Syslog service is restarted, and later logs about the FTP protocol are stored in the/var/log/netfilter file.

The log described here is handled by syslog, and there are more advanced methods that can be used Ulog processing method Here is not a detailed introduction of interested readers reference "Unix/linux Network log analysis and traffic monitoring" a book.

Netfilter/iptables Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.