[转] Using iptables under Linux to implement package-consuming firewall

xiaoxiao2021-03-06  47

Using iptables under Linux to implement package-profound firewall

// from: http://kunming.cyberpolice.cn/aqjs/20008.html

BYE2000 Summary: This article introduces the principle and configuration of firewall tools in Linux2.4.x core, and also gives examples of practical use, and finally the IPTables and IPchains are summarized in the article. 1. Overview Starting from the 1.1 kernel, Linux has already had a package, and we use IPFWADM to operate the kernel package and exert rules in the kernel of 2.0. In the 2.2 kernel, you have used IPChains that everyone is not strange to control the rules of the kernel package. The latest Linux kernel version is now 2.4.1, we no longer use ipchains in the 2.4 kernel, but use a new core package management tool - Iptables. This new core package will make users easier to understand their working principles, and it is more likely to be used, and will of course have more powerful functions. We said that iptables is just a tool for managing kernel packages, iptables can join, insert or delete rules in the core package filtering table (chain). It is actually true to implement these tax rules is Netfilter (a general architecture in Linux core) and its related modules (such as IPTables modules and NAT modules). Let's take a look at Netfilter's working principle. Second, the principle Netfilter is a general architecture in the Linux core. It provides a series of "tables" (Tables), each of which is composed of several "chain", and one or several rules can be included in each chain. (rule). We can understand this, Netfilter is the container of the table, the table is the container of the chain, and the chain is the container of the rule (as shown in Figure 1). [img] http://www.linuxAid.net.cn/Engineer/bye2000/Images/iptables/iptables1.gif []] The default table "filter", which contains INPUT, Forward and Output 3 chains. There can be one or several rules in each chain, each of which is defined as "If the data packet header meets such conditions, this data package is processed". When a packet reaches a chain, the system starts checking from the first rule to see if the conditions defined by this rule: If satisfaction, the system will process the data package according to the method defined by the rule; if not The satisfaction continues to check the next rule. Finally, if the data packet does not meet any of the rules in the chain, the system will process the packet based on the first defined policy (POLICY). [img] http://www.linuxAid.net.cn/Engineer/bye2000/Images/iptables/iptables2.gif [/ img] The process in the FILTER table is shown in Figure 2. When there is a packet to enter the system, the system first determines which chain to send the data package according to the routing table, there may be three cases: 1. If the destination address of the packet is this machine, the system is sent to the Input chain. If the package is passed through the rule check, the package is sent to the corresponding local process; if it is not checked, the system will lose this package; 2. If the address of the packet is not a native, that is, this package will Forward, the system is sent to the Forward chain. If the package is passed through the rule check; if you do not pass the rules, the system will lose this package. 3. If the packet is By the local system process, the system is sent to the OUTPUT chain. If the package is checked, the package is sent to the corresponding local process; if it is not checked, the system will lose this package.

From the above we can see that Netfilter has clearly made a lot more than the previous IPFWADM and Ipchains idea, which is undoubtedly a gospel for users who originally felt a mist to Ipfwadm and Ipchains. Third, preparations 1. System requirements Netfilter require the kernel version not less than 2.3.5, when compiling new kernels, require selection and NetFilter-related projects. These items are usually located under "NetWorking Options" subples. Take the 2.4.0 core as an example, we should select the items: kernel / user netlink socket [] routing message <*> NetLink Device Emulation Network Packet Filtering (Replace Ipchains) ....... then in "IP: Netfilter Configuration ----> "select: Connection tracking (required for masq / NAT) FTP protocol support IP tables support (required for filtering / masq / NAT) limit match support MAC address match support Netfilter MARK match support Multiple port match support TOS match support Connection state match support Packet filtering REJECT target support Full NAT MASQUERADE target support REDIRECT target support Packet mangling TOS target support MARK target support LOG target support ipchains (2.2-style) support ipfwadm (2.0-style) support The last two items can Not selected, but if you compare ipchains or ipfwadm, you can also select it in the 2.4 core to use ipchians or ipfwadm. However, it should be noted that iptables is relatively opposed to IPCHIANS / IPFWADM, while using iptables while using ipchains / ipfwadm at the same time. After the compilation is successful, these module files are located in the following directory /Lib/Modules/2.4.0/kernel/net/ipv4/netfilter Compile 2.4.0 new kernel should be given to "Processor Type and Features" to select and Your CPU corresponds to the correct CPU option, otherwise the new kernel may not work properly. 2. Loading modules To use iptables, you must also load related modules. You can use the following command to load related modules: #MODPROBE iptable_tables modprobe command automatically loads the specified module and its related modules. The iptables_filter module is automatically loaded at runtime. Third, grammar 1. Establish a new chain (-n) on the operation of the chain. Delete an empty chain (-X). Change the principle of an internal chain (-P). List rules (-L) in a chain. Clear all rules (-f) in a chain. Zero (ZERO) Packing byte (BYTE) (-Z) in a chain. 2. A new rule to a new rule to a chain (-A) for the operation of the rule. Insert a new rule (-i) in the chain, usually inserted to the front. Replace a rule (-R) in a location in the chain.

Remove a rule (-d) in a location in the chain. Delete the first rule (-d) in the DELETE. 3. Specify the source address and destination address to specify the source address (here / indicated or meaning here, the same), and specify the purpose by -dstination / - dst / -s. address. You can use the following four methods to specify an IP address: a. Use a complete domain name, such as "www.linuxaid.com.cn"; b. Use the IP address, such as "192.168.1.1"; c. Specify one with xxxx / xxxx Network address, such as "192.168.1.0"; d. Specify a network address with xxxx / x, such as "192.168.1.0/24" here 24 indicates the effective number of bits of subnet mask, this is UNIX A representation of the representation of the environment in the environment. The default subnet mask is 32, that is, designated 192.168.1.1 is equivalent to 192.168.1.1/32. 4. The specified protocol can specify the protocol, such as the -p TCP via the -Protocol / -p option. 5. Specify the network interface to specify the network interface using -in-interface / -i or -out-interface / -O. It should be noted that for the INPUT chain, it may only have -i, that is, there will be accessible packages; the pendant, for the Output chain, only may have -O, which will only have a package. Only the Forward chain can have both the -i network interface, or there is a -o network interface. We can also specify a network interface that is currently not present, such as PPP0, which is only valid after the dial is successful. 6. Specify IP Debris In the TCP / IP communication process, each network interface has a maximum transmission unit (MTU), which defines the maximum size of the packet that can pass. If a packet is greater than this parameter value, it is divided into smaller numerous packets (called IP debris) to transmit, and the recipient will reorganize these IP fragments to restore the entire package. However, when the package is filtered, IP debris can cause such a problem: When the system is divided into IP fragment transfer, the first fragment contains complete cladding information, but subsequent fragments have only partial information of the header, such as Source address, destination address. Therefore, if we have such a rule: iptables -a forward -p tcp -s 192.168.1.0/24 -d 192.168.2.100 - DPORT 80 -J Accept and the policy of Forward is only DROP, the system is only The first IP fragment will pass, and the rest of the IP fragments, because the first fragment contains complete header information, which can meet the conditions of this rule, and the remaining fragments cannot meet the rules defined because the header information is incomplete. Therefore, it is impossible to pass. We can specify the second and future IP fragments through the -fragment / -f option. For example, as an example above, we can add such a rule to solve this problem: iptables -a forward -f - S 192.168.1.0/24 -d 192.168.2.100 -j Accept But it should be noted that there are now many instances of IP fragment attacks (such as sending a large number of IP debris to Win98 NT4 / SP5, 6 Win2k), Therefore, IP debris is allowed to pass by security risks. For this point we can use iptables match extensions, but this will affect the quality of service, we will discuss this problem below.

7. Specify that you can add a non-specified value before some options, such as "-s -! 192.168.1.1/32" means that in addition to the IP address other than 192.168.1.1, "- p -! Tcp" means except A protocol other than TCP. 8. TCP matching Extensions By using the -TCP-Flags option, the TCP-Flags option can be filtered according to the flag of the TCP package. This option is connected to two parameters: the first parameter is the flag to check, can be SYN, ACK, FIN, RST, URG, PSH combination, can specify all flags with all; the second parameter is a flag of the flag bit value 1. For example, if you want to filter out all the TCP packages of all SYN flags, you can use the following rules: iptables -a forward -p tcp --tcp-flags all syn -j drop option - Syn is a special case, quite Simply written on "--TCP-Flags Syn, RST, ACK SYN". 9. MAC matching extension You can use the -m option to extend matching content. Using -Match Mac / -M MAC matching extension can be used to check the source MAC address of the IP packet. Just keep up with the MAC address after - Mac-Source. For example: iptables -a forward -m mac - Mac-Source 00: 00: Ba: A5: 7D: 12 -J DROP Need to note is that after the router is forwarded, its source MAC address has become router MAC address. 10. LIMIT matching extension LIMIT extension is a very useful matching extension. Use -m NAT to specify, thereafter there will be two options: --Limit AVG: Specify the number of packets allowed within the unit time. The unit time can be / second, / minute, / hour, / day, or the first letter, such as 5 / second, and 5 / s, are the default value, the default value is the 5 packets per second. 3 / hour. --Limit-Burst Number: Specifies the threshold of the trigger event, the default value is 5. It seems that it seems a bit complicated, let us see an example: assumptions and the following rules: iptables -a input -p icmp -m limited --LIMIT 6 / M --LIMIT-BURST 5 -J Accept iptables -p Input Drop Then from another host PING this host, the following phenomenon: First, we can see that the response of the first four packs is normal, then start from the fifth package, we can receive one every 10 seconds. Normal response. This is because we set the number of packets allowed by the unit time (here every minute), which is 6, which is one minute, which is one minute; after we set the event trigger threshold 5, so our top four packs are normal, just starting from the fifth package, the restriction rules begin to take effect, so they can only receive a normal response every 10 seconds. Suppose we stop ping, starting ping after 30 seconds, at this time, the first two packs are normal, start packet from the third package, because I am here to allow a package to pass the cycle 10 Seconds, if the system does not receive the eligible package in one cycle, the system's trigger value will restore 1, so if we do not meet the conditions within 30 seconds, the trigger value of the system will return to 3, if 5 There is no eligible package in a period, and the system is triggered to recover. I don't know if you understand, you are welcome to discuss.

11. LOG Ontario expansion Netfilter default goals (that is, once the system is met, the system's processing method for packets) is: aceept: Receive and forwarding the packet DORP: Drop the packet target extension module provides an extension target. The LOG target provides the ability to record the packet. This target extension has the following parameters: --Log-level: Specifies the level of the record information, and the levels of Debug, Info, NOTICE, WARNING, ERR, Crit, Alert, and Emerg correspond to the number of 7 to 0. It is, please refer to the MAN manual of syslog.conf. --Log-prefix: After connecting a string that is up to 30 characters, the string will appear in front of each log. 12. Reject Goal Extension This target extension is completely in the DORP standard goal, in addition to returning to the sender's ICMP information of "port unreachable". There are other extensions are common, if you want to know you can refer to Packet-filtering-howto. Of course, the most direct acquisition method is to view the online help of iptables. For example, you want to get the "iptables -m mac -help" command to get the "iptables -m mac -help" command, you want to get the help target extension can be executed "iptables -j log -help "command. Fourth, IPTables use instances first let us take a look at the interaction of the server / client. Server provides a particular functional service is always provided by a specific background program. This particular service is often bound to a specific TCP or UDP port in the TCP / IP network. Thereafter, the background program is constantly listening to this port. Once the eligible client request is received, the service is set up with the client with the client, responding to the customer request. At the same time, a copy of the binding copy is generated to continue to listen to the client's request. To give a specific example: Suppose there is a server A (IP address is 1.1.1.1) in the network provides WWW services, and also client B (2.2.2.2), C (3.3.3.3). First, the server A runs a background program (such as Apache) that provides the WWW service and binds the service to port 80, that is, listens on port 80. When b is initiated, B will open a connection port greater than 1024 (1024 for a defined port), assuming 1037. A After receiving the request, establish a connection with B with B to respond to the request of B, while generating a copy of an 80-port binding, continuing to listen to the client's request. If a concurrent connection request (set up the connection request port is 1071), a request to continue listening to the client at the same time as the connection is established with the C. As shown below, because the system is identified by the source address, source port, destination address, destination port, which is unique here. Server client connection 1: ABC1: 80 <=> ABC4: 1037 Connection 2: ABC1: 80 <=> ABC7: 1071 Every specific service has its own specific port, which is generally less than 1024 The port is mostly reserved, or the port is defined, the low-port assigned to well-known services (such as WWW, FTP, etc.), from 512 to 1024 ports typically reserve to special UNIX TCP / IP applications, please Reference / etc / service file or RFC1700.

Suppose the network environment is as follows: one unit, rent DDN line online, the network topology is as follows: ------------ | Internal network segment | Eth1 ------ Eth0 DDN | ------------ | firewall | <============================ 198.168.80.0 | -------- -------------- Eth0: 198.199.37.254 Eth1: 198.168.80.254 The above IP address is the true IP on the Internet, so IP spoof is not used. And, we assume that there is the following servers in the internal network: www.yourdomain.com 198.168.80.11 FTP server: ftp.yourdomain.com 198.168.80.12 Email Server: mail.yourdomain.com 198.168.80.13 Let's use iptables Step step by step to build our package filter firewall, it is necessary to explain that in this example, we are mainly to protect the internal servers. 1. Create a firewall file with the touch command in the /etc/rc.d/ directory, execute the CHMOD U X Firewll to change the file properties, edit the /etc/rc.d/rc.local file, plus / etc / Rc.D / firewall can be automatically executed when it is turned on. 2. Refresh the rules of all chains #! / Bin / sh echo "Starting iptables rules ..." #Refresh All chains / sbin / iptables -f 3. We will first prohibit forwarding any packages, then set step by step to allow pass Pack. So first set the firewall Forward chain policy for Drop: / sbin / iptables -p Forward DROP 4. Setting up the enuters of the server: It should be noted here that the server / client interaction is available, that is Said to be two-way, so we don't just set the rules of the packet, but also set the rules returned by the packet, we first build a rule for confidence from the Internet packet. WWW service: The service port is 80, using TCP or UDP protocol. The rules are: eth0 => Allow the purpose of the Package of the internal network WWW server. #################### DEFINE HTTP PACKETS ######################## ################ #allow www request packets from internet cliants to www servers / sbin / iptables -a forward -p TCP -D 198.168.80.11 --dport www -i eth0 - J Accations FTP Service: The FTP service is a bit special because two ports are required because the FTP has command channels and data channels.

The command port is 21, the data port is 20, and there are active and negative two service modes. The negative mode connection process is: the FTP client initiates a connection request to the FTP server, and the command channel is established after three steps, then build the command channel, then by FTP The server requests to establish a data channel. After successful, the data is started, and most FTP clients are now supporting negative mode because this model can improve security. The FTP service uses the TCP protocol. Rules is: eth0 => Allows only the purpose of the internal network FTP server. ########################################################################################################################################################################################################################################################################################################## ################### #allow ftp request packets from internet clients to intranet ftp server / sbin / iptables -a forward -p tcp -d 198.168.80.12 --dport ftp - I ETH0 -J Accept Email Service: Contains two protocols, one is SMTP, one is POP3. For security considerations, only the internal POP3 services are usually provided, so we only consider the security issues for SMTP. The SMTP port is 21 and the TCP protocol is adopted. Eth0 => Allows only the purpose of the EMAIL server's SMTP request. #################### d d SMTP Packets ####################### ################ / sbin / iptables -a forward -p tcp -d 198.168.80.13 --dport smtp -i eth0 -j accept 5. Setting up confidence for intranet customers : In this example, our firewall is located in the gateway, so we mainly prevent attacks from Internet and cannot prevent attacks from Intranet. If our server is Linux, you can also set up relevant tax rules on each server to prevent attacks from intranet. We define the following rules for the Intranet customer's return package. ############# Define Packets from Internet Server to intranet ####################### / sbin / iptables -a forward -p TCP -S 0/0 --Sport ftp-data -d 198.168.80.0/24 -i eth0 -j accept / sbin / iptables -a forward -p tcp -d 198.168.80.0/24! -syn -i eth0 -j accept / sbin / iptables -a forward -p UDP -D 198.168.80.0/24 -i eth0 -j accept Description: Article 1 Allow intranet customers to access the Internet's FTP server in a negative mode; the second receiving from Internet Non-connection requests TCP package; the last one receives all UDP packages, mainly for the use of UDPs such as idiochemia.

6. Accept the data package from the entire intranet, we define the following rules: ################################################################################################################################################################################################################################################################ ## / sbin / iptables -a forward -s 198.168.80.0/24 -i eth1 -j accept 7. Processing IP debris We accept all IP debris, but use LIMIT matching extension to the number of IP pieces that can pass through the unit time Restrictions to prevent IP debris attacks. ######################################################################################################################################################################################################################################################################################################## #################### / sbin / iptables -a forward -f -m limit --LIMIT 100 / s --LIMIT-BURST 100 -J ACCEPT Description: No matter where IP debris is limited, it is allowed to pass 100 IP debris per second, which is 100 IP debris. 8. Setting the ICMP package filter ICMP package is usually used for network testing, so all ICMP packages are allowed. However, hackers often use ICMP to attack, such as ping of death, so we use LIMIT matching extensions to limit: ########################### ###### DEFINE ICMP RULE ################################################# -p icmp -m limit --limit 1 / s --limit-burst 10 -j accept description: Regarding the ICMP package from where to do, allow each second to pass a package, the condition triggering condition is 10 packs . Through the above steps, we have established a relatively complete firewall. Only a limited number of ports are only open, and the customer provides a seamless access to the Internet, and provides effective protection for IP debris attacks and ICMP Ping of Death.

The following is the complete script file content, I hope to pass this instance to understand the usage of iptables: #! / Bin / sh echo "Starting iptables rules ..." #Refresh all chains / sbin / iptables -f ### ######################################################################################################################################################################################################################################################################################################## ############# #allow www required packets from internet clients to www servers / sbin / iptables -a forward -p tcp -d 198.168.80.11 --dport www - e0 -j accept # #################### d f FTP Packets ###################################### ################# orthol / iptables -a forward -p tcp -d 198.168.80.12 --dport ftp -i Eth0 -j accept #################### DEFINE SMTP PACKETS ################ ################################################################################################################# ######## Define packets from Internet server to intranet ##################################### 0/0 --sport ftp-data -d 198.168.80.0/24 -i eth0 -j accept / sbin / iptables -a forward -p TCP -D 198.168.80.0/24! -Syn -i Eth0 -j accept / sbin / iptables -a forward -p UDP -D 198.168.80.0/24 -i eth0 -j accept ######################################################################################################################################################################## ########### / sbin / iptables -a forward -s 198.168.80.0/24 -i eth1 -j accept ####################### ############## DEFINE FREGMENT RULE ############################################################################################################################################################################################################################################################################# # / sbin / iptables -a forward -f -m limited --LIMIT 100 / s --LIMIT-BURST 100 -J Accept ################################################################################################################################################################################################################################################################ ########### Define ICMP rule ################################################################ / iptables -a forward -p ICMP -M LIMIT --LIMIT 1 / S --LIMIT-BURST 10 -J Accept 5. Iptables and ipchains 'distinguishing · iptables' default chains name from lower-write to uppercase, and meaning Then the same: INPUT and OUTPUT are placed on the destination address, respectively, and the data packets issued by this unit. · -I option only represents the input network interface, and enter the network interface, use the -o option.

转载请注明原文地址:https://www.9cbs.com/read-79996.html

New Post(0)