Netfilter/Iptables, netfilteriptables

Source: Internet
Author: User
Tags syslog ftp protocol

Netfilter/Iptables, netfilteriptables
Netfilter/Iptables

The Linux kernel is developed and maintained by the www.kernel.org organization. The Netfilter/iptables discussed below is the firewall software developed for Linux by www.netfilter.org. Because Linux is very modular, many functions are loaded by modules to expand the system function, Netfilter also uses this method in Linux. If you understand Linux module loading, you can understand the module Loading Method of Netfilter. You can see a lot in the/lib/modules/kernel_version/kernel/net/ipv4/netfilter/directory. ko "is a file with the extension, where it stores the compiled module File.

To learn Iptables, you must first understand the basic concepts of TCP/IP and how packets are transmitted over the network. What are the limitations, in particular, what is the relationship between the TCP/IP and IP packet header structures and TCP, UDP, and Socket? Understanding these content is the basis of this chapter.

1. Functions of Netfilter

If you go to the Netfilter Module Directory and check it carefully, you will find modules with various functions. These modules only provide some filtering functions. If you want Netfilter to be used by me, you also need to assign the rule to it. After the rule is determined, Netfilter knows which packets pass, which packets are blocked, and which packets are replaced. According to the function division, Netfilter is divided into four functions: Filter, NAT, Mangle, and RAW. The four functions also generate four tables. Their main functions are as follows:

L Filter: its main function is to Filter data packets.

L NAT (Network Address Translation): IP Address Translation, mainly used to solve Internet access problems.

L Mangle: its main function is to modify firewall packets.

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

Note: The four tables are ranked in this Order Based on the usage ratio from the first to the second, but the priority is based on the processing priority of the table, as shown in the following figure: Raw> Mangle> Nat> Filter.

1. 1. Understand the Filter mechanism

First, let's take a look at the following example. The Web page on the remote Apache server is accessed through Firefox on the client. In such a normal operation, Netfilter has these three types of packets, this is the key mechanism of Filter.

Graph packet type

INPUT type

When the client accesses the httpd process of the Web server, the Web Server is an inbound package. In other words, it is the packet sent from other hosts on the Internet to the httpd process of the local machine, it is defined as an INPUT packet (the red arrow in the figure ).

OUTPUT type

In contrast to INPUT, the packets that are linked by the httpd process of the Web server to the client belong to the OUTPUT type (the green arrow in the figure), that is, the packets generated by the httpd process on the local machine.

FORWARD Type

As shown in the figure, Web server packets pass by belong to the FORWARD type. Under what circumstances will this type of packets be generated? When we use Linux as a router, a FORWARD packet is generated.

With the basic concepts above, we will discuss the filtering Table below. The Filter Table has three chains. The Chain can be understood as a Chain in a bicycle, Which is interlocking, the same is true for packets transmitted over the network.

Filter table structure

Because it is the structure of the Filter table, do you find that this is not the three types of packets? The following is a detailed analysis:

INPUT chain: To understand this problem, we still need to take an instance for analysis. For example, which of the three packet types should we pay attention to when we want to protect the httpd process of the Web server? It must be an INPUT-type packet, so you need to write the packet used to filter the INPUT type into the rules of the INPUT chain. In this way, the httpd process can be protected. Broadly speaking, the INPUT chain is used to store the rules for filtering INPUT packets. It is often used to protect the local machine.

OUTPUT chain: Let's continue with the example of accessing the website above. If we want to restrict the client from visiting www.website.com, which package should we restrict? You can guess the OUTPUT type of packets. We can write "if the packet is generated by the httpd process and sentError! The hyperlink reference is invalid.The packet is discarded. This restricts the network connection behavior. Therefore, the OUTPU chain is used to store the rules for filtering INPUT packets. It is often used to restrict the network links of local processes.

FORWARD chain: When a linux server is used as a router to protect a remote Web server, which type of packets should be restricted? It must be the FORWARD type, that is, the FORWARD chain is used to protect the servers behind the firewall.

Because the Filter mechanism is very complex, a simple representation of the Filter principle is used for your easy understanding. Note that although two route tables are drawn in the diagram, there is only one actually, that is, the content we see in "route-n" in the system. The route table determines the packet transmission path, especially in the Multi-nic system. The local process is the Web server process described above. You can understand it as the httpd process.

Figure Filter schematic

Next, we will describe how network packets are processed in the Filter mechanism in three different scenarios.

1) when accessing 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 first sent to the route table, and the content of the route table determines the transmission path. Since the client accesses the page on the Web server, that is, the packet is sent to the httpd of the local process, the packet is sent to the INPUT chain. If the INPUT chain is too long, the packet will be sent to the local process, and will be dropped if it is not allowed ).

2) When the server returns the result, it needs to link the client process. This is the packet sent out by the local process httpd. First, the packet will be transmitted as in the route table. The content here determines the packet transmission path, it is then sent to the OUTPUT chain. If allowed, the site will be released. If not, the site will be dropped ).

3) when the Linux system is deployed as a firewall and used as a gateway-based firewall, when packets need to pass through the firewall, the first entry enters the route table and the route table determines that the packets must be sent from another NIC port, the packet will be sent to the FORWARD chain. If the rules in the FORWARD chain are not allowed to pass the packet, the packet will be discarded directly. Otherwise, the outbound packet leaves the firewall.

2. Rule matching process

After introducing the working principle of Filter, it is also very important to explain how packets match in each chain. In practice, the number of rules contained in each chain is different. No matter which Filter table matches, the rule is "First Match", that is, the rule is executed First. When the new rules we add to the firewall are added to the INPUT chain one by one, they are numbered sequentially, such as rules1 and rules2. When a packet enters the INPUT chain, the Filter mechanism matches the first rule in the INPUT chain one by one based on the characteristics of the packet. If the first rule is allowed to pass in the packet, then the packet will enter the local process httpd, regardless of the following rules of rule2 and rule3 are not important. On the contrary, if the first rule is discarded, even rule2 rules allow passing, this is the "first match" principle.

When using rules, you should pay attention to the principle of minimizing unnecessary rules, because when packets enter the firewall, they will be compared one by one in a specific chain. The more rules, the longer the packet remains in the firewall, the lower the firewall performance.

The sequence of firewall rules also affects the efficiency of the client. For example, if the client receives an Internet mail through the Linux firewall, the client uses the Outlook program and uses 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 needs to be matched four times, if an email requires 1000 packets, the number of matching times of the TCP three-way handshake packets reaches tens of thousands, if the fourth rule is moved to the first rule, the matching times are only one thousand times. Therefore, the order of rules has a great impact on the firewall performance. Therefore, you only need to write the rules with the highest level in the first place, and so on.

So how can we determine which rule is frequently used or low? You can use the following command to View Details:

In other special cases, the first rule from the INPUT chain does not match the last one. What should I do? The system has considered that there is a default policy at the end of each chain, and this default policy is always matched at the end, and there is only one (ACCEPT or DROP) status of this default policy ), assume that the Default policy is ACCEPT, and then the packets can enter the local process. If the policy is DROP, the packets are discarded by the Default policy. Finally, it is emphasized that the default value of Netfilter is ACCEPT, which can be modified.

3. Iptables practice

The principle of Iptables is hard to understand. The Operation Command has many parameters and is also complicated to use. No matter the complex syntax and a wide range of parameters, let's take a look at the following simple example application:

1) list all contents of the Filter table

# Iptables-t filter-L

2) Clear all contents in the Filter table

# Iptables-t filter-F

3) add rules to the INPUT chain

# Iptables-t filter-a input-p udp-j ACCEPT

4) Insert a new rule at the position of the second row in the INPUT chain

# Iptables-t filter-I INPUT 2-p tcp-j ACCEPT

Note: 2 indicates the location where the second rule is inserted.-p tcp-j ACCEPT is the secondary rule inserted, -L-line-number is added to the end of the parameter, indicating that the row 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 that the letter P here is uppercase \\

After reading the above demo, I am not careful about getting started. Just use the above commands on other tables as you can. Next we will continue to explain.

7) Disable ping from the host 192.168.11.100

The ICMP packet sent from 192.168.11.100 to the local machine needs to be discarded as follows:

# Iptables-a input-p icmp-s 192.168.11.100-j DROP

Analysis:

Because the local machine is protected, the INPUT chain is selected;

-P icmp must be in lower case. Here we match icmp protocol packets, extend "-p tcp" to match TCP packets,-p udp to match UDP packets, and "-p all" to match all protocol packets.

-S 192.168.11.100: the source IP address is 192.168.11.100. If it is the destination address, it is "-d". If the destination is a website address, "-d www.website.com ", for a CIDR Block, "-d 192.168.11.0/24" is represented in CIDR format.

-J DROP: DROP if the preceding two conditions are met.

8) allows the host 192.168.11.100 to log on to the local machine through ssh.

# Iptables-a input-p tcp s0 192.168.11.100-dport 22-j ACCEPT

-- Dport 22 matches the packet whose destination port is 22, and TCPPort 22 is the SSH service port.

-J ACCEPT: packets that meet the first three conditions can enter

9) Allow all hosts in the 192.168.11.0/24 network segment to access the local host 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 internal enterprise hosts from accessing the Internet

# Iptables-a forward-I eth1-o eth0-p tcp-dport 80-j DROP

Here, linux is installed on a dual-nic server as a firewall, so you must use the FORWARD chain. eth0 is connected to the Internet, and eth1 is connected to the enterprise intranet.

-I eth1: interface for matching packets

-O eth0: the interface that matches the packet departure. Combined with the-I and-o parameters, the target Transmission Direction of the packet can be matched.

-P tcp: Packets matching the TCP protocol

-- Dport 80: match the packet whose destination port is 80. You can add a new one with "!". To represent the reverse, such as "-sport! "80" indicates matching packets not sent from the Web.

-J DROP: discard packets that meet the preceding four conditions

4 Iptables syntax

I have to explain the syntax below. After reading the above 10 examples, I believe that you already have basic concepts. Below I will summarize them:

Iptables Command Format

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

We are not familiar with this format. In fact, many of the above commands are written in this format.

Table: Specifies the Table name, such as the filter Table, raw Table, mangle Table, and nat Table.

Command: A chain operation. For example,-A indicates an append rule, and-I indicates an insert rule.

Chain: Chain name, such as INPUT Chain, OUTPUT Chain, FORWARD Chain, PREROUTING Chain, and POSTOUTING Chain

Rules: rule

Target: how the action is performed, that is, whether it is handled by ACCEPT or DROP) REJECT (discard and respond to a sender's ICMP packet destined for Unreachable)

NAT principles of Netfilter

NAT is short for Network Address Translation. Its main function is to hide Intranet IP addresses rather than saving public IP addresses. This technology can be used on both the Server side and the Client side. There are many types of NAT. This book mainly introduces one-to-multiple NAT.

Figure NAT principles

NAT process:

The following figure shows how to use NAT to enable Internet Access for All Intranet hosts through a public Ip address. The device parameters in the figure are described as follows:

? Client IP address 192.168.11.10

? The NAT server is implemented by Linux Iptables, And the Linux server is installed with dual NICs.

? Eth1 is connected to the Intranet, and the Private Ip address is 192.168.11.1

? Eth0 is connected to the Internet, and the Public IP is 10.0.0.1

? The public network WebserverIP address is 202.202.202.202.

First, the client 192.168.11.10 enters http: // 202.202.202.202/in the browser and completes the webpage display process in the following six steps.

Step 1, 192.168.11.10 sends the packet to the 202.202.202.202 server;

Step 2The packet is sent to the NAT gateway for processing. Then, the NAT host changes the received packet source address to the PublicIP of the NAT host;

Step 3The NAT host records the packet and sends it to the 202.202.202.202 host immediately;

Step 4The remote host 202.202.202.202 sends a response packet to the host. However, the target host for this response is the Public IP address 10.0.0.1, rather than the Client IP address;

Step 5The package is sent back to the NAT host;

Step 6When the NAT host receives the packet, it finds the record from the previously recorded information that the original NAT host converts 192.168.11.10 to 10.0.0.1, finally, the NAT host changes the destination IP address in the packet to 192.168.11.10, and the client finally receives a response from the Web server. That is, the Intranet host uses NAT to access Internet resources.

Note: In the process from step 1 to step 2, the source address of the package has changed. The process of changing the source address is called SNAT. in step 5 to step 6, the destination address is changed. Similarly, it is called DNAT. Basically, each type of NAT is composed of SNAT and DNAT.

Then, based on the analysis of the above instance, the packet is entered by the eth1 interface, and eth0 leaves after the package is changed. The packet generation sequence is POSTROUTING (source address conversion), Routing Table, and PREROUTING (destination address conversion) changes in three different mechanisms. If the packet is sent by eth0 and eth1 is sent, the order is the opposite. Therefore, the position of POSTROUTING and PREROUTING is related to the packet flow.

Relationship between the packet flow direction and SNAT and DNAT

The command to view the Nat Table structure is as follows:

# Iptables-t nat-L

In summary, POSTROUTING is a source address conversion. You need to convert your intranet address to a public address to enable Internet access. PREROUTING is a conversion of destination addresses. You need to replace others' public IP addresses with your internal IP addresses so that you can access your internal firewall-protected machines. Describes the complete structure of NAT.

Figure NAT Structure

1) PREROUTING

When you want to change the target IP address of the packet, place the rule in the PREROUTING Chain because the PREROUTING Chain function is to execute DNAT.

2) POSTROUTING

POSTROUTING China is used to change the source IP address of the packet, that is, it is mainly used to execute SNAT tasks. It is worth noting that it is at the end of the entire NAT mechanism, so we execute SNAT and the source IP address change is also at the end.

One-to-multiple NAT

One-to-multiple NAT applications are most commonly used. Let's take a look at the actual application, topology, and configuration.

When setting such NAT, we consider the inbound and outbound packets. First, we consider the situation where packets are transmitted to the Internet by the enterprise, if a host in the 192.168.11.0/24 CIDR Block needs to access the host 202.202.202.202 on the Internet, the source IP address in the server request packet can be a scheduled private IP address, and it is certainly impossible to directly deliver the IP address to the Internet, therefore, the SNAT mechanism on the NAT host must change the source IP address in the outbound packet to the PublicIP address on the NAT host, in this way, the packets returned by the Internet host can be smoothly returned to the public IP address of the NAT host. The 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: The system placed behind the NAT host is not secure. Take one-to-one NAT as an example. When a hacker attacks the Public IP address of the NAT host from the Internet, the attack packets are forwarded to the host after NAT. To improve security, you must combine the Filter mechanism.

Iptables rule repository Management

We know that iptables rules are stored in different chains, which is equivalent to a rule repository. After the rules are modified, the iptables-save command can be used for storage. For the ossim system, iptables rules are stored in the/etc/ossim_firewall file. Each time the system is started, the/etc/ossim_firewall file is called through iptables-restore to the memory. If the Redhat system is used, the "service iptables save" command is used for storage. The default rule path is in the/etc/sysconfig/iptables file. However, such management may not be a good thing. For example, if there are 100 rules in the rule repository and 80 Rules contain the address 192.168.11.10, change the original 192.168.11.10 to 192.168.12.10, are you planning to reenter all the addresses? The efficiency is too low. We recommend that you use the script management method, that is, to write the rule to the shell script, so that you can store the IP address in the Variable

Mangle Mechanism

The Mangle table is mainly used To modify the Type Of Service (TOS), TTL (Time To Live) Of data packets, and To set the Mark for data packets, for Quality Of Service (Qos) adjustment and policy routing, the kernel module corresponding to the mangle table is iptable_mangle. It is not widely used because it requires the support of corresponding routing devices. Note that Mark does not actually change the data packet. It only sets a flag for the package in the kernel space. The Mangle application sequence is higher than nat and filter.

Iptables-F-t mangle # Clear all rules in the Rule chain in the mangle table

Iptables-t mangle-X # Clear the rules in the Custom link in the mangle table

RAW Mechanism

RAW tables are only used in the PREROUTING chain and OUTPUT chain. Because of the highest priority, the received data packets can be processed before connection tracking. 1. If a RAW table is used, the NAT table and ip_conntrack will be skipped after the RAW table is processed on a chain. That is, address translation and packet Link Tracking will no longer be performed.

RAW tables can be used to improve performance without requiring nat. For example, if a large number of web servers are accessed, port 80 can no longer enable iptables to track the links of data packets to improve the user's access speed.

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 method for Netfilter to filter packets. The more matching methods, the more detailed the types of extracted packets. This increases the protection scope of the firewall.

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) match the target port

Prohibit all hosts in the 192.168.11.0/24 CIDR Block from accessing the internet FTP service. The rules are as follows:

# Iptables-a forward-I eth1-o eth0-p tcp-s 192.168.11.0/24 -- dport 21:22-j REJECT

What if it matches the source port? You only need to change "-- dport" to "-sport.

3) TCP-Flags matching

To prevent some abnormal packets, we can use netfilter to filter the tcp-flags status. We can use-syn to determine whether the packet contains syn marks. For example:

# Iptables-a input-p tcp -- tcp-flags all syn, FIN-j DROP

4) MAC address matching

Some companies use DHCP to allocate Client IP addresses, but sometimes a specific IP address is required to access the database server. How can this problem be solved? We can filter the MAC addresses of these specified machines. Suppose that the port used by the ms SQL Server is 1433, And the MAC address of the specified host Nic is 00: 0c: 29: 53: AB: 60, the rules are as follows:

# Iptables-a input-p tcp -- dport 1433-m mac -- mac-source 00: 0c: 29: 53: AB: 60-j ACCEPT

-M mac indicates that the xt_mac.ki module is called, and its function is to match the MAC address.

5. IP address range matching

When you want to block an IP address segment, do not enter one IP address. The ipt_iprange.ko module in Netfiletre can use one 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 want to restrict the destination address, replace "-- src-range" with "-- dst-range.

6. TTL value matching

Time-to-live specifies the number of CIDR blocks allowed to pass before a packet is discarded by the router. It is a value in the IP (network protocol) protocol package, it tells the network whether the packet in the network is too long and should be discarded, in general, the TTL value is 64 or 255, and the Windows 2000/xp ttl value is 128.

TTL value matching is implemented by the ipt_ttl.ko module of Netfilter. For example, we need to discard packets whose TTL value is 128. The rules are as follows:

# Iptables-a input-m ttl -- ttl-sqls 128-j REJECT

7. Match MTU Value

This is related to the packet length. MTU is the maximum transmission unit. It refers to the maximum data packet size (in bytes) that can be passed on a layer of a communication protocol ), the following uses ICMP packets as an example to illustrate a special scenario.

Ping is a common command. in linux, ping-f-s 16384 1.2.3.4 will generate a large number of ICMP packets that not only occupy the machine's CPU but also occupy the network bandwidth, "-s 16386" generates a data size of 16 kb for the icmp packet. If you run the ping-f-s 0 1.2.3.4 command, more ICMP request packets are generated. In this way, the DOS attack will be gradually formed.

Some may use the following command to disable Ping:

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

Sometimes it is inconvenient to ping your own machine, or use the xt_length.ko module of iptables.

# 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: The purpose of filtering out ICMP type 8 packets that do not meet the requirements is to prevent the host from being attacked by a large number of ICMP packets. -- Length 1000: 16386 indicates that the MTU value is between 1000 and ~ 16386 Bytes packets

8. matching of the specified packet repetition rate

Limit is more flexible than the above rules, rather than killing a single stick. For example, I want 10 ICMP packets to enter every minute. If the number of ICMP packets exceeds the limit, only 6 ICMP packets can be entered 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 m represents minutes, and-limit-burst 10 represents 10 packets per minute. Do not forget the second rule. Only two inputs work.

9. Match the content in the packet

Suppose an Internet attacker sends "./winnt/system32/cmd.exe? /C + dir "attacks the IIS server on the Intranet. Before the Server vulnerability is completely fixed, we can try to use the matching function of the xt_string.ko module on the Linux gateway firewall to temporarily prevent further attacks. 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 sent to port 80 of the IIS Server, it will be matched by the string module. bm represents the Boyer-Morre algorithm. If the packet contains system32 characters, it will be discarded. However, note that this is only a temporary solution, rather than a life-saving means.

10. log processing

Netfilter does not generate logs by default. If you need to record logs, you need to use the ipt_log.ko module. The following example shows that we want to record the IP addresses that have sent FTP service requests to the local machine. The following command can be used:

# Iptables-a input-p tcp -- dport 21-j LOG

# Iptables-a input-p tcp -- dport 21-j ACCEPT

LOG records only the packet information, but does not process the packet. LOG is a special processing method. This packet will continue to match other rules in the INPUT chain, logs recorded by logs are stored in/var/LOG/messages:

# Tail-f/var/log/messages

In use, you will find that the log volume increases rapidly because the LOG records the information of each FTP protocol packet. Next let's modify it to record only the first packet of each connection, so that the log size is greatly reduced.

# Iptables-a input-p tcp -- syn -- dport 21-j LOG

The following question is how to extract logs from/var/log/messages. We can use the -- LOG-level parameter. The improvement method is as follows:

# Iptables-a input-p tcp -- syn -- dport 21-j LOG -- log-level alert

Do not worry. You need to add the following configuration in the/etc/syslog. conf file as a line.

Kern. = alert/var/log/netfilter

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

Finally, restart the syslog service. The FTP protocol logs will be stored in the/var/log/netfilter file.

The logs described here are processed by the system syslog, and more advanced ULOG processing methods are available. For more information, seeNetwork Log Analysis and traffic monitoring for UNIX/LinuxA book.

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.