Iptables-1.1.9 Guide (Super Classic)
Iptables Guide 1.1.19 Oskar Andreasson Blueflux@koffein.net CopyRight © 2001-2003 by OSKAR Andreasson This article can copy, distribute, change, but must retain the general words and all chapters, such as Printing books, covering covers include "Out of Oskar Andreasson, and the book is not allowed to have text. This article has a detailed content of "GNU Free Documentation License". All scripts in the article are all in GNU General Public License 2, which can be freely distributed and changed. These scripts are given to see them, but there is no guarantee, and there is no commercial availability or the inner guarantee of certain special purposes. See GNU General Public License This article comes with a GNU General Public License, in the chapter "GNU Free Documentation License", if not, please contact The Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0211- 1307 Usa first, I want to give this document to my wonderful girlfriend Ninel (she gives me the help far better than I gave her): I hope I can let you be happy, just like you give me. (Translator Note: I didn't think of the right words to express the author's girlfriend's Wonderful, you want to go. Also, I don't know if they are married :)) Second, I have to dedicate this article to all Linux. Developers and maintainers are that they have completed unable to believe in hard work, making such excellent operating systems.
Directory translator's order about how the author reads the necessary knowledge This article is agreed 1. Prior art 1.1. Why should I write this guide 1.2. How to write 1.3. Terminal appears in article 2. Preparation stage 2.2. Core configuration 2.3. Compilation 2.3.2. Compile 2.3.2. Install 3. Table and Chain 3.1 on Red Hat 7.1. Overview 3.2. Mangle Table 3.3. NAT Table 3.4. Filter Table 4. State Mechanism 4.1. Overview 4.2. Concentrack Record 4.3. Packet in the user space status 4.4. TCP connection 4.5. UDP connection 4.6. ICMP connection 4.7. Default connection operation 4.8. Complex protocol and connection tracking 5. Save and recover data management rules 5.1. Speed 5.2. Restore The deficiency is 5.3. Iptables-save 5.4. Iptables-Restore 6. How to practice 6.1. Basis 6.2. TABLES 6.3. Commands 6.4.1. Matches 6.4.1. Generic Match 6.4.2. Implicit Match 6.4.3 Explicitly matched 6.4.4. Matching 6.5. Targets / Jumps 6.5.1. DNAT Target 6.5.3. Drop target 6.5.3. DROP TARGET 6.5.4. Log target 6.5.5. Mark Target 6.5.5. Mark Target 6.5 .6. Masquerade target 6.5.7. Mirror Target 6.5.8. Queue Target 6.5.9. Redirect target 6.5.10. Reject target 6.5.11. Return Target 6.5.12. Snat target 6.5.13. TOS Target 6.5.14 TTL Target 6.5.15. Ulog Target 7. Firewall Configuration Instance Rc.fireWall 7.1. About Rc.FireWall 7.2. Rc.FireWall Detailed 7.2.1. Parameter Configuration 7.2.2. External Module Load 7.2.3. PROC Settings 7.2.4. Optimization of the rules 7.2.5. Default policy setting 7.2.6. Setting 7.2.7. I. I NPUT chain 7.2.8. Forward chain 7.2.9. Output chain 7.2.2.10. Preloading chain 7.2.11. PostRouting Chain 8. Example Introduction 8.1. Rc.firewall.txt Script Structure 8.1. Script Structure 8.2. Rc. Firewall.txt 8.3. rc.dmz.firewall.txt 8.4. rc.dhcp.firewall.txt 8.5. rc.utin.firewall.txt 8.6. rc.test-iptables.txt 8.7. rc.flush-iptables.txt 8.8. Limit-match.txt 8.9. Pid-owner.txt 8.11. Sid-owner.txt 8.11. TTL-Inc.txt 8.12. Iptables-save ruleset A. Common commands A.1. View the command of the current rule set A.2 Correct and empty iptables command B. Frequently Asked Questions on and answer B.1. Module load problem B.2. SYN's new status package B.3. New status SYN / ACK package B.4. Use private IP Address ISP B.5. Pretine DHCP Data B.6. About MIRC DCC issues C. ICMP Type D. Other Resources and Links E. Acknowledgments F. History G. GNU Free Documentation License 0. Preamble 1. Applicability and Definitions 2 Verbatim Copying 3. Copying in Quantity 4. MODIFICATIONS 5. Combining Documents 6. Colining
LECTIONS OF DOCUMENTS 7. AGGREGATION WITH INDEPENDENT WORKS 8. TRANSLATION 9. TERMINATION 10. FUTURE REVISIONS OF THIS LICENSE How to use this License for your documents H. GNU General Public License 0. Preamble 1. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 2. How to Apply these Terms to your new program I. Sample script code I.1. Rc.firewall script code I.2. Rc.dmz.firewall script code I.3. Rc.utin.firewall script code I. 4. rc.dhcp.firewall script code I.5. Rc.flush-iptables script code I.6. Rc.test-iptables script code List of Tables 3-1. Local-oriented target (that is our own machine) Pack 3-2. Take the local source package 3-3. The forwarded package 4-1. Packet in the user space status 4-2. Internal state 6-1. TABLES 6-2. Commands 6-3 ....................................................... .. MULTIPORT MATCH OPTION 6-12. Owner Match Options 6-13. State Matches 6-14. TTL Matches 6-16. DNAT Target 6-17. Log target Options 6-18. Mark Target Options 6 -19. Masquerade Target 6-20. Redirect Target 6-21. REJECT TARGET 6-23. TS TARGET 6-24. TTL Target 6-25. Ulog Target C-1. ICMP Type Translator SLLSCN is the "Linux Fresh Society" in China Linux Commune, A Linux enthusiast, when using iptables to construct a firewall in actual work, found that there is too little Chinese data about iptables, so you must not refer to the English version of the material. For the convenience of the future, in order to make the user, he is not afraid that his English is too bad, and the dictionary translated this article. Translation is only to understand, you can't reach "good-looking", don't weird! The first chapter preamble part except the terminology introduced in the third section, there is nothing else. The second chapter is some help from the brothers who want to compile iptables yourself. Third, the fourth chapter can make us understand, master the IPTables working methods and processes. Chapter 5 and Chapter 6 are a detailed description of the use of iptables commands. Chapter VII and Chapter VII are explained in an instance, which is very guiding for our rules to write their own rules. It is strongly recommended that you look at it. There are some resource links in the appendix to be very good, I believe you will like it. Because of the term of the term, the directory part has some unrelated translation, but the content of the text is translated. Appendix F is the update history of this article. Appendix G is GNU Free Documentation License, and Appendix H is GNU General Public License, which does not have any effects that IPTables does not work, so it is not translated. When reading this article,
You may find a replicated place, this is not the original level of the original, but it is precisely what he considers us. You can take out any chapter of this article to read, without having to repeatedly refer to other chapters. Here, I will pay tribute to the author again! Due to the limited level of translator, the understanding of the original text does not dare to ensure that it is completely correct. If there is any opinion or suggestion, you can contact the translator slcl@sohu.com solemnly statement: Translate Get the author Oskar Andreasson license. For this article (not original), free use, modification, dissemination, reprint, but use all rights to use by profitability. About the author I have a lot of "old" computers in my LAN, they also want to connect to the Internet, but also guarantee safety. Do this, iptables is a good upgrade of Ipchains. Use ipchains to create a secure network by discarding all "destination ports are not specific ports" bags. But this will result in problems with some services, such as passive FTP, and DCC flowing out in IRC. They allocate ports on the server and inform the client, and then let the customer join. However, there are also some small problems in iptables, in some respects I found that these code did not prepare for the full product release, but I still recommend the use of Ipchains or older IPFWADMs to upgrade, unless they are The code is satisfied with the code, or they are sufficient to meet their needs. How to read this article This article describes the iptables so you can understand the wonderful iptables, which does not contain iptables or NetFilter in security BUG. If you find any bug or special behavior, contact Netfilter Mailing Lists, they will tell you whether it is bug or how to solve it. There is almost no security bug in iptables or NetFilter, of course, occasionally there will be some problems, they can be found in the NetFilter home page. The script used in the article cannot solve the bug within Netfilter, give them, just to demonstrate how to construct the rules so that we can solve the problem of data stream management. However, this article does not include "how to turn off the HTTP port, because Apache 1.2.12 occasionally attacks" such a problem. This guide will tell you how to close the HTTP port via iptables, but because Apache occasionally attacks. This article is suitable for beginners, but it is also perfect as much as possible. Because there are too many Targets or Matches, there is not fully included. If you need this information, you can access the Netfilter home page. The necessary knowledge is reading this article, there are some basic knowledge, such as Linux / UNIX, Shell scripts, kernel compilation, preferably there are some simple kernel knowledge. I tried to make the reader don't need these knowledge, but I understand that the extension is not possible. So still have a bit base :) This article will be appointed below the following: * Code and command output use a wide font, command to use bold. [Blueflux @ Work1 Neigh] $ LS Default Eth0 Lo [Blueflux @ Work1 Neigh] $ * All commands and program names are bold. * All system components such as hardware, kernel components, loopback uses a bevel. * Computer text outputs this font. * File name and path attorney like this / usr / local / bin / iptables. 1. Preface 1.1. Why?
To write this guide I found that all HOWTOs still lack information about iptables and NetFilter functions in the Linux 2.4.x kernel, so I tried to answer some questions, such as status matching. I will explain with illustrations and example rc.firewall.txt, where the example can be used in your /etc/rc.d/. Initially, this article is written in the form of a HOWTO document, because many people only accept howto documents. There is also a small script rc.flush-iptables.txt, I wrote it just to make you feel like I am as successful when you configure it. 1.2. How is the guide written I asked other core members of the Marc Boucher and Netfilter team. For their work and help me writing this guide for BoingWorld.com, this guide is now maintained on my own site. Frozentux.net. This document will teach you a stepup process step by step, so you have more understanding of the iptables package. This majority is based on an example rc.firewall file, because I found this is a good way to learn iptables. I decided to follow the rc.firewall files down to learn iptables. Although this will be difficult, but more logical. When you encounter something you don't understand, you will check this file. 1.3. The terms in the article contain some terms, you should have something to know. Here are some explanations and explain how to use them herein. DNAT - Destination Network Address Translation Destination Network Address Transformation. DNAT is a technique of changing the IP address of the data package, often couples with SNAT to allow multiple servers to share an IP address into the Internet and continue to serve. Decide the flow of the data by assigning different ports to the same IP address. The stream - stream refers to a connection between the two parties of the transmitting and reception of packets and communication (the translator Note: In this article, the author regards the connection as a one-way, stream represents the two-way connection). In general, this term is used to describe the connection between two or three packets in both directions. For TCP, the stream is meaningful, it sends a SYN and then replying to SYN / ACK. However, it may also refer to such a connection, send a SYN, and the ICMP host is not accessible. In other words, I am very casual with this word. Snat - Source Network Address Translation Source Network Address Transformation. This is a technique for changing the data package source IP address, often used to make multiple computers to share an Internet address. This is only used in IPv4 because IPv4's address is running quickly, and IPv6 will solve this problem. State - Status Indicates what state is in the packet. Status is defined in RFC 793 - Transmission Control Protocol or is customized by the user in Netfilter / iptables. It should be noted that NetFilter sets some states about the connection and packets, but not fully use the definition of RFC 793. User Space - user space, refers to anything that is outside the kernel or outside the kernel. For example, calling iptables -h occurs outside the kernel, but iptables -a forward -p tcp -j accept (partially) occurs inside the kernel, as a new rule joins the rule set. KERNEL SPACE - kernel space, relative to user space, refers to the internal nuclear interior. Userland - See User Space Target - This word has a lot of applications in the following text, which indicates the operation of the matching packet. 2. Preparation stage This chapter is to learn the beginning of iptables, it will help you understand Netfilter and IPTA
Bles played in Linux. It will tell you how to configure, install firewalls, your experience will grow. Of course, if you want to achieve your goal, it takes time, but also perseverance. (Translator Note: It sounds very scary :)) 2.1. Where can IPtables iptables can be downloaded from www.netfilter.org, and the FAQs in the website is also a good tutorial. Iptables also uses some kernel space, which can be configured in the process of configuring the kernel with make configure, and the necessary steps will be described below. 2.2. Kernel Configuration To run iptables, the kernel configuration needs to select the following options during kernel configuration, whether you use make config or other commands. Config_packet - Allows the program to access network devices directly (Translator Note: The most commonly used NIC), like TCPDUMP and SNORT to use this feature. Note Strictly speaking, iptables do not need config_packet, but it has a lot of use (translator Note: other programs need), so it is selected. Of course, you don't want, you don't choose. (Translator Note: It is recommended or selected as a good) config_netfilter - Allows the computer to be used as a gateway or firewall. This is required because the entire article is used to use this feature. I think you also need this, who told you to learn iptables :) Of course, you have to install the correct driver to the network device, such as the ethernet network card, PPP has SLIP. The above options are just a framework in the kernel, and iptables do already run, but you can't do any substantive work. We need more options. The following is given below and a simple description: config_ip_nf_conntrack - connection tracking module, used for NAT (network address translation) and Masquerading (IP address camouflage), of course, there are other applications. If you want a machine in the LAN as a firewall, this module is right. Script rc.firewall.txt To work properly, you must have its existence. CONFIG_IP_NF_FTP - This option provides a function of connecting to the FTP connection. Under normal circumstances, it is difficult to connect to the FTP connection. To do this, you need a dynamic link library called Helper. This option is used to compile Helper. If there is no such function, you cannot use FTP through the firewall or gateway. CONFIG_IP_NF_IPTABLES - With it, you can use filter, camouflage, NAT. It joined the iptables identification framework for the kernel. Without it, iptables have no effect. CONFIG_IP_NF_MATCH_LIMIT - This module is not very necessary, but I am used in an example rc.firewall.txt. It provides features that match the Limit to facilitate the use of an appropriate rule to control the number of packets to match each minute. For example, the effect of -m limit --limit 3 / minute is up to three packets per minute. This feature can also be used to eliminate some kind of DOS attack. CONFIG_IP_NF_MATCH_MAC - Select this module to match the packet according to the MAC address. For example, we want to block a packet of some MAC addresses, or block communication with some computers, it is easy. Because each Ethernet network card has its own MAC address, it is almost never changed. But I am in rc.firewall.
This feature is used in txt, and other examples are not used. (Translator Note: This turns out that learning is to play the foundation for future :)) config_ip_nf_match_mark - this option is used to mark the packet. Mark the data package, we can match the packet with this tag in the table below. There is a detailed description thereof. CONFIG_IP_NF_MATCH_MULTIPORT - Select this module We can use the port range to match the packet, without it, it is unable to do this. CONFIG_IP_NF_MATCH_TOS - allows us to set the TOS (Type of Service service type) of the packet. This job can also be done with the command IP / TC, and you can set it with a rule in the mangle table. Config_ip_nf_match_tcpmss - can match TCP packets based on MSS. CONFIG_IP_NF_MATCH_STATE - Compare IPChains This is the biggest update, with it, we can match the status of the packet. For example, there is already a communication in two directions of a TCP connection, and the packet on this connection is considered as an Establish state. The functionality of this module is used in rc.firewall.txt. Config_ip_nf_match_unclean - Match P, TCP, UDP, ICMP packets that do not meet the type standard or invalid (Translator Note: This module is named unclean, which can be understood that any package that is not correct mode is dirty. This is some With the "dirty page" in operating system memory management, here can be called "dirty", nature is also unclean). We generally discard such a package, but I don't know if this is correct. Also note that this matching function is still in the experimental phase, there may be some problems. Config_ip_nf_match_owner - matches the packet based on the owner of the socket. For example, we only allow root to access the Internet. In iptables, this module initially only uses an example to explain its function. Similarly, this module is also in the experimental stage and cannot be used. CONFIG_IP_NF_FILTER - This module adds a basic filtering table for iptables, which contains input, forward, output chains. Full IP filtering can be made through a filter table. As long as you want to filter packets, whether it is received or sent, this module is required no matter what to do. Config_ip_nf_target_reject - This action allows us to respond to the received packet with ICMP error message, not simply discard it. Some situations must have respond, for example, to reset or reject TCP connections relative to ICMP and UDP always require a TCP RST package. CONFIG_IP_NF_TARGET_MIRROR - This action returns the packet to the computer sent. For example, we set the mirror operation on the packet for the destination port in the INPUT chain. When someone accesses HTTP, the package is sent back to the original computer, and finally, he visited may be his own home page. (Translator Note: It should not be difficult to understand why Mirror) config_ip_nf_nat - as the name suggests, this module provides NAT function. This option allows us to access the NAT table. Port forwarding and camouflage is required for this module. Of course, if all computers in your LAN have a unique valid IP address, there is no need to do this when doing firewalls or camouflage. Rc.fireWall.txt is required :) config_ip_nf_target_masquerade - provide M
Asquerade operation. If we don't know IP to connect Internet, the preferred method is to use Masquerade, not DNAT or SNAT. In other words, if we use PPP or SLIP, IP, allocate IP by DHCP or other services, and use this better than SNAT. Because Masquerade does not need to know the IP connected to the Internet, although Masquerade is slightly higher than the NAT load for your computer. CONFIG_IP_NF_TARGET_REDIRECT - This operation is useful for use with the agent. It does not allow the packet to pass directly, but re-mapped the package to the local host, which is to complete the transparent agent. CONFIG_IP_NF_TARGET_LOG - Add log (log) operation for iptables. Through it, you can use the system log service to record certain packets so that we can understand what happened on the bag. This is invalvible for us to do safety reviews and debug scripts. Config_ip_nf_target_tcpmss - This option can deal with some ISP (service providers) or services that block ICMP segmentation information. There is no ICMP segmentation information, some webpages, big emails cannot be passed, although small mail can, and after the handshake is completed, SSH can but SCP cannot work. We can solve this problem with TCPMSS, which is to make MSS (Maximum Segment Size) to PMTU (Path Maximum Transmit Unit). This method can handle issues called "Criminally Brain-Dead ISPS or Servers" in the kernel configuration help by Netfilter developers. CONFIG_IP_NF_COMPAT_IPCHAINS - IPCHAINS, this is only used for the kernel to 2.2 to 2.4, it will be removed in 2.6. Config_ip_nf_compat_ipfwadM - is the same, this is just a temporary use of IPFWADM. Above, I briefly introduced a lot of options, but this is just in the kernel 2.4.9. To see more options, I suggest you go to Netfilter to see Patch-O-Matic. There, there are some other options. POM may be added to the kernel, of course, there is no. There are many reasons, such as, still unstable, Linus Torvalds are not intended or not to put these patches into the mainstream kernel because they are still experimenting. Compile the following option into the kernel or compile into modules, rc.firewall.txt can use. * CONFIG_PACKET * CONFIG_NETFILTER * CONFIG_IP_NF_CONNTRACK * CONFIG_IP_NF_FTP * CONFIG_IP_NF_IRC * CONFIG_IP_NF_IPTABLES * CONFIG_IP_NF_FILTER * CONFIG_IP_NF_NAT * CONFIG_IP_NF_MATCH_STATE * CONFIG_IP_NF_TARGET_LOG * CONFIG_IP_NF_MATCH_LIMIT * CONFIG_IP_NF_TARGET_MASQUERADE above is the least option to ensure the normal work rc.firewall.txt needed. Other scripts needed to have an explanation in the corresponding chapter. Currently,
We only need to pay attention to this script to learn. 2.3. Compile and install below, let's take a look at how to compile iptables. IPTables Many components are configured, compile with the configuration of the kernel, compiled and associated, understanding this is important. Some Linux products are pre-installed with iptables, such as Red Hat, but its default settings do not enable iptables. We will introduce it to how to enable it, and you will also introduce iptables in other Linux products. 2.3.1. Compile first to extract the iptables package. Here, I use iptables 1.2.6a (Translator Note: When I translate, the latest version is already 1.2.9, which has many improvements, fix some bugs, add several Match and Target.) . Command bzip2 -cd iptables-1.2.6a.tar.bz2 | tar -xvf - (of course, TAR -XJVF iptables-1.2.6a.tar.bz2 can also be used, but this command may not apply to some old version of Tar not applicable) The compressed package is decompressed to the directory iptables-1.2.6a, where the install file has many information for compilation and running. This step, you will be configured, install some additional modules, or add some options for the kernel. We just check this, install some patches that are not included in the kernel. Of course, more patchs in the experimental phase will only be used only when other certain operations are performed. Note has some patches only in the experimental phase, and it is not a good idea to install them. This step, you will encounter a lot of interesting matching and the operation of packets, but they are still experimenting. To accomplish this step, we have to use some commands in the directory of iptables: make pointing-patches kernel_dir = / usr / src / linux / variable kernel_dir points to the true path of the kernel's original code. Under normal circumstances, it is / usr / src / linux /, but will not be the same, this depends on the Linux product you use. Note In short, only certain patches will be asked to join the kernel, and NetFilter's developers have a lot of patches or attachments to join the kernel, but they have to be experimentally. If you want to install these things, use the following command: make Most-of-pom kernel_dir = / usr / src / linux / this command will install some of the Patch-O-Matic (Netfilter World's name of the patch), ignored It is very extreme part that may cause serious damage to the kernel. You have to know the role of this command, to understand their influence on kernel's original code, it will be prompted before you choose. The following command can install all Patch-O-Matic (Translator Note: Be careful). Make Patch-o-matic kernel_dir = / usr / src / linux / To read each patch's help file, because some Patch-O-Matic will damage the kernel, and some have destroyed other patches. Note, if you don't plan to use the Patch-O-Matic to repair the kernel, the above commands can not be used, they are not required. However, you can use these commands to see what interesting stuff, this will not affect anything. Installing Patch-O-Matic, should now recompile the kernel because some patches have been added. But don't forget to reconfigure the kernel, you can do not have information on your added patch in the existing configuration file. Of course, you can also compile iptables first, then compile the kernel. Next, you should compile
iptables, use this simple command: make kernel_dir = / usr / src / linux / iptables should be compiled, if not, consider considering the problem, or subscribe to Netfilter Mailing List, there may be someone can help you. Everything goes well, we should install iptables, this is hard to have any problems. We use the following command to complete this step: make install kernel_dir = / usr / src / linux / now is very successful. If you don't recompile it in front, install the kernel, now you have to do it, otherwise, you still can't use the updated iptables. Take a look at Install, there is a detailed installation information. 2.3.2. Install Red Hat 7.1 on Red Hat 7.1 Using 2.4.x kernel, support Netfilter and iptables. Red Hat contains all basic programs and needs, but the default is b class = command> ipchains. "Why can't IPTables can't be used" is the most common problem. Let us let us talk about how to close ipchains and use iptables. Note Red Hat 7.1 pre-installed iptables versions are some old, before use, you may want to install a new, and compile the kernel. Let's first turn off ipchains and don't want it to run, do this, to change some of the file names under the directory /etc/rc.d/. Complete with the following command: chkconfig --level 0123456 ipchains off This command renamed all soft connections to /etc/rc.d/init.d/ipchains to K92IPchains. Taking the beginning, this script is run by the initialization script at startup. After the start of K, it indicates that the service is terminated, or it will not run in the startup. In this way, Ipchains will not be turned on again. To terminate the running service, use the service command. The command to terminate the ipchains service is: Service Ipchains Stop Now, we can launch the iptables service. First, to determine which run layer is running, it is generally 2, 3 and 5, which have different use: * 2. Multi-user environment without NFS, and the difference between the layer 3 is only for network support. * 3. Multi-user environment is the layer we generally used. * 5. x11, graphical interface. Use the following command to run iptables to run in these layers: ChkConfig --Level 235 iptables ON You can also use this command to enable iptables to run on other layers. But there is not this, because layer 1 is single user mode, generally used in repair; layer 4 reserves no need; layer 6 is used to turn off the computer. Start iptables Use: Service iptables Start There is no rule in script iptables. The method of adding rules in Red Hat 7.1 has two: The first method is to edit /etc/rc.d/init.d/iptables, pay attention to the existing rules may be deleted when upgrading IPTables with RPM. Another method is to load the rules, then save the rules to the file with the command iptables-save, and then load it by the script under the directory RC.D (/etc/rc.d/init.d/iptables). Let's first explain how to use "shear paste Dafa"
Set /etc/rc.d/init.d/iptables. In order to launch the IPTables when the computer is launched, the rules can be placed in the "start" section or function start (). Note: If the rule is placed in the "START" section, don't run start () in the "Start" festival, you have to edit the "STOP" section so that it is when it is shut down or when you enter a layer that doesn't require iptables. The script knows how to handle it. It should also be checked to check the settings of the "Restart" section and "Condrestart" section. Be sure to note that the changes we do may be deleted when upgrading iptables, regardless of the automatic upgrade of the Red Hat network or RPM. The second method is described below: write a rule script first, or use the iptables command to generate a rule. The rules should be suitable for their needs, don't forget whether there is a problem with the experiment, after confirming the normal, use the command iptables-save to save the rules. Generally use iptables-save> / etc / sysconfig / iptables to generate files / etc / sysconfig / iptables, you can also use Service Iptables Save, which automatically saves rules in / etc / sysconfig / iptables. When the computer is started, the script under RC.D will call this file with the iptables-restore, so that the rules are automatically recovered. The above two methods are best not mixed, so as not to affect the rules defined by different methods, even make the firewall settings are invalid. At this point, the pre-installed IPChains and IPTables can be deleted, which avoids conflicts between new and old version of iptables. In fact, this only needs to do this when you install it from the original code. However, in general, there will be no mutual impact, as RPM-based packages do not use the original default directory. Delete the following command: rpm -e iptables, now you don't need ipchains? Delete! The order is as follows: rpm -e ipchains have been hard, and victory is finally coming. You have been able to install iptables from the source code. Those old version deletes it. Chapter 3. Table and Chapter of this chapter we discuss what the packet is in order, how to cross different chains and tables. Later, when you write rules yourself, you will know how important this order is. Some components are iptables and kernels, for example, the data packet routing judgment. It is important to understand this, especially when you use iptables to change the route of packets. This will help you understand how the packet is, why is it routed by that, a good example is DNAT and SNAT, don't forget the role of TOS. 3.1. Overview When the packet reaches the firewall, if the MAC address is in line with the corresponding driver, it will be received by a series of operations, which is determined whether to send to the local program, or forward to other machines, or other other What. Let's first look at the local packet, it will go through the following steps to reach the program to receive it: there is a word mangle below, I really didn't expect any suitable words to express this meaning, just because of mine English is too bad! I can only write my understanding. The expression of this word is that some transmission characteristics of the packet are modified, and the operations allowed in the mangle table are TOS, TTL, and Mark. In other words, as long as we see this word, we can understand its role. Table 3-1. Table STEP (step) Table (Table) Chain (Chain & # xff09
Comment (Note) 1 Transport (for example, Internet) 2 Enter the interface (for example, eth0) 3 mangle preording This chain is used by the mangle packet, such as changing TOS, etc. 4 Nat preording this chain is mainly used to do DNAT. Don't worry about this chain, because in some cases you slip over. 5 routing judgment, for example, the package is sent to the local or forwarded. 6 Mangle Input After the route, the Mangle packet is sent to the local program. 7 Filter INPUT All the local-purpose packages must pass this chain, no matter where they come, the filtration conditions of these packages are located here. 8 Reach the local program (such as a service programs or client program) Note, compared to previous (translator Note: means ipchain) now the packet is chained by the Input, not the Forward chain. This is more in line with logic. Just looks not very well understood, but think about it, I will realize it. Now let's take a look at the source address. What steps are you going through: Table 3-2. Take the local source package Step Table Chain Comment 1 Local program (such as service programs or client programs) 2 routing judgment, to use Source address, outgoing interface, and other information. 3 Mangle Output can be a mangle package here. It is recommended not to filter it here, there may be side effects. 4 Nat Output This link is DNAT operation from the package emitted from the firewall itself. 5 Filter Output is filtered to the local package. 6 mangle postrouting This chain is mainly after the package DNAT (the translator Note: The author refers to this DNAT as the actual route, although there is a routing in front. For the local package, once it is generated, it must pass the routing code. Processing, but this package is specific to where it is to be determined later. So this is called this actual route.), Before leaving local, packet mangle. There are two packages that will pass through this, and the package produced by the firewall itself is also a forwarded package. 7 Nat PostRouting is here for SNAT. But don't filter it here, because there is side effects, and some packages will slip over, even if you use a DROP policy. 8 Leaving the interface (such as: eth0) 9 Transport on the line (for example, the Internet) In this example, we assume that the purpose of a package is a machine in another network. Let's take a look at this bag: Table 3-3. The forwarded package Step Table Chain Comment 1 Transport (for example, Internet) 2 Enter the interface (for example, eth0) 3 mangle preloading mangle packet, such as changing TOS, etc. 4 Nat preording This chain is mainly used for DNAT. Don't worry about this chain, because in some cases you slip over. Will do Snat later. 5 routing judgment, for example, the package is sent to the local or forwarded. The 6 Mangle Forward package continues to be sent to the Forward chain of the mangle table, which is very special. Here, is it covered by mangle (Remember Mangle's meaning). After this MANGLE occurs after the initial routing, the last change package
Previous (Translator Note: It is done by the FORWARD chain, because its filtering function may change some of the destination of some packages, such as discard packages). 7 Filter Forward packets continue to be sent to this Forward chain. Only if you need to forward the package will come here, and all filtrations for these packets are also taken here. Note that all the packs to be forwarded must go through it, whether it is the external network to the intranet, an intranet to the external network. This is to take into account this when you write a rule. 8 mangle postrouting This chain is also for some special types of packages (translator Note: Refer to step 6, we can find that both of the Both chains of the mangle table are used in special applications when forwarding the package). This step Mangle is done after the operation of all the destination addresses of all changing packages, but this package is still on local. 9 Nat PostRouting This chain is used to do SNAT, and of course, Masquerade is also included. But don't do it here, because some packages will pass even if it is not satisfied. 10 Leaving the interface (such as: eth0) 11 Transfer (for example, LAN) on the line (for example, LAN) is as you can see, the package is going to experience many steps, and they can be blocked on any chain, or any problematic place . Our main interest is the outline of iptables. Note that there is no special chain and table for different interfaces. All packs that need to be forwarded by firewall / router must pass through the Forward chain. Do not filter it on the INPUT chain in the Input chain in the input chain. INPUT is designed to operate the package of the address of our machine, which will not be routed to other places. Now let's take a look at what different chains have been used in the above three situations. The illustration is as follows: To figure out the picture above, it can be considered this. At the first routing judgment, it is not sent to the local package, we will send it through the Forward chain. If the purpose of the package is the IP address of the local listener, we will send this package through the INPUT chain, and finally reach local. It is worth noting that during the process of doing NAT, the destination address sent to this unit may be changed in the preording chain. This operation occurs before the first route, so after the address is changed, the package can be routed. Note that all packs will pass through a path in the figure above. If you put a package DNAT back to its original network, this package will continue to walk through the remaining chains on the corresponding path until it is sent back to the original network. Tip wants more information, you can take a look at rc.test-iptables.txt, this script includes some rules, which will show you how to pass all tables and chains. 3.2. Mangle Table This table is primarily used by mangle packages, you can use the mangle match to change the TOS and other features of the package. CAUTION strongly recommends that you don't filter anything in this table, whether it is DANT, SNAT or MASQUERADE. The following is a few operations in the mangle table: * TOS * TTL * Mark TOS operation is used to set or change the service type field of the packet. This is often used to set up a policy of how the data packet on the network is routed. Note that this operation is not perfect, sometimes it is willing. It can't be used on the Internet, and many routers do not notice this domain value. In other words, don't set the package to the Internet unless you plan to rely on TOS to route, such as use iProute2. TTL operations are used to change the living time domain of the packet, and we can let all packets have only one special TTL. Its existence has a good reason
From, that is, we can deceive some ISPs. Why deceive them? Because they are not willing to let us share a connection. Those ISPs will look for whether a separate computer uses different TTLs, and with this as a sign that the connection is shared. Mark is used to set a special mark to the package. iProute2 can identify these tags and determine different routes according to different tags (or no tags). Use these tags we can do bandwidth restrictions and request-based categories. 3.3. NAT Table This table is for NAT, which is the source or destination address of the converted package. Note that just that we have said earlier, only the first package of the stream will be matched by this chain, and thereafter, the package will automatically do the same processing. The actual operation is divided into the following categories: * DNAT * Snat * Masquerade DNAT operation is mainly used in such a case, you have a legal IP address, to redirect access to the firewall to other machines (such as DMZ) . That is, we changed the destination address to make the package can be reached to a host. SNAT changes the source address of the package, which can hide your local network or DMZ, etc. A good example is that we know the external address of the firewall, but must replace the local network address with this address. With this operation, the firewall can automatically do SNAT and DE-SNAT (in reverse SNAT) to the Internet to connect the LAN to the Internet. If you use an address like 192.168.0.0.054, it will not respond from the Internet. Because IANA defines these networks (other), it can only be used inside the LAN. Masquerade's role is exactly the same as Masquerade, just a little bit a little bit. Because of each matching package, Masquerade is looking for available IP addresses, rather than the IP address of SNAT is configured. Of course, this is also advantageous, we can use the addresses obtained by PPP, PPPOE, SLIP, etc., which are randomly assigned by ISP DHCP. 3.4. Filter Table Filter Table is used to filter the packet, we can match the package and filter them at any time. We are here to do DROP or ACCEPT according to the content of the package. Of course, we can also do some filtration in other places, but this group is designed to filter. Almost all Targets can be used here. A large amount of specific introduction is behind, now you know that the filter is mainly completed here. Chapter 4. State Mechanism This chapter will detail the status mechanism. Read this chapter, you will have a comprehensive understanding of how the status mechanism works. We use some examples to explain the state mechanism. Practice the real knowledge. 4.1. Overview The state mechanism is a special part of iptables, in fact it should not be called the status mechanism because it is just a connection tracking mechanism. However, many people are recognized by the state mechanism. I also use this name in the text to represent the same meaning as the connection. This should not cause any confusion. Connection tracking allows NetFilter to know the status of a particular connection. The firewall running the connection track is called a firewall with a state mechanism, hereinafter referred to as a status firewall. Status firewall is safe than non-state firewall because it allows us to write a strict rule. In iptables, packages are related to four different states that are tracked. They are New, Established, Related and Invalid. Later we will discuss each state in depth. Using -State matching operation, we can easily control "whoever can initiate a new session". All connection tracks made by Netfilter's specific framework in the kernel are called Concentrack (Translator Note: is the first letter of Connection Tracking &
# xff09 ;. Concentrack can be installed as a module or as part of the kernel. In most cases, we want, more detailed connection tracking, which is compared to the default Conntrack. Because of this, there are many components for handling TCP, UDP, or ICMP protocols in Concentrack. These modules extract detailed, unique information from the packet, thus maintaining tracking of each data stream. This information also informs the CONNTRACK current state. For example, the UDP stream is generally uniquely determined by their destination address, source address, destination port, and source port. In the previous kernel, we can turn the reorganization function on or off. However, since iptables and Netfilter, especially the connection tracking is introduced into the kernel, this option is canceled. Because there is no bag, the connection tracking cannot work properly. Now the recombination has been integrated into the Concentrack and starts automatically when the Concentrack is started. Do not turn off the reorganization, unless you want to turn off the connection tracking. All connection tracks are processed in the preording chain in addition to the Output chain process, in addition to the PREROUTING chain, meaning that iptables will calculate all states from the preverting chain. If we send a stream initialization package, the status will be set to new in the Output chain. When we receive the bag, the status is set to Established in the preording chain. If the first packet is not generated locally, it will be set to the new state in the preording chain. In summary, all state changes and calculations are completed in the preording chain in the NAT table and the Output chain. 4.2. Concentrack Record Let's take a look at how to read the CONNTRACK record in / proc / net / ip_conntrack. These records represent the current tracked connection. If the IP_CONNTRACK module is installed, the display of CAT / PROC / NET / IP_CONNTRACK is similar: TCP 6 117 SYN_SENT SRC = 192.168.1.6 DST = 192.168.1.9 Sport = 32775 / DPORT = 22 [unreplied] SRC = 192.168.1.9 DST = 192.168. 1.6 Sport = 22 / DPORT = 32775 Use = 2 Concentrack Module Maintenance All information is included in this example, and you can know what a particular connection is in. The first display is the protocol, which is TCP, followed by decimal 6 (Translator Note: TCP protocol type code is 6). The subsequent 117 is the survival time of this Conntrack record, which will be regularly consumed until more packages are received. At that time, this value was set to the default value of the state at the time. The next thing is the state of this connection in the current time point. The above example shows that this package is in the state syn_sent, this value is iptables displayed so that we understand, and the value used is slightly different. SYN_SENT shows that this connection we are observing is only a TCP SYN package in one direction. Then the following is the source address, destination address, source port, and destination port. There is a special word unreplied, indicating that this connection has not received any response. Finally, it is desirable to receive the information of the response package, and their address and port are opposite to the front. The information of the connection tracking record is different depending on the protocol contained in the IP, all corresponding values are defined in the header file Linux / include / NetFilter-IPv4 / IP_ConNTrack * .h. The default value for IP, TCP, UDP, and ICMP protocol is Linux / include / Netfil
Ter-IPv4 / ip_conntrack.h is defined. The specific values can view the corresponding protocol, but we don't use them here because they are only used inside the Conntrack. As the state changes, the survival time will also change. Note has a new patch in Patch-O-Matic, which can be used as system variables as the timeout mentioned above, so that we can change their values when the system is idle. In the future, we don't have to compile the kernel in order to change these values. These can vary from some special system calls under / proc / sys / net / ipv4 / netfilter. Take a closer look at the variables in / proc / sys / net / ipv4 / netfilter / ip_ct_ *. When a connection is transmitted in both directions, the ConNTrack record deletes the [Unreplied] flag and resets. Records of [Assured] at the end Description Two directions have no traffic. Such records are determined, and when the connection tracking is full, it is not deleted, and the recording without [assoced] is to be deleted. Connection tracking table energy accommodation is controlled by a variable, which can be set by IP-Sysctl function in the kernel. The default value depends on your memory size, 128MB can contain 8192 catalogs, 256MB is 16376. You can also view, setup in / proc / sys / net / ipv4 / ip_conntrack_max. 4.3. The state of the packet is different from the state of the user space, the state of the package is different depending on the protocols contained in IP, but outside the kernel, that is, only 4 states: new, established, related and INVALID. They are mainly used with status matching. The following statements are briefly introduced: Table 4-1. Packets in user space State State (Status) Explanation (Note) NEW Note This package is the first package we have seen. Means, this is a connection first package that the Concentrack module sees, which is about to be matched. For example, we see a SYN package, which is the first package we pay attention to, just match it. The first package may not be an SYN package, but it will still be considered a new state. Doing so sometimes leads to some problems, but it is very helpful for some situations. For example, when we want to restore a connection from another firewall, or a connection has timeout, but it is actually not closed. ESTABLISHED ESTABLISHED has noticed data transfer in both directions, and will continue to match this connection package. Connections in the Established state are very easy to understand. Just send and receive a response, the connection is Establish. A connection is going to be Established from the New, just need to receive a response package, whether this package is sent to the firewall, or by firewall forward. ICMP errors and redirects and other packets are also seen as Established, as long as they are the response of our information. Related related is a more troublesome state. When a connection is a connection and a connection that is already in the ESTABLISHED state, it is considered to be related. In other words, if a connection wants to be related, you must first have an ESTABLISHED connection. This ESTABLISHED connection generates a connection other than the main connection. This new connection is Related, of course, the connTrack module can understand the Related. FTP is a good example, FTP-DATA connection is RELATED with FTP-Control. There are other examples, such as DCC connection through IRC. Have
This state, ICMP response, FTP transmission, DCC, etc. can only work through the firewall. Note that most of the UDP protocols rely on this mechanism. These protocols are very complicated, they put the connection information in the packet and require that this information can be correctly understood. Invalid INVALID Description Packet cannot be identified which connection or no status. Several reasons can be produced, for example, memory overflow, received ICMP error messages that do not know which connection belongs to. Generally, our Drop is in this state. These states can be used together in order to match the packet. This makes our firewall very strong and effective. Previously, we often open all ports of 1024 or more to release the data of the response. Now, there is a state mechanism, you don't have to do this again. Because we can only open those ports with answering data, others can close. This is much safe. 4.4. TCP Connect this section and the following sections, let's discuss these states in detail, and how to operate them in three basic protocols in TCP, UDP, and ICMP. Of course, other protocols will also be discussed. We still start from TCP because it is a stateful protocol and has a lot of details about the IPTables state mechanism. A TCP connection is established by three handshake negotiation connection information. The entire session started by a SYN package, then a SYN / ACK package, and finally an ACK package. At this time, the session is successful, and data can be sent. The biggest problem is how the connection tracks control this process. In fact, it is very simple. By default, the connection tracking is basically the same operation on all connection types. Take a look at the pictures below, we can understand what the stream is in the different stages of the connection. As you can see, the code for connection tracking is not from the user's point of view, and the TCP connection is established. Connection tracking When you see the SYN package, you think this connection is a New state. When you see the returned SYN / ACK package, it is considered that the connection is an ESTABLISHED state. If you think about the second step, you should understand why. With this special treatment, the New and Established packages can send local networks, and only the Established connection can have response information. If the data packets transmitted throughout the connection is as New, then the bags used in three handshakes are New Status, so that we cannot block the connection from the outside to the local network. Because even if the connection is inward from the outside, it is also the new state, and for other connections, we have to allow the new state to return and enter the firewall. More complicated is that many internal states are used for TCP connection kernels, and they are defined in 21-23 pages of RFC 793 - Transmission Control Protocol. But it is good to be in the user's space. Behind we will introduce these content in detail. As you can see, it is very simple to see by the user's point of view. However, this block is still difficult to see from the perspective of the kernel. Let's take a look at an example. Consider how to change the status of the connection in / proc / net / ip_conntrack. TCP 6 117 SYN_SENT SRC = 192.168.1.5 DST = 192.168.1.35 Sport = 1031 / DPORT = 23 [Unreplied] src = 192.168.1.5 Sport = 192.168.1.5 Sport = 23 / DPORT = 1031 USE = 1 From the above record Out, SYN_SENT status is set, this shows that the connection has already issued a SYN package, but the response has not been sent, which can be from [unreplied]
Sign. TCP 6 57 SYN_RECV SRC = 192.168.1.5 DST = 192.168.1.35 Sport = 1031 / DPORT = 23 SRC = 192.168.1.5 DST = 192.168.1.5 Sport = 23 DPORT = 1031 / Use = 1 Now we have received the corresponding SYN / The ACK package, the state also changes to SYN_RECV, which indicates that the original SYN package has been transmitted correctly, and the SYN / ACK package also reaches the firewall. This means that there are data transmission in both parties to connect, so it can be considered that there is a corresponding response in both directions. Of course, this is assumed. TCP 6 431999 ESTABLISHED SRC = 192.168.1.5 DST = 192.168.1.35 / Sport = 1031 DPORT = 23 SRC = 192.168.1.5 / Sport = 192.168.1.5 / Sport = 23 DPORT = 1031 USE = 1 Now we send three steps to handshake A package, an ACK package, and the connection will enter the Established state. Transfer a few packets, the connection is [assoced]. The following describes the status of the TCP connection during the closing process. As shown above, the connection (referring to two directions) is not closed before issuing the last ACK package. Note that this is only for a general situation. Connections can also be closed by sending, which is used when rejecting a connection. After the RST package is sent, the connection can be broken after a predetermined period of time. After the connection is closed, enter the TIME_WAIT state, the default time is 2 minutes. The reason why this time is to allow the data package to be inspected through various rules, but also to the destination by a crowded router. If the connection is reset by the RST package, it will change directly to Close. This means that only 10 seconds of default time before turning off. The RST package does not need to be confirmed, it will close the connection directly. For TCP connections, there are other states we have not talked. The full status list and timeout value are given below. Table 4-2. Internal state State Timeout value NONE 30 minutes ESTABLISHED 5 days SYN_SENT 2 minutes SYN_RECV 60 seconds FIN_WAIT 2 minutes TIME_WAIT 2 minutes CLOSE 10 seconds CLOSE_WAIT 12 hours LAST_ACK 30 seconds LISTEN> 2 minutes These values are not absolute, as can be The revision of the kernel changes, or can be changed by / proc / sys / net / ipv4 / netfilter / ip_ct_tcp_ *. These default values are practical. Their units are Jiffies (one percent), so 3000 represents 30 seconds. Note Attention The status mechanism does not look at the flag of the TCP package (that is, the TCP flag is transparent). If we want the New State package through the firewall, we must specify the New Status. We understand that the New status of our understanding refers to the SYN package, but iptables do not view these flags. This is where the problem lies. Some packages do not set SYN or ACK, will also be seen as a New status. Such a package may be used by redundant firewall, but the network is very disadvantageous to only one firewall (may be attacked). So how can we not be affected by such a package? You can use not set SYN
The command in the New status package. There is also a way to install the TCP-WINDOW-TRACKING extension in patch-o-matic, which allows the firewall to be tracked according to some of the TCP signs. 4.5. UDP connection UDP connection is stateless because it does not have any connection establishment and closing the process, and most of them are unquenceless. Two packets received in a sequence are unable to determine their issuance order. However, the kernel can still set the status of the UDP connection. Let's take a look at how to track UDP connections, and related records of Conntrack. As can be seen from the above figure, the UDP connection is established almost the same as the TCP at the perspective of the user. Although ConNTrack information looks a bit different, it is inherently the same. Let's take a look at the first UDP package after the CONNTRACK record. UDP 17 20 SRC = 192.168.1.2 DST = 192.168.1.5 Sport = 137 DPORT = 1025 / [unreplied] src = 192.168.1.5 DST = 192.168.1.2 Sport = 1025 / dport = 137 USE = 1 From the first two values, this Is a UDP package. The first is the name of the protocol, the second is the protocol number, the third is the survival time of this state, the default is 30 seconds. Next is the source, destination address, and port of the package, and the source, destination address, and port of the expectation. [Unreplied] tag description has not received a response. UDP 17 170 SRC = 192.168.1.2 DST = 192.168.1.5 Sport = 137 / dport = 1025 SRC = 192.168.1.5 DST = 192.168.1.2 Sport = 1025 / dport = 137 USE = 1 Once received the first package, The [unreplied] tag will be deleted, and the connection is considered ESTABLISHED, but the Established tag is not displayed in the record. Accordingly, the timeout time of the state has also become 180 seconds. In this example, there is only 170 seconds left, and after 10 seconds, it will be reduced to 160 seconds. There is something that is indispensable, although it may change, it is the previously used [Assured]. To change it to [Assured] status, you must have some traffic on the connection. UDP 17 175 SRC = 192.168.1.5 DST = 195.22.79.2 Sport = 1025 / dport = 53 SRC = 195.22.79.2 DST = 192.168.1.5 Sport = 53 / dport = 1025 [Assured] USE = 1 can be seen, [assoced] There is no major difference in the state record and the front, in addition to the marking by [unreplied] into [Assured]. If this connection continues to 180 seconds, it is to be interrupted. 180 seconds is a short bit, but it is enough for most applications. As long as you encounter this connection-through the firewall, the timeout value will be reset to the default, all the status is like this. 4.6. ICMP connection ICMP is also a stateless protocol, which is only used to control instead of establishing a connection. There are many types of ICMP packages, but only four types have a response package, they are echo request and reply, timestamp request and reply, information requests and answers (i
Nformation request and reply, there is an address mask request and reply, which have two states, new and establish. The timestamp request and information request has been abolished, and the request is still common, such as the ping command is used, the address mask request is not common, but it may sometimes be useful and worthwhile. Take a look at the picture below, you can understand the NEW and ESTABLISHED status of the ICMP connection. As shown, the host sends an echo request to the target, and the firewall thinks this package is in the new state. The goal responds to an obvious answer, the firewall thinks that the package is in Established. When the returns are sent, there is such a record in ip_conntrack: ICMP 1 25 SRC = 192.168.1.6 DST = 192.168.1.10 Type = 8 Code = 0 / ID = 33029 [Unreplied] src = 192.168.1.10 DST = 192.168.1.6 / type = 0 code = 0 ID = 33029 USE = 1 can be seen, ICMP record and TCP, UDP a little difference, protocol name, timeout time, source, destination address, no The port, which added three new fields: Type, Code, and ID. Field TYPE Description ICMP type. Code illustrates the code of ICMP, which has instructions in the appendix ICMP type. The ID is the ID of the ICMP package. Each ICMP package is sent to a ID, and the acceptor assigns the same ID to a response package, so that the sender can recognize which request response. [Unreplied] The meaning is the same as before, and the number of transmissions only occur in one direction, that is, the response is not received. Yes, it is the source, destination address, and the corresponding three new fields. What should be noted that Type and Code have changed as the answer package, the ID and the request package. Like the previous, the answering package is considered to be Established. However, after answering packages, this ICMP connection will no longer have data transmission. Therefore, once the response package passes through the firewall, the ICMP connection tracking record is destroyed. The above circumstances, the request is considered new, and the response is Established. In other words, when the firewall sees a request package, it is considered that the connection is in the new state. When there is a response, it is the Established state. Note Note that the answering package must meet a certain standard, and the connection can be considered as Establish, and each transmission type is like this. The default timeout of ICMP is 30 seconds, which can be modified in / proc / sys / net / ipv4 / netfilter / ip_ct_icmp_timeout. This value is suitable, suitable for most situations. Another very important role of ICMP is to tell UDP, TCP connection, or is working hard to build what is happening, then the ICMP response is considered to be related. The host is not reaching and the network is not arrival. When trying to connect a certain machine, it is not successful (may be closed), the last router arriving at the packet will return the above ICMP information, which is related, as shown below: We sent a SYN package To a certain address, the firewall thinks it is New. However, the target network is problematic, the router is
Will return information that is unreachable, this is Related. Connection tracking recognizes which connection is connected, the connection is interrupted, and the corresponding record delete will be deleted. When the UDP connection encounters a problem, there will be corresponding ICMP information returns, of course, their status is also related, as shown below: We send a UDP package, of course it is new. However, the target network is prohibited by some firewalls or routers. Our firewall will receive information from the network. The firewall knows that it is related to which opened UDP connection, and puts this information (status is related), and deletes the corresponding record. The client receives information that is prohibited, and the connection will be interrupted. 4.7. The default connection operation is sometimes, the ConNTrack mechanism does not know how to handle a particular protocol, especially when it doesn't understand this protocol or does not know how the agreement works, for example, NetBLT, MUX has EGP. In this case, ConNTrack uses the default operation. This operation is very similar to the UDP connection, that is, the first package is recognized as New, and the subsequent response package and the like are Established. The timeout value of the package that uses the default operation is the same, 600 seconds, that is, 10 minutes. Of course, this value can be changed via / proc / sys / net / ipv4 / netfilter / ip_ct_generic_timeout to adapt to your traffic, especially if there is more time consumption, such as satellite, etc. 4.8. Complex protocols and connection tracks Some protocols are more complicated than other protocols, which means that the connection tracking mechanism is difficult to correctly track them, such as ICQ, IRC, and FTP, they all carry a certain in the data field of the packet. Some information, this information is used to establish additional connections. Therefore, some special helper is required to do work. The following is an example in FTP. The FTP protocol first establishes a separate connection - FTP control session. We publish commands through this connection, and other ports open to transfer data related to this command. There are two ways to establish these connections: active mode and passive mode. First look at the active mode, the FTP client sends port and IP address information to the server side, then, the client opens this port, the server side establishes the connection with this port from its own 20-port (FTP-DATA port number), then You can send data using this connection. The problem is that the firewall does not know that these additional connections (relative to the control session), because these connects are in the data domain of the protocol packet during the establishment, not in the data domain that can be analyzed. Therefore, the firewall does not know whether it will put these connections from the server to the client. The solution is to add a special Helper for the connection tracking module to detect those information. In this way, those connections from the FTP server to the client can be tracked, the status is the Related, which is shown below: The DATA connection is established in the DATA connection in the passive FTP mode of operation. The opposite of the active FTP. The client tells the server that some data is required, and the server sent the address and port back to the client, and the client establishes the connection acceptance data. If the FTP server is behind the firewall, or you are strict to the user-limited, only all of them are allowed to access all other ports, in order to let the client access to the FTP in the Internet, it is also necessary to increase the above mentioned Helper. Below is the establishment of DATA connection in passive mode: Some Conntrack Helper already included in the kernel, FTP and IR when writing this article.
C has the corresponding Conntrack Helper. If you don't have the helper you want in the kernel, you can take a look at the Patch-O-Matic directory of the iptables user space, there are many helper, such as the NTALK or H.323 protocol, etc.. If you don't find it, there are several options: You can check the CVS of iptables, or contact Netfilter-Devel ask if you want. If you can't do it, you only write it yourself, I can introduce you a good article, Rusty Russell's Unreliable Netfilter Hacking How-to, connected to other resources and links in the appendix. ConNTrack Helper can be staticly compiled into the kernel, but also as a module, but use the following command to load: ModProbe ip_conntrack_ * Note that the connection tracking does not process NAT, so you need to increase the corresponding module to the connection. For example, you want NAT and track FTP connections, in addition to the corresponding modules of the FTP, there must be a NAT module. All NAT Helper names start with IP_nat_, this is a naming habit: FTP Nat Helper called IP_NAT_FTP, IRC's corresponding module is IP_nat_irc. The name habit of Concentrack Helper is also followed: Concentrack Helper called IP_CONNTRACK_IRC, FTP is called IP_ConNTrack_FTP. Chapter 5. Saveness and Recovery of Rules The IPTables provides two very useful tools to handle larget sets: iptables-save and iptables-restore, which puts rules into a special format with standard script code only. In the file, or recover the rules from it. 5.1. One of the most important reasons for using iptables-save and iptables-restore is that they can increase their loading and save rules to a considerable extent. The problem with the script changes the rules is that the changes must be transferred to the command iptables, and each time call iptables, which first extract the entire rule set in the NetFilter kernel space, then insert or attach, or do other Change, finally, the new rule set is inserted into the kernel space from its memory space. This will spend a lot of time. In order to solve this problem, you can use the iptables-save and restore. IPTables-save is used to save the rule set into a special format text file, and iptables-restore is used to reload this file into kernel space. The best place in these two commands is that the rule set can be loaded and saved at once, and each rule in the script is called once iptables. Iptables-save runs once, you can extract the entire rule set from the kernel and save it to the file, and iptables-restore is loaded with a rule table each time. In other words, for a large rule set, if the script is set, then these rules will be uninstalled repeatedly, install many times, and we can now save the entire rule set once, installation It is a table, which saves a lot of time. If your work object is a huge rule, these two tools are obvious options. Of course, they also have deficiencies, the following chapters will be described in detail. 5.2. RESTORE's deficiencies IPTABLES-RESTORE can set up a rule for all scripts? No, until now, it is very likely that you will never do it. The main shortcomings of iptables-restore can't be used
Miscellaneous rule set. For example, we want to get the dynamically assigned IP address of the connection when the computer is started, and then use it in the script. This, use iptables-restore to achieve, more or less impossible. A possible solution is to write a small script to get that IP address and set the corresponding keyword in the configuration file called by iptables-restore, and then replace the keyword with the obtained IP value. You can save the changed configuration file to a temporary file, and then use it by iptables-restore. However, this will bring a lot of problems, and you can't use iptables-save to save profiles with keywords. This method is stupid. Another way is to load into the iptables-restore file, running a specific script to put dynamic rules. In fact, this is also a stupid method. IPTables-Restore is not suitable for use dynamic IP, if you want to implement different requirements in the configuration file, iptables-restore is not applicable. Iptables-restore and iptables-save have a deficiencies, which is not complete enough. Because people used are not too many, there are not many people who have found this problem, and there are some Match and Targets that are quoted when they are quoted, which may have behavior outside our expectations. Despite these problems, I also strongly recommend that you use them because they are still very good for most rule sets, as long as they don't include those new, I don't know how to use Match and Target. 5.3. Iptables-save iptables-save is used to store the current rules into a file for iptables-restore. It is very simple, only two parameters: iptables-save [-c] [-t table] parameter-C function is the value of the package and byte counter. This allows us to lose statistics for packages and bytes after restarting the firewall. The iptables-save command with the -c parameter makes it possible to restart the firewall without interrupting the statistics. This parameter is not used by default. Parameters -T Specify the table to be saved, default is to save all the tables. The output of iptables-save is given below without loading any rules. #Enerated by iptables-save v1.2.6a on wed Apr 24 10:19:17 2002 * filter: Input Accept [404: 19766]: Forward Accept [0: 0]: Output Accept [530: 43376] commit # completed on WED APR 24 10:19:17 2002 # generated by iptables-save v1.2.6a on WED APR 24 10:19:17 2002 * Mangle: PREROUTING Accept [451: 22060]: Input Accept [451: 22060]: Forward Accept [0: 0]: Output Accept [594: 47151]: Postrouting Accept [594: 47151] commit # completed on wed Apr 24 10:19:17 2002 # generated by iptables-save v1.2.6a on WED APR 24 10: 19:17 2002 * Nat: PREROUTING Accept [0: 0]: PostRouting Accept [3: 450]: Output Accept [3: 450] commit # completed on WED APR 24 10:19:17 2002 Let's explain this output format . # Back is comments. The table begins with * > n Tell iptables-restore not to overwrite the rules in existing tables or tables. The default is to clear all saved rules. The long form of this parameter is --noflush. There are several ways to load rules with iptables-restore, let's take a look at the simplest, most general: Such rule sets should be properly loaded into the kernel and work normally. If you have any questions, you have to take it. Chapter 6. The rule is how to practice this chapter will discuss how to install your own rules. Rules is to point to the standard, on a chain, block different connections and packets or allow them to go. Each line of the insert chain is a rule. We will also discuss basic Matche and its usage, and there are also a variety of Targets, and how to build our own target (for example, a new sub-chain). 6.1. Basic, we have explained what is rules. In the kernel, the rule is to determine how to handle a packet. If a package meets all the conditions (that is, we run the target or JUMP instruction. The grammatical format of writing rules is: iptables [-t table] Command [match] [target / jump] There is nothing to say for this sentence, but pay attention to the Target instruction must be in the end. For easy reading, we generally use this grammar. In short, most rules you will see are written in this grammatical. Therefore, if you see the rules written by others, you can find that this kind of grammar is also easy to understand those rules. If you don't want to use a standard table, you must specify a table name at the [Table]. In general, there is no need to specify the table used because iptables defaults to perform all commands using the Filter table. There is no need to specify a table name here, which is actually almost anywhere in the rules. Of course, the name of the name is already the criteria of the convention. Although the command is always on the beginning, or put it directly behind the table name, we must consider what is easy to read. Command tells the program what to do, such as: Insert a rule, or add a rule at the end of the chain, or delete a rule, below will be carefully introduced. Match describes a feature of the package to distinguish this package from all other packages. Here, we can specify the source IP address, network interface, port, protocol type, or anything else. Below we will see many different matches. Finally, it is the target of the packet. If the packet is in line with all the match, the kernel uses target to handle it, or send the bag to Target. For example, we can let the kernel send the package to other chains in the current table (probably our own creation), or just discard this package without any processing, or returning a special response to the sender. There is a detailed discussion below. 6.2. TABLES Options - THP is used to specify which table used, which can be any of the tables described below, the default is the Filter table. Note that the following introduction is just a summary of the chapter table and chain. Table 6-1. Tables TABLE (Note) The main use of the NAT NAT table is network address translation, namely NetWork address translation, abbreviated as NAT. The address of the packet that did the NAT operation is changed, of course, this change is based on our rules. A packet belonging to a stream will only pass through this table. If the first package is allowed to do NAT or Masqueraded, then the remaining packages are automatically identical to the same operation. That is, the remaining bag will not pass this table, one one is NAT, but Completed. That is why we should not do any of the main reasons for any filtering in this table, which will have a more detailed discussion on this. The role of the PREROUTING chain is to change its destination address when the package just reaches the firewall, if needed. The Output chain changes the destination address of the localized package. The PostRouting chain change its source address before leaving the firewall. Mangle This table is primarily used by the mangle packet. We can change the contents of different packages and cladheads, such as TTL, TOS or Mark. Note that Mark does not really change the packet, it is just a tag that is packaged in the kernel space. Other rules or procedures in the firewall (such as TC) can be filtered or advanced with this marker. This table has five built-in chains: preording, postrouting, Output, Input, and Forward. After the PREROUTING after the package enters the firewall, the route judges before changing the package, postrouting is after all routing judgment. Output changes the packet before determining the purpose of the package. INPUT After the package is routed to the local, the package is changed before the user space. After the initial routing judgment, the last time change the packet. Note that the mangle table cannot do any NAT, which is just changing the TTL, TOS or Mark of the packet, not its source address. NAT is operating in the NAT table. The Filter Filter table is a special filter package, built-in three chains, which can do DROP, LOG, ACCEPT, and REJECT, etc. without problems. Forward chain filters all the packages not generated by the local and the destination is not local (so-called local is a firewall), and INPUT is just a local package for those destinations. OUTPUT is used to filter all local generated packages. The most basic content of three different tables is introduced above. You should know that their purpose is completely different, but also know the use of each chain. If you don't know, you may leave a vulnerability on the firewall to give people a machine. In the chapter table and chain, we have discussed these must-have tables and chains in detail. If you don't have a full understanding of how to pass these tables, the chain, I suggest you go back and take a closer look. 6.3. Commands In this section, we will introduce all Command and their use. Command specifies what kind of operation that IPTables should do for the rules we submit. These operations may be increasing or deleted in a table, or do something else. The following is a Command available for iptables (Be careful, if not explained, the default table is the Filter table.): Table 6-2. Commands command -a, --append example iptables -a input ... explanation in selected Add rules for the chain. When the source address or destination address is in the form of name instead of IP addresses, if these names can be parsed into multiple addresses, this rule will combine all available addresses. Command -d, --delete eXample iptables -d input --dport 80 -j drop or iptables -d INPUT 1 Explan The rule is removed from the selected chain. There are two ways to specify the rules to be deleted: First, write the rules and finish, and then the specified rules in the selected chain (each chain is numbered). Command -r, --Replace Example iptables -r INPUT 1 -S 192.168.0.1 -j DROP Explanation On the selected row in the selected chain (each chain is numbered from 1). Its main use is Test different rules. When the source address or destination address appears in the form of name instead of IP addresses, if these names can be parsed to multiple addresses, the Command will fail. Command -i, - ISERT EXAMPLE IPTABLES -I INPUT 1 - Dport 80 -j Accept Explanation Insert rules into the selected chain according to the rule serial number given. If the serial number is 1, the rule will be inserted into the head, in fact, the default number is 1. Command -l, --List Example iptables -l Input Explanation Displays all rules of the selected chain. If no chain is specified, display all the chains in the specified table. If nothing is specified, you will display all the chains of the default table. Precise output is affected by other parameters, such as -n and -V parameters, will be described below. Command -f, - Flush Example iptables -f input explanation Empty the selected chain. If no chain is specified, clear all the chains in the specified table. If nothing is specified, clear all the chains of the default table. Of course, you can also delete one by one, but it will be fine with this command. Command -z, - ZERO EXAMPLE iptables-z input explanation Rectributes the specified chain (if not specified, it is considered to be all chain). COMMAND-N, --NEW-CHAIN EXAMPLE iptables -n allowed explanation creates a new chain according to the name specified by the user. The above example establishes a chain called the allowed. Note that the name used cannot be and the same name in the existing chain. Command -x, - DELETE-CHAIN EXAMPLE IPTABLES -X ALLOWED EXPLANATION Deletes the specified user-defined chain. This chain must not be referenced, if referenced, you must delete or replace the rules associated with it before deleting. If the parameters are not given, this command will delete all non-built-in chains of the default table. Command -p, --Policy Example iptables -p Input Drop Explanation For the link settings the default target (available from DROP and Accept, if there are other available, please tell me), this Target is called a strategy. All packets that do not meet the rules are enforced using this strategy. Only the built-in chain can use rules. However, the built-in chain and user custom strands cannot be used as a policy, which means that it is not like this: iptables -p input allowed (or built-in chain). Command -E, --Rename-Chain Example iptables-E Allowed Dislowed Explanation renames the custom chain, the original name is before, the new name is behind. As mentioned, it is to change the allowed to disallowed. This is just the name of changing the chain, and there is no impact on the structure of the entire table. When using iptables, if the necessary parameters are not input, press Enter, then it will give some prompt information: tell you what parameters, etc. you need. Iptables' options -v is used to display the version of iptables, and a short description of the grammar. . The following will be introduced is some options, and their role. Table 6-3. Options Option (option) -V, --verbose (Detailed) Use this option in command - List, - Append, - Isert, --dete, - Replace Explanation Explanation) This option makes the output detail, often with -LIST. When serving with -list, the output includes an address, rule option, TOS mask, byte and packet counter in the output, where the counter is k, m, g (here is 10 power rather than 2 Power oh) is in units. If you want to know how many packages have, how many bytes, you have to use the option -X, which will be introduced below. If -v and -append, - insert, - delete or-Replace use, iptables will output detailed information telling you how rules are explained, whether it is correctly inserted. Option -x, --Exact (Precise) Commands Used with --List Explanation Removes the counter in the -List output to exactly values without K, M, g. Note This option can only be used with -LIST. Option -n, --Numeric (value) Commands buy with --list explanation displays the IP addresses and ports in the output, rather than the default name, such as host name, network name, program name, etc. Note This option can only be used with -LIST. Option --Line-NumBers commands use with --liist explanation is another option to use -List, and the function is to display the serial number of each rule in the corresponding chain. This way you can know the serial number, which is useful for inserting new rules. Option -c, - set-counters command, -replace explanation sets the counter when creating or changing rules: - SET-Counters 20 4000, meaning let the kernel package The counter is set to 20, and the byte counter is set to 4000. Option --Modprobe Commands Used with all explanation This option tells IPTables to detect and load the modules you want to use. This is a very useful option, in case the modprobe command is not used in the search path, it is used. With this option, when the module is loaded, even if there is a module that needs to be used, iptables also knows to search. 6.4. Matches this section, we will discuss some Matche in detail, I will pay them five categories. The first category is Generic Matches, for all rules; the second category is TCP Matches, as the name suggests, which can only be used for TCP packages; third categories are udp matches, of course it can only be used in UDP packages It's up; the fourth category is ICMP Matches, for ICMP packages; fifth categories are special, targeting state, owner (Owner), and accessed Frequency Limit (Limit), they have been divided into more Although they are not completely different. I hope this is a classification that everyone is easy to understand. 6.4.1. Universal Matching Regardless of the agreement we use, no matter what extension we matches, generic matching is available. That is, they can be used directly without what prerequisites, where you will see it, there are many matching operations that require other matching as a premise. Table 6-4. Generic Matches Match -p, --Protocol Example iptables -a Input -p TCP Explanation matches the specified protocol. The specified protocol has the following: 1, name, regardless of case, but must be defined in / etc / protocols. 2, you can use their corresponding integer values. For example, the value of ICMP is 1, TCP is 6, and UDP is 17. 3, default settings, all, corresponding values are 0, but pay attention to this represents all protocols that match TCP, UDP, ICMP, not / etc / protocols. 4, can be a list of protocols, with a comma of English as a separator, such as: UDP, TCP 5, can refuse to reject in English before the protocol, pay attention to space, such as: --Protocol! TCP means non-TCP protocol, also It is UDP and ICMP. It can be seen that this reflect is only TCP, UDP, and ICMP. Match -s, --src, --source example iptables -a input -s 192.168.1.1 Explanation Package with IP source address. The form of the address is as follows: 1. A single address, such as 192.168.1.1, can also be written in 192.168.255 or 19255.168.0.0.04, or 192.168.0.0/255.255.255.0 3, in the address, add the English exclamation point, indicate the reverse, pay attention to space, such as - Source! 192.168.0.0/24 indicates all addresses except for the address 4, the default is all addresses match -d, --dst, Destination Example Iptables -a Input -D 192.168.1.1 Explanation Package with IP destination address. The address of the address is exactly the same as - SOURCE. Match -i, --in-interface example iptables -a input -i eth0 explanation enters the package to entert the network interface to the network interface used. Note that this matching operation can only be used for the three chains of Input, Forward and preording, and use anywhere to prompt the error message. The specified interface has a method: 1. Specify the interface name, such as: eth0, PPP0, etc. 2, using wildcard, ie the English plus, which represents the character numeric string. If you use a plus sign directly, iptables -ainput -i represents all packets without considering which interface is used. This is also the default behavior of the interface. Wildcards can also be placed behind a certain type of interface, such as: Eth means all Ethernet interfaces, that is, match all the packages from the Ethernet interface. 3. Adding English exclamation points before the interface indicates to reverse, pay attention to space, such as: -i! Eth0 means matching all packets from except Eth0. Match -o, --out-interface example iptables -a forward -o eth0 explanation with packets to match the network interface used by the local area. The range of use and the specified interface is exactly the same as -in-interface. Match -f, --fragment example iptables -a input -f explanation is used to match the second piece or subsequent portion of a fragmentation package. Because they do not include information such as source or destination, or ICMP type, other rules cannot match it, so there is this matching operation. Pay attention to the shard attack. This operation can also be refused to add English exclamation mark, but pay attention to the position, such as:! -F. In reverse, indicating that only the package that can only be matched or