Iptables Guide 1.1.19
Oskar Andreasson
Oan@frozentux.net
Copyright © 2001-2003 by Oskar Andreasson
This article can copy, distribute, change, but must be copied, distributed, changed, but must be reserved, such as printing books, cover, including "original: Oskar Andreasson", and books are 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
Resign
First of all, I want to give me the 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 word to express the author's girlfriend's Wonderful, you want to go. Also, I don't know if they are married now :))
Second, I have to dedicate this article to all Linux developers and maintaines, that is, they have completed the hard work that is unable to believe, making such excellent operating systems.
table of Contents
Translator
About author
How to read
Prerequisite
This convention
1.
Preface
1.1.
Why write this guide
1.2.
How is the guide written?
1.3.
Termatic term
2.
Preparation Phase
2.1.
Where can I get iptables?
2.2.
Kernel configuration
2.3.
Compilation and installation
2.3.1.
Compile
2.3.2.
Install on Red Hat 7.1
3.
Table and chain
3.1.
Overview
3.2.
Mangle table
3.3.
NAT table
3.4.
Filter table
4.
State mechanism
4.1.
Overview
4.2.
ConNTrack Record
4.3.
Packet in the state of user space
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 restore data management rules
5.1.
speed
5.2.
RESTORE's shortcomings
5.3.
iptables-save
5.4.
Iptables-Restore
6.
How is the rule practiced?
6.1.
basis
6.2.
Tables
6.3.
Commands
6.4.
Matches
6.4.1.
Universal match
6.4.2.
Implicit match
6.4.3.
Explicit match
6.4.4.
Matching of abnormal packets
6.5.
Targets / jumps
6.5.1.
Accept target
6.5.2.
DNAT Target
6.5.3.
DROP TARGET
6.5.4.
Log 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 example rc.firewall
7.1.
About rc.firewall
7.2.
Rc.firewall
7.2.1.
Parameter configuration
7.2.2.
External module loading
7.2.3.
PROC settings
7.2.4.
Optimization of the rule location
7.2.5.
Default policy settings
7.2.6.
Custom chain setting
7.2.7.
INPUT chain
7.2.8.
Forward chain
7.2.9.
OUTPUT chain
7.2.10.
PREROUTING chain
7.2.11.
Postrouting chain
8.
Introduction to Example
8.1.
Rc.firewall.txt script structure
8.1.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.10.
Sid-owner.txt
8.11.
TTL-Inc.txt
8.12.
Iptables-save ruleset
A.
Commonly used commands detailed
A.1.
View the current rule set command
A.2.
Correct and empty iptables
B.
Frequently Asked Questions
B.1.
Module loading problem
B.2.
No SYN NEW status package
B.3.
NEW status SYN / ACK package
B.4.
ISP with private IP address
B.5.
Pulling DHCP data
B.6.
About MIRC DCC
C.
ICMP type
D.
Other resources and links
E.
Thank you
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.
Collections of Documents
7.
Aggregation with Independent Works
8.
Transction
9.
Termination
10.
Future Revision 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 Programs
I.
Example 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.
Take local (it is our own machine) package
3-2.
Local source package
3-3.
Forward bag
4-1.
Packet in the state of user space
4-2.
Internal state
6-1.
Tables
6-2.
Commands
6-3.
Options
6-4.
Generic matches
6-5.
TCP matches
6-6.
UDP matches
6-7.
ICMP matches
6-8.
Limit Match Options
6-9.
Mac Match Options
6-10.
Mark Match Options
6-11.
MultiPort Match Options
6-12.
Owner Match Options
6-13.
State matches
6-14.
TOS matches
6-15.
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-22.
Snat Target
6-23.
TOS Target
6-24.
TTL Target
6-25.
Ulog Target
C-1.
ICMP type
Translator
Translator SLLSCN is the "Linux Fresh Society" in the Linux Commune, a Linux fan, when using iptables to construct a firewall in actual work, found that there is too little Chinese data about iptables, so you may not have reference to the English version. 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, which is not the original authority 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 advice or suggestions, you can contact the translator slcl@sohu.com
Solemn statement: Translate has been licensed by the author Oskar Andreasson. For this article (not original), free use, modification, dissemination, reprint, but use all rights to use by profitability.
About author
There are a lot of "old" computers in my LAN, and they also want to connect to the Internet, but also guarantee security. 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 describes iptables so you can understand the wonderful 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.
Prerequisite
Read this article, there are some basic knowledge, such as Linux / UNIX, Shell scripts, kernel compilation, and it is best to have 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 convention
The following conventions will be used in text:
The 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 use bold. All system components such as hardware, kernel parts, loopback uses a bevel. Computer text outputs this font. File names and path names This / usr / local / bin / iptables.
Prizted
1.1. Why write this guide?
I found that all HOWTOs lack information about the 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 invite other core members of 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. Terms in the article
The article contains some terms, you should have something to understand. 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
This word has a large number of applications in the following, indicating the operations made to the matching packet.
2. Preparation stage
This chapter is to learn the beginning of iptables, which will help you understand NetFilter and iptables playing roles 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 scary :))
2.1. Where can I get 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. Core configuration
In order to run iptables, you need 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.
Strictly speaking, iptables do not need config_packet, but it has a lot of use (the translator's note: other programs need), so it is selected. Of course, you don't want, you don't choose. (Translator Note: It is good to choose it)
Config_netfilter - Allows your computer 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 iptables :)
Of course, you have to install the correct driver to the network device, such as the Ethernet NIC, 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 the options and simple descriptions of the kernel 2.4.9:
Config_ip_nf_conntrack - Connect 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 didn't use this function in rc.firewall.txt, and other examples were not used. (Translator Note: This has once again explained that learning is to play foundations 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 be not difficult to understand why Mirror is called)
CONFIG_IP_NF_NAT - As the name suggests, this module provides NAT features. 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 - Provides Masquerade 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
The above is to ensure the least options required by Rc.FireWall.txt. Other scripts needed to have an explanation in the corresponding chapter. At present, we only need to pay attention to this script to learn.
2.3. Compilation and installation
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. Compilation
First, you must decompress 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.
Some patches are only in the experimental stage, and they are also installed. It is not a good idea. This step, you will encounter a lot of interesting matching and the operation of packets, but they are still experimenting. In order to complete this step, we have to use some of the following commands in iptables' directory:
Make Pending-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.
In summary, only some 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 the very extreme part, which 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, some Patch-O-Matic will damage the kernel, and some have destroyed other patches.
If you don't plan to use the patch-o-matic to fix 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, it's compiled by iptables, with the following simple command: make kernel_dir = / usr / src / linux /
iptables should be compiled, if not, consider how to consider 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 /
I am now telling it. 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. Installation on Red Hat 7.1
Red Hat 7.1 uses 2.4.x kernels to 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.
Red Hat 7.1 pre-installed iptables version is 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 for /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. The difference between multi-user environments 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 make iptables can run in 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 for:
Service iptables start
There is no rule in the 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 the "shear paste Dafa" setting /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
Since you don't need ipchains? Delete! The command is as follows:
RPM-E ipchains
After that, the victory has finally arrived. You have been able to install iptables from the source code. Those old version deletes it.
Chapter 3. Table and chain
This chapter we discuss what the packet is in the 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, the corresponding driver will be received, which is determined whether to send to the local program or forward to other machines, or what is other.
Let's first look at a local packet, it is necessary to get the procedure to receive it after the following steps:
There is a word mangle below, I really didn't expect any suitable words to express this, just because my 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. Target (that is our own machine) package
Step Table (Note) Comment (Note) 1 Transfer (for example, Internet) 2 Enter the interface (for example, eth0) 3ManglePREROUTING This chain is used to make the data package, such as changing TOS, etc. 4natpRerouting this chain main 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. 6MangleInput After the route, the mangle packet is sent to the local program. 7filterInput All 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 is which steps are available for the local package:
Table 3-2. Locally source package
SteptableChainComment1 local programs (such as servers or client programs) 2 routing judgments, to use the source address, out of the interface, and some other information. 3MangleOutput can be a mangle package here. It is recommended not to filter it here, there may be side effects. 4natoutput This link is DNAT operation from the package emitted from the firewall itself. 5FILTEROUTPUT is filtered to the local package. 6manglepostrouting 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 be processed by the routing code. But this package is specific to it, it can be determined after being processed by the NAT code. 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. 7natPostrouting 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 a packet is the purpose of another network. Let's take a look at this bag:
Table 3-3. Improved package
SteptableChaInComment1 Transport (for example, Internet) 2 enters the interface (for example, eth0) 3manglepReroutingMangle packet, such as changing TOS, etc. The 4natpRerouting 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 6mangleForward 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). This time the MANGLE happened before the initial routing, before the last change package (the translator Note: It is done by the FORWARD chain below, because its filtering function, may change some destination, such as discard the package ). The 7filterForward package continues 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. 8manglepostrouting This chain is also for some special types of packages (translator Note: Refer to step 6, we can find that 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. 9natPostrouting 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.
In the above case, do not filter it on 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, you can consider 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.
For more information, you can check out rc.test-iptables.txt, this script includes some rules that will show you how to pass all tables and chains.
3.2. Mangle table
This table is primarily used for mangle packages, you can use the mangle match to change the TOS and other characteristics of the package.
It is highly recommended that you do not do any filter in this table, whether it is DANT, SNAT or Masquerade. The following is several ways to operate in the mangle table:
TOS TTL MARK
TOS operation is used to set or change the service type domain 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, 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 only used 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
The DNAT operation is mainly used in such a case where you have a legitimate 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
The 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 a state 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 the Netfilter's specific framework in the kernel are called Concentrack (Translator Note: The first letters of Connection Track). 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 ConNTrack. 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. ConNTrack 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
All information maintained by the ConNTrack module 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 values for IP, TCP, UDP, and ICMP protocols are defined in Linux / Include / NetFilter-IPv4 / IP_ConNTrack.h. 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.
Recently, there is a new patch in Patch-O-Matic, you can use the timeout mentioned above as a system variable 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. Packet in the state of user space
As mentioned earlier, the state of the package is different depending on the protocol 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. Packet in the state of user space
State Explanation NEWNEW Description 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. EstablishedStablished 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. RelatedRelated 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. With 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. InvalidInvalid Description Packet cannot be identified which connection or no status is. 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 connection
This section and the following sections, we will 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.35 DST = 192.168.1.5 Sport = 23 /
DPORT = 1031 USE = 1
As can be seen from the previous record, the SYN_SENT state is set, this shows that the connection has already issued a SYN package, but the response has not been sent, which can be seen from the [Unreplied] flag.
TCP 6 57 SYN_RECV SRC = 192.168.1.5 DST = 192.168.1.35 Sport = 1031 /
DPORT = 23 SRC = 192.168.1.35 DST = 192.168.1.5 Sport = 23 DPORT = 1031 /
Use = 1
Now we have received the corresponding SYN / ACK package, and the state has changed 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.35 DST = 192.168.1.5 /
Sport = 23 dport = 1031 USE = 1
Now let's send a three-step handshake, that is, 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
STATETIMEOUT VALUENONE30 minuteseSTablished5 dayssyn_sent2 minutessyn_recv60 secondsfin_wait2 minutestime_wait2 minutesclose10 secondsclose_wait12 Hourslast_ack30 Secondslisten> 2 Minutes
These values are not absolute, can vary with the revision of the kernel, or changeable via / 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 that 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 the commands in the New status package that is not set to SYN. 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
The UDP connection is stateless because it does not have any connection establishment and closing the process, and most of them are unruly. 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 the response from the first package is received, 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
It can be seen that the recording of the [Assured] state is not much different from the front, except that the tag is changed by [unreplied]. 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 (Information Request and Reply) ), Also address mask requests and answers, which have two states, new and establishs. 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, the NDP is a bit different, the protocol name, timeout, the source, the destination address, the difference is that there is no port, and the new Increase 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 that the answering package must meet certain standards, and the connection can be considered as Established, 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 is unsuccessful (may be closed), the last router reached by the data package will return the above ICMP information, which is related, as shown below:
We sent a SYN package to a address, the firewall thought it was New. However, the target network is problematic, and the router 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 problems, 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. Default connection operation
Sometimes the ConNTrack mechanism does not know how to handle a particular protocol, especially when it does not 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 protocol and connection tracking
Some agreements are more complicated than other protocols, which means that the connection tracking mechanism is difficult to track them correctly, such as ICQ, IRC, and FTP, they all carry some information in the data field of the packet, which is used for Establish other 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 relative, the process is shown below:
In the passive FTP mode of operation, the establishment process of the DATA connection and 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 the DATA connection in passive mode:
Some Conntrack Helper already included in the kernel. FTP and IRC have the corresponding Conntrack Helper when writing this article. 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.
Concentrack Helper can be static to compile into the kernel, or as a module, but to load with the following command:
MODPROBE IP_CONNTRACK_ *
Note that the connection tracking does not process NAT, so you need to increase the corresponding module to connect 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
Iptables offers two very useful tools to handle larget sets: iptables-save and iptables-restore, which stores rules into a special format with standard script code, or recovering rules from it.
5.1. Speed
One of the most important reasons for using iptables-save and iptables-restore is that they can increase the speed of load 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 deficiency
Can IPTABLES-RESTORE replace all the scripts to set the rules? No, until now, it is very likely that you will never do it. The main shortcomings of iptables-restore are not to be used for complex rules sets. 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]
The role of the parameter-C 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
#Enerated 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
#Enerated 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 *
The above example is the most basic, I want to use a short example to show better, which contains a very small rule set iptables-save ruleset. The output of iptables-save is as follows: #enerated by iptables-save v1.2.6a on WED APR 24 10:19:55 2002
* Filter
: Input Drop [1: 229]
: Forward Drop [0: 0]
: Output Drop [0: 0]
-A INPUT -M State --State Related, Established -j Accept
-A Forward -i Eth0 -m State --State Related, ESTABLISHED -J ACCEPT
-A Forward -i Eth1 -m State --State New, Related, ESTABLISHED -J ACCEPT
-A output -m star --state new, related, established -j accept
Commit
# Completed on WED APR 24 10:19:55 2002
#Enerated by iptables-save v1.2.6a on wed Apr 24 10:19:55 2002
* mangle
: PREROUTING Accept [658: 32445]
: INPUT Accept [658: 32445]
: Forward Accept [0: 0]
: Output Accept [891: 68234]
: Postrouting Accept [891: 68234]
Commit
# Completed on WED APR 24 10:19:55 2002
#Enerated by iptables-save v1.2.6a on wed Apr 24 10:19:55 2002
* Nat
: PREROUTING Accept [1: 229]
: Postrouting Accept [3: 450]
: Output Accept [3: 450]
-A postrouting -o eth0 -j snat --to-Source 195.233.192.1
Commit
# Completed on WED APR 24 10:19:55 2002
There are packets and byte counters before each command, which means that the -c parameter is used. In addition to counter, others are the same as ordinary scripts. The problem now is how to save the output to the file. Very simple, since using Linux, you should know, use it back to the direction:
iptables-save -c> / etc / iptables-save
This will save the rule set to / etc / iptables-save, and there are counters.
5.4. Iptables-restore
iptables-restore is used to load rule sets saved by iptables-save. Unfortunately, it can only accept input from standard input, and cannot accept from files. Here is its way:
iptables-restore [-c] [-n]
Parameter-C requires the package and byte counters. If you save the counter with iptables-save, you must use this parameter now. Its another longer form is --Counters.
Parameters -N tells 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 working properly. If you have any questions, you have to take it.
Chapter 6. How is the rule?
This chapter will discuss how to install your own rules in detail. 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. Foundation
We have explained what is rules. In the kernel opinion, the rules are to determine how to handle a packet statement. If a package meets all the conditions (that is, we run the target or JUMP instruction. The syntax 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 TABLES
Option -t is used to specify which table that uses it, it can be any one in the table 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 TABLES
Table (Name) Explanation (Note) The main use of the NATNAT 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 packets will not pass this table, one one is NAT, but automatically. 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 Filterfilter table is a special filter package, built-in three chains, which can do DROP, LOG, Accept, and Reject of the package 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 a Filter table.):
Table 6-2. Commands
Command-a, --appendexampleiptables -a input ... explanation adds rules in the selected chain end. 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, --deleteexampleiptables -d input --dport 80 -j drop or iptables -d input 1 explanation deletes rules 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, --ReplaceExampleiptables -r INPUT 1 -S 192.168.0.1 -j DROPEXPLANATION On the selected chain selected (each chain is numbered from 1). Its main use is a different rule of test. 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, - ISERTEXAMPLEIPTABLES -I INPUT 1 - Dport 80 -j AcceptExplan is inserted 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, --Listexampleiptables -l InputExplan 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, - FlusHexampleiptables -f INPUTEXPLANATION Clear 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, --ZeroExampleiptables -z INPUTEXPLANATION The specified chain (if not specified, it is considered to be all chain) to zero. Command-n, --new-chainexampleiptables -n allowedexplanation 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-chainexampleiptables -x allowedExplanation deletes the specified user custom 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, --PolicyExampleiptables -p Input Dropexplanation For the chain settings default target (available from DROP and Accept, if there are other available, please tell me), this Target is called a policy. 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-chainexampleiptables-E Allowed DisallowedExplan 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 to command --List, --Append, --ensert, --dete ,-replaceexplanation (Description) This option makes the output detail, often --List is used. 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 - Listexplanation 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 use with - listExplan is displayed in the form of the IP address and port in the output, not the default name, such as host name, network name, program name, etc. Note This option can only be used with -LIST. Option - Line-NumBersCommands Used with - Listexplanation is another option with -List to use options that show 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-counterscommands used with - INSERT, APPEND, - RepeceExplanation Sets the counter when creating or changing rules, the syntax is as follows: - SET-Counters 20 4000, meaning let the kernel handle counter 20, set the byte counter to 4000. Option - MODPROBECMMAVANDS USED WITHALLEXPLANATION 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
In 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 match
Regardless of the agreement we use, no matter what extension we matches, generic matches make it 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, --protocolexampleiptables -a input -p tcpexplan Qaistaties 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, --sourceexampleiptables -a input -s 192.168.1.1explanation 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 mark, indicate that the 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, DestinationExampleiptables -a INPUT -D 192.168.1.1Explanation Package with IP destination address. The address of the address is exactly the same as - SOURCE. Match-i, --in-interfaceexampleiptables -a input -i eth0explanation enters the package to enter the local network interface to match the package. 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-interfaceexampleiptables -a forward -o eth0explan is enabled with 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, --fragmentexampleiptables -a input -fexplanation is used to match the second tablet or subsequent portion of a fragmented 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.
Inverse, indicating that only the first fragments that can only be matched to the package without fragmentation, and the subsequent sheets will not be. Now the kernel has a complete fragment restructuring function, which prevents the debris attack, so it is not necessary to use the reverse function to prevent the debris. If you use connection tracking, you won't see any debris, because it is handled before they reach any chain. 6.4.2. Include matching
This matching operation is automatically or implied to load into the kernel. For example, when we use -Protocol TCP, you don't need to put anything else to match only some of the IP packets. There are now three implicit matching for three different protocols, namely TCP Matches, UDP Matches, and ICMP Matches. They respectively include a set of discriminant only applicable to the corresponding protocol. It is explicitly loaded relative to implicit matching, which must be loaded with -m or -match, and cannot be automatically or implicit, the next section will be introduced.
6.4.2.1. TCP matches
TCP matches can only match the TCP package or flow details, they must have -Protocol TCP as a prerequisite.
TABLE 6-5. TCP Matches
Match - Sport, - Source-PortexampleipTables -a Input -p TCP - Sport 22Explanation Based on the source port of the TCP package to match the package, the specified form of the port is as follows: 1, but does not specify this, you hint all ports. 2, use the service name or port number, but the name must be defined in / etc / services, because iptables look for the corresponding port number from this file. As can be seen from this, the use of the port number will enable the rules to put a little bit, of course, readability is almost. But if you want to write a set of rules that contain 200 or more rules, then you are still old, use the port number, time is the main factor (on a slightly slow-in-plane machine, this will be 10 seconds Different, but will be 1,000, 10,000). 3. A continuous port can be used, such as: - Source-Port 22:80 This represents all ports from 22 to 80, including 22 and 80. If the order of the two numbers is negative, if: - Source-port 80:22 This is the same as the - Source-Port 22:80. 4, you can omit the first number, the default is the first 0, such as: - Source-Port: 80 represents all ports from 0 to 80. 5, can also omit the second number, the default is 65535, such as: - Source-port 22: Represents all ports from 22 to 65535 6, in front of the port number, the English exclamation mark indicates the reverse, pay attention to space, such as: -Source-port! 22 denotes all ports other than the 22nd; - Source-Port! 22:80 represents all ports from 22 to 80 (including 22 and 80). Note: This matching operation cannot identify discontinuous port lists, such as: - Source-port! 22, 36, 80 This is done by the multi-port matching extension that will be described later. Match - dport, --dstination-portexampleiptables -a input -p tcp --dport 22explanation Based on the TCP package to match the package, the specified form of the port is exactly the same as - Sport. Match - TCP-FlagSexampleExplanation matches the specified TCP tag. There are two parameters, they are all lists, and the list is divided by English comma, and the two lists are separated from spaces. The first parameter specifies the tag we have to check (the function is like mask), the second parameter specifies "" The "mark" appears in the first list and must be set to 1 (ie, the state is open) "tag ( Other tags in the first list must be set 0). That is, the first parameter provides an inspection range, and the second parameter provides the conditions set (which position 1). This matching operation can identify the following tags: SYN, ACK, FIN, RST, URG, PSH. There are also two words that can also be used, that is, All and None. As the name suggests, all refers to the selected all tags, and NONE means that no tags are selected. This match can also be refused to reflect in English before the parameter. For example: 1, iptables -p tcp --tcp-flags syn, fin, ACK SYN indicates that matches those SYN tags are set to be set and the package does not have set, pay attention to only one comma between the respective markers without space. 2, - TCP-Flags All None matches all markers without 1 package.
3, iptables -p tcp --tcp-flags! SYN, FIN, ACK SYN indicates that matching those FIN and ACK tags are set and the SYN tag is not set, and the attention is compared. Match - SYNEXAMPLEIPTABLES -P TCP - Synexplanation This match or more is a legacy of the Ipchains era, and the reason why it remains, it is backward compatible, but also to convenient rules in iptables and ipchains. It matches those SYN tags that are set and the ACK and RST tags are not set, this and iptables -p tcp -tcp-flags SYN, RST, ACK SY are no different. Such a package is mainly used to send a request when the TCP connection is initialized. If you block such a package, it also prevents all connected attempts from the outside, which prevents some attacks to some extent. However, the outgoing connection is not affected, and now there is a lot of attacks to take this. For example, some software will be installed after the black-off server, they can use the existing connection to your machine, not to open a port. This match can also be used in the English exclamation point, such as:! --Syn to match those RST or ACK set packages, in other words, the state is a package that has been established. Match - TCP-OptionExampleipTables -p TCP --TCP-OPTION 16EXPLANATION According to the matching package. The TCP option is a special part of the TCP header, there are three different parts. The first 8-bit group represents the type of option, the second 8-bit group represents the length of the option (this length is the length of the entire option, but does not include the byte of the fill portion, and should be noted that each TCP option With this part), the third part is of course the content of the option. In order to meet the standard, we don't have to perform all options, but we can view the type of options, if not what we support, then look at the length and skip the data section. This operation is matched according to the decimal value of the option, which can also be used in the English exclamation point. All options can be found in Internet Engineering Task Force. 6.4.2.2. UDP matches
UDP matches is automatically loaded when specified --Protocol UDP. UDP is a connectionless protocol, so it does not require any type of confirmation when it is open, shut down the connection, and when sending data. The data is lost, it is lost (not sending ICMP error message). This means that udp matches is much less than TCP Matches. Even if UDP and ICMP are no connection protocols, the status mechanism can work well, just like the TCP, this is discussed earlier.
Table 6-6. UDP Matches
Match - Sport, - Source-portexampleiptables -a input -p UDP --sport 53Explanation Based on the source port of the UDP package to match the package, the port specified in the port is exactly the same as TCP mathes. Match - dport, --dstination-portexampleiptables -a input -p UDP - DPORT 53EXPLANATION Based on the destination port of the UDP package to match the package, the specified form of the port is exactly the same as the TCP mathes.
6.4.2.3. ICMP matches
The ICMP protocol is also a connection protocol, and the ICMP package is even shorter than the UDP is still short. The ICMP protocol is not a subordinate protocol of the IP protocol, but its auxiliary, its main role is to report error and connection control. The head and IP of the ICMP package are very similar, but there are many different. The most important feature of this protocol is that it has a lot of types to deal with different situations. For example, we want to access an address that cannot be accessed, it will receive an ICMP Host Unreachable message, which means that the host cannot arrive. There is a complete ICMP type list in the appendix ICMP type. Although there are so many types, there is only one ICMP Matche, which is enough to deal with them. This Matche is automatically loaded when specified -Protocol ICMP. Note that all generic matches can be used so that we can match the source of the ICMP package, a destination address. Table 6-7. ICMP Matches
Match - ICMP-TYPLEXAMPLEIPTABLES -A INPUT-ICMP --ICMP-TYPE 8EXPLANATION According to the ICMP type match package, the specified specified by the type can use the decimal value or the corresponding name, the value is defined in RFC792, the name can be used in iptables --Protocol ICMP - HELP view, or look for in the appendix ICMP type. This match can also be used in English exclamation, such as: - ICMP-TYPE! 8 represents all ICMP packets outside the matching type 8. It is important to note that some ICMP types are abandoned, and some may bring "danger" to unprotected hosts, as they may redirect the package to the wrong place.
6.4.3. Explicit match
Explicit match must be loaded with -m or -match, such as the use of state matches, you must use -mstate. Some match also require a specified protocol, some do not need, such as connection status. These states are New (the first package that has not been established, ESTABLISHED (established connections, is already registered in the kernel), Related (from already existing, in-established connection) New connection), and so on. Some match is still in the development phase, or just to illustrate the power of iptables. This shows that all matches are practical, but you may use it later. With the release of the IPTables new version, there will be some new match available. The biggest difference between implies matching and explicit match is that the following protocol match is automatically loaded, one is explicitly loaded.
6.4.3.1. Limit Match
This matching operation must be explicitly specified by -m Limit to use. With its help, you can limit the number of logs of the specified rules to avoid being flooded by the floods you are in the information. For example, you can set a qualified value in advance. When the number of qualified packages do not exceed it, record; more than, it is not recorded. We can control a number of matches in a period of time (that is, the number of packets can be matched) so that the impact of the DOS SYN FLOOD attack can be reduced. This is its main role, of course, there are many other roles (translator Note: For example, for some unopened services to limit the number of connections, avoiding other services). Limit match can also be used in English exclamation, such as: -m Limit! --Limit 5 / s indicates that all packages are matched after the quantity exceeds the qualifier.
(Translator Note: In order to better understand this matching operation, we explain it through a metaphor. Original text has also been a similar metaphor, but I feel that it is not easy to understand, so it is not used.) Limit match work mode A security guard like a unit door, when someone wants to enter, you need to find a pass. When I was going to work in the morning, there was a number of passes in the security hand. When I came, I tried one. When the passes used it, I will come back, but they will not wait, but to other places (in In iptables, this is equivalent to a package that does not meet a rule, which will be processed by the following rules, and if it does not match, it is processed by the default policy. But there is a provision, and every other time security will issue a new pass. In this way, if the person behind, if it happens to catch up, it can go in. If no one comes, the pass is retained, and it is used by people. If no one is coming, the number of available passes has increased, but not infinitely increased, the number is the number of security hands when the start of the security hand. That is to say, the number of passes is limited at the beginning, but there is a new pass available every other period of time. Limit match has two parameters to correspond to this situation, - Limit-Burst specifies how many passages available at the beginning, - Limit Specifies how long it takes to sign a new pass. It should be noted that I emphasized here is "issuing a new pass", which is considered by iptables. When you write rules yourself, you will take this angle. For example, you specified --Limit 3 / Minute --Limit-Burst 5, meaning that there are 5 passages, add one every 20 seconds (this is from the angle of iptables, if the user's angle Look, the statement is that every minute increases three or only three per minute). If you think about one every 20 minutes, you can only write --Limit 3 / Hour --Limit-Burst 5, that is, you have to make the time unit. TABLE 6-8. Limit Match Options
Match - limitexampleiptables -a INPUT -M LIMIT --LIMIT 3 / HOUREXPLANATION for the maximum average match rate for Limit Match, which is the limit match can match several packages during the unit time. Its form is a value plus a time unit, which can be / second / minute / hour / day. The default is 3 times per hour (user angle), that is, 3 / Hour, which is once every 20 minutes (Iptables angle). Match - limited-burstexampleiptables -a INPUT -M LIMIT --LIMIT-BURST 5EXPLANATION The peak value of the Limit Match is defined, which is the maximum number of packages in unit time (this time is specified above -Limit) ( It can be seen that - the value of Limit-Burst is better than that of -LIMIT. The default is 5. In order to observe how it works, you can start "Script of only one rule" Limit-Match.txt, then use different time intervals to send different quantities of ping packets. In this way, it can be seen by returning Echo Replies.
6.4.3.2. Mac match
Based on the package-based MAC source address matching package. When you write this article, this Match has a little restriction (just to match the MAC source address), but it will be more useful in the future. Note that this match is loaded by the -m Mac, not some people who want to be -m Mac-Source, the latter is just the former's option.
Table 6-9. Mac Match Options
Match - Mac-SourceExampleiptables -a Input -m Mac --Mac-Source 00: 00: 00: 00: 00: 01EXplanation Based on the package-based MAC source address matching package, the address format can only be xx: xx: xx: xx: XX: XX, of course, it can also be used in English exclamation points, such as --mac-source! 00: 00: 00: 00: 00: 01, it means very simple, it is acceptable to additional addresses. Note that because Mac Addresses is only used for the Ethernet type network, this Match can only be used for Ethernet interfaces. Moreover, it can only be used in preording, forward, and input chains.
6.4.3.3. Mark Match
Matches the package with the Mark set, this value can only be changed by the kernel. As mentioned earlier, Mark is more special, it is not part of the package itself, but is allocated by the kernel in the process of packing through the computer. It may be used to change the transmission path or filtering. Today, there is only one way in Linux to set up Mark, namely IPTables, Mark Target, which was previously fwmark target in ipchains. That's why we still have to refer to fwmark in advanced routing. The value of the Mark field is an unsigned integer, the most largest in the 32-bit system can be 4294967296 (already 32 times), this is enough :)
Table 6-10. Mark Match Options
Match - markxampleiptables -t mangle -a input -m mark --mark 1Explanation Match the package with the Mark value set, this value is set by the Mark Target that will be introduced below, it is an unsigned integer . All packages through Netfilter will be assigned a associated Mark Field. However, pay attention to the Mark value is not available in any case, it can only be used in that machine assigned to it, because it is only assigned by the kernel and package related by the kernel, It does not belong to the package itself, so we cannot use it on the router outside the unit. The Mark's format is -mark value [/ mask], as the example above is no mask, with mask examples such as -mark 1/1. If a mask is specified, the Mark value and mask are logically logically, and then compare the Mark value of the package.
6.4.3.4. MultiPort Match
Multi-port matching extensions enable us to specify multiple ports inseparable in a rule. If we don't have this extension, we can only write rules by port. In fact, this is only a reinforced version of the standard port, making our writing rules more convenient.
Note: You cannot use standard port matching and multi-port matching in a rule, such as -Sport 1024: 63353 -M MultiPort - Dport 21, 23, 80. This rule does not want to work as you think, but it is not a work, iptables will use the first legitimate condition, then the multi-port match is white-written :)
Table 6-11. MultiPort Match Options
Match - source-portexampleiptables -a input -p tcp -m multiport --source-port 22, 53, 80, 110explanation source port multi-port matches, up to 15 ports, separated by English comma, pay attention to no spaces. The -p TCP or -P UDP must be prerequisites. Match - DESTINATION-PORTEXAMPLEIPTABLES -A INPUT -P TCP -M MultiPort - Destination-Port 22, 53, 80, 110Explanation Destination Port Multi-port matching, use method, and source port multi-port matching, the only difference is that it matches Destination port. Match - Portexampleiptables -a Input -p TCP -M MultiPort --port 22, 53, 80, 110EXPLANATION The multi-port match match is that it matches the package of the source port and destination port, such as: The packets 80 to the packets of port 80, 110 to 110, and the like. Use the method and the source port multi-port match. 6.4.3.5. Owner Match
Based on the package-based generator (that is, owner, or owner, owner), the OWNER can be the ID of the user who starts the process, or the ID, or the ID of the group where the user is located, or a session ID. This extension is just to illustrate what IPTables can do, and now develop to the practical phase. But note that this extension can only be used in Output, which is obvious: We almost impossible to get any information of the ID of the sender routine, or where there is a route on the road to the real destination. Even in the Output chain, this is not very reliable, because some bags do not have Owner, such as ICMP Responses, so they never caught this match :)
Table 6-12. Owner Match Options
Match - uid-ownerexampleiptables -a output -m owner --uid-owner 500Explan The Id (UID) of the package is generated to match the outgoing package. Using this match can do so, for example, preventing users from ROOT from establishing new connections to firewalls, or blocking anyone other than user HTTP to send data using HTTP ports. Match - gid-ownerexampleiptables -a output -m owner --gID-Owner 0explan The Id (GID) of the group where the package is generated is matched to the outgoing package. For example, we can only let users belonging to the NetWork group on the Internet, and other users are not; or only members of the HTTP group can send data from the HTTP port. Match - pid-ownerexampleiptables -a output -m owner --Pid-owner 78explan The ID (GID) of the process of generating the package is matched to the outgoing package. For example, we can only allow the PID 94 process (the HTTP process must of course be multi-threaded) use the HTTP port. This match uses a little difficulty because you have to know the ID number of the process. Of course, you can also write a small script, first get the PID from the output of the PS, add the corresponding rules, here there is an example of Pid-Owner.txt. Match - sid-ownerexampleiptables -a output -m owner --sid-owner 100explan The ID (SID) that generates the package is displayed. A process and its sub-process or a plurality of threads have the same SID. For example, all HTTPD processes are the same as its parent process (initial httpd process), even if httpd is multi-thread (most of them, such as Apache and Roxen). Here is a script sid-owner.txt can reflect this. 6.4.3.6. State Match
Status matching extension There is a help of connection tracking code in the kernel because it is a state in which the package is obtained from the connection tracking mechanism. This way we can understand the status of the connection. It is almost suitable for all protocols, including those stateless protocols such as ICMP and UDP. There is a default timeout value for each connection. If the connection time exceeds this value, then the record of this connection is deleted from the log database of the connection, that is, the connection will no longer exist. This match must have -m State as a prerequisite to use. The details of the state mechanism are in the chapter state mechanism.
Table 6-13. State Matches
Match - stateExampleIptables -a input -m state --state relative, established explanation Specifies the status of the package to match, there are currently 4 states available: Invalid, Establish, New and Related. Invalid means that this package is not associated with a known stream or connection, or it may be a problem with the data or header it contains. Established means full and effective, and belongs to a established connection, and both ends of this connection already have data transmission. New means that the package will or have already started establishing a new connection, or this package and one connection that has not been delivered at both ends. The Related Description Pack is building a new connection, which is related to a established connection. For example, FTP Data Transfer, ICMP ERROR and a TCP or UDP connection. Note that the New Status does not try to create a newly connected TCP package to find the SYN tag, so it should not be modified to use only one firewall or there is no load balance between the different firewalls. Specifically, you will look at the chapter status mechanism:) 6.4.3.7. TOS Match
According to the TOS field matching package, -m TOS must be used to load. TOS is part of the IP header, its meaning is Type of Service, consisting of 8 binary locations, including a 3 bit of the priority status field (now ignored), 4 Bit's TOS subfield and 1 bit unused bit ( It must be 0). It is generally used to notify the router with priority and needs of the current stream (such as minimum delay, maximum throughput, etc.). However, routers and administrators have a large difference in this value, and some will ignore it, and some will try to meet the requirements.
Table 6-14. TOS Matches
Match - Tosexampleiptables -a INPUT -P TCP -M TOS --TOS 0x16Explanation Match the package according to the TOS field. This Match is often used in the MARK package for later use, in addition to this, it is often used with iProute2 or advanced routing. Its parameters can be a 16-based number, or a decimal number, or the corresponding name (can be found with iptables -m TOS -H). When you write this article, you have the following parameters available: minimize-delay 16 (0x10), requires a path to make the delay, some standard services such as Telnet, SSH, FTP-Control require this option. Maximize-Throughput 8 (0x08), requires a path to make the most throughput, and the standard service ftp-data can be used. Maximize-reliability 4 (0x04) requires a path to make the highest reliability, using it with BOOTP and TFTP. Minimize-Cost 2 (0x02), requires a path to make the cost, usually use this option, is some video audio stream protocols, such as RTSP (Real Time Stream Control Protocol). NORMAL-service 0 (0x00), general service, no special requirements.
6.4.3.8. TTL Match
The package is matched according to the TTL (Time to Live) field in the IP header, which must be loaded by -m TTL. TTL Field is a byte (8 binary bits), once a value processes its router, its value minus 1 its value. When the value of this field is reduced to 0, the message is considered to be unprepared, the datagram is discarded, and the ICMP packet is sent to the source host, and the packets that cannot be forwarded are discarded. There are two cases. First, ICMP packets for transmission during transmission time, using type 11 code is 0 ICMP packets; the second is to survive during data report restructuring, using type 11 code is 1 ICMP packet . This match is just based on the TTL matching package, but it does not do any changes, so any type of Match can be used after it. TTL Matches
Match - TTLEXAMPLEIPTABLES -A OUTPUT -M TTL - TTL 60Explanation Pack the package according to the value of the TTL, and the form of the parameters is only one, which is the decimal value. It can be used to debug your local area network, such as solving the connection problem of hosts in the LAN to the host on the Internet, or find the possible portal of Trojan (Trojan). This match is relatively limited, but it is actually very useful, this is what your imagination is. For example, it can be used to find that TTL has an error default value (this may be the error of the program itself that implements TCP / IP stack functions, or has problems).
6.4.4. Matching of abnormal packets
This match does not have any parameters, nor does it need to be reversed. Note that this should be seen as an experimental match, it is not always working properly, and it is not observable for some abnormal packages (Unclean Package, the so-called dirty bag) or problem. This Match tries to match those that seem to be malformed or abnormal, such as cladding or verification and error, and so on. It may often use the DROP error connection to check the wrong stream, but you must know that this will also interrupt the legal connection.
6.5. Targets / Jumps
Target / Jump decided where to meet the conditions, the syntax is --jump target or -j target. (Translator Note: In this article, the original author divided Target into two categories, namely Target and Jump. Their only difference is that JUMP's goal is a chain in the same table, and Target's goals are specific operations. We will first come into contact with two basic Targets, which is accept and drop.
The previous mentioned user-defined chain is used to use the -n command. Below we build a chain called TCP_PACKETS in the Filter table:
iptables -n tcp_packets
Then use it as a JUMP's goal:
iptables -a input -p tcp -j tcp_packets
This way we will jump into the TCP_PACKETS chain from the INPUT chain and start travel in TCP_PACKETS. If the end of the TCP_PACKETS chain is reached (that is, any rule matching in the chain), the next rule will be retired to the INPUT chain to continue its trip. If it is accept in the sub-chain, it is equivalent to being accept in the parent chain, then it will not pass through other rules in the parent chain. But note that this package can be matched by the chain of other tables, and the process can view the chapter table and the chain.
Target Specifies what we have to do, such as DROP and Accept, there are a lot, we will introduce it. Different Target have different results. Some Targets will stop the packets, which is no longer to continue to compare other rules in the current chain, the best examples are DROP and Accept. Other Targets will continue to compare with other rules after doing operations for packets, such as log, ulog, and tos. They record packages, Mangle, and then pass to match other rules in this chain. With such a Target, we can change its TTL and change its TOS for the same package. Some Targets must have accurate parameters (such as TOS requires a value), some are not necessary, but if we want to specify or (such as port prefix, the port used by the log, etc.). We will fully introduce each Target as comprehensively as possible. Now let's take a look at what kind of Target. 6.5.1. Accept target
This Target does not have any options and parameters, and the use is also very simple, specify -J ACCEPT. Once the package satisfies the specified matching criteria, it will be accept, and will not match the other rules in the current chain or other rules in the same table, but it also passes through the chain in other tables, and may Will be a hundred drops.
6.5.2. DNAT Target
This Target is used to make a target network address translation, which is the destination IP address of the rewrite package. If a package is matched, then all the packages it belong to the same stream will be automatically converted, and then the routing to the correct host or network. DNAT Target is very useful. For example, your web server is inside the LAN, and there is no real IP address that can be used on the Internet, you can use this target to make the firewall to send all the packets to its own HTTP port to the LAN internal real web server. The destination address can also be a range, in which DNAT will allocate an address for each stream. Therefore, we can use this target to do some type of load balance.
Note that Dant Target can only be used in the preording and Output chain in the NAT table, or is called by these two chains. However, it should also be noted that the chain containing the Dant Target cannot be adjusted to other chains other than this, such as postrol.
Table 6-16. DNAT Target
Option - TO-DESTINATIONEXAMPLEIPTABLES -T NAT -A PREROUTING -P TCP -D 15.45.23.67 - Dport 80 -J DNAT - TO-DESTINATION 192.168.1.1-192.168.1.10 Explanation Specifies the address to write to IP headers, this It is also where the package is forwarded. The above example is to forward all the packages to the address 15.45.23.67 to a private address used by a LAN, namely 192.168.1.1 to 192.168.1.10. As mentioned earlier, in this case, each stream is randomly assigned an address to be forwarded, but the same stream always uses the same address. We can also specify only an IP address as a parameter, so all packages are forwarded to the same machine. We can also specify one or a range of ports after the address. For example: - To-Destination 192.168.1.1:80 or --to-destination 192.168.1.1:80-100. Snat's syntax is the same as this Target, just a destination. Be careful, only the TCP or UDP protocol is specified first in -Protocol, you can use the port. Because DNAT wants to do a lot of work, I have to come again. We pass the example to roughly understand how it works. For example, I want to release our website via the Internet, but http server is in our intranet, and we have only one legal IP, which is the external IP - $ inet_ip of the firewall. The firewall has an intranet IP - $ lan_ip, HTTP Server IP is $ http_ip (this is of course the intranet). In order to complete our ideas, the first thing to do is to add this simple rule to the prerouting chain of the NAT table:
iptables -t nat -a preording - DST $ inet_ip -p tcp --dport 80 -j dnat / --to-destination $ http_ip
Now, all packets from the Internet, the 80-port to the firewall will be forwarded (or called DNAT) to the HTTP server on the intranet. If you trial on the internet, everything is normal. Test it again from the intranet, can't use it at all. This is actually the problem of route. Let's take a better analysis of this problem. For easy reading, we remember the IP address of the IP address of the machine that accesses our server on the Internet as $ ext_box.
Depart from the address of the address of $ ext_box, go to the machine for the address of $ inet_ip. The package arrives at the firewall. The firewall DNAT (which is forwarded) this package, and the package will pass many other chain inspections and processes. The package leaves the firewall forward to $ http_ip. The package reaches the HTTP server, the server will respond through the firewall, of course, this requires the firewall to reach the gateway of $ ext_box as HTTP. In general, the firewall is the default gateway of the HTTP server. The firewall is another un-dnat to return to the package (that is, the step of DNAT is over again), which is like a firewall to reply to the request package from the outer network. Back to the package seems to have been so complex processing, there is nothing to return to $ ext_box.
Now let's consider the network of the HTTP server in the same intranet (herein, all the machines do not need to pass the router directly to access each other, not the customer who divides the server and the client in different subnets) What happens when accessing it. We assume that the client's IP is $ lan_box, and the other settings are the same.
Leave $ lan_box, go to $ inet_ip. The package arrives at the firewall. The package is DNAT, and it will also pass through other processing. However, the package has not been treated by Snat, so the package is still using its own source address, which is $ lan_box (Translator Note: This is the characteristics of the IP transfer package, only change the destination address according to the different destination, but not due to transmission To change its source address with a lot of routers, unless you separate the source address changes. In fact, this step is the same, the processing of the outside package is the same, only the problem of the inner network package is here, so here Alternately explain the reason). The package leaves the firewall to reach the HTTP server. HTTP server tries to reply to this package. It sees a package in the routing database from the same network, so it will send the reply package directly to the source address of the request package (now the destination address of the reply package), which is $ lan_box. Reply to the package to reach the client, but it will be confused because this package is not from the machine it visited. In this way, it will throw this package to wait for the "real" reply package. There is a simple solution for this issue, because these packages must enter the firewall, and they are going to the address that needs to be DNAT to arrive, so we only need to do SNAT operations for these packages. For example, let's consider the above example, if you enter the firewall and get the address for $ http_ip, the port is 80 packs, then these packages are as if it is from $ lan_ip, that is, said, The source address of these packages is changed to $ lan_ip. In this way, the HTTP server will send the reply package to the firewall, and the firewall will make UN-DNAT operations for the package and send the package to the client. The rules that solve the problem are as follows:
iptables -t nat -a postrouting -p TCP - DST $ http_ip --dport 80 -j snat / --to-source $ lan_ip
To remember, pressing the order of the posting chain is the last one in all chains, so when you reach this chain, we have been done by DNAT, so we should be based on the address of the intranet $ http_ip (Package) Land) to match the package.
WARNING: The rules we just wrote will have a great impact on the logs, which should be said to be very bad. Because the DNAT and SNAT processing from the Internet package in the firewall can reach the HTTP server (above), the HTTP server believes that the package is sent by the firewall, and does not know the true source is other IP. Thus, when it records the service situation, all source addresses of all access records are the IP of the firewall instead of a real access source. If we want to understand access, we want to understand access. Therefore, the "simple approach" provided above is not a wise choice, but it does solve the problem that "accessible", just not considering the log. Other services have similar problems. For example, you have established a SMTP server in the LAN, then you will set a firewall so that you can forward SMTP's data streams. This creates an open SMTP relay server, which is the problem of the log. Be sure to note that the problem mentioned here is only for networks that do not establish DMZ or similar structures, and the internal network user is accessible to the server's external network address. (Translator Note: Because if DMZ is established, or the server and client are divided into different subnets, then don't need to be so troubles. Because all the sources of access are not in the network where the server is located, there is no It is necessary to do SNAT to change the source address of the package, so that the record is not a problem. If the internal network customer is the internal network address of the server directly access the server, it is better) The best solution is for your LAN. Establish a separate DNS server (Translator Note: This, when the internal network customer uses the website name to access the HTTP server, DNS can parse it into the intranet address. The client can directly access the internal network address of the HTTP server Therefore, thereby avoiding the operation of the firewall, and the source address of the package can also be used by the HTTP server, there is no log problem mentioned above.), Or simply establish DMZ (this is the best way, but You have to have money, because more equipment used is used. For the above example, you should consider it. Now there is still a problem that the firewall will happen when you have access to the HTTP server. Can you access it? Do you think :) Unfortunately, now the configuration is still not working, think about it. The foundation we discussed here is a hypotherapy to access the external network address of the HTTP server, but this external network address is actually an external address of the firewall, so when the firewall accesses this external network address, it is to access itself. If there is an HTTP service on the firewall, the client will see the page content, but this is not what it wants to see (it wanted in DNAT), if there is no HTTP service, the customer can only receive the error message. . The reason why the rules given earlier is because the request packets issued from the firewall will not pass through the two strands. I still remember which chain of the firewall you have emitted :) We have to add the following rules in the Output chain of the NAT:
iptables -t nat -a output --dst $ inet_ip -p tcp --dport 80 -j DNAT / - TO-DESTINATION $ HTTP_IP
With the last rule, everything is normal. And the HTTP server does not access the service normally, and it can also access the service in a network, the firewall can also access the service normally, there is no problem. This kind of mood, a sentence in the "Westward Journey", is "the world is clean". (Don't say you don't know what is "Westward Journey")
I think everyone should understand that these rules only explain how the packet is properly DNAT and SNAT. In addition, other rules are required in the Filter table (in the Forward chain) to allow specific packages to be written (in the postrouting chain and Output chain) rules. Don't forget, those packages have been dnat in the preording chain before arriving in the Forward chain, which means that their destination address has been rewritten, pay attention to this when writing rules. 6.5.3. Drop Target
As the name, if the package meets the conditions, this target will lose it, which means the life of the package to the end, will not take a step forward, the effect is that the package is blocked. In some cases, this target will cause an unexpected result because it does not return any information to the sender, nor will it return information to the router, which may cause the other party of the connection to the Sockets :) The better way to solve this problem is to use the Reject Target, (the translator Note: Because it also returns an error message to the sender while the package is discarded, the other party can end), especially When the port scanning tool obtains more information, you can hide the filtered port, etc. (Translator Note: When the scanning tool scans a port, if the information is not returned, the port is generally considered to filter out the port without opening or being fired. . Also note that if the package is dropped in the sub-chain, then it will not move in the main chain, whether it is in the current table or in other tables. In short, the package is tight.
6.5.4. Log target
This Target is designed to record information about the package. This information may be illegal, then it can be used to except. Log will return the details of the package, such as most of the IP header and other interesting information. This feature is done through the log tool of the kernel, usually syslogd. The returned information can be read with Dmesg, or you can directly view the syslogd log file, or you can use other programs. Log has a great help to debug rules, you can see where the package goes, what kind of rules have been processed, and what packages are processed, and so on. When you debug a rule set that does not dare to guarantee 100%, you don't dare to guarantee the normal rule set (with detailed information, the error is easy to locate, solved), because a small grammar Error may cause serious connection issues, users don't like this. If you want to use the true expansion log, you may have some interest in Ulog Target because it can log directly into the MySQL Databases or similar databases.
Note that if the information obtained at the console is not what you want, it is not an iptables or NetFilter problem, but a syslogd configuration file, this file is generally /etc/syslog.conf. For more information on this issue, please check through Man Syslog.conf.
Log now has 5 options, you can use them to specify the required information types or set some values for different information to use in the record. The options are as follows:
Table 6-17. Log target options
Option - Log-Levelexampleiptables -a forward -p tcp -j log --log-level debug expeneration tells iptables and syslog which record level. Details of the recording level You can view the file syslog.conf, which generally says the following levels are: Debug, Info, Notice, Warning, Warn, Err, Error, Crit, Alert, Emerg, PANIC. Among them, Error and Err, Warn and Warning, PANIC and EMERG are synonymous, that is, the function is exactly the same. Note that these three levels are not used in favor, in other words, do not use them (because the amount of information is too large). The information level illustrates the severity of the problem reflected by the recorded information. All information is recorded through the function of the kernel, that is, first set Kern. = INFO / VAR / LOG / IPTABLES in the file syslog.conf, then let all the LOG information about iptables use INFO, you can Use all information into file / var / log / iptables. Note that there may be other information, which are generated in the kernel using the INFO. For more information on logs, I suggest you see the help of syslog and syslog.conf, and HOWTO, and so on. Option - Log-prefixexampleiptables -a input -p tcp -j log --log-prefix "input packets" Explanation tells iptables to add the specified prefix before the recorded information. This is easy to track specific issues when working with GREP or other tools, and it is also convenient to output from different rules. The prefix can have a maximum of 29 English characters, which already includes a total length of blank characters and other special symbols. Option - log-tcp-sequenceExampleiptables -a input -p tcp -j log --log-tcp-sequenceExplan records the package's TCP serial number and other log information. The TCP serial number can uniquely identify a package, which is also used when the reorganization is used to determine the location of each packet in the package. Note that this option may cause danger, because these records that are not authorized by unauthorized users, may make them easier to destroy the system. In fact, any iptables' output information has increased this danger. (Translator Note: Now, I understand what is "Musow", what is "silent is gold") Option - log-tcp-optionsexampleiptables -a forward -p tcp -j log --log-tcp -OptionSexplanation Records options in the field size in the TCP header. This is very valuable to some extent, through the information it provides, you can know where it may be wrong, or where is wrong. Option - Log-ip-optionsexampleiptables -a forward -p tcp -j log-ip-optionSexplanation records the size of the field size in the IP header. This is valuable for some densities, and can also be used to track packages for specific addresses. 6.5.5. Mark Target
Used to set up a Mark value, this value can only be used in local mangle tables, and can not be used anywhere, it is not necessary to say routers or another machine. Because Mark is particularly special, it is not part of the package itself, but is allocated by the kernel in the process of packet through the computer. It can be used with local advanced routing features to make different packages can use different queue requirements, and so on. If you want this feature during the transmission, or use TOS Target. For more information on advanced routing, you can view Linux Advanced Routing and Traffic Control How-To. Table 6-18. Mark Target Options
Option - set-markxampleiptables -t mangle -a preording -p tcp --dport 22 -j mark --set-mark 2EXPLANATION Sets the Mark value, this value is an unsigned integer. For example, we set a Mark value for all packages issued by a stream or from a single machine, you can use advanced routing functions to perform traffic control.
6.5.6. Masquerade Target
The role of this Target and Snat target is the same, the difference is that it does not need to specify --to-Source. Masquerade is a dedicated connection for those that are dynamically acquired, such as dial-up, DHCP connections, and more. If you have a fixed IP address, use the Snat Target.
A connection means that we automatically get the IP address of the network interface without using --to-source. When the interface is deactivated, Masquerade does not remember any connections, which is very good when we kill off the interface. If we use the Snat Target, the data of the connection track is reserved, and the time will take a few days, this is to take up the memory of many connection tracking. Under normal circumstances, this processing method is better for dial-up Internet (this is conducive to the existing connection to continue). If we are assigned to a previous IP, no matter how the existing connections are lost, but more or less still have some connection records (really idiot, yes).
Even if you have a static IP, you can use Masquerade without Snat. However, this is not agreed because it will bring additional overhead, and it may also cause contradictions, such as it may affect your script, so that they cannot be used.
Note that Masquerade and SnAT can only use the postrol chain of the NAT table, and it has only one option (not required):
Table 6-19. Masquerade Target
Option - to-portsexampleiptables -t nat -a posteing -p tcp -j masquerade - TCP-PORTS 1024-31000EXPLANATION Under the premise of specifying TCP or UDP, set the port that can be used out of the package, the way is a single port, such as -to-ports 1025, or port range, such as --to-ports 1024-3000. Note that a linked font size is used when specifying a range. This changed the selection of the default port in Snat. For details, please see the Snat Target.
6.5.7. Mirror Target
This Target is experimentally, it is just a demonstration, it is not recommended to use it because it may cause a loop, in addition to this, it may also cause serious DOS. The role of this Target is to reverse the source address in the IP header and then forward the package. This will cause a very interesting thing, and a hacker is finally broken by his own machine. It seems that using this target can at least make our machine more strong :) What happens if the 80-port of the machine A uses mirror? It is assumed that there is a machine b from Yahoo.com Want to access a HTTP service, then he gets the Yahoo home page, because the request is from Yahoo. Note that mirror can only be used in input, forward, preording chains and in custom chains they call them. Also note that if the outgoing package is issued due to the Mirror target, they are not processed by chains within the Filter, NAT or Mangle tables, which may cause loop or other issues. For example, a machine sends a machine that is configured with mirror and the TTL value of 255 will be considered a deceived packet, and this machine also deceives his own packets so that it is considered to be from the first Three machines used Mirror. In this way, the package will not be interrupted many times until TTL is 0. If there is only one router between the two machines, this package will go to and from 240-255 times. For hackers, this is not bad, because he just wants to send a 1500-byte data (that is, a package), you can consume 380k bytes of your connection. This is ideal for hackers or script kids (regardless of us calling them).
6.5.8. Queue Target
This Target is a program or application software management package queue for user space. It is a program or tools other than iptables or tools, including network counting tools, advanced packet proxy, or filtering applications, and more. The encoding of the discussion procedure has exceeded the scope of this article. Even if you discuss, it takes a lot of time, and you can't make a clerivin about Netfilter and iptables within such an article. See Netfilter Hacking How-To for specific information.
6.5.9. Redirect Target
Internal forward packages or flow to another in the firewall. For example, we can put all the ports of the port HTTP to http proxy (such as Squid), of course, this happens within our own host. Local generated packages are mapped to 127.0.0.1. In other words, this Target rewrote the destination address of the package to be forwarded as the IP of our own machine. We are doing a transparent agent (the machine in the LAN does not need to know the existence of the agent, this Target has played a lot.
Note that it can only use the prerouting in the NAT table, the Output chain, and the custom chain that is called by them. Redirect has only one option:
Table 6-20. Redirect Target
Option - TO-portsexampleiptables -t nat -a preording -p tcp --dport 80 -j redirect --to-ports 8080explan The definition port, the way is as follows: 1, do not use this Options, the destination port will not be changed. 2, specify a port, such as --to-ports 8080 3, specify the port range, such as --to-ports 8080-8090
6.5.10. REJECT TARGET
REJECT and DROP are basically the same, the difference is that it returns an error message to the sender except for blocking packages. Now, this target can only be used in Input, Forward, Output, and their subclops, and the chains containing the reject can only be called, otherwise it is not possible. It has only one option, which is used to control the type of error message returned. Although there are many types, if you have the basics of TCP / IP, it is easy to understand them. Table 6-21. REJECT TARGET
Option - REJECT-WITHEXAMPLEIPTABLES-A Forward -P TCP - Dport 22 -j respject --Reject-with tcp-resetExplan presents what kind of information should be returned to the sender. Once the package satisfies the settings, the corresponding information is to be sent, and then they will abandon those packages like DROP. The types of information available are: 1, ICMP-NET-UNREACHABLE 2, ICMP-HOST-UNREACHABLE 3, ICMP-Port-Unreachable 4, ICMP-Proto-Unreachable 5, ICMP-Net-Prohibited 6, ICMP-Host-Prohibited. The default is Port-unreachable. You can see more information in the appendix ICMP type. There is also a type of -echo-reply that can only be used with rules that match the ICMP PING package. The last type is TCP-RESET, (Obviously, only TCP protocols can only be used to tell Reject to return a TCP RST package (this package closes TCP connection in elegance, about it), RFC 793 - Transmission In Control Protocol) gives the sender. As IPTables's Man Page, TCP-RESET is primarily used to block identity identification probes (ie 113 / TCP, when sending mail to the destroyed mail host, the probe is often used, otherwise it will not accept you Letter).
6.5.11. Return Target
As the name, it returns the package back to the previous layer, the order is: sub-chain -> Father Chain -> Default Policy. Specifically, if the package encountered Return in the sub-chain, the next rule that returns the parent chain continues to make conditions, if it encounters returna in the parent chain (or called the main chain, such as input), it is necessary to be The default policy (typically an Accept or DROP) is operated. (Translator Note: This is very like a case where the function is returned in the C language)
Let's give an example to explain that, suppose a package enters the Input chain, matches a Target to --jump Example_Chain rule, and then enter the subclunner_chain. In the sub-chain, a rule is matched, it happens to Target is --Jump Return, then return to the INPUT chain. If you encounter -jump Return in the Input chain, this package will be handled by the default strategy.
6.5.12. Snat Target
This Target is used to do source network address translation, that is, the source IP address of the rewrite package. When we have a few machine sharing an Internet connection, we can use it. First open the IP forwarding function in the kernel, then write a SNAT rule, you can change all the source addresses from the local network to the Internet connection. If we don't do this but directly forward the local network package, the machine INTERNET does not know where to send an answer, because in the local network, we generally use the IANA organization specified one address specified, they can't be Used on the Internet. The role of Snat Target is to let all the packages from the local website look from a machine, this machine is generally a firewall. Snat can only use the postrol chain in the NAT table. As long as the first eligible package is connected by Snat, then all other packages of this connection are automatically Snat, and this rule is also applied to all packets where this connection is located.
Table 6-22. Snat Target
Option - to-sourceExampleiptables -t nat -A POSTROUTING -p tcp -o eth0 -j SNAT --to-source 194.236.50.155-194.236.50.160: 1024-32000 Explanation source address and port, the following ways: 1, separate address. 2, a continuous address, separated by a hyphen, such as 194.236.50.155-194.236.50.160, which can achieve load balancing. Each stream is randomly assigned an IP, but the same IP is used for the same stream. 3. Under the premise of specifying the -p TCP or -P UDP, the range of the source port can be specified, such as 194.236.50.155:1024-32000, such source ports are limited to 1024-32000. Note that if possible, iptables always want to avoid any port changes, in other words, it always tries to use the ports used when establishing a connection. But if the two machines use the same source port, iptables will map one of them to another port. If there is no specified port range, all source ports within 512 will be mapped to another port within 512, and the 512 and 1023 will be mapped to 1024, and other will be mapped to greater or for 1024. The port, that is, the same range mapping. Also note that this mapping and destination ports have nothing to do. Therefore, if the customer wants to contact the HTTP server outside the firewall, it will not be mapped to the port used by FTP Control.
6.5.13. TOS Target
TOS is used to set the Type of Service field in the IP header. This field is a byte, which can control the route of the package. It is also one of the fields that iProute2 and its subsystems can be used directly. It is worth noting that if you have several independent firewalls and routers, but also want to pass routing information between the heads of the package, TOS is the only way. As mentioned earlier, Mark cannot be used to pass this information. If you need to pass routing for a package or stream, you should use the TOS field, which is also developed for this.
There are many routers on the Internet, there is no job in this regard, so there is no big use of TOS before sending a package. The best situation is that the router does not care, the worst case is that the router will process according to TOS, but it is wrong. However, if you are in a large WAN or LAN, and there are many routers, TOS can still have a good one. Overall, TOS-based values are also possible to give a package with different routes and parameters, even if it is restricted in the network (the translator's note: big deal, it is, it is.). TOS can only be used to set specific or specific values (these predefined values are in the internal nuclear source code of the internal nuclear code - Linux / IP.H), the reason is much, but no matter what to say, don't use other The value is it. Of course, we have a way to break through this limit, just use a Patch called FTOS, you can get it at the site maintained by Matthew G. Marsh, but be careful. In addition to very special, extreme cases, we should not use values other than predefined.
Note that this target can only be used within the mangle table.
Also note that this Target included in some old version (1.2.2 or lower) iptables is set after setting TOS, which will not adjust the checksum of the package, so that the package will be considered to be wrong and require retransmission . Moreover, this is likely to cause more MANGLE operations to make the entire connection cannot work. (Translator Note: It won't use this old version now :))
TOS Target has only one option:
TABLE 6-23. TOS TARGET
Option - set-tosexampleiptables -t mangle -a preording -p tcp --dport 22 -j TOS --SET-TOS 0X10EXPLANATION Sets the value of TOS, the value of the value can be name or make the corresponding value (decimal or 16) of). In general, it is recommended that you use the name without using numeric forms, because these values may change, and the name is generally fixed. The TOS field has 8 binary bits, so a possible value is 0-255 (decimal) or 0x00-0xFF (16). As mentioned earlier, you'd better use predefined values, they are: 1, minimize-delay 16 (0x10), ask for a path to minimize delay, some standard services such as Telnet, SSH, FTP-Control need this Options. 2, Maximize-Throughput 8 (0x08), requires a path to make the most throughput, and the standard service ftp-data can be used. 3, Maximize-reliability 4 (0x04), requires a path to make reliability, using it with BOOTP and TFTP. 4, Minimize-Cost 2 (0x02), requires a path to make the cost, usually use this option, is some video audio stream protocols, such as RTSP (Real Time Stream Control Protocol). 5, NORMAL-Service 0 (0x00), general service, no special requirements. This value is also the default value of most packages. A complete list can be obtained by command iptables -j tos -h. When you are 1.2.5, this list is already complete, and it will remain a long time. 6.5.14. TTL Target
This target requires Patch-O-Matic's Patch called TTL, available from http://www.netfilter.org. The FAQ of this site is a great place to learn iptables and NetFilter.
TTL can modify the value of the Time to Live field in the IP header. It has a lot of roles, we can change all the Time to Live values of all outbounds, such as 64, this is the default value of Linux. Some ISPs do not allow us to share connections (they can distinguish between TTLs, do not have multiple machines to use the same connection), if we change TTL to the same value, they can no longer be judged according to TTL.
For any TTL default value for Linux, see IP-sysctl.txt within the appendix additional resources and links.
TTL can only be used in the mangle table, it has three options:
TTL TARGET
Option - TTL-STEXAMPLEIPTABLES -T MANGLE -A PREROUTING-I Eth0 -j TTL - TTL-SET 64EXPLANATION Sets the value of TTL. This value should not be too large, don't be too small, about 64 is very good. The value of the Taihua will affect the network, and it is a bit unstead, why do you say this? If the configuration of some routers is not very correct, the TTL of the package is very large, and they will go back and forth between these routers, the greater the value, the more bandwidths. This Target can be used to limit the package how far, a relatively proper distance is just to reach the DNS server. Option - TTL-DECEXAMPLEIPTABLES -T MANGLE -A PREROUTING-I Eth0 -j TTL - TTL-DEC 1EXPLANATION Sets the value to be reduced, such as - TTL-DEC 3. Assuming a TTL of a package that is 53, then when it leaves our machine, TTL has changed to 49. Why isn't it 50? Because of our machine, TTL itself will be reduced by 1, but also by TTL Target to reduce 3, of course, the total is minus 4. Using this Target can limit "users who use our services" how far from us. For example, the user always uses a relatively close DNS, then we can perform several-TTL-DECs for the package issued by our DNS server. (Translator Note: Means, we just want users to access our services from the DNS server), of course, more convenient to control with -set-TTL. Option - TTL-INCEXAMPLEIPTABLES -T MANGLE -A PREROUTING -I Eth0 -j TTL - TTL-INC 1EXPLANATION Set the value to be increased, such as - TTL-INC 4. Suppose the TTL of a package that is 53, then how much should TTL should be in the TTL when it leaves us? The answer is 56, the reason is the same - TTL-DEC. Using this option allows our firewall more hidden, not by Trace-Routes, the method is to set -ttl-inc 1. The reason should be very simple, the package is automatically reduced by one after a device, but this 1 is added again in our firewall, that is, TTL's value has not changed, then TRACE-ROUTES will think Our firewall does not exist. Trace-Routes make people love and hate, love it because it can provide us with a very useful information when they connect problems, tell us where there is a problem; hate it is because it can be used by hackers or hackers Collect the information of the target machine. How to use it? There is a good example here, please see the script TTL-Inc.txt. 6.5.15. Ulog Target
Ulog can record information that is matched in user space, which will be multicast through NetLink Socket through NetLink Socket through NetLink Socket. Then, the process of one or more user space will receive them. In other words, Ulog is the most mature, perfect log tool, which is now the most mature, perfect log tools under Iptables and Netfilter, which contains a lot of better tools for the record. This Target can be we recorded information in mysql or other database. In this way, it is very convenient to search for a specific package or put the record packet. You can find the software of Ulogd user space in Ulogd Project Page.
Table 6-25. Ulog Target
Option - ulog-nlgroupexampleiptables -a input -p tcp --dport 22 -j ulog - ulog-nlgroup 2Explanation Specifies which NetLink group to send packets, such as-ulog-nlgroup 5. One has 32 NetLink groups that are simply numbered 1-32. The default is 1. Option - ulog-prefixexampleiptables -a input -p tcp --dport 22 -j ulog-prefix "SSH Connection Attempt:" EXPLANATION Specifies the prefix of the record information to distinguish between different information. Like the use of the LOG's prefix, the length can reach 32 characters. Option - ulog-cprangeexampleiptables -a input -p tcp --dport 22 -j ulog-cprange 100explan The number of bytes sends to "Ulog in the user space", such as -ulog- CPRANGE 100, indicating that the first 100 bytes of the entire package is recorded to the user space, which contains this header, and some packets of boot data. The default is 0, indicating that the copy is the entire package, no matter how much it is. Option - ulog-qthresholdexampleiptables -a input -p tcp --dport 22 -j ulog -ulog-qthreshold 10EXPLANATION Tell the number of packets collected in the kernel before sending data to the user space, the number of packets to be collected in the kernel (Translator Note: Just like a container, such as -ulog-qthreshold 10. This means that 10 packs are accumulated in the kernel, and then send them to the user space, they will be seen as the same NetLink information, just consisting of several parts. The default is 1, which is backward compatible because the previous version cannot handle the segmentation information. Chapter 7. Firewall Configuration Example Rc.fireWall
In this chapter, we will build a firewall, and explain how to read and understand it. In this example, we use the most basic configuration, which has an in-depth explanation of what we have made and we have inside. This example should be able to give you basic ideas in some ways, such as how to solve different problems (of course, network), and then, if you really apply scripting to work, you should consider something, and so on. Some modifications to this example may be used in the actual network, but do not recommend you to do this, because your network configuration and what I use in the example is not the same. But as long as you have this basic firewall rule set, it is likely that only a small amount of adjustment can be used to actually.
There may be more efficient methods to establish rule sets, but this script is written for easy reading, so everyone can understand it, even if there is no knowledge of Bash scripting programming.
7.1. About rc.firewall
Ok, since you can see it from the beginning, you will explain that you have prepared to check this script. Example rc.fireWall.txt (code in the code of the appendix sample script) is large, but not much comment. I suggest you first take a look at its content, leave an impression, and then read this chapter carefully (you must be patient).
7.2. Rc.firewall
7.2.1. Parameter configuration
This section is to look at the rc.firewall script code.
The first section of rc.firewall.txt is a configuration option, which is some crucial information, which varies with your network. For example, the IP address of each network is different, all the places you want to put it here. The value of $ inet_ip should be available on the Internet, if you have $ INET_IP. If not, you have to look at the rc.dhcp.firewall.txt this configuration method, there are many interesting things. Variable $ INET_IFACE should point to the real device connected to the Internet, such as Eth0, Eth1, PPP0, TR0, and the like. This script does not contain any DHCP or PPPoE option, so these two are blank. The other blank part is also the reason. The reason why these gaps are retained, which is to easier to distinguish between the same and different scripts. If you need these parts, you can copy it from other scripts, or write it yourself :)
The Local Area Network section contains information necessary for the LAN, such as the address segment used by the IP of the NIC connected to the LAN.
The information in the Localhost Configuration section is not changed in 99%, because we always use 127.0.0.1 as an address, always named the interface to LO. Followed by IPtables Configuration, there is only one variable inside, ie iptables. It specifies the exact location of the iptables program, and if you are compiling, you are generally / usr / local / sbin / iptables. But more distributions are placed in additional places such as / usr / sbin / iptables, and so on.
7.2.2. Loading of external modules
First, we want to use command / sbin / depmod -a to keep the module dependencies file up to, then load the modules required for the script. We should always avoid the unwanted modules. If possible, we must try to avoid loading uneven modules unless you really need them. This is mainly for safety, because each of the additional modules will cost additional efforts to increase new rules (this is easy to make vulnerabilities). For example, if you want to support log, reject, and masquerade target, do not static compile into the kernel, we use the modules to complete:
/ sbin / insmod pt_log
/ sbin / insmod pt_reject
/ sbin / insmod pt_masquerade
Note that the scripts used herein are loaded with similar commands, which may cause load failure (with error message display). The reason is multifaceted, but if the more basic modules fails, the maximum may be which module or corresponding function has been static compiled into the kernel. Further information can look at the module load problem in Appendix FAQ and the answer.
The next line is to load the IPT_OWNER module, and its role is "only allows specific users to create specific connections." In this example, I didn't use it, but you might be used. For example, you may only allow root to establish FTP and HTTP connections to access Redhat.com, and other users are not available. You can also only allow yourself to use the username and root to access the Internet, so others will be annoying, but your security will improve in some respects, for example, putting you as a springboard that initiates attacks . For more information on IPT_OWNER, you can check how the chapter rules are packed in Owner Match.
We can also match the expansion modules for status matching. The names of all expansion modules for status matching and connection tracking are: ip_conntrack_ * and ip_nat_ *. Helper, which is connected, is some special modules, which is exactly how to properly track special connections in the kernel. Without these helper, the kernel doesn't know what to see when dealing with special connections. NAT helper is the connection tracking Helper extension, which will tell the kernel to find something in the package, how to convert them, so that this connection can really work. For example, FTP is a complex protocol that uses the valid data portion of the package to send connection information. If a machine that needs to be by NAT (the translator's note: That is, the machine is connected to the FTP server on the Internet, it will put your own intranet IP address in the package of the package. So that the FTP server can be connected to that address. But private addresses cannot be used outside of LAN, so the FTP server does not know what to do with it, the connection will be broken. FTP Nat Helper can complete all address conversion work in these connections, so the FTP server knows where to connect. The same thing also happens in DCC file transfer (herein refers to sending) and chatting, in order to establish a connection, IP addresses and ports need to be sent using the data area of the IRC protocol, and also do some conversion work. Without these helper, only some of the FTP and IRC work is normal, but the other part will not work. For example, you can receive files through DCC, but you can't send it. The reason for this problem is how DCC is established. When the DCC wants to send a file, you will tell the recipient you want to send a file and let it know where to connect. If there is no helper, this DCC connection will eventually disconnect because the recipient receives the address of the intranet. This way, when it is connected to that address, it is actually a machine that is connected to it in the same intranet. So why can you receive it? Because the sender gives you an IP address that can be used on the Internet (most cases, the IRC server has a real IP address). If you encounter problems when using MIRC DCC through the firewall, but communicate with other IRC customers is normal, take a look at Appendix FAQs and answers about MIRC DCC in the answer.
In this example, we load modules that support the FTP and IRC protocol here. For more information on connection tracking and NAT, check out the common questions and answers of Appendix. In Patch-O-Matic, there are other modules such as Nat Helper, such as H.323 Concentrack Helper. However, in order to use them, you need to use patch-o-matic patch, but also compile the kernel. Detailed operation information can be viewed in the chapter preparation phase.
Note that in order to make network address translations for FTP and IRC protocol, IP_nat_ftp and ip_nat_irc are required. Before loading the NAT module, you must load ip_conntrack_ftp and ip_conntrack_irc modules. The NAT module and the CONNTRACK module are used in the same way, but the NAT module allows us to make NATs to these two protocols.
7.2.3. Settings of PROC
We can use the following statements to open the IP forwarding function (IP forwarding):
Echo "1"> / proc / sys / net / ipv4 / ip_forward
Note, when and where to open this feature is appropriate to be a problem worth considering. In the scripts used in this article, I have opened it before creating an IP filter (in this article refers to IPTables filter rules). This may cause such a situation, that is, in a period of time (the length of time with the complexity of the script and the performance of the machine, may have only one millisecond, may also be a minute, the firewall can forward any package (Translator Note: Because the firewall's filtering rules are not loaded). This situation will lead to security issues, and those who are uncomfortable may take this through the firewall to destroy our network. That is, we should open the IP forwarding function after creating the rules of all firewalls, I do just to keep all script compatibility. (Translator Note: We must pay attention to this in practical applications. Try not to open IP forwarding function first). In case you use SLIP, PPP or DHCP, that is, you are dynamically getting IP, then use The following command turns on ip_dynaddr:
Echo "1"> / proc / sys / net / ipv4 / ip_dynaddr
If you want to open another Proc option, it is also a similar approach, but about the specific introduction of those options is not the content of this article, you can take a look at other related articles. There are some short-skinned articles that introduce the kernel PROC system in the appendix other resources and links. If you can't find the information you want in this article, you can go to the appendix additional resources and links to see, you will gain something.
The script in this article also includes a section called Non-Required Proc Configuration (Non-Required Proc Setting). When there is anything that is not as normal, you can come here, it can provide you with some of the basic information, but don't change before you really understand their meaning.
7.2.4. Optimization of the rules position
This section briefly describes the script rc.firewall.txt, how will I choose, use built-in chain and custom chains. Some path I have chosen may be wrong from this or that angle, I will point out when these circumstances and problems occur. Here is a brief review to the chapter table and the chain, I hope to give you a little reminder so that you can think of how to table and chain in practical applications.
In order to take as little as possible, we have replaced all different custom chains. At the same time, I put the main energy in security and readability. I don't let TCP went to experience the baptism of ICMP, UDP, and TCP rules, but simply match all TCP packages and let it go to a custom chain to travel. This method is not better than letting it experience all rule overhead. The following figure can be explained in the NetFilter, how the foreign package is processed (in depth discussion relative to the chapter table and chain, this graph is too rough). I hope that through the explanation of the above and the graphics below can make you understand the purpose of writing this script, detailed comment in the later section.
With this graph, we can figure out the purpose of the script. The entire script is based on such a hypothesis, we have a local area network, a firewall and an Internet connection, and there is a static IP address (relative to dynamic address, the connection used by DHCP, PPP, SLIP, etc.) Run some services as a server on the Internet. We fully trust the LAN, so we cannot block any data transfer issued from the LAN. There is also a matter of priority, we only allow those that are explicitly explained as acceptable. In order to do this, we have to set the default policy to Drop. In this way, those that are not explicitly identified as allowing access to it is blocked. In the above hypothesis, we want the LAN to access the Internet. Because the local area network is fully trusted, we should allow all data from the LAN. But the Internet is not trusted, so we want to block the connection from the Internet to our local area network. Based on all the assumptions, let's consider what you need to do, don't do what we want to do.
First, we solve the problem of the LAN to connect to the Internet. Then we have to do NAT operations for all packets because the machines in the LAN have no real IP address. NAT is done in the preording chain, which is also the chain where the rule that the script is finally created. This means we have to do filter work in the Forward chain, otherwise we are allowing all external machines to fully access the LAN. Because we fully trust the local area network, all of them is allowed to pass. Since we assume that machines on the Internet cannot access machines in the LAN, it is necessary to block all connected connections in the outward, but have been established or related connections, because they are only used to respond to access to the Internet of the Internet, and Not a new connection to the intranet.
Due to limited funding, our firewall only provides limited services: HTTP, FTP, SSH and Identd. Therefore, we have to allow these protocols to pass in the Input chain, but also allow returning data to be passed in the Output chain. In addition to fully trusting the LAN, we also trust loopback and its IP address, so we have to have corresponding rules to allow all data from LAN and Loopback. But we will not allow some special packages or headers to pass, nor will they accept access to a certain paragraph IP on the Internet. For example, the network segment 10.0.0.0/8 is preserved for the LAN. In general, we do not allow packages from their bags, because such packages 90% are used to deceive. However, before implementing this standard, pay attention to a problem, that is, some ISPs are just these addresses in their network. There is a further explanation of this problem in the common problem with the appendix.
Because we run the FTP service on the firewall and want to make the package experience the least rules, put the rules that handle the Established and the Related state to the top of the INPUT chain. Based on the same reasons, we divide these rules into the child chain. In this way, the package can travelily cross the rules, thereby saving time, or reduces the redundancy of the network.
In this script, we score the package into the sub-chain according to different protocols (such as TCP, UDP or ICMP). The chain used to match the TCP package is called TCP_PACKETS, which matches all we allow TCP ports and sub protocols (such as ftp, http, etc.). We also have to create a subchain called Allowed to add additional checks before truly accepting the TCP package that uses a valid port to access the firewall. As for the ICMP package, a chain called ICMP_PACKETS is processed. When I decided how to build this chain, I consider if we agree to accept the type and code of the ICMP package, there is no need to check them, so I will accept them directly. Finally, who is the UDP package? Of course, UDP_PACKETS is. If the package is the type allowed to be received, it will be released. Because our network is small, the firewall is also used as a workstation. This requires us to allow some special protocols to communicate with it, such as Speak Free, and ICQ.
Now let's consider considering the Output chain. Because of the trustwall, we allow almost all of the package that leaves its package, and no blocking any users and protocols. But we don't want people to use this machine for IP deception, so we only release the packages from the IP from the firewall itself. To achieve this, we are likely to add such a rule in the Accept chain: if the package is sent by the firewall's IP, it will be released, otherwise they will be dropped by the default policy of the Output chain.
7.2.5. Default policy settings
Before you start writing other rules, we must use the following statement to establish a default policy:
iptables [-p {chain} {policy}]
The strategy for each chain is used to handle those packages that are not ruled in the corresponding chain. That is, if there is any rule that is not in the rule set, that strategy is useful.
To be cautiously set the strategy of the chains in other forms, because they are not used to filter packages, which may cause a very weird behavior.
7.2.6. Custom chain settings
Now, your firewall should already have a very clear impression, your heart. The heart is not as good as action, let us turn it into a reality. This section we must carefully create rules in all custom chains and chains.
As mentioned earlier, we have to build these custom strands: ICMP_PACKETS, TCP_PACKETS, UDP_PACKETS, and ALLOWED, where the AlLowed chain is called by the TCP_Packets. All ICMP packages entering $ inet_iface will be redirected to the ICMP_PACKETS chain, the TCP package is to the TCP_Packets chain, and the UDP package is naturally the UDP_PACKETS chain, and the detailed explanation is in Input Chain. Remember the command to create a custom chain? Very simple, just use the option -n, then specify the name of the chain (don't forget, the new chain is empty), as follows:
iptables [-chain]
In the following sections, we will detailed to introduce each chain to create to make you understand which rules are included.
7.2.6.1. BAD_TCP_PACKETS chain
This chain contains rules to check whether the header of the incoming packet is abnormal or has any other problems, and processes accordingly. But in fact, we use it just to filter out some special packages: No SYN bit is set but the TCP package for the New status, and the TCP package that sets SYN / ACK but is also considered to be a new state. This chain can be used to check the possible inconsistency, such as the above or Xmas Port-Scans, etc. We can also add a rule for the package of the Invalid state. If you want to fully understand the New Not Syn, you can go to Appendix FAQ and answer to see the NEW State Pack of SYN, which introduces the NEW status package that does not set SYN through other rules. Case. In some cases, this package can be allowed, but 99% is that we don't want them to pass. Therefore, we will record this package first, then throw them away.
We reject the SYN / ACK package is also very simple in New Status, in-depth instructions in the SYN / ACK package in the NEW status of Appendix and the solution. Basically, we do this for the good intention to other hosts, because we prevent the serial number predictive attack (SEQUENCE NUMBER PREDITION).
7.2.6.2. ALLOWED chain
If the package is from $ inet_iface, and it is a TCP package, it will pass the TCP_PACKETS chain test. If this connection is rolled out of the port that is allowed, we have to check it to determine if you really have to accept it. These "final trials" are carried out in the allowed chain.
First, let's see if this package is a SYN package. If it is, it is probably the first package of the new connection, which is of course accepted. If not, then look at whether the package is connected from an ESTABLISHED or RELATED status, it is accepted. The connection of the ESTABLISHED state is a connection that there is traffic in both directions. According to the statist of the state mechanism, this connection must be in the Establish state, because we can now see this package, indicating that the corresponding SYN package has been received before. The last rule will Drop all other packages. When the package arrives at the last rule, almost all connectors will have two-way communication, that is, we will not respond to the SYN package. When trying to start a new connection with a non-SYN package, the package will come to this rule. There is no practical use of the new connection without the SYN package, of course, port scans are excluded. As I know, there is no useful TCP / IP program that uses the package other than the SYN package to open a TCP connection. Therefore, we have to take such packages, I have 99% of grasp that they are port scans.
7.2.6.3. Handling the chain of TCP
The TCP_PACKETS chain specifies which ports can be accessed from Internet. But we have to do more inspections on the incoming package, so each package will be sent to the Allowed chain mentioned above.
-A TCP_PACKETS tells iptables to add rules in which chain, the rule is placed at the end of the specified chain. -p tcp Specifies that the TCP package is to match, and -s 0/0 means that the source address to match is from the network mask 0.0.0.0, in other words, it is all the addresses. This is actually the default value, I wrote that it makes you understand as much as possible. --dport 21 specifies the destination port, that is, if the package is sent to the port 21, it will match. If all criteria matches, the package is to be sent to the Allowed chain.
TCP's 21st port is also allowed to access, that is, FTP's control port, which can control FTP connections, mentioned earlier, I also allow all Related status to pass. In this way, we can also use Passive and Active (passive) to connect, of course, load the IP_ConNTrack_FTP module in advance. If we don't want to provide an FTP service, uninstall the IP_ConNTrack_FTP module and remove $ iptables -a tcp_packets -p tcp -s 0/0 --dport 21 -j allowed from the file rc.firewall.txt. The 22nd port is used by SSH. If you allow you to access your machine through Telnet (using 23 port), you still use SSH, it is much better. Note that you are a firewall, allocating any access rights to people outside your own, is not a good idea. Firewalls should always be exposed as little as possible.
80 is the HTTP port, that is, you have running web services on the firewall. If you don't provide web services, you will delete this rule.
Finally, we also provide IdentD services, ports are 113. This service is required for some protocols, such as IRC. Note that if you have some hosts in the intranet, the software OIDENTD is also worthwhile, it will relay the IDENTD request to the correct machine in the intranet.
If there is no match on any of the rules, the package will be sent back to the parent chain of the TCP_PACKETS chain, which is the chain where it is sent to the rule of the TCP_PACKETS chain. If you want to open more ports, just use "copy, paste Dafa" on any line of the TCP_PACKETS chain, and then modify the port number.
7.2.6.4. Handling the chain of UDP
If we encounter a UDP package in the Input chain, send it to the UDP_PACKETS chain. There, we only deal with the UDP package, so use -P UDP to specify the corresponding protocol. We accept packages from any address, so there are -s 0/0, which is actually the default value of the source address option, but in order to be more clear, we still write it out. In addition, we only accept packages sent to specific ports, which we want to open to Internet. Note that we do not need to decide whether to open a port according to the source port of the sender, this work is done by the status mechanism. If we want to run a service (such as DNS) using a UDP port, as long as the corresponding port is opened, the other ports do not need to open. Those who are in the ESTABLISHED, packets that are entering the firewall are reaching the rules containing -State Established, Related (this is the first rule in the INPUT chain "to handle the rules from the Internet), will be accepted. .
We don't accept the UDP package for foreign ports, which means that we don't want to accept foreign DNS queries. In fact, the rules have been written, I just drop it. If you want to put the firewall as a DNS server accessible to the Internet, then remove the comment symbol.
In my personal concern, I will open the 123-port port, and its corresponding protocol is NetWork Time Protocol, referred to as NTP. We can use this protocol to contact some time server with exact time to set the time. Most of you may not use this agreement, so I also commented it, although I have written the rules.
I opened the 2074 port, which is used in some real-time multimedia applications. For example, Speak Freely, you can use this program to communicate with others through speakers, microphones or headsets. If you don't need it, please comment this rule. Port 4000 The corresponding protocol is an ICQ protocol, used by ICQ, one of the most widely used chat programs in the world, "Earth people know". There are at least 2-3 different ICQ clones on Linux. I don't want to explain why I have to open this port. (Translator Note: Domestic chat procedures, common QQ (port 8000), now there is UC (port 3001), etc.)
If you are experiencing the distress of the logs, there are two additional rules to use, of course, this is because what is caused. The first rule of us will block the destination port is a broadcaster of 135 to 139. Most Microsoft users use NetBIOS or SMB, and they use these broadcast packages. This rule can block all the broadcast packages generated by Microsoft Network in the external network, and our logs can be simple. The second rules are also solving the log problem, but the problem of the problem has changed, this is the DHCP query of the external network. If your outer network is composed of non-exchange Ethernet, where the client can get an IP address through DHCP, that is, if there will be many DHCP query broadcasters in the external network, then this rule is enabled.
Note that I also commented in the last two rules, because some people may want to see related records. If you are experiencing the pain of "too much legal log", try discarding those bags. In fact, in the INPUT chain, there are more rules of this type before these two logs.
7.2.6.5. Handling the chain of ICMP
Now, we should decide which ICMP types can be accepted. In the INPUT chain, if the ICMP package is entered from ETH0 (i.e., the Internet interface of this example), we will redirect it to the ICMP_PACKETS chain (previously mentioned) to check if it is acceptable. Currently, I only accept three ICMP packages: ICMP Echo Requests, TTL Equals 0 During Transit and TTL Equals 0 During Reassembly. By default, any other ICMP type is not accepted is that almost all other types of ICMP packages are the Related state, that is, they are all processed by the rule of the Related state.
If an ICMP package is used to respond to "package or flow", it is related to those streams, that is, its status is Related. More information is in the chapter state mechanism.
Now let's explain why I only accept three ICMP packages mentioned above. Echo Request is used to request Echo Reply, which is mainly used to ping other machines to determine if those machines are available. If there is no rule, other machines will not be able to determine if we are available through ping. Note that some people tend to delete this rule, just because they don't want to be seen by the Internet. Deleting this rule will make anything from the Internet, the PING of our firewall is invalid, because the firewall has not responded at all.
Allow timing (TIME EXCEED, such as TTL Equals 0 During Transport During Transfer Spending Time is 0) During the Data Running During the Data Quotation time is 0) information, we can track the path from local to a host, Or when the TTL of the package is 0, we can get the response information. For example, when we track the path to a host, it will start with a package of TTL = 1. When it gets the first route, TTL is reduced to 0, and we will also get the timeout information returned by the first route. Then the package of TTL = 2, we will get the timeout information returned by the second router. So until the information returned by our destination host. In this way, we can get a response from every host on the path, so we can see every host on the path, you can know which machine is broken. The complete ICMP type list is in the appendix ICMP type. More information and usage about ICMP type, I suggest you see the following article:
Ralph Walden's The Internet Control Message Protocol. J. Postel RFC 792 - Internet Control Message Protocol.
Note that I block all ICMP packs I don't want to accept, this may have problems with your network, but in me, everything works fine.
7.2.7. INPUT chain
Most of my INPUT chain is to use other chains to complete this difficult job. In doing so, we don't need to load too much from iptables (Translator Note: This is a rule that is loaded with the INPUT chain, because the other rules have been loaded), and it is also on the slower machine. It can work very well, but on the other hand, such a machine will still discard a lot of packages during high load (the translator's note: the machine is slow, it is not line). This is because we can determine their category for a large number of different packages, we will send these packages to the corresponding custom chain to process. In this way, we can split the rules of the rules that contain few rules, and each package is going to experience. Thus, when the package is filtered, the firewall is expensive.
First, we have to check if the form of the entry TCP package is not normal or we don't want. This work is done so, we send all TCP packages to the Bad_TCP_PACKETS chain, check it by the rules, and specific descriptions in the section Bad_tcp_packets chain.
Then we start processing data transfer of trusted networks. This includes all traffic from "NIC", all from and sent to loopback (pay attention, and the IP address corresponding to loopback includes all assigned to the firewall, including the address of the Internet) . We put the rules of the traffic of the LAN in the upper part of the firewall because our local area network is far more than the Internet connection. In this way, the rules will be more efficient, and the firewall can match the package with a smaller overhead, so that the possibility of network blocking is reduced, and it is also convenient for us to see what is the main type of the firewall.
Some of the following rules handle information from the Internet, with a related rule before touching these rules, we can use it to reduce some overhead. This is a rule that processes the status, which allows all packets that are in state ESTABLISHED or RELATED and sent to the Internet interface. There is a similar rule in the allowed chain (the translator's note: it is quiz, I suggest that everyone will take it off). In order of order, of course, the rules in the INPUT chain will be treated first. However, there are still some reasons for the allowed chain --state Establish, the Related rules, such as, so that some people want to cut this feature and paste them elsewhere. In the Input chain, we will send all TCP packages from $ inet_iface to the TCP_PACKETS chain, similarly, send UDP packages to the UDP_PACKETS chain, send the ICMP package to the ICMP_PACKETS chain. Generally speaking, the most popular package encountered by the firewall is a TCP package, followed by a UDP package, and finally ICMP package. But note that this is just a general situation and may not apply to you. The same rule is different because of the different order, or the logic is different, and the efficiency will have a big difference. If the rule is not written, even if there is only 100 rules, and there is a 100Mbit network card, even if the Pentium III's machine will also eat. So you must pay attention to this when you write the rules.
Here is an annotated rule. In case there are some Microsoft networks outside our firewall, we can enable it to lift too much troubles. Microsoft's client has a bad habit, which is to send a large number of multicast packages 224.0.0.0/8. So we have to have this rule to block those packages, so as to be filled by them. do you remember? There are two similar rules in the UDP_PACKETS chain. If you forget, let's take a look at the chain of UDP.
Before the other package is handled by the INPUT chain, we will record them in order to find possible problems or bugs: it may be that we don't want to allow it to enter the package, or what is the bad thing for us Users may also be a firewall problem. If we block the package that should be released. We have to understand all situations so the problem can be resolved. We record up to 3 packs per minute, because we don't want to make nonsense to talk nonsense. In order to easily identify the source of the package, we also set a prefix for all records.
All packets that are not processed by the above rules will be dropped by the strategy DROP. The strategy is set in the set of default strategies in this chapter, and we are far away.
7.2.8. Forward chain
In this example, the rule containing the Forward chain contains very few. First, we will send all the bags to the BAD_TCP_PACKETS chain. This chain we mentioned many times, it can be called by multiple chains, in fact it is designed for this purpose.
Then the main rule of the Forward chain. The first allows all data from $ lan_iface, there is no limit, that is, our LAN is free to access the Internet. The second package allows the ESTABLISHED and the RELATED state to pass through the firewall. In other words, all the responses issued by our intranet can return to the local area network. In order to enable our intranet to access the Internet, these rules must be because we have set the policy of the Forward chain in front of DROP. This setting rule is also very smart because it prevents Internet access to the LAN while ensuring that the LAN can access the Internet.
Finally, we also have a rule that handles the log, used to record the package that is not matched by any of the above rules. Such a package is likely to be abnormal or other problems, such as a hacker attack. This rule is similar to that in the Input chain, just different prefixes, here is: "IPT Forward Packet Died:". The prefix is mainly used to separate the log record, which makes it easy for us to find some information from the package and the header. 7.2.9. OUTPUT chain
Apart from almost no one to use the firewall as a workstation, it is because of this, I will allow almost all of the data from the firewall's IP (including localhost_ip, $ lan_ip or $ static_ip), which blocks other situations. Because anything else may be deceived in some way. The last rule is still used to record packages that are to be dowed by the strategy DROP. In this way, we can understand them, which will continue to be active on the problems that are generated (maybe a threatening mistake, or for spoof packages).
7.2.10. PREROUTING chain
As the name suggests, the prerouting chain (NAT table) is to do network address conversion before routing. Then, the package will be sent to the INPUT or Forward chain of the FILTER table. The only reason we are discussing this chain is that we feel responsible to point out that you should not do any filter in this chain. The preording chain will only match the first package of the flow, that is, all other packages of this stream will not be checked by this chain. In fact, in this script, we have not used the prerouting chain at all. If you want to do DNAT operations for some packages, for example, you put the web server in the LAN, here is where you put the rules. Details about the preloading chain are in the chapter table and the chain.
It is noted that the preording chain can only be used for network address transformation, which cannot be used to make any filtering, because each stream is only the first package will pass this chain.
7.2.11. Postrouting Chain
Our final task should be constructed to construct network address transformation, right? At least it is for me. We only added a rule in the PostRouting in the NAT table, which will perform NAT operations for all packages from the Internet (for me, this is ETH0). In all example scripts, there are some variables that are to be configured with the correct configuration. Option -t Specifies to insert rules in that table, here is a NAT table. Command -a Description We have to add rules to the end of the postrol chain. -o $ inet_iface Specifies the package to match all from the interface INET_IFACE, where we use Eth0. Finally, we set the target to SNAT. In this way, all packets that match this rule will be processed by the Snat Target, and then their source address is the address of the Internet interface. Don't forget that Snat is necessary to have an IP address, set it with --to-source.
In this script, we choose SNAT without masquerade. The main reason is that our firewall has a static IP address, which will be more effective faster to use SNAT. Another reason is that we have to show its role in this example and how to use it. If you don't have a static IP address, if you want to implement SNAT, or use Masquerade as well because it is easy to use, and it can automatically get the IP address. Of course, the consumption of the computer will be more worthwhile if you use DHCP. If you want to know the manifestation of Masquerade Target, you should look at the script rc.dhcp.firewall.txt. Chapter 8. Introduction
The purpose of this chapter is to give each script mentioned in the guide to explain, and provide a framework for these scripts to describe their services. These scripts are not available any case, they may not meet your intentions. In other words, in order to meet your needs, it is still necessary to depends on yourself. In this regard, the following content may give you a lot of help. The first section describes the structure of these scripts, and you will find that the way we use in these scripts is still relatively easy.
8.1. Rc.firewall.txt script structure
All scripts in this guide are written in accordance with a specific structure. Reason, that is, this can make them similar to each other, which makes it find out. This chapter will make a good description of this structure, and will also simply describe why these scripts will be written in this look, and why I have used this structure.
Note that even if I choose this structure, you don't necessarily use it. For you, it may not be the best. I chose it just because it is easy to read, and I can meet my logic.
8.1.1. Script structure
This is the script structure that follows all scripts in this guide. If there is a different place, it may be that I have an error, unless I specifically explain why this structure is broken.
Configuration - The first is a configuration option area, which is used in the script. Almost any script's first part is the configuration optionspace.
Internet - Configuration for Internet Connections. If we don't have any Internet connection, this section can jump over. Note that this part may contain more shorts than we are listed, although we have only a few, but it is enough to connect our existing Internet.
DHCP - If the script uses DHCP, we have to add a corresponding configuration here. PPPoE - If you want to use the script for the PPPoE connection, you should add a corresponding configuration here. LAN - If there is a local area network after the firewall, you should use it here. It will be used here in most cases because the local area network is almost always existing. DMZ - Configuration of non-military zone (DMZ Zone). Most scripts will not be used this setting because these scripts are mainly some of ordinary home networks, or small businesses. LocalHost - Local-Host's related settings. Although I write them into variables, it is generally not changed, and there should be no reason to change them. iptables - settings for iptables. In most cases, only one variable is set to point to the iptables program. Other - If there is any information, you should first put them in the corresponding section. If there is no corresponding section, let it go. Module Loading - The script should maintain a list of modules. It is divided into two parts, the first part contains the required modules, and the second part should contain a list of unnecessary modules. Note that these modules may increase security, or add certain services to managers, and some modules are not required, but they may have also been added. However, in this case, I have already paid this question.
Required Modules - The necessary modules are loaded here, they may increase certain services for the manner, customers increase certain services. Non-Required Modules - The unnecessary modules are listed here, so they are all commented. If you use the features they provide, you can enable them. Proc Configuration - This is concerned about the settings of the PROC system. If some options are must, we enable it. If not, you will comment out. Most useful Proc configurations are listed here, but it is far from all.
Required Proc Configuration - All necessary PROC configurations that make the script can work normally, which can also include options that improve security or administrators, customers add specific services. Non-Required Proc Configuration - The option mentioned here is not required, although they may be useful. Therefore, I will tell them all. Of course, there is no such option here. Rules Set Up - Now, the rules should be added. I clearly allocated all rules into the table and chain corresponding section. All custom rules are written before the built-in chain in the system (the translator's note: Of course, it is going to write, because there is a call to call them). In addition, I am arranging the order of this script and the chain in the order of the order iptables -l output (the translator's note: This is convenient for us to view it).
Filter Table - The first is the Filter table, and we first set the policy.
Set Policies - Settings Strategies for all systems. Typically, I will set the DROP, and the services that allow for use are explicitly given to Accept. This way, we can easily eliminate all we don't want to use ports. CREATE User Specified Chains - Create all the custom chains that will be used later. If you don't have in advance, you can't use them later, so we have to build these chains as soon as possible. Create Content In User Specified Chains - Create the rules used in the custom chain. In fact, you can also write these rules in some places in some places, the only reason is that this rules and chain will be close to it, which is convenient for us to view. Input Chain - Create the rules of the INPUT chain. From here, I just follow the iptables -l output format to create rules, the only reason for this is to make it easy to read and avoid confusion.
Forward Chain - Create a rule for the Forward chain. Output Chain - Create a rule for the Output chain. In fact, there are very few rules to build here. NAT TABLE - The setting NAT table after processing the Filter table. We have a reason for doing this. First, we don't want to open the forwarding mechanism too early (the translator Note: : We opened NAT, but the filtering rules have not yet run) through the firewall. Also, I regard NAT table as a layer around the Filter table. That is, the Filter table is the core, the NAT table is a layer outside it, and the Mangle table is the second layer. From some point of view, this may be a bit wrong, but it is also eight or nine.
Set Policies - Like Filter, let's set the strategy first. Generally, the default strategy, that is, Accept, it is very good. This table should not be used to make any filtration, and we should not discard any bag here, because there may be some difficult things that are difficult to deal with for the network of us assume. I set the policy to Accept, because there is nothing why it doesn't do it. Create User Specified Chains - Create a custom chain that the NAT table here is available here. Under normal circumstances, I have no rules to build here, but I still retain this section to prevent it. Note that you must build a corresponding custom chain before you build chain calls in the system. Create Content In User Specified Chains - Rules for establishing a custom chain. PREROUTING CHAIN - If you do DNAT operations to the package, you should use this chain. Most scripts will not use this chain, or take off the rules inside, because we don't want to tear open a big mouth on the firewall without understanding it, this will threaten our local area network. Of course, there are some scripts to use this chain by default because the purpose of those scripts is to provide such services. PostROUTING CHAIN - If you use SNAT, you will build a rule here. You may have one or more local area networks to protect the firewall, and I will write this script based on such a situation, so the postrouting chain used in this script is quite practical. In most cases, we will use Snat Target, but some cases, such as PPPoE, we have to use Masquerade Target. Output Chain - no matter what script will hardly use this chain. So far, I have no good reason to use it. If you have any reason to use it, please give me a copy of the corresponding rules, I will add it to this guide. Mangle Table - The last thing to do is to process the mangle table. Usually, I will not use this table, because in general, it will not be arrived by anyone, unless they have any special needs, for example, in order to hide a plurality of machines, we have to set up TTL or TOS, etc. . In this script, this form is blank. But in this guide still has a small example of the use of the mangle table. Set Policies - Settings Policy. The situation here and the NAT table are almost identical. It should not be filtered here, and any bag should not be discarded. I will not set the policy table to other values in any script, nor does it encourage you to do this. Create User Specified CHAINS - Create a custom chain. I barely use this chain, so I don't have any rules. Keep this section, just after it is already available. Create Content In User Specified Chains - Rules for establishing a custom chain. PREROUTING - All scripts in this guide are not established in this chain. Input Chain - All scripts in this guide are not established in this chain. Forward Chain - All scripts in this guide are not established in this chain. Output Chain - All scripts in this guide are not established in this chain. Postrouting Chain - All scripts in this guide are not established in this chain.
This should be explained in more detail how each script is structured and why do they use this structure.
Note that the above description is actually very simple, it should be seen as a summary, it briefly explains why the script is written in accordance with this loose structure. I don't pay attention to it, I haven't said this structure is the only one, the best.
8.2. Rc.firewall.txt
Script rc.firewall.txt is the core, Chapter 7 Firewall Configuration Instance Rc.FireWall has made a very detailed explanation of it, and other scripts are based on it. This script is mainly designed for a home network with two connected, such as a local area network connection, an Internet connection. We assume that you have a static IP address, don't need DHCP, PPP, SLIP, or other protocols to dynamically allocate IP. If you want it is just using these protocols, you will go to rc.dhcp.firewall.txt.
Script rc.firewall.txt To fully function, the system must have the functions listed below, you can compile them into the kernel, or compile into modules. If you change the script, join the corresponding functional module or you can submit them the kernel.
CONFIG_NETFILTER config_ip_nf_conntrack config_ip_nf_iptables config_ip_nf_match_limit config_ip_nf_match_state config_ip_nf_filter config_ip_nf_nat config_ip_nf_target_log
8.3. Rc.dmz.firewall.txt
This is the case that the script rc.dmz.firewall.txt is this: there is a trusted intranet, a DMZ, and an Internet connection. The DMZ here is obtained by setting one-to-one NAT operation, it requires an IP alias (that is, sets multiple IP addresses on a single network card). We have other ways to implement DMZ: If you have a whole network segment, you can divide the subnet, then divide a subnet to DMZ, and then configure the corresponding intranet and external network IP address (Translator's Note : The first method is for the case of multiple network segments, namely a network segment, a network segment of DMZ, and the second method is to divide a network segment into several subnets, which is the same as the first case. . Note that this method will consume two IPs, one is the network address, one is the broadcast address (the translator Note: Please check the information about the subnet division, this guide does not contain such information). Which one of the above two methods is to be determined. This guide will give you a means of firewalls and NAT or called technology, but how to do, there is no complete description, because this has exceeded the scope of this article.
This script requires the following modules, or they have been compiled into the kernel.
CONFIG_NETFILTER config_ip_nf_conntrack config_ip_nf_iptables config_ip_nf_match_limit config_ip_nf_match_state config_ip_nf_filter config_ip_nf_nat config_ip_nf_target_log
As can be seen from the figure, this script assumes that you have two intranets, one is a trusted intranet, using address 192.168.0.0/24, the other is DMZ (we are doing one-to-one NAT) , Use address 192.168.1.0/24. If someone sends a package from the Internet to our DNS_IP, we have to use DNAT, after which the destination address of this package points to the DNS server in DMZ, it can also reach the real DNS server. Otherwise, the DNS server will not see this package, and there is no response. Below is a statement that implements the above DNAT functionality:
$ Iptables -t nat -a preording -p tcp -i $ inet_iface -d $ dns_ip /
--DPORT 53 -J DNAT - TO-DESTINATION $ DMZ_DNS_IP
We can see that this rule is to be placed in the prerouting chain of the NAT table. The conditions that the package should be satisfied is: Use the TCP protocol and use the 53-port port, enter the interface $ inet_iface, and to be available for $ DNS_IP. The matching package is handed over to the DNAT Target, which will change the destination address of the package to the address specified by -to-destination $ DMZ_DNS_IP. This is the workflow of DNAT. When the corresponding answering package is sent to the firewall, it will be automatically subjected to UN-DNAT.
Now you should read this script now. If you don't understand what you don't understand is not used in the other parts of the script, it may be my mistake, tell me.
8.4. Rc.dhcp.firewall.txt
Script rc.dhcp.fireWall.txt is suitable for situations where DHCP, PPP, or SLIP connects to the Internet, which is almost the same as the original script rc.firewall.txt, the main difference is no longer using the variable static_ip. The reason is very simple, it is it can't be used with dynamic IP. This script is very small relative to the original script, but there are still some people who ask me to change. After everyone's test, this script should be a good solution.
It requires the following functional modules.
CONFIG_NETFILTER CONFIG_IP_NF_CONNTRACK CONFIG_IP_NF_IPTABLES CONFIG_IP_NF_MATCH_LIMIT CONFIG_IP_NF_MATCH_STATE CONFIG_IP_NF_FILTER CONFIG_IP_NF_NAT CONFIG_IP_NF_TARGET_MASQUERADE CONFIG_IP_NF_TARGET_LOG
The change I made is mainly to delete the variable static_ip and all things related to it. Previously, the main filtration work was based on the variable static_ip, and now is inet_iface. That is, in this script, we no longer use -d $ static_ip as the filtering condition, but use -i $ inet_iface. This is almost the only change and the necessary changes.
There are still some problems to consider. Now, we cannot filter with certain conditions, such as - INTERFACE $ LAN_IFACE - DST $ INT_IP (Translator Note: INT_IP). This is forced to use the Internet interface based on the Internet interface, in which case the internal network must access the variable Internet IP. There will be some problems, there is an example to explain this, that is, we run HTTP services on the firewall. If we visit this website (where the home page contains a static connection pointing to the HTTP server, this may be a dynamic DNS solution), the problem is exposed. After the NAT operation, the machine will query the IP of the HTTP server to DNS, and then try to access this IP. In case, we are filtered based on interface and IP, this machine cannot access HTTP, because the Input chain DROP off this package (Translator Note: Or because the IP of the Internet interface is not fixed). In some cases, this will happen when you have a static IP, but in that case, we can add a rule to check if the package of the LAN interface is sent to inet_ip, if yes, then Accept. If you have seen the previous content, get or write a script that can get dynamic IP may be a good solution to a problem. For example, we can write a script that is tight with the startup of the Internet connection, and it can extract IP from the output of the command ifconfig, and then assign this IP to a variable. A preferred way is to use some programs that come with the scripts such as the script IP-Up of the PPPD. There are also some websites, such as LinuxGuruz.org, providing a lot of useful scripts, you can find its links in appendix additional resources and links.
This script is a bit more than rc.firewall.txt. I clearly recommend that you use the latter as much as possible, because the former is open, so the threat of external attacks is big.
There is also a method to get IP, just add a statement like this in the script:
INET_IP = `ifconfig $ inet_iface | GREP INET | CUT -D: -F 2 |
/
Cut -d '' -f 1`
The role of the above sentence is to extract the IP of the INET_IFACE from the output of the IFConfig, and then assign $ INET_IP. A better way is to use the script RetreiveIP.txt. But note that this method may cause some abnormal situations, such as stopping the existing connection between the firewall and the internal network. Here is the most common problem.
If the code of this script is running in another script, and that script is started by PPP Daemon, it will hang because New Not Syn Rules (Specific Information Views No SYN NEW State Pack) Current active connection. If you delete the rule, there may be no things, but it is still not insurance. If you don't want to change the existing rules, but also to add or delete rules, it will not harm the existing rules, which can't do it. For example, you want to block the machine in all local area networks to access the firewall, and want them to control the PPP Daemon on the firewall. If you don't delete the rules used to block, how can you complete this? Things may not be so complicated, just like the above, this will lead to some security issues. But if this script is easy to maintain, the order of maintaining rules is easy to find problems.
8.5. Rc.utin.firewall.txt
Script rc.utin.fireWall.txt is suitable for this situation: We do not trust any network connected to the firewall, including the intranet. We only allow intranet to use POP3, HTTP, and FTP. As for connecting, permissions, and other scripts from the Internet. This script requires the following functional modules.
CONFIG_NETFILTER config_ip_nf_conntrack config_ip_nf_iptables config_ip_nf_match_limit config_ip_nf_match_state config_ip_nf_filter config_ip_nf_nat config_ip_nf_target_log
The principle of this script follows is not to believe anyone, including our own employees. This is a sad reality, most of the damage and attacks are indeed from our interior. This script just gives you an example in strengthening firewalls. It and rc.firewall.txt did not have too much difference, just some of some of the allowable rules.
8.6. Rc.test-iptables.txt
This script is used to test all the chains in iptables. Of course, this should be done according to your configuration, such as opening ip_forwarding or setting Masquerading, and so on. You can use it as long as your installed basic iptables can be used. In fact, this script only uses logs so that all PING requests and answers can be recorded. In this way, we can understand which chains are traveled and traveled. The method is as follows, first run this script, then release a ping command, such as:
Ping -c 1 host.on.the.internet
Then use the command tail -n 0 -f / var / log / message to see which chains and what the order is replaced unless the record is replaced by some reasons.
This script is only written for testing. That is, do not use a rule similar to this, which records all the information of a class package, which will quickly account for your log partition, and it will become a valid DOS attack. It may also result in real attack information after the initial DOS attack.
8.7. Rc.flush-iptables.txt
rc.flush-iptables.txt should not be called scripts, it is just reset and empty all tables, chains. It first sets the policy of the Filter table for the policy to the default Accept, then the PREROUTING, PostRouting, and Output chain of the NAT table. We don't have to worry about closing connections and unblosed bags. This script is for firewall settings and amplifies, so we only care about opening all things and restoring their default values.
After that, we clear all the chains in the Filter table, followed by the NAT table. In this way, there will be no rules that should not exist. This will delete the Filter table and the custom chain in the NAT table. At this time, the work of the script should be completed. Of course, if you use the mangle table, you can add the corresponding empty rules in this script. (Translator Note: In fact, the author has been doing this)
Finally, some people write to the letter that I put this script in the rc.firewall script, and the syntax of the Red Hat Linux script so that this script can also be activated when Rc.firewall starts. But I won't do this, because this is a guide, mainly used to learn the use of iptables, should not have too many SHELL scripts unique syntax. Join the Shell script unique grammar increases the difficulty of reading, which is far from my original intention. This guide is written according to the easy-to-read standard, and I will continue to do this later.
8.8. Limit-match.txt
This script is used to test Limit Match, and you will make you understand how Limit Match works. Load this script, send a ping packet with a different time interval, you can see which package can be passed, and these packages are adopted. You should be able to see that all Echo Replies will be blocked before the Limit's BURST value arrives again.
8.9. Pid-owner.txt
This script illustrates how to use Pid Owner Match. It doesn't do anything, but you can run, or the output of iptables -l -v will show that it does match something.
8.10. Sid-owner.txt
An example of how Sid Owner Match uses. Similarly, it is also nothing, but you can run, the iptables -l -v output will show that it does match something.
8.11. TTL-Inc.txt
A small example illustrates how to hide our firewall or router so that the tracking router can't see so that you can hide a lot of information on possible attackers.
8.12. Iptables-save ruleset
This is just an example of an output, which is used in the regular saving and recovery to illustrate how the iptables-save command is used. So, it doesn't have any use, just a reference.
Appendix A. Common Order Details
A.1. View the command of the current rule set
See the rule set that is currently in use is a very common operation, what ordlined uses iptables still remember? We introduced this chapter that is practiced in the rule. Although it is simple when it comes to it. Retrieve it, the command syntax is as follows:
iptables -l
This command will display the rule set currently in use as much as possible. For example, it will try to represent the port number with the corresponding name in the file / etc / service, indicate the IP address with the corresponding DNS record. However, the latter may cause some problems, for example, it wants to try to parse the LAN's IP address (e.g., 192.168.1.1) into a corresponding name. But 192.168.0.0/16 This network segment is private, that is, it can only be used in the LAN without being used in the Internet, so it won't be parsed by DNS servers on the Internet. Therefore, when the address is parsed, the command seems to stop there. In order to avoid this happening, we will use the options:
iptables -l -n
If you want to see each policy or each rule, a simple traffic statistics of each chain, you can add a Verbose flag after the above command, as follows:
iptables -l -n -v
Don't forget, the iptables -l command can also view the contents of the NAT table and the mangle table (more don't forget, the default table is filter), just use the -t option, such as the rules we just want to see the NAT table, Use the following command:
iptables -l -t nat
In / proc, there may be some files you will be interested. For example, you can see which connections are currently in the connection tracking record. This table contains all current connections, you can also learn what states in each connection. Be careful, this table cannot be edited, even if it can, it should not change it. You can view this table with the following command:
CAT / proc / net / ip_conntrack | less
This command displays all current tracked connections, but it is a bit difficult to read those records.
A.2. Correct and empty iptables
Even if you make the iptables, we also have a very effective command to process without having to restart your computer. I have received a lot of inquiry about this question, so I think it is best to answer here. If you have a problem with the rules, you want to delete it, just change -a in the command to -d. In this way, iptables will find that error rules and delete it, but if there are several same rules in your rules, it can only delete the first one. If you don't want to happen like this, try using the serial number to delete. For example, you want to delete the 10 rule of the INPUT chain, you can use iptables -d input 10. There is also a situation, that is to empty the entire chain, this is to use the option -f. For example, we have to empty the entire INPUT chain, and the command used is iptables -finput. However, pay attention to, option -f does not change the default policy of the chain. So, if the strategy of the INPUT chain we can't empty is DROP, it will still block all packages. How can you reset the strategy? Remember how the strategy DROP is set, or use that method. For example, we change the strategy of the Input chain to Accept, use iptables -p input accept.
I have written a script used to empty and reset iptables, called rc.flush- iptables.txt (there is a code in the appendix), which is likely to be used when you write your own firewall script. But if you have caused problems in the mangle table, this script is not busy. Because in the script rc.firewall.txt, I didn't use the mangle table, so there is no corresponding recovery function in rc.flush-iptables.txt.
Appendix B. Frequently Asked Questions & Answers
B.1. Module loading problem
When loading the module, you may encounter a few questions, for example, there is an error message that there is no name that you specify the name:
Insmod: iptable_filter: no module by
That name Found
This tips are irrelevant because those modules are likely to be static compiled into the kernel. This is what you should first think of when you encounter this information. As for whether it is really as we think, the simplest test party is to knock a command to use the module function. For the above situation, it may be that the Filter table has not been loaded, so that there is no corresponding function, of course, the Filter table cannot be used. In order to check if the Filter table is loaded, you can use the following command:
iptables -t filter -l
This command outputs all chains in the Filter table, or runs failed, gives an error message. If everything is normal, the output is similar to the situation below. Of course, this will also see if you have joined the rules in the Filter table (the translator Note: In this example, the table is empty).
CHAIN INPUT (Policy ACCEPT)
Target Prot Opt Source Destination
Chain Forward (Policy ACCEPT)
Target Prot Opt Source Destination
Chain Output (Policy ACCEPT)
Target Prot Opt Source Destination
If you do not load the Filter table, you get the following information:
iptables
V1.2.5: Can't Initialize iptables Table `Filter ': Table / Does Not Exist (Do You NEED TO INSMOD?)
Perhaps iptables or your kernel needs to be upgraded.
This problem is somewhat serious. From this prompt we can get two information: First, we do not compile the corresponding function into the kernel; second, this module should not be found in the directory of the module. This means that the problem is that you or forget the module that is ready to use, or does not update the module database with the depmod -a command, or does not compile the corresponding function into the kernel (whether it is still still as a module). Of course, it may also be other reasons, but these are the main, in any case, mostly because most reasons are easy to solve. For example, the first question can simply solve the Make modules_install command in the internal nuclear source directory, which is of course premise, the source code has been compiled (Compile) and the module has been built. The solution to the second question is also very simple. Just run the depmod -a command, then look at whether it can work properly. The third issue is a bit beyond our scope, and this problem is more or less to make you feel dizzy. More information can be found in the Linux document plan.
When running iptables, you may also get another error message:
iptables: no chain / target / match by That Name
This shows that the chain or target you have to use, or Match does not exist, there are many reasons, but the most common thing is that you are missing. This error will also be generated when you want to use an unavailable module. The reason why the module is not available may be because you don't have the correct module, or the kernel does not contain that module, or the iptables automatically loads the module. Typically, you should not only consider all the solutions mentioned above, and consider the spelling errors in the rules, or other reasons.
B.2. Nothing set of SYN NEW status package
Iptables have a "feature" that is not well given, so many people (of course, including me) ignore it. This "feature" is: If you use the status new, then the SYN package is not set to the firewall. This feature is because in some cases, we want to treat such a package as a part of the ESTABLISHED state. This feature makes it possible to work with two or more firewalls, and the data is not lost in the server, such as the auxiliary firewall to accept the operation of the firewall of the subnet. But it will also cause this: Status New will allow almost all TCP connections to enter, regardless of whether there is 3 handshakes. In order to deal with this problem, we need to add the following rules in the firewall's INPUT, OUTPUT and Forward links (Translator Note: This rule is called "New Not Syn Rules", the next section will mention):
$ Iptables -a
INPUT -P TCP! --SYN -M STATE --STATE New -j log /
--Log-prefix "New Not Syn:"
$ Iptables -ainput -p tcp! --Syn -m state --state new -j drop
WARNING, in the Netfilter / Iptables project, this feature has the lack of document description, more clearly, on your firewall, it is a very unsafe factor. Note that this rule is used for Microsoft TCP / IP (Microsoft implemented TCP / IP is not, at least not now), is still a problem. If the package is generated by Microsoft's product, and is labeled as a state new, then the rule record is then discarded. It seems that the rules are working very normal, yes. But the problem is here, because the connection cannot be interrupted. This problem occurs when the connection is turned off, after the last package, the FIN / ACK package, the NetFilter's status mechanism will turn off the connection and delete the corresponding record in the connection trace table. But at this time, Microsoft's imperfect program will send another package. This package is the package that is not set to SYN and is considered to be a new state, so it will match the above rule. In other words, it is not necessary to pay too much for this rule. If you are in mind, add options in the rules --Log-Headers. This way, you can record the header, so you can better understand the corresponding package.
There are also some known issues for this rule. For example, a connection (such as from the LAN) has been connected to the firewall, and there is a script to activate when PPP is started. When you start the PPP connection, the connection mentioned just mentioned will be done away. Of course, this will only happen in a specific case, that is, you run the ConNTrack and NAT as a module and each two modules are loaded and uninstalled each time the script runs. If you run Telnet on the machine outside the firewall, and through this telnet connection running script rc.firewall.txt, it will also cause the above problem. In order to simply express this problem, you first prepare a Telnet connection, or other stream connection, run the connection tracking module, then load the above rules, finally, try to send some data with Telnet Client or Daemon. The effect should come out, the connection tracking code will think that this connection is illegal, because before this, it did not see any direction in any direction, more serious is that there is no SYN package, because it is The package issued by Telnet Client or Daemon is certainly not the first package of this connection. Therefore, the above rules work, that is, this package will be recorded and then throw away ruthlessly, thus interruption.
B.3. SYN / ACK package in New State
Some, the technology used by TCP spoof attack is called a sequence number prediction (SEQUENCE NUMBER). In such an attack, an attacker uses another IP access attack object (the translator's note: This is why the deception is the reason, the attacker is a machine who wants to trust another attacked object to achieve deception. The purpose of the attack object), then try to predict what serial number used by the attack object.
Let's take a look at how the typical sequence number prediction technology is deceptive. Participants: attacker [a] (attacker) attempts to pretend that another machine [O] (Other Host) to victim [V] (Victim )send data.
[A] SYN is sent to [V] with the "O] IP. [V] responds to SYN / ACK to [O]. Now, if [O] responds to this unknown SYN / ACK with RST, the attack failed, but if [o] has no ability? For example, it has already been removed by additional attacks (such as SYN FLOOD), or is closed, or its RST package is rejected by the firewall. If [O] can not destroy this connection, and [A] guess the serial number, it can talk with [O] and [V]. As long as we fail to respond to the unknown SYN / ACK package in the third step, [V] will be attacked, and we will also be tired (the translator Note: Because we are also attacked, and may also Become an attacker's replacement sheep is prosecuted, hey, it is very miserable). Therefore, for safety, we should send an RST package to [V] in the correct way. If we use the rules similar to "New Not Syn Rules" (Translator Note: In the previous section), the SYN / ACK package can be discarded. Therefore, we joined the following rules in the Bad_TCP_PACKETS chain:
iptables -a
BAD_TCP_PACKETS -P TCP --TCP-Flags SYN, ACK SYN, ACK /
-m State --State New -j Reject --Reject-with TCP-RESET
In this way, you want to be the chance of [o] above (the translator Note: The author is good humor, we don't want to be the object being used by others), and this rule is safe in most cases There will be no side effects, except for many firewalls to work together. In that case, the firewall is often transmitted, accepted, and there is this rule, and some connections may be blocked, even if it is a legal connection. The existence of this rule has also produced another problem, that is, several portscan (port scanners) will see our firewall, but it is just this.
B.4. Use the private IP address ISP
A friend told me that some things I have forgotten, from the time, I put this section. The network you just connected to the Internet is provided by ISP, but some stupid ISPs are using private addresses in that network, and that IANA is specifically assigned to a local area network. Swedish Internet Service Provider and phone monopoly enterprise Telia is doing so, for example on the DNS server, the IP address segment they use is 10.x.x.x.x. The problem we are most prone to is that in this script, in order to prevent being deceived, it is not allowed to access us from 10.x.x.x. Unfortunately, for the above example, we have to relax a rule to the rules for DNS. That is to say, we or add a rule to the rules mentioned on the prevention of deception (as shown), or annotate that rule:
/ usr / local / sbin / iptables -t nat -i preording -i
Eth1 -s /
10.0.0.1/32 -J ACCEPT
I am willing to pay more about these ISPs. These IP addresses are not assigned to you like this stupid use, at least I know not this. For a large group's site or our own home network, this is very suitable, but you can't just force us to publicize yourself in the world because of some of your reasons.
B.5. Pulling DHCP data
Once you know how DHCP works, you will know that this is actually a very simple task. But you have to deal with it, let who enters, don't let you enter. First of all, we must understand that DHCP is above the UDP protocol, so the UDP protocol is the first condition we expect. Second, we should check it from that interface to receive and send requests. For example, if we set DHCP to use interface Eth0, then to block DHCP requests on Eth1. In order to make the rules more detailed, we only need to open the UDP port actually used by DHCP, usually 67 and 68. These two ports are standard definitions, and we use them to match the permitted package. Now, the rules should be this: $ iptables -i input -i $ lan_iface -p udp --dport 67:68 --Sport /
67:68 -J ACCEPT
Note that we can now accept all data from the UDP port 67, 68, which seems not safe, but this is not much problem, because this rule only allows the host connected to the 67 or 68 port to access. Of course, this rule can also be more rigorous, but it should also accept all DHCP requests and updates, not to open a big hole on the firewall. If you care about whether the rules are now relaxed, you can of course write a restriction condition tighter.
B.6. About MIRC DCC
Mirc uses a special setting, which allows the MIRC connection through the firewall, or the DCC connection can work normally in the case of the firewall. If this option and iptables have IP_CONNTRACK_IRC modules with IP_NAT_IRC modules, the mirc cannot work. The problem is that the MIRC will automatically perform NAT operations, so when the package arrives at the firewall, the firewall does not know what to do at all, and I don't know what to do. If it is a firewall to process, it just simply uses its own IP to ask the IRC server, and then send DCC requests with that address. MIRC does not want the firewall to replace this package in this way, in this way.
Open "I am Behind A FireWall" This configuration option is used and use IP_CONNTRACK_IRC and IP_NAT_IRC modules, which will cause NetFilter to build records that contain "Forged DCC Send Packet".
The easiest solution is to do not select the option of MIRC and let iptables do these work. It is to clearly tell Mirc, it is not behind the firewall.
Appendix C. ICMP Type
This is a list of complete ICMP types:
Table C-1. ICMP type
TYPECODEDescriptionQueryError00Echo Reply-- echo reply (Ping reply) x 30Network Unreachable-- network unreachable x31Host Unreachable-- host unreachable protocol unreachable x32Protocol Unreachable-- x33Port Unreachable-- port unreachable x34Fragmentation needed but no frag. Bit set-- Need to piece slide but set up the bit x35source routing failed - Source station selection road failed X36Destination network unknown - destination network Unknown X37Destination Host Unknown - destination host Unknown X38Source Host Isolated (Obsolete) - Source host is isolated (invalid) no) x39Destination network administratively prohibited-- purpose of the network is forced to ban x310Destination administratively prohibited-- destination host host is forced to ban x311Network unreachable for TOS-- due to the type of service TOS, network unreachable x312Host unreachable for TOS-- due to the type of service TOS, host unreachable x313Communication administratively prohibited by filtering-- since the filter, a communication is forcibly prohibited x314Host precedence violation-- host priority override x315Precedence cutoff in effect-- suspension commencement x40Source quench-- source is turned off (elementary stream control) 50Redirect for network-- Redirect 51redirect for Host - Redirect 52red For Tos and Network - Redirect 53redirect for TOS AND HOST for Service Types and Network Redirects 80 Echo Request - Election Request for Service Types and Hosts (PING Request) x 90Router Advertisement - Router Notification 100 Route Solicitation - Router Request 110ttl Equals 0 During Transit - Transfer Survival Time is 0 x111ttl Equals 0 During Reassembly - During the data report assembly time is 0 x120ip header bad (catchall error) - bad IP header (including Various errors) X121REquired Options Missing - Missing required option X130TimeStamp Request (Obsolete) - Timestamp Request (notified) x 14 TimeStamp Reply (Obsolete) - Time Stamp Answer (notified) x 150Information request (Obsolete) - Information request (notified) x 160information reply (obsolete) - Information response (notified) x 170Address mask request - Address Mask Request x 180Address mask reply - Address Mask Answer X Appendix D. Other resources and links
There are some resource links here, I have got a lot of information from these places, I believe it should also help you:
IP-sysctl.txt - from core 2.4.14, a short-intensive reference article on IP network control parameters. The Internet Control Message Protocol - A well detailed introduction to the article of ICMP protocol, the author is Ralph Walden. RFC 792 - Internet Control Message Protocol - Acouv's authority file, if you want to find information about the ICMP protocol, this is where you should first think of it. Author:. J Postel. RFC 793 - Transmission Control Protocol - TCP authority file, starting from 1981, it became TCP's norms. As long as you want to learn TCP, you must read this technical article. Author: J Postel ip_dynaddr.txt - 2.4.14, refer to the article on setting ip_dynaddr through sysctl and the proc file system from the kernel. Iptables.8 - iPtables 1.2.4 help, this is the HTML version. This is a good reference when you read the iptables rules, you should take it around. FireWall Rules Table - a small PDF file given by Stuart CLARK, which is a reference style for the firewall configuration, which is helpful to write your own firewall rules. Http://www.netfilter.org/ --Netfilter and iptables' official website is that every person intended to configure iptables and NetFilter in Linux. http://www.netfilter.org/documentation/index.html#faq - Official Netfilter Frequently Asked Questions starts learning Iptables and NetFilter's good place. http://www.netfilter.org/unreliable-guides/packet-filtering-howto/index.html - Very good packing filter foundation guide, introduces how to use iptables for packet filtering. The author is one of the core developers of iptables and Netfilter, Rusty Russell. http://www.netfilter.org/unreliable-guides/nat-howto/index.html - Introducing a good guide for network address transformation. The author is one of the core developers of iptables and Netfilter, Rusty Russell. http://www.netfilter.org/unreliable-guides/netfilter-hacking-howto/index.html - Only rare article describes how to write code in Netfilter and iptables, the kernel space, this is one of them . Author is still Rusty Russell. http://www.linuxguruz.org/iptables/ - Very good resource link page, which contains most of the Internet about iptables on the Internet, especially it contains a lot of iptables scripts written for different uses. . http://www.islandsoft.net/verapen.html - This article discusses the possibility of iptables automatically enhanced robustness, and how to make your computer automatically join the hostile sites to iptables "Prohibited List". / etc / protocols - This file is extracted from the SlackWare release. You can use this file to find the protocol number corresponding to the protocol, such as the number corresponding to the IP, ICMP, or TCP. / etc / services - This file is also extracted from the Slackware release.
It is very worth reading, you can roughly understand what port used by the agreement. Internet Engineering Task Force --ietf is one of the largest organizations to develop and maintain Internet standards. Many large enterprise groups and individuals are their members, and their work is to ensure internet interoperability. Linux Advanced Routing and Traffic Control How-To - This site mainly discusses Linux advanced routing and traffic control, this how-to is the greatest in the LINUX advanced routing. The author is Bert Hubert. Paksecured Linux Kernel Patches - This site contains all kernel patches written by Matthew G. Marsh, and ftos patches are here. Ulogd Project Page - Set of ulogd. The Linux Documentation Project - Excellent sites for Linux documents (can be said to be the best) site. There are many larger documents about Linux. If there is no TLDP, you have to search on the Internet. If you want to know more, let's take a look. Http://kalamazoolinux.org/pesentations/20010417/conntrack.html - There is an extremely wonderful example in this article, which is used to show the CONNTRACK module and its work in Netfilter. If you want to see some articles about Conntrack, this article should be read. http://www.docum.org/ - This site contains all information about CBQ (Class Based Queue), TC and IP commands, which is a few such sites in several sites. This site is maintained by Stef Coene. Http://lists.samba.org/mailman/listinfo/netfilter --Netfilter's official mailing list is very useful. In case you have encountered some problems, and this article or some links mentioned here can't solve it. It is your savior. Of course, resources are more than I mentioned above, and there are iptables source and documentation, and a lot can help your friends.
Appendix E. Acknowledgment
Many friends gave me enthusiastic help when I wrote this article, I would like to thank them:
Fabrice Marie, made a large number of revised words and spellings, and converted this guide into docbook with Make files. Marc Boucher, gave me a lot of help in the use of status matching code. Frode E. Nyboe has greatly improved the rules of Rc.firewall. When I want to rewrite this rule set, I introduced a lot of inspiration when introducing multiple table traversing. Chapman Brad, Alexander W. Janssen, I am wrong when I have the understanding of the package of NAT and FILTER tables, who makes me understand this, and they also give me the right order. Michiel Brandenburg, Myles Uyema, helped me solve some status matching code and let it work properly. Kent `artech 'stahre, help me draw graphics, and help me check the error. Anders 'Dezent' Johansson, prompts me some quirky ISP to use the reserved URL on the Internet, at least for him. Jeremy `SPLIFFY 'Smith, prompting me that some content is easy to make everyone confused, and help me test and check. There are still many people, I have been discussing with them, and I will also teach them, and I can't mention one by one. Appendix F. HISTORY
Version 1.1.19 (21 May 2003) .By: Oskar AndreassonContributors: Peter van Kampen, Xavier Bartol, Jon Anderson, Thorsten Bremer and Spanish Translation Team.Version 1.1.18 (24 Apr 2003) .By: Oskar AndreassonContributors: Stuart Clark, Robert P. J. Day, Mark orenstein and edmond shwayri.version 1.1.17 (6 Apr 2003) .by: Oskar Andreassontrols: Geraldo Amaral Filho, Ondrej Suchy, Dino Conti, Robert P. J. Day, Velev Dimo, Spencer Rouser , Daveonos, Amanda Hickman, Olle Jonsson and Bengt Aspvall.Version 1.1.16 (16 Dec 2002) .By: Oskar AndreassonContributors: Clemens Schwaighower, Uwe Dippel and Dave Wreski.Version 1.1.15 (13 Nov 2002) .By: Oskar AndreassonContributors : Mark Sonrte, A. Lester Buck, Robert P. J. Day, Togan Muftuoglu, Antony Stone, Matthew F. Barnes and Otto Matejka. Version 1.1.14 (14 Oct 2002) .by: Oskar Andreassontributors: Carol Anne, Manuel Minzoni , Yves Soun, Miernik, Uwe Dippel, Dave Klipec And Eddy L o Jansson. Version 1.1.13 (22 Aug 2002) http: // ipt ables- tutorial.haringstad.comBy: Oskar AndreassonContributors: Tons of people reporting bad HTML version.Version 1.1.12 (19 Aug 2002) http://www.netfilter.org/tutorial/By: Oskar AndreassonContributors: Peter Schubnell, Stephen J . Lawrence, Uwe Dippel, Bradley Dilger, Vegard Engen, Clifford Kite, Alessandro Oliveira, Tony Earnshaw, Harald Welte, Nick Andrew and Stepan Kasal.Version 1.1.11 (27 May 2002) http://www.netfilter.org/tutorial / By: Oskar AndreassonContributors: Steve Hnizdur, Lonni Friedman, Jelle Kalf, Harald Welte, Valentina Barrios and Tony Earnshaw.Version 1.1.10 (12 April 2002) http://www.boingworld.com/workshops/linux/iptables-tutorial / By: Oskar AndreassonControlrs:
Jelle Kalf, Theodore Alexandrov, Paul Corbett, Rodrigo Rubira Branco, Alistair Tonner, Matthew G. Marsh, Uwe Dippel, Evan Nemerson and Marcel Je Mol. Version 1.1.9 (21 March 2002) http://www.boingworld.com/ workshops / linux / iptables-tutorial / By: Oskar Andreasson Contributors: Vince Herried, Togan Muftuoglu, Galen Johnson, Kelly Ashe, JanneJohansson, Thomas Smets, Peter Horst, Mitch Landers, Neil Jolly, Jelle Kalf, Jason Lam and Evan Nemerson.Version 1.1.8 (5 March 2002) http://www.boingworld.com/workshops/linux/iptables-tutorial/by: Oskar AndreassonVersion 1.1.7 (4 february 2002) http://www.boingworld.com/Workshops/ linux / iptables-tutorial / By: Oskar Andreasson Contributors: Parimi Ravi, Phil Schultz, Steven McClintoc, Bill Dossett, Dave Wreski, Erik Sj flounder und, Adam Mansbridge, Vasoo Veerapen, Aladdin andRusty Russell.Version 1.1.6 (7 December 2001 ) http://people.unix-fu.org/andreasson/by: Oskar Andreassontributors: Jim Ramsey, Phil Schultz, G 鰎 AN B 錱 E, Doug Monroe, Jasperaikema, Kurt Lieber, Chris Tallon, Chris Martin, Jonas Pasche, Janlabanowski, Rodrigo R. Branco, Jacco Van Koll and Dave WRESKI.VERSION 1.1.5 (14 November 2001) http://people.unix-fu.org/andreasson/by: Oskar AndreassonContributors: Fabrice Marie, Merijn Schering and Kurt Lieber.Version 1.1.4 (6 November 2001) http://people.unix-fu.org/andreassonBy: Oskar AndreassonContributors: Stig W. Jensen, Steve Hnizdur, Chris Pluta and Kurt Lieber.Version 1.1.3 (9 October 2001) http://people.unix-fu.org/andreassonby: Oskar Andreassontributors: Joni Chu, N.Emile Akabi- Davis and Jelle Kalf.Version 1.1.2 (29 September 2001) Http://people.unix-fu.org/andreassonby: Oskar AndreassonVersion 1.1.1 (26 September 2001) http://people.unix-fu.org/andreassonby:
Oskar AndreassonTributors: Dave Richardson.Version 1.1.0 (15 September 2001) http://people.Unix-fu.org/andreassonby: Oskar Andreassonversion 1.0.9 (9 September 2001) http://people.unix-fu.org / Andreasson By: Oskar Andreassonversion 1.0.8 (7 September 2001) http://people.unix-fu.org/andreassonby: Oskar Andreassonversion 1.0.7 (23 August 2001) http://people.unix-fu.org/ andreassonBy: Oskar AndreassonContributors: Fabrice Marie.Version 1.0.6http: //people.unix-fu.org/andreassonBy: Oskar Andreasson Version 1.0.5http: //people.unix-fu.org/andreassonBy: Oskar AndreassonContributors: Fabrice Marie. Appendix G. GNU Free Documentation License
Version 1.1, March 2000
Copyright (C) 2000 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. Preamble
The purpose of this License is to make a manual, textbook, or other written document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially Secondarily. .,...........
This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The "Document", below, refers to any such manual or work. Any member of the public IS a licensee, and is address as "you".
A "Modified Version" of The Document Means Any Work Containing The Document OR a Portion of It, Either Copied Verbatim, or with modifications and / or translated Into Another Language.
A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal , Commercial, Philosophical, Ethical or Political Position Regarding Them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License.The "Cover Texts" are certain short passages of text that are listed, AS Front-Cover Texts or Back-Cover Texts, in The Notice That Says That The Document IS Released Under this license.
A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup Has Been Designed to Thwart or Discourage Subsequent Modification by Readers Is Not Transparent. a Copy That Is Called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and / or processing tools are not generally available, and the machine-generated HTML produced by some word processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any TITLE Page As Su, "Title page" Means the text Near The MOMINENT APPEARANCE OF THE WORK's Title, Preceding The Beginning of The Body of TEXT.2. Verbatim Copying
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. you may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you Must Also Follow The Conditions in Section 3.
You May Also Lend Copies, Under The Same Conditions Stated Above, And You May Publicly Display Copies.
3. Copying in quantity
If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. you may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.If the required texts for either cover are too voluminous to Fit Legibly, You Should Put The First On The Actual Cover, And Continue The Rest Onto Adjacent Pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparent copy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public That You Contact The Authors of The Document Well Before Redistributing Any Large Numr of Copies, To Give The Chance To Provide YOU WITH AN Updated Version of The Document.
4. Modifications
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of THE MODIFIED VERSION TOWHOEVER POSSESS A COPY OF It. in Addition, You Must do these Things in The Modified Version:
Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. List on the title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has less than five). State on the Title page the name of the publisher of the Modified Version, as the publisher. Preserve all the copyright notices of the Document. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, i n the form shown in the Addendum below. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. Include an unaltered copy of this License. Preserve the section entitled "History", and its title And add to it, year, new authors, and publisher of the model page. if the title page. if it is no section .. History
in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. in any section entitled "Acknowledgements" or "Dedications", preserve the section's title, and preserve in the section all the substance and tone of each of the contributor acknowledgements and / or dedications given therein. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the eq uivalent are not considered part of the section titles. Delete any section entitled "Endorsements". Such a section may not be included in the Modified Version. Do not retitle any existing section as "Endorsements" or to conflict in title with any Invariant Section. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. to do this, add their titles to the List of invariant Sections in The Modified Version's License Notice. These Titles Must Be distinct from any Other section Titles.
You may add a section entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties - for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You May Add A Passage of Up to Five Words as a Front-Cover Text, And A Passage of Up To 25 Words As A Back-Cover Text, To The End of The List of Cover Texts in The Modified Version. Only One Passage of Front-Cover text and one of Back-Cover text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same .
The author (s) and publisher (s) of the document do not by this license give permission to use their names for publicity for or to assert or imply endorsement of any modified version.
5. Combining Documents
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all AS Invariant Sections of Your Combined Work In Its License Notice.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work .In the combination, you must combine any sections entitled "History" in the various original documents, forming one section entitled "History";. likewise combine any sections entitled "Acknowledgements", and any sections entitled "Dedications" you must delete all sections Entitled "endorsements."
6. Collections of Documents
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for Verbatim Copying of Each of The Documents in All Other Respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
7. aggation with independent works
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an "aggregate", and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document .If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entire aggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise The Must Appear On Covers Around The Whole Aggregate.
8. Translation
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. you may include a translation of this License provided that you also include the original English version of this License. In case of a disagreement between the translation and the original English version of this License, the original English version Will Prevail.
9. Termination
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, Parties WHO Haved Copies, or Rights, from you under this license Will NOT HAVETIR LICENSES TERMINATED SO Long AS Such Parties Remain in full compliance.10. Future Revision of this license
.. The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns See http: / / www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.
How to use this license for your documents
TO Use this license in a document you have ion, incrude a copy of the license in the document and put the following copyright and license notices just after the title
. Copyright (c) YEAR YOUR NAME Permission is granted to copy, distribute and / or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. A copy of the license is included in the section entitled "GNU Free Documentation License" .If you have no Invariant Sections, write "with no invariant Sections "instead of saying which ones are invariant If you have no Front-Cover Texts, write." no Front-Cover Texts "instead of" Front-Cover Texts being LIST "; likewise for Back-Cover Texts.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
Appendix H. gnu general public license
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. Preamble
The licenses for most software are designed to take away your freedom to share and change it By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software -. To make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you Wish), That You Receive Source Code or Can Get It IT IT ITETY IN New Free Programs; And That You Know You Can do these Things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you Must show the their rights.
WE Protect Your Rights with Two Stes: (1) Copyright The Software, and (2) Offer You this license Which Gives You Legal Permission to copy, distribute and / or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses In Effect Making The Program Proprietary. To Prevent this, We Have Made It Clear That Any Patent Must Be Licensed for Everyone's Free Use Or Not Licensed At All.
The Precise Terms and Conditions for Copying, Distribution and Modification Follow.
1. Terms and Conditions for Copying, Distribution and Modification
This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a " work based on the Program "means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and / or translated into another language (Hereinafter,. translation is included without limitation in the term "modification") Each licensee is addressed as "you" Activities other than copying, distribution and modification are not covered by this License;.. they are outside its scope The act of running the Program is. not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License And to the absence of any warranty;
and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way , to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.). These requireme nts apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the Entire Whole, And Thus to Each and Every Part Regardless of Wrote It. This, IT IS NOT INTENT OF THIS Section To Claim Rights or Contemlely By You;
rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or , Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding Source Code, To Be Distributed Under Terms of Sections 1 and 2 Above ON A Medium Customarily Used for Software Interchange
or, Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. for an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so ) of the operationable system on which the executable runs, unless That Component Itself Accompanies The Executable. if Distribution of Executable or Object Code Is Made by O ffering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received Copies, or Rights, from you under this license will not have.com..
You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise Of the Rights Grand Herein. You are not responsible for enforcing completion by third parties to this license. IF, as a consequence of a court judgment OR Allegation of Patent Infringement Or r any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you can not distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those WHO Receive Copies Directly or Indirectly Through You, Then The Only Way You Could Satisfy Both IT and this License Would Be To Refrain Entirely from Distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices Many people have made generous contributions to. the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author / donor to decide if he or she is willing to distribute software through any other system and a licensee can not impose that choice This. Section is intended to make thoroughly clear what is believed to be a connectionquence of the rest of this license. if the distriction and / or use of the program s restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. The Free Software Foundation may publish revised and / or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the .
If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission . for software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting. The Sharing and Reuse of Software Generally. No Warranty Because The Program Is Licensed Free of Charge, There Is No Warranty for the Program, To The Extent Permitted B Y APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND / OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND / OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN If Such Holder Or Other Party Has Been Advised of The Possibility of Such Damages.end of Terms and conditions
2. How to Apply THESE TERMS to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
. To do so, attach the following notices to the program It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to WHERE The Full Notice Is Found.
This program is free software; you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;. Without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU General Public License for more details.You should have received a copy of the GNU General Public License Along with this Program; if not, Write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also Add Information on How To Contact You by Electronic and Paper Mail.
IF The Program Is Intective, Make It Output A Short Notice Like thisime Starts in An Intective Mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w '. This is free software, and you are welcome to redistribute it under certain conditions; type` show c' for details .
The hypothetical commands `show w 'and` show c' should show the appropriate parts of the General Public License Of course, the commands you use may be called something other than `show w 'and` show c';. They could even be Mouse-ClickS or Menu Items - Whate Suits your Program.
You Should Also Get Your Employer (if You Work As a Programmer) Or Your School, IF ANY, TO SIGN A "Copyright Disclaimer" for the program, if Necessary. Here is a sample; alter;
YOYODYNE, INC., Hereby Disclaims All Copyright Interest in The Progra M `Gnomovision '(Which Makes Passs At Compilers) Written By James Hacker.
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library Appendix I. Code of Sample Script of General Public License.
I.1. Rc.firewall script code
#! / bin / sh
#
# rc.firewall - Initial Simple IP FireWall Script for Linux 2.4.x and iptables
#
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify
# ip Under The Terms of The GNU General Public License As Published by
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 1. Configuration Options.
#
#
# 1.1 Internet configure.
#
INET_IP = "194.236.50.155"
INET_IFACE = "Eth0"
INET_BROADCAST = "194.236.50.255"
#
# 1.1.1 DHCP
#
#
# 1.1.2 pppoe
#
#
# 1.2 Local Area NetWork Configuration.
#
# Your Lan's IP Range and localhost ip. / 24 means to only use the first 24
# Bits of the 32 bit ip address. The Same as netmask 255.255.255.0 #
LAN_IP = "192.168.0.2"
LAN_IP_RANGE = "192.168.0.0/16"
LAN_IFACE = "Eth1"
#
# 1.3 DMZ Configuration.
#
#
# 1.4 localhost configuration.
#
LO_IFACE = "LO"
LO_IP = "127.0.0.1"
#
# 1.5 iptables configuration.
#
Iptables = "/ usr / sbin / iptables"
#
# 1.6 Other Configuration.
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 2. Module Loading.
#
#
# Needed to Initially Load Modules
#
/ sbin / depmod -a
#
# 2. Required Modules
#
/ sbin / modprobe ip_tables
/ sbin / modprobe ip_conntrack
/ sbin / modprobe iptable_filter
/ SBIN / MODPROBE iptable_mangle
/ sbin / modprobe iptable_nat
/ sbin / modprobe ipt_log
/ sbin / modprobe ipt_limit
/ sbin / modprobe ipt_state
#
# 2.2 Non-Required Modules
#
# / sbin / modprobe ipt_owner
# / sbin / modprobe ipt_reject
# / sbin / modprobe ipt_masquerade
# / sbin / modprobe ip_conntrack_ftp
# / sbin / modprobe ip_conntrack_irc
# / sbin / modprobe ip_nat_ftp
# / sbin / modprobe ip_nat_irc
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 3. / proc set up.
#
#
# 3.1 Required Proc Configuration
#
Echo "1"> / proc / sys / net / ipv4 / ip_forward
#
# 3.2 Non-Required Proc Configuration
#
#echo "1"> / proc / sys / net / ipv4 / conf / all / rp_filter
#echo "1"> / proc / sys / net / ipv4 / conf / all / proxy_arp
#echo "1"> / proc / sys / net / ipv4 / ip_dynaddr
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 4. Rules set up.
#
######
# 4.1 Filter Table
#
#
# 4.1.1 Set Policies
#
$ Iptables -p input drop
$ Iptables -p output drop
$ Iptables -p forward drop
#
# 4.1.2 CREATE USERSPECified CHAINS #
#
# CREATE CHAIN for BAD TCP Packets
#
$ Iptables -n bad_tcp_packets
#
# Create Separate Chains for ICMP, TCP and UDP To Traverse
#
$ Iptables -n allowed
$ Iptables -n tcp_packets
$ Iptables -n udp_packets
$ Iptables -n icmp_packets
#
# 4.1.3 CREATE Content in Usespecified CHAINS
#
#
#BAD_TCP_PACKETS CHAIN
#
$ Iptables -a bad_tcp_packets -p tcp --TCP-FLAGS SYN, ACK SYN, ACK /
-m State --State New -j Reject --Reject-with TCP-RESET
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m state --state new -j log /
--Log-prefix "New Not Syn:"
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m State --State New -j Drop
#
# allowed chain
#
$ Iptables -a allowed -p tcp --Syn -j Accept
$ Iptables -a allowed -p tcp -m state --state established, Related -j Accept
$ Iptables -a allowed -p tcp -j drop
#
# TCP Rules
#
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 21 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 22 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 80 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 113 -j allowed
#
# Udp ports
#
# $ Iptables -a udp_packets -p udp -s 0/0 --Destination-port 53 -j ACCEPT
# $ Iptables -a udp_packets -p udp -s 0/0 --Destination-port 123 -j ACCEPT
$ Iptables -a udp_packets -p udp -s 0/0 --dstination-port 2074 -j accept
$ Iptables -a udp_packets -p udp -s 0/0 --Destination-port 4000 -J ACCEPT
#
# In Microsoft Networks You Will Be Swadped by Broadcasts. There Lines
# Will Prevent Them From Showing Up in the logs.
#
# Iptables -a udp_packets -p udp -i $ inet_iface -d $ inet_broadcast /
# - DESTINATION-Port 135: 139 -J Drop
#
# I i Get DHCP Requests from The Outside of Our Network, Our Logs Will
# be swamped as well. This rule will block the from getting logged. #
# Iptables -a udp_packets -p udp -i $ inet_iface -d 255.255.255.255 /
# - destination-port 67:68 -j drop
#
# ICMP Rules
#
$ Iptables -a icmp_packets -p ICMP -S 0/0 --ICMP-TYPE 8 -J ACCEPT
$ Iptables -a icmp_packets -p ICMP -S 0/ICMP-TYPE 11 -J ACCEPT
#
# 4.1.4 Input Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a input -p tcp -j bad_tcp_packets
#
# Rules for Special Networks NOT Part of The Internet
#
$ Iptables -a input -p all -i $ lan_iface -s $ lan_ip_range -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ lo_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ lan_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ inet_ip -j accept
#
# Special Rule for DHCP Requests from Lan, Which Are Not Caught Properly
# αwise.
#
$ Iptables -a input -p udp -i $ lan_iface --dport 67 --sport 68 -j acceptpt
#
# Rules for incoming packets from the Internet.
#
$ Iptables -a input -p all -d $ inet_ip -m state --state established, Related /
-J ACCEPT
$ Iptables -a input -p tcp -i $ inet_iface -j tcp_packets
$ Iptables -a input -p udp -i $ inet_iface -j udp_packets
$ Iptables -a input -p ICMP -I $ inet_iface -j icmp_packets
#
# If you have a Microsoft Network on The Outside of Your FireWall, You May
# Also get flooded by multicasts. We Drop The so we do not get flooded by
# logs
#
# Iptables -a input -i $ inet_iface -d 224.0.0.0.0/8 -j drop
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a INPUT -M LIMIT --LIMIT 3 / Minute --Limit-Burst 3 -J log /
--Log-Level Debug --log-prefix "ipt input packet died:"
#
# 4.1.5 Forward Chain
#
#
# Bad TCP Packets WE Don't want
#
$ Iptables -a forward -p TCP -J BAD_TCP_PACKETS #
# Accept the packets we activually want to forward to forward
#
$ Iptables -a forward -i $ lan_iface -j acceptpt
$ Iptables -a forward -m state --state established, Related -j Accept
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a forward -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt forward packet died:"
#
# 4.1.6 Output Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a output -p tcp -j bad_tcp_packets
#
# Special Output Rules To Decide Which IP's To Allow.
#
$ Iptables -a output -p all -s $ lo_ip -j acceptpt
$ Iptables -a output -p all -s $ lan_ip -j accept
$ Iptables -a output -p all -s $ inet_ip -j acceptpt
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a output -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt output packet died:"
######
# 4.2 Nat Table
#
#
# 4.2.1 Set Policies
#
#
# 4.2.2 Create User Specified Chains
#
#
# 4.2.3 Create Content in User Specified Chains
#
#
# 4.2.4 preording chain
#
#
# 4.2.5 PostRouting Chain
#
#
# Enable Simple ip Forwarding and Network Address Translation
#
$ Iptables -t nat -a postrol -o $ inet_iface -j snat --to-source $ inet_ip
#
# 4.2.6 Output Chain
#
######
# 4.3 Mangle Table
#
#
# 4.3.1 Set Policies
#
#
# 4.3.2 Create User Specified Chains
#
#
# 4.3.3 CREATE Content in User Specified CHAINS
#
#
# 4.3.4 PREROUTING CHAIN
#
#
# 4.3.5 Input Chain
#
#
# 4.3.6 Forward Chain
#
#
# 4.3.7 Output Chain
#
#
# 4.3.8 PostRouting Chain
#
I.2. Rc.dmz.firewall script code
#! / bin / sh
#
# rc.dmz.firewall - DMZ IP FireWall Script for Linux 2.4.x and iptables #
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify
# ip Under The Terms of The GNU General Public License As Published by
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 1. Configuration Options.
#
#
# 1.1 Internet configure.
#
INET_IP = "194.236.50.152"
HTTP_IP = "194.236.50.153"
DNS_IP = "194.236.50.154"
INET_IFACE = "Eth0"
#
# 1.1.1 DHCP
#
#
# 1.1.2 pppoe
#
#
# 1.2 Local Area NetWork Configuration.
#
# Your Lan's IP Range and localhost ip. / 24 means to only use the first 24
# Bits of The 32 Bit IP Address. The Same As Netmask 255.255.255.0
#
LAN_IP = "192.168.0.1"
LAN_IFACE = "Eth1"
#
# 1.3 DMZ Configuration.
#
DMZ_HTTP_IP = "192.168.1.2"
DMZ_DNS_IP = "192.168.1.3"
DMZ_IP = "192.168.1.1"
DMZ_IFACE = "Eth2"
#
# 1.4 localhost configuration.
#
LO_IFACE = "LO"
LO_IP = "127.0.0.1"
#
# 1.5 iptables configuration. #
Iptables = "/ usr / sbin / iptables"
#
# 1.6 Other Configuration.
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 2. Module Loading.
#
#
# Needed to Initially Load Modules
#
/ sbin / depmod -a
#
# 2. Required Modules
#
/ sbin / modprobe ip_tables
/ sbin / modprobe ip_conntrack
/ sbin / modprobe iptable_filter
/ SBIN / MODPROBE iptable_mangle
/ sbin / modprobe iptable_nat
/ sbin / modprobe ipt_log
/ sbin / modprobe ipt_limit
/ sbin / modprobe ipt_state
#
# 2.2 Non-Required Modules
#
# / sbin / modprobe ipt_owner
# / sbin / modprobe ipt_reject
# / sbin / modprobe ipt_masquerade
# / sbin / modprobe ip_conntrack_ftp
# / sbin / modprobe ip_conntrack_irc
# / sbin / modprobe ip_nat_ftp
# / sbin / modprobe ip_nat_irc
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 3. / proc set up.
#
#
# 3.1 Required Proc Configuration
#
Echo "1"> / proc / sys / net / ipv4 / ip_forward
#
# 3.2 Non-Required Proc Configuration
#
#echo "1"> / proc / sys / net / ipv4 / conf / all / rp_filter
#echo "1"> / proc / sys / net / ipv4 / conf / all / proxy_arp
#echo "1"> / proc / sys / net / ipv4 / ip_dynaddr
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 4. Rules set up.
#
######
# 4.1 Filter Table
#
#
# 4.1.1 Set Policies
#
$ Iptables -p input drop
$ Iptables -p output drop
$ Iptables -p forward drop
#
# 4.1.2 CREATE USERSPECIFIED CHAINS
#
#
# CREATE CHAIN for BAD TCP Packets
#
$ Iptables -n bad_tcp_packets
#
# Create Separate Chains for ICMP, TCP and UDP To Traverse
#
$ Iptables -n allowed
$ Iptables -n icmp_packets
#
# 4.1.3 CREATE Content in Usespecified CHAINS
#
#
#BAD_TCP_PACKETS CHAIN
#
$ Iptables -a bad_tcp_packets -p tcp --TCP-FLAGS SYN, ACK SYN, ACK / -M State --State New -j Reject --Reject-with TCP-RESET
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m state --state new -j log /
--Log-prefix "New Not Syn:"
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m State --State New -j Drop
#
# allowed chain
#
$ Iptables -a allowed -p tcp --Syn -j Accept
$ Iptables -a allowed -p tcp -m state --state established, Related -j Accept
$ Iptables -a allowed -p tcp -j drop
#
# ICMP Rules
#
# Changed Rules Totally
$ Iptables -a icmp_packets -p ICMP -S 0/0 --ICMP-TYPE 8 -J ACCEPT
$ Iptables -a icmp_packets -p ICMP -S 0/ICMP-TYPE 11 -J ACCEPT
#
# 4.1.4 Input Chain
#
#
# Bad TCP Packets WE Don't want
#
$ Iptables -a input -p tcp -j bad_tcp_packets
#
# Packets from the Internet to this box
#
$ Iptables -a input -p ICMP -I $ inet_iface -j icmp_packets
#
# Packets from lan, DMZ or localhost
#
#
# From DMZ Interface to DMZ FireWall IP
#
$ Iptables -a input -p all -i $ dmz_iface -d $ dmz_ip -j acid
#
# From lan interface to Lan FireWall IP
#
$ Iptables -a input -p all -i $ lan_iface -d $ lan_ip -j acceptpt
#
# From localhost interface to localhost ip?
#
$ Iptables -a input -p all -i $ lo_iface -s $ lo_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ lan_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ inet_ip -j accept
#
# Special Rule for DHCP Requests from Lan, Which Are Not Caught Properly
# αwise.
#
$ Iptables -a input -p udp -i $ lan_iface --dport 67 --sport 68 -j acceptpt
#
# All established and relanded packets incoming from the internet to the
# firewall
#
$ Iptables -a input -p all -d $ inet_ip -m state --state established, Related /
-J ACCEPT
#
# In Microsoft Networks You Will Be swamped by Broadcasts. These Lines # Will Prevent The From Showing Up in the logs.
#
# Iptables -a input -p udp -i $ inet_iface -d $ inet_broadcast /
# - DESTINATION-Port 135: 139 -J Drop
#
# I i Get DHCP Requests from The Outside of Our Network, Our Logs Will
# be swamped as well. This rule will block the from getting logged.
#
# Iptables -a INPUT -P UDP -I $ INET_IFACE -D 255.255.255.255 /
# - destination-port 67:68 -j drop
#
# If you have a Microsoft Network on The Outside of Your FireWall, You May
# Also get flooded by multicasts. We Drop The so we do not get flooded by
# logs
#
# Iptables -a input -i $ inet_iface -d 224.0.0.0.0/8 -j drop
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a INPUT -M LIMIT --LIMIT 3 / Minute --Limit-Burst 3 -J log /
--Log-Level Debug --log-prefix "ipt input packet died:"
#
# 4.1.5 Forward Chain
#
#
# Bad TCP Packets WE Don't want
#
$ Iptables -a forward -p tcp -j bad_tcp_packets
#
# DMZ Section
#
# General rules
#
$ Iptables -a forward -i $ dmz_iface -o $ inet_iface -j acceptpt
$ Iptables -a forward -i $ inet_iface -o $ dmz_iface -m state /
--State Established, Related -j Accept
$ Iptables -a forward -i $ lan_iface -o $ dmz_iface -j acceptpt
$ Iptables -a forward -i $ dmz_iface -o $ lan_iface -m state /
--State Established, Related -j Accept
#
# Http server
#
$ Iptables -a forward -p tcp -i $ inet_iface -o $ dmz_iface -d $ DMZ_HTTP_IP /
--DPORT 80 -J ALLOWED
$ Iptables -a forward -p iCMP -I $ inet_iface -o $ dmz_iface -d $ dmz_http_ip /
-J ICMP_PACKETS
#
#DNS Server
#
$ Iptables -a forward -p tcp -i $ inet_iface -o $ dmz_iface -d $ dmz_dns_ip /
--DPORT 53 -J ALLOWED
$ Iptables -a forward -p UDP -I $ inet_iface -o $ dmz_iface -d $ dmz_dns_ip / - dport 53 -j accept
$ Iptables -a forward -p iCMP -I $ inet_iface -o $ dmz_iface -d $ dmz_dns_ip /
-J ICMP_PACKETS
#
# Lan section
#
$ Iptables -a forward -i $ lan_iface -j acceptpt
$ Iptables -a forward -m state --state established, Related -j Accept
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a forward -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt forward packet died:"
#
# 4.1.6 Output Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a output -p tcp -j bad_tcp_packets
#
# Special Output Rules To Decide Which IP's To Allow.
#
$ Iptables -a output -p all -s $ lo_ip -j acceptpt
$ Iptables -a output -p all -s $ lan_ip -j accept
$ Iptables -a output -p all -s $ inet_ip -j acceptpt
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a output -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt output packet died:"
######
# 4.2 Nat Table
#
#
# 4.2.1 Set Policies
#
#
# 4.2.2 Create User Specified Chains
#
#
# 4.2.3 Create Content in User Specified Chains
#
#
# 4.2.4 preording chain
#
$ Iptables -t nat -a preording -p tcp -i $ inet_iface -d $ http_ip --dport 80 /
-J DNAT - TO-DESTINATION $ DMZ_HTTP_IP
$ Iptables -t nat -a preording -p tcp -i $ inet_iface -d $ dns_ip --dport 53 /
-J DNAT - TO-DESTINATION $ DMZ_DNS_IP
$ Iptables -t nat -a preording -p udp -i $ inet_iface -d $ dns_ip --dport 53 /
-J DNAT - TO-DESTINATION $ DMZ_DNS_IP
#
# 4.2.5 PostRouting Chain
#
#
# Enable Simple ip Forwarding and Network Address Translation
#
$ Iptables -t nat -a postrouting -o $ inet_iface -j snat --to-source $ inet_ip #
# 4.2.6 Output Chain
#
######
# 4.3 Mangle Table
#
#
# 4.3.1 Set Policies
#
#
# 4.3.2 Create User Specified Chains
#
#
# 4.3.3 CREATE Content in User Specified CHAINS
#
#
# 4.3.4 PREROUTING CHAIN
#
#
# 4.3.5 Input Chain
#
#
# 4.3.6 Forward Chain
#
#
# 4.3.7 Output Chain
#
#
# 4.3.8 PostRouting Chain
#
I.3. Rc.utin.firewall script code
#! / bin / sh
#
# rc.firewall - UTIN FIREWALL Script for Linux 2.4.x and iptables
#
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify
# ip Under The Terms of The GNU General Public License As Published by
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 1. Configuration Options.
#
#
# 1.1 Internet configure.
#
INET_IP = "194.236.50.155"
INET_IFACE = "Eth0"
INET_BROADCAST = "194.236.50.255"
#
# 1.1.1 DHCP
#
#
# 1.1.2 pppoe
#
#
# 1.2 Local Area NetWork Configuration.
#
# Your Lan's IP Range and localhost ip. / 24 means to only use the first 24
# Bits of the 32 bit ip address. The Same as netmask 255.255.255.0 #
LAN_IP = "192.168.0.2"
LAN_IP_RANGE = "192.168.0.0/16"
LAN_IFACE = "Eth1"
#
# 1.3 DMZ Configuration.
#
#
# 1.4 localhost configuration.
#
LO_IFACE = "LO"
LO_IP = "127.0.0.1"
#
# 1.5 iptables configuration.
#
Iptables = "/ usr / sbin / iptables"
#
# 1.6 Other Configuration.
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 2. Module Loading.
#
#
# Needed to Initially Load Modules
#
/ sbin / depmod -a
#
# 2. Required Modules
#
/ sbin / modprobe ip_tables
/ sbin / modprobe ip_conntrack
/ sbin / modprobe iptable_filter
/ SBIN / MODPROBE iptable_mangle
/ sbin / modprobe iptable_nat
/ sbin / modprobe ipt_log
/ sbin / modprobe ipt_limit
/ sbin / modprobe ipt_state
#
# 2.2 Non-Required Modules
#
# / sbin / modprobe ipt_owner
# / sbin / modprobe ipt_reject
# / sbin / modprobe ipt_masquerade
# / sbin / modprobe ip_conntrack_ftp
# / sbin / modprobe ip_conntrack_irc
# / sbin / modprobe ip_nat_ftp
# / sbin / modprobe ip_nat_irc
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 3. / proc set up.
#
#
# 3.1 Required Proc Configuration
#
Echo "1"> / proc / sys / net / ipv4 / ip_forward
#
# 3.2 Non-Required Proc Configuration
#
#echo "1"> / proc / sys / net / ipv4 / conf / all / rp_filter
#echo "1"> / proc / sys / net / ipv4 / conf / all / proxy_arp
#echo "1"> / proc / sys / net / ipv4 / ip_dynaddr
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 4. Rules set up.
#
######
# 4.1 Filter Table
#
#
# 4.1.1 Set Policies
#
$ Iptables -p input drop
$ Iptables -p output drop
$ Iptables -p forward drop
#
# 4.1.2 CREATE USERSPECified CHAINS #
#
# CREATE CHAIN for BAD TCP Packets
#
$ Iptables -n bad_tcp_packets
#
# Create Separate Chains for ICMP, TCP and UDP To Traverse
#
$ Iptables -n allowed
$ Iptables -n tcp_packets
$ Iptables -n udp_packets
$ Iptables -n icmp_packets
#
# 4.1.3 CREATE Content in Usespecified CHAINS
#
#
#BAD_TCP_PACKETS CHAIN
#
$ Iptables -a bad_tcp_packets -p tcp --TCP-FLAGS SYN, ACK SYN, ACK /
-m State --State New -j Reject --Reject-with TCP-RESET
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m state --state new -j log /
--Log-prefix "New Not Syn:"
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m State --State New -j Drop
#
# allowed chain
#
$ Iptables -a allowed -p tcp --Syn -j Accept
$ Iptables -a allowed -p tcp -m state --state established, Related -j Accept
$ Iptables -a allowed -p tcp -j drop
#
# TCP Rules
#
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 21 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 22 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 80 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 113 -j allowed
#
# Udp ports
#
# Iptables -a udp_packets -p udp -s 0/0 --Source-port 53 -j Accept
# Iptables -a udp_packets -p udp -s 0/0 --Source-port 123 -j Accept
$ Iptables -a udp_packets -p udp -s 0/0 --Source-Port 2074 -j Accept
$ Iptables -a udp_packets -p udp -s 0/0 --Source-port 4000 -J ACCEPT
#
# In Microsoft Networks You Will Be Swadped by Broadcasts. There Lines
# Will Prevent Them From Showing Up in the logs.
#
# Iptables -a udp_packets -p udp -i $ inet_iface -d $ inet_broadcast /
# - DESTINATION-Port 135: 139 -J Drop
#
# I i Get DHCP Requests from The Outside of Our Network, Our Logs Will
# be swamped as well. This rule will block the from getting logged. #
# Iptables -a udp_packets -p udp -i $ inet_iface -d 255.255.255.255 /
# - destination-port 67:68 -j drop
#
# ICMP Rules
#
$ Iptables -a icmp_packets -p ICMP -S 0/0 --ICMP-TYPE 8 -J ACCEPT
$ Iptables -a icmp_packets -p ICMP -S 0/ICMP-TYPE 11 -J ACCEPT
#
# 4.1.4 Input Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a input -p tcp -j bad_tcp_packets
#
# Rules for Special Networks NOT Part of The Internet
#
$ Iptables -a input -p all -i $ lo_iface -s $ lo_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ lan_ip -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -s $ inet_ip -j accept
#
# Rules for incoming packets from anywhere.
#
$ Iptables -a input -p all -d $ inet_ip -m state --state established, Related /
-J ACCEPT
$ Iptables -a input -p tcp -j tcp_packets
$ Iptables -a input -p udp -j udp_packets
$ Iptables -ainput -p icmp -j icmp_packets
#
# If you have a Microsoft Network on The Outside of Your FireWall, You May
# Also get flooded by multicasts. We Drop The so we do not get flooded by
# logs
#
# Iptables -a input -i $ inet_iface -d 224.0.0.0.0/8 -j drop
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a INPUT -M LIMIT --LIMIT 3 / Minute --Limit-Burst 3 -J log /
--Log-Level Debug --log-prefix "ipt input packet died:"
#
# 4.1.5 Forward Chain
#
#
# Bad TCP Packets WE Don't want
#
$ Iptables -a forward -p tcp -j bad_tcp_packets
#
# Accept the packets we activually want to forward to forward
#
$ Iptables -a forward -p tcp --dport 21 -i $ lan_iface -j acceptpt
$ Iptables -a forward -p tcp --dport 80 -i $ lan_iface -j accept
$ Iptables -a forward -p tcp --dport 110 -i $ lan_iface -j acceptpt
$ Iptables -a forward -m state --state established, related -j accept #
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a forward -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt forward packet died:"
#
# 4.1.6 Output Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a output -p tcp -j bad_tcp_packets
#
# Special Output Rules To Decide Which IP's To Allow.
#
$ Iptables -a output -p all -s $ lo_ip -j acceptpt
$ Iptables -a output -p all -s $ lan_ip -j accept
$ Iptables -a output -p all -s $ inet_ip -j acceptpt
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a output -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt output packet died:"
######
# 4.2 Nat Table
#
#
# 4.2.1 Set Policies
#
#
# 4.2.2 Create User Specified Chains
#
#
# 4.2.3 Create Content in User Specified Chains
#
#
# 4.2.4 preording chain
#
#
# 4.2.5 PostRouting Chain
#
#
# Enable Simple ip Forwarding and Network Address Translation
#
$ Iptables -t nat -a postrol -o $ inet_iface -j snat --to-source $ inet_ip
#
# 4.2.6 Output Chain
#
######
# 4.3 Mangle Table
#
#
# 4.3.1 Set Policies
#
#
# 4.3.2 Create User Specified Chains
#
#
# 4.3.3 CREATE Content in User Specified CHAINS
#
#
# 4.3.4 PREROUTING CHAIN
#
#
# 4.3.5 Input Chain
#
#
# 4.3.6 Forward Chain
#
#
# 4.3.7 Output Chain
#
#
# 4.3.8 PostRouting Chain
#
I.4. Rc.dhcp.firewall script code
#! / bin / sh
#
# rc.firewall - DHCP IP FireWall Script for Linux 2.4.x and iptables
#
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify # it under the terminal of the gnu general public license as publictrib
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 1. Configuration Options.
#
#
# 1.1 Internet configure.
#
INET_IFACE = "Eth0"
#
# 1.1.1 DHCP
#
#
# Ioning pertaining to dhcp over the Internet, if NEEDED.
#
# Set dhcp variable to no if you don't get ip from dhcp. If you get DHCP
# Over the Internet set this variable to yes, and set up the property ip
# Address for the dhcp server in The dhcp_server variable.
#
DHCP = "no"
DHCP_SERVER = "195.22.90.65"
#
# 1.1.2 pppoe
#
# Configuration Options Pertaining to PPPoe.
#
# Imp You Have Problem with your pppoe connection, Such as large mails not
# getting through limited, you may set
# this option to "yes" Which May Fix The Problem. This Option Will Set A
# Rule in The preording Chain of the Mangle Table Which Will Clamp
# (Resize) All Routed Packets To Pmtu (Path Maximum Transmit Unit).
#
# Note That it is better to set this Up in the PPPOE Package Itself, Since # The PPPOE Configuration Option Will Give Less Overhead.
#
PPPOE_PMTU = "NO"
#
# 1.2 Local Area NetWork Configuration.
#
# Your Lan's IP Range and localhost ip. / 24 means to only use the first 24
# Bits of The 32 Bit IP Address. The Same As Netmask 255.255.255.0
#
LAN_IP = "192.168.0.2"
LAN_IP_RANGE = "192.168.0.0/16"
LAN_IFACE = "Eth1"
#
# 1.3 DMZ Configuration.
#
#
# 1.4 localhost configuration.
#
LO_IFACE = "LO"
LO_IP = "127.0.0.1"
#
# 1.5 iptables configuration.
#
Iptables = "/ usr / sbin / iptables"
#
# 1.6 Other Configuration.
#
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 2. Module Loading.
#
#
# Needed to Initially Load Modules
#
/ sbin / depmod -a
#
# 2. Required Modules
#
/ sbin / modprobe ip_conntrack
/ sbin / modprobe ip_tables
/ sbin / modprobe iptable_filter
/ SBIN / MODPROBE iptable_mangle
/ sbin / modprobe iptable_nat
/ sbin / modprobe ipt_log
/ sbin / modprobe ipt_limit
/ sbin / modprobe ipt_masquerade
#
# 2.2 Non-Required Modules
#
# / sbin / modprobe ipt_owner
# / sbin / modprobe ipt_reject
# / sbin / modprobe ip_conntrack_ftp
# / sbin / modprobe ip_conntrack_irc
# / sbin / modprobe ip_nat_ftp
# / sbin / modprobe ip_nat_irc
######################################################################################################################################################################################################################################################################################################## ##############################
#
# 3. / proc set up.
#
#
# 3.1 Required Proc Configuration
#
Echo "1"> / proc / sys / net / ipv4 / ip_forward
#
# 3.2 Non-Required Proc Configuration
#
#echo "1"> / proc / sys / net / ipv4 / conf / all / rp_filter
#echo "1"> / proc / sys / net / ipv4 / conf / all / proxy_arp
#echo "1"> / proc / sys / net / ipv4 / ip_dynaddr ############################################################################################################################################################################################################################################################################# #############################################################################
#
# 4. Rules set up.
#
######
# 4.1 Filter Table
#
#
# 4.1.1 Set Policies
#
$ Iptables -p input drop
$ Iptables -p output drop
$ Iptables -p forward drop
#
# 4.1.2 CREATE USERSPECIFIED CHAINS
#
#
# CREATE CHAIN for BAD TCP Packets
#
$ Iptables -n bad_tcp_packets
#
# Create Separate Chains for ICMP, TCP and UDP To Traverse
#
$ Iptables -n allowed
$ Iptables -n tcp_packets
$ Iptables -n udp_packets
$ Iptables -n icmp_packets
#
# 4.1.3 CREATE Content in Usespecified CHAINS
#
#
#BAD_TCP_PACKETS CHAIN
#
$ Iptables -a bad_tcp_packets -p tcp --TCP-FLAGS SYN, ACK SYN, ACK /
-m State --State New -j Reject --Reject-with TCP-RESET
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m state --state new -j log /
--Log-prefix "New Not Syn:"
$ Iptables -a bad_tcp_packets -p tcp! --Syn -m State --State New -j Drop
#
# allowed chain
#
$ Iptables -a allowed -p tcp --Syn -j Accept
$ Iptables -a allowed -p tcp -m state --state established, Related -j Accept
$ Iptables -a allowed -p tcp -j drop
#
# TCP Rules
#
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 21 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 22 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 80 -j allowed
$ Iptables -a tcp_packets -p tcp -s 0/0 --dport 113 -j allowed
#
# Udp ports
#
$ Iptables -a udp_packets -p udp -s 0/4 --Source-port 53 -j ACCEPT
IF [$ dhcp == "yes"]; then
$ Iptables -a udp_packets -p udp -s $ dhcp_server --sport 67 /
--DPORT 68 -J ACCEPT
Fi
# Iptables -a udp_packets -p udp -s 0/0 --Source-port 53 -j Accept
# Iptables -a udp_packets -p udp -s 0/0 --Source-port 123 -j accept $ iptables -a udp_packets -p udp -s 0/0 - Source-Port 2074 -j Accept
$ Iptables -a udp_packets -p udp -s 0/0 --Source-port 4000 -J ACCEPT
#
# In Microsoft Networks You Will Be Swadped by Broadcasts. There Lines
# Will Prevent Them From Showing Up in the logs.
#
# Iptables -a udp_packets -p udp -i $ inet_iface /
# - DESTINATION-Port 135: 139 -J Drop
#
# I i Get DHCP Requests from The Outside of Our Network, Our Logs Will
# be swamped as well. This rule will block the from getting logged.
#
# Iptables -a udp_packets -p udp -i $ inet_iface -d 255.255.255.255 /
# - destination-port 67:68 -j drop
#
# ICMP Rules
#
$ Iptables -a icmp_packets -p ICMP -S 0/0 --ICMP-TYPE 8 -J ACCEPT
$ Iptables -a icmp_packets -p ICMP -S 0/ICMP-TYPE 11 -J ACCEPT
#
# 4.1.4 Input Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a input -p tcp -j bad_tcp_packets
#
# Rules for Special Networks NOT Part of The Internet
#
$ Iptables -a input -p all -i $ lan_iface -s $ lan_ip_range -j acceptpt
$ Iptables -a input -p all -i $ lo_iface -j acceptpt
#
# Special Rule for DHCP Requests from Lan, Which Are Not Caught Properly
# αwise.
#
$ Iptables -a input -p udp -i $ lan_iface --dport 67 --sport 68 -j acceptpt
#
# Rules for incoming packets from the Internet.
#
$ Iptables -a input -p all -i $ inet_iface -m state --state established, Related /
-J ACCEPT
$ Iptables -a input -p tcp -i $ inet_iface -j tcp_packets
$ Iptables -a input -p udp -i $ inet_iface -j udp_packets
$ Iptables -a input -p ICMP -I $ inet_iface -j icmp_packets
#
# If you have a Microsoft Network on The Outside of Your FireWall, You May
# also get flooded by multicasts. We Drop theo we do not get flooded by # logs
#
# Iptables -a input -i $ inet_iface -d 224.0.0.0.0/8 -j drop
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a INPUT -M LIMIT --LIMIT 3 / Minute --Limit-Burst 3 -J log /
--Log-Level Debug --log-prefix "ipt input packet died:"
#
# 4.1.5 Forward Chain
#
#
# Bad TCP Packets WE Don't want
#
$ Iptables -a forward -p tcp -j bad_tcp_packets
#
# Accept the packets we activually want to forward to forward
#
$ Iptables -a forward -i $ lan_iface -j acceptpt
$ Iptables -a forward -m state --state established, Related -j Accept
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a forward -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt forward packet died:"
#
# 4.1.6 Output Chain
#
#
# Bad TCP Packets We don't want.
#
$ Iptables -a output -p tcp -j bad_tcp_packets
#
# Special Output Rules To Decide Which IP's To Allow.
#
$ Iptables -a output -p all -s $ lo_ip -j acceptpt
$ Iptables -a output -p all -s $ lan_ip -j accept
$ Iptables -a output -p all-μ $ inet_iface -j accept
#
# Log Weird Packets That Don't match the Above.
#
$ Iptables -a output -m limited --LIMIT 3 / Minute --Limit-Burst 3 -j log /
--Log-level debug --log-prefix "ipt output packet died:"
######
# 4.2 Nat Table
#
#
# 4.2.1 Set Policies
#
#
# 4.2.2 Create User Specified Chains
#
#
# 4.2.3 Create Content in User Specified Chains
#
#
# 4.2.4 preording chain
#
#
# 4.2.5 PostRouting Chain
#
IF [$ PPPOE_PMTU == "YES"]; then
$ Iptables -t nat -a postrouting -p tcp --TCP-FLAGS SYN, RST SYN /
-J TCPMSS - CLAMP-MSS-TO-PMTU
Fi
$ Iptables -t nat -a postrouting -o $ inet_iface -j masquerade #
# 4.2.6 Output Chain
#
######
# 4.3 Mangle Table
#
#
# 4.3.1 Set Policies
#
#
# 4.3.2 Create User Specified Chains
#
#
# 4.3.3 CREATE Content in User Specified CHAINS
#
#
# 4.3.4 PREROUTING CHAIN
#
#
# 4.3.5 Input Chain
#
#
# 4.3.6 Forward Chain
#
#
# 4.3.7 Output Chain
#
#
# 4.3.8 PostRouting Chain
#
I.5. Rc.flush-iptables script code
#! / bin / sh
#
# rc.flush-iptables - resets iptables to default values.
#
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify
# ip Under The Terms of The GNU General Public License As Published by
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
# Configurations
#
Iptables = "/ usr / sbin / iptables"
#
# RESET The Default Policies in The Filter Table.
#
$ Iptables -p input accept accept
$ Iptables -p forward accept
$ Iptables -p output accept
#
# RESET The Default Policies in the Nat Table.
#
$ Iptables -t nat -p preloading accept
$ Iptables -t nat -p postrouting accept
$ Iptables -t Nat -P Output Accept
#
# RESET The Default Policies in the mangle table.
#
$ Iptables -t mangle -p prerouting accept $ iptables -t mangle -p output accept accept
#
# flush all the rules in the filter and nat Tables.
#
$ Iptables -f
$ Iptables -t nat -f
$ Iptables -t mangle -f
#
# Erase All Chains That's Not Defeult in Filter and Nat Table.
#
$ Iptables -x
$ Iptables -t nat -x
$ Iptables -t mangle -x
I.6. Rc.test-iptables script code
#! / bin / bash
#
# rc.test-iptables - Test Script for iptables CHAINS AND TABLES.
#
# Copyright (c) 2001 Oskar Andreasson
#
# This program is free software; you can redistribute it and / or modify
# ip Under The Terms of The GNU General Public License As Published by
# The Free Software Foundation; Version 2 of the license.
#
# This program is distributed in the Hope That IT Will BE Useful,
# But without Any Warranty; WITHOUT EVEN THE IMPLIED WARRANTY OF
# Merchantability or fitness for a particular purpose. See the
# Gnu general public license for more details.
#
# You shouth have received a copy of the gnu general public license
# along with this program or from the site you downloaded it
# from; if not, Write to The Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# Filter Table, All Chains
#
iptables -t filter -a input -p icmp --ICMP-TYPE Echo-request /
-j log --log-prefix = "Filter Input:"
iptables -t filter -a input -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "Filter Input:"
iptables -t filter -a output -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "Filter Output:"
iptables -t filter -a output -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "Filter Output:"
iptables -t filter -a forward -p ICMP --ICMP-TYPE ECHO-Request / -j log --log-prefix = "Filter Forward:"
iptables -t filter -a forward -p icmp --ICMP-TYPE Echo-reply /
-j log --log-prefix = "Filter Forward:"
#
# Nat Table, All Chains Except Output Which Don n't work.
#
iptables -t nat -a preording -p icmp --ICP-TYPE Echo-Request /
-j log --log-prefix = "nat preording:"
iptables -t nat -a preording -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "nat preording:"
iptables -t nat -a postrouting -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "NAT postrol:"
iptables -t nat -a postrouting -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "NAT postrol:"
iptables -t nat -a output -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "nat output:"
iptables -t nat -a output -p icmp --ICMP-TYPE Echo-reply /
-j log --log-prefix = "nat output:"
#
# Mangle table, all chains
#
iptables -t mangle -a preording -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "mangle preording:"
iptables -t mangle -a preording -p ICMP --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "mangle preording:"
iptables -t mangle -i forward 1 -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "mangle fort:"
iptables -t mangle -i forward 1 -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "mangle fort:"
iptables -t mangle -i input 1 -p icmp --ICMP-TYPE ECHO-Request /
-j log --log-prefix = "mangle input:"
iptables -t mangle -i input 1 -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "mangle input:"
iptables -t mangle -a output -p ICMP --ICMP-TYPE ECHO-Request / -j log --log-prefix = "Mangle Output:"
iptables -t mangle -a output -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "mangle output:"
iptables -t mangle -i postrouting 1 -p icmp --ICMP-TYPE Echo-Request /
-j log --log-prefix = "mangle postrol:"
iptables -t mangle -i postrol 1 -p icmp --ICMP-TYPE ECHO-RepLY /
-j log --log-prefix = "mangle postrol:"