Basic and Application of iptables (1)

Source: Internet
Author: User

1. What is firewall?

A firewall is a combination of hardware and software devices that can be connected between two or more networks and clearly separate physical connections. The isolated network can communicate with each other through the packet forwarding technology. Through the security management mechanism of the firewall, it can determine which data can be circulated and which data cannot be circulated, to achieve network security protection.

Firewall Products can be roughly classified as hardware-based firewalls and software-based firewalls. However, both hardware-based and software-based firewalls require hardware for online intercommunication, software is also required to set security policies. Strictly speaking, there is not much difference between the two. We can only distinguish between the hardware used and the operating system. hardware firewalls use proprietary hardware, while software firewalls use general computer hardware, hardware firewalls use proprietary operating systems, while software firewalls use general operating systems.

Firewalls are classified according to their operating methods. They can be classified into Packet Filter and Application-Level Gateway) circuit Layer Gateway (Circuit-Level Gateway ). The encapsulation filter firewall is widely used. The iptables firewall described in this article belongs to this type.

Packet filtering is the first firewall technology to be implemented. It operates at the IP layer under the TCP/IP layer-4 architecture. The function of the packet filter is to check each IP address data packet passed. If the data content contained in the header meets the filter conditions, further processing will be performed. The main processing methods include: allow accept), discard drop) or reject ). To filter packets, the firewall must be able to analyze the source IP addresses and destination IP addresses of packets, you must also be able to check data such as the package type, source port number and destination port number, Packet Flow Direction, Nic interface for packets entering the firewall, and online status of TCP.

Firewall costs remain high for various reasons. It is impossible for poor primary and secondary schools to purchase a firewall. Due to the popularity of Linux, Linux is used as a software-based firewall, it seems to be a good solution. This article will introduce the latest and most powerful iptables firewall software on Linux to build filtering rules suitable for schools, to enable schools with insufficient funds to have an easy-to-use firewall to guard the door of campus networks.

Ii. Brief History of Linux Firewall Evolution

The earliest firewall software in Linux is called ipfw. ipfw can analyze IP packet headers, identify the source IP address and destination IP address of the packet, the type of the packet, the source port number and destination port number, the packet flow direction, and the interface of the packet entering the firewall ...... the analysis results are used to compare the rules for packet filtering, and the IP camouflage function is also supported. This function can solve the problem of insufficient IP addresses. Unfortunately, this program lacks elastic design, you cannot set up a rule combination ruleset on your own to simplify the settings. At the same time, you also lack the URL translation function. You cannot cope with the increasingly complex network environment and are gradually eliminated.

The ipchains are not only easier to understand the command syntax, but also more powerful than ipfw. ipchains allow custom rule combinations (ruleset), which is called user-define chains. Through this design, we can combine rules related to each other and jump to this group of rules for filtering as needed, effectively reducing the number of rules. In the past, ipfw can only perform sequential filtering, as a result, the rules are smelly and long, and the problem becomes worse. In addition to this obvious benefit, ipchains can combine its own port functions with the redir program's packet forwarding mechanism to simulate the URL translation capability and meet the complete needs of NAT, it is a mature set of firewall works.

The emergence of firewall software has indeed made the hackers sleep at night, because the firewall's barrier can effectively make the stand-alone hosts with no security protection on the internal network not exposed, but also effectively reduce the visibility of the server, reducing the chance of being attacked. The network detection technology used by hackers in the past has been severely challenged. More and more attack objects are hiding behind the firewall, making it difficult for hackers to approach. Therefore, they must address new situations, this article does not discuss the new detection technology to avoid firewall checks, find targets, and attack intrusions, please refer to the technical documents organized by CERT at www.cert.org. If you want to see Chinese, please connect to www.cert.org.tw.

As the new generation successor of ipchains, iptables, of course, also develops some countermeasures for the hacker's constantly new detection technology, that is, to make a more detailed analysis of the online status of packets, such: whether it is a new online or response packet, whether it is online, whether it has lost response, whether the online time is too long ...... and so on. For more information about the vulnerabilities that may be exploited by hackers, see the following description, without the help of other programs, you do not need to simulate website translation. In addition, iptables is also directly supported by the system core, and you do not need to re-compile the core like ipchains.

The superior performance of iptables has replaced ipchains and become the mainstream of network firewalls, while ipchains have not been eliminated. Currently, ipchains has been transformed into a single-host firewall. When the new version of Linux is installed, it is automatically installed and enabled to protect unused communication ports on a single machine.

Introduction to iptables Firewall

Iptables firewall commands are very similar to ipchains. People who have used ipchains should be very easy to use. However, the iptables mechanism is very different from ipchains. The ipchains concept is used to set rules, this will make the firewall unable to operate normally. The biggest difference between ipchains and iptables lies in the different definitions of the INPUT, FORWARD, and OUTPUT network types. These three network types are part of the TCP/IP driver. The structure is shown in, it is between the NIC Driver and application. INPUT, OUTPUT, and LOOPBACK are enabled in the Linux core preset, and the FORWARD function must be enabled on its own. You can use the following command, or directly modify the/etc/sysconfig/network configuration file:

Echo "1">/proc/sys/net/ipv4/ip_forward

The figure on the left shows the operation of ipchains.

The following table describes how ipchains process the flow of packets:

• Ip input: all packets are processed by the ip input function. Therefore, when filtering rules are set, they are almost all set in the INPUT rule refining.

• Ip forward: the destination IP address is not the local IP address. These packets need to be transferred further. This function is used to handle IP Spoofing and Port forwarding.

• Ip output: all outbound packets are processed by this function. Generally, no rules are required.

In addition to the preceding three functions, iptables also uses two new functions: Prerouting and Postrouting. Now let's compare the loopback interface of the iptables operation mode with the same one, so it is omitted and not shown ):

The following table describes how iptables processes the flow of packets:

• Ip input: only packets sent to the local machine are processed by the INPUT function. Therefore, packets from the internal network are allowed to be opened unconditionally. packets from the external network are filtered out to determine whether the packets are response packets, if yes, allow access.

• PREROUTING: This function is used to process the packets to be transferred. This function is used to translate the destination IP address into DNAT ).

• Ip forward: All forwarded packets are processed here, And the filtering rules are the most complex.

• POSTROUTING: This function is used to translate the source IP address into SNAT ).

• Ip output: This function processes the packets sent from the local machine, and usually releases all packets.

Both iptables and ipchains can define the rule group rule-set). The rule group is called rule refining chains, there are also corresponding rules for refining INPUT, FORWARD, OUTPUT, Prerouting, and Postrouting). To be different from custom rules, these rules are called built-in rule refining, its operation process simulation is as follows:

From the above two hypothetical figures, it is not difficult for students to understand why ipchains is called chains, because it concatenates all rules into a sequence and checks and filters them one by one, just like a chain, one ring, and one ring, in the filtering process, if one rule is met, it will be processed immediately. If the processing action is to jump to a Rule group, the system will continue to check the rule settings in the group, however, if the processing action is ACCEPT, REJECT, DROP, REDIRECT, or MASQUERADE, the filter program will be interrupted and the subsequent rule settings will not be checked. Under such a structure, sometimes the reverse results are generated when the Rule Order is reversed, so you must be cautious when setting the firewall.

Iptables uses the rule stack for filtering. When a packet enters the NIC, it first checks Prerouting and then checks the destination IP to determine whether the packet needs to be transferred out, then, it will jump to INPUT or Forward for filtering. If the packet needs to be transferred for processing, it will check Postrouting. If it is from the local packet, it will check OUTPUT and Postrouting. If a rule is met during the process, the processing will be performed in addition to ACCEPT, REJECT, DROP, REDIRECT, and MASQUERADE, there are also more LOG, ULOG, DNAT, SNAT, MIRROR, QUEUE, RETURN, TOS, TTL, MARK, and so on, some of the processing actions will not interrupt the filtering program, some processing operations will interrupt the filtering of the same rule refining, and continue filtering of the next rule refining according to the above process. Note: This is different from ipchains) until the rule check in the stack is completed. The advantage of this mechanism is that we can perform complex and multi-packet filtering. In short, iptables can be used to filter tables in an interactive manner) instead of refining the chins ).

Although iptables must adopt a complicated filtering process to expand the firewall function, the rule setting under the same rule refining still has a sequential relationship in actual applications, therefore, you must pay attention to the logic when setting rules.

Establishing Campus Network Security Policies

Before setting a firewall, we must formulate a security policy based on the security requirements of the campus network. Before formulating a security policy, we must collect the following information:

1. Find the server to be filtered and protected

2. List the network services that the protected server will provide

3. What kind of protection is required for normal workstations?

4. Understand network architecture and server placement

Based on the data, we can decide the security policy. The following example uses Shi Pai as an example:

1. NAT virtual network is used in the school. The number of IP addresses requires two groups of C. All IP addresses must be disguised as IP addresses.

2. Campus security requirements are not high, servers and workstations are placed in the same network segment, and DMZ design is not required.

3. Due to frequent expansion of server functions, all servers adopt a one-to-one mechanism without using the port forwarding function.

4. All workstations are free to use network resources, so they can only view webpages.

5. Services provided by the server include dns, web, mail, ftp, wam, webmin, ssh, rdp, and pcaw. proxy and other network services are not provided.

6. To improve the security of Campus Networks, use the forward table to filter packets and define the packets to be released. All other packets will be blocked)

There are also some precautions for network security, which should be prevented by every school. There is no difference between them. For example: online kidnapping, blocking attacks, connection port scanning .......

Wu and iptables commands

Syntax:

Iptables [-t table] command [match] [-j target/jump]

The-t parameter is used to specify the rule table. The built-in rule table has three rules: nat, mangle, and filter. If the rule table is not specified, it is regarded as a filter. The functions of each rule table are as follows:

Nat this rule table has two rules: Prerouting and postrouting. The main function is to perform one-to-one, one-to-many, and many-to-many website translation tasks SNAT and DNAT. Due to the characteristics of translation, source URL translation is not required for packets that need to be translated from the destination URL, and vice versa. Therefore, in order to improve the efficiency of rewrite packets, during firewall operation, each Packet Only goes through this rule table once. If we define the packet filtering rule in this data table, it will cause the same packet to be unable to be compared multiple times. Therefore, this rule table is not translated as a URL, do not use it for other purposes.

Mangle this rule table has three rule refining rules: Prerouting, FORWARD, and postrouting.

In addition to modifying the packets for website translation, some special applications may have to rewrite the packet TTL and TOS) or set the MARK to MARK the packets for subsequent filtering ), in this case, the work must be defined in the mangle rule table. Because the usage is not high, we do not intend to discuss the mangle usage here.

The filter rule table is a preset rule table that has three rules: INPUT, FORWARD, and OUTPUT. As the name suggests, this rule table is used to filter packets. For example: DROP, LOG, ACCEPT, or REJECT), we will create the basic rules in this rule table.

List of Common commands:

Command-A, -- append

Example iptables-a input...

It indicates that a new rule is added to a Rule refining, And the rule will become the last rule in the Rule refining.

Command-D, -- delete

Example iptables-d input -- dport 80-j DROP

Iptables-d input 1

This indicates that a rule can be deleted from a rule refining process. You can enter a complete rule or directly specify a rule number to delete it.

Command-R, -- replace

Example iptables-r input 1-s 192.168.0.1-j DROP

It indicates that the current rule is replaced, and the order of the rule is not changed after it is replaced.

Command-I, -- insert

Example iptables-I INPUT 1 -- dport 80-j ACCEPT

It indicates that a rule is inserted. The rule at the specified position will move a forward position.

Command-L, -- list

Example iptables-L INPUT

Lists All rules in a rule.

Command-F, -- flush

Example iptables-F INPUT

Delete all rules in a rule refining.

Command-Z, -- zero

Example iptables-Z INPUT

This indicates that the packet counter is set to zero. The packet counter is used to calculate the number of occurrences of the same packet and is an indispensable tool for filtering block attacks.

Command-N, -- new-chain

Example iptables-N allowed

Define new rules.

Command-X, -- delete-chain

Example iptables-X allowed

Delete a rule.

Command-P, -- policy

Example iptables-P INPUT DROP

Define a filter policy. That is, the default Processing Method for packets that do not meet the filtering conditions.

Command-E, -- rename-chain

Example iptables-E allowed disallowed

Modifies the name of a custom rule.

Common packet comparison parameters:

Parameter-p, -- protocol

Example iptables-a input-p tcp

It indicates whether the communication protocol type is consistent and can be used! The operator performs reverse comparison, for example,-p! Tcp, which means other types except tcp, including udp, icmp, etc. If you want to compare all types, you can use the all keyword, for example,-p all.

Parameter-s, -- src, -- source

Example iptables-a input-s 192.168.1.1

The description is used to compare the source IP address of the packet. It can be compared to a single machine or network. When comparing the network, use a number to block it. For example,-s 192.168.0.0/24 can also be used to compare the IP address! The operator performs reverse comparison, for example,-s! 192.168.0.0/24.

Parameter-d, -- dst, -- destination

Example iptables-a input-d 192.168.1.1

Description used to compare the destination IP address of the packet. The setting method is the same as above.

Parameter-I, -- in-interface

Example iptables-a input-I eth0

The description is used to compare the network card from which the package enters. You can use wildcard character + to perform large-scale comparison. For example,-I eth + indicates all ethernet network cards. You can also use it! The operator performs reverse comparison, for example,-I! Eth0.

Parameter-o, -- out-interface

Example iptables-a forward-o eth0

Specifies the network card from which the packet is sent.

Parameter -- sport, -- source-port

Example iptables-a input-p tcp -- sport 22

It indicates that the source port number of the packet can be compared to a single port or a range, for example, -- sport 22: 80, indicating that the port from 22 to 80 is qualified, to compare multiple non-consecutive ports, you must use the -- multiport parameter. For more information, see the following section. You can use it when comparing the port number! The operator performs reverse comparison.

Parameter -- dport, -- destination-port

Example iptables-a input-p tcp -- dport 22

Description used to compare the destination port number of the package. The setting method is the same as above.

Parameter -- tcp-flags

Example iptables-p tcp -- tcp-flags SYN, FIN, ACK SYN

This section compares the status flag of TCP packets. The parameters are divided into two parts: the first part lists the flag to be compared, and the second part lists which of the aforementioned banners are set, the unenumerated flag must be empty. TCP status banners include: SYN sync), ACK response), FIN end), RST Reset), URG urgent), and PSH force push, in addition, you can use the keywords ALL and NONE for comparison. You can use it when comparing the banners! The operator performs reverse comparison.

Parameter -- syn

Example iptables-p tcp -- syn

The description is used to compare whether a TCP packet is online. It works exactly the same as iptables-p tcp -- tcp-flags SYN, FIN, and ack syn. If yes! The operator can be used to compare non-required online packets.

Parameter-m multiport -- source-port

Example iptables-a input-p tcp-m multiport -- source-port 80,110

The description is used to compare multiple source ports that are not consecutive. Up to 15 ports can be compared at a time. You can use this description! The operator performs reverse comparison.

Parameter-m multiport -- destination-port

Example iptables-a input-p tcp-m multiport -- destination-port 80,110

The description is used to compare non-consecutive destination port numbers. The setting method is the same as above.

Parameter-m multiport -- port

Example iptables-a input-p tcp-m multiport -- port 80,110

This parameter is special and used to compare packets with the same source port number and destination port number. The setting method is the same as above. Note: In this example, if the source port number is 80 but the destination port number is 110, this packet does not meet the condition.

Parameter -- icmp-type

Example iptables-a input-p icmp -- icmp-type 8

The description is used to compare the type numbers of ICMP. You can use code or number numbers for comparison. Please call iptables-p icmp -- help to check which code can be used.

Parameter-m limit -- limit

Example iptables-a input-m limit -- limit 3/hour

The description is used to compare the average traffic of packets within a certain period of time. The example above is used to compare whether the average traffic per hour exceeds three packets at a time. In addition to the average time per hour, it can also be an average time per second, every minute or every day. The default value is an average time per hour. parameters such as:/second,/minute,/day. In addition to comparing the number of packets, setting this parameter will also suspend the packet comparison when conditions are met to avoid service interruption due to the use of the flood attack method by hackers.

Parameter -- limit-burst

Example iptables-a input-m limit -- limit-burst 5

The description is used to compare the quantity of a large number of packets in an instant. The example above is used to compare whether the number of packets that flood in at a time exceeds 5. This is the default value). packets that exceed this limit will be discarded directly. The usage effect is the same as that.

Parameter-m mac -- mac-source

Example iptables-a input-m mac -- mac-source 00: 00: 00: 00: 01

The description is used to compare the hardware address of the packet source network interface. This parameter cannot be used in the OUTPUT and Postrouting rules refining. This is because the packet must be sent to the NIC, only when the NIC Driver detects the MAC address of the destination through the ARP communication protocol, iptables does not know the network interface to which the packet will be sent during packet comparison.

Parameter -- mark

Example iptables-t mangle-a input-m mark -- mark 1

The description is used to compare whether a number is indicated by a packet. When the packet is compared successfully, we can MARK a number through the MARK processing action. The maximum number cannot exceed 4294967296.

Parameter-m owner -- uid-owner

Example iptables-a output-m owner -- uid-owner 500

The description is used to compare the packets from the local machine and whether the packets are generated by a specific user. This prevents the server from transmitting sensitive data using root or other identities, and reduces the loss of system hacking. Unfortunately, this function cannot compare the packets from other hosts.

Parameter-m owner -- gid-owner

Example iptables-a output-m owner -- gid-owner 0

The description is used to compare whether the packets from the local machine are generated by a specific user group. The usage time is the same as above.

Parameter-m owner -- pid-owner

Example iptables-a output-m owner -- pid-owner 78

The description is used to compare the packets from the local machine and determine whether the packets are generated for a specific trip.

Parameter-m owner -- sid-owner

Example iptables-a output-m owner -- sid-owner 100

Indicates whether the response packet from the local machine is compared with a specific online Session ID.

Parameter-m state -- state

Example iptables-a input-m state -- state RELATED, ESTABLISHED

The description is used to compare the online status. There are four online statuses: INVALID, ESTABLISHED, NEW, and RELATED.

INVALID indicates the package's online number Session ID) cannot be identified or the number is incorrect.

ESTABLISHED indicates that the package belongs to a ESTABLISHED online network.

NEW indicates that the package wants to start with an online resetting or online redirection ).

RELATED indicates that the packet belongs to a newly established online host. For example, FTP-DATA online must be from an FTP online.

Common handling actions:

-The j parameter is used to specify the action to be processed. common actions include: ACCEPT, REJECT, DROP, REDIRECT, MASQUERADE, LOG, DNAT, SNAT, MIRROR, QUEUE, RETURN, and MARK are described as follows:

After the ACCEPT completes the processing, it will not compare other rules and directly jump to the next rule for nat: postrouting ).

REJECT blocks the packet and sends the packet to notify the other party. You can choose to transfer the packet: ICMP port-unreachable, ICMP echo-reply, or tcp-reset packets will require the other party to disable online). After this operation, the filtering program will not be directly interrupted after comparison with other rules. Example:

Iptables-a forward-p TCP -- dport 22-j REJECT -- reject-with tcp-reset

DROP discarded packets are not processed. After this operation, the filter program is directly interrupted instead of comparing other rules.

REDIRECT redirects the packet to another port PNAT). After this action is completed, it will continue to compare with other rules. This function can be used to implement transparent porxy or to protect web servers. For example, iptables-t nat-a prerouting-p tcp -- dport 80-j REDIRECT -- to-ports 8080

MASQUERADE changes the source IP address of the packet to the nic ip address of the firewall. You can specify the port range. After this operation is completed, directly jump to the next rule to refine mangle: postrouting ). This function is slightly different from SNAT. When you perform IP camouflage, you do not need to specify which IP address you want to disguise. The IP address will be directly read from the NIC. When you use a dial connection, the IP address is usually assigned by the DHCP server of the ISP company. In this case, MASQUERADE is particularly useful. Example:

Iptables-t nat-a postrouting-p TCP-j MASQUERADE -- to-ports 1024-31000

LOG records the packet-related information in/var/log. For detailed location information, see the/etc/syslog. conf configuration file. After this operation is completed, it will continue to compare with other rules. For example:

Iptables-a input-p tcp-j LOG -- log-prefix "INPUT packets"

SNAT modifies the source IP address of the packet to a specific IP address or IP address range. You can specify the port range. After this operation, it will directly jump to the next rule to refine mangle: postrouting ). Example:

Iptables-t nat-a postrouting-p tcp-o eth0-j SNAT -- to-source 194.236.50.155-194.236.50.160: 1024-32000

DNAT rewrite the IP address of the packet destination to a specific IP address or IP address range. You can specify the port range. After this operation, the system will directly jump to the next rule to refine the filter: input or filter: forward ). Example:

Iptables-t nat-a prerouting-p tcp-d 15.45.23.67 -- dport 80-j DNAT -- to-destination 192.168.1.1-192.168.1.10: 80-100

MIRROR package, that is, after the source IP address and the destination IP address are reversed, the package is sent back. After this operation, the filter program will be interrupted.

The QUEUE interrupt filtering program puts the packets into the QUEUE and submits them to other programs for processing. Other applications can be implemented through self-developed processing programs, such as calculating the online cost.

The RETURN statement ends with the filtering program in the current rule refining process. It returns the master rule refining to continue filtering. If you think of custom rule refining as a sub-program, this action is performed, it is equivalent to early completion of the subroutine and return to the main program.

MARK marks a code on the package to provide a judgment basis for the filter conditions. After this processing, the MARK will continue to compare with other rules. Example:

Iptables-t mangle-a prerouting-p tcp -- dport 22-j MARK -- set-mark 2


Related Article

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.