Home > Article > System Tutorial > In-depth analysis of how to use iptables under CentOS
I. Introduction
Firewalls, to put it bluntly, are used to implement access control functions under Linux. They are divided into two types: hardware or software firewalls. No matter which network you are in, the place where the firewall works must be at the edge of the network. Our task is to define how the firewall works. This is the firewall's strategy and rules, so that it can detect IP and data entering and exiting the network.
Currently, the more common firewalls on the market include layer 3 and layer 4 firewalls, which are called network layer firewalls, and layer 7 firewalls, which are actually gateways at the proxy layer.
For the seven-layer model of TCP/IP, we know that the third layer is the network layer, and the three-layer firewall will detect the source address and destination address at this layer. But for a seven-layer firewall, no matter what your source port or destination port, source address or destination address is, all your things will be checked. Therefore, in terms of design principles, seven-layer firewalls are more secure, but this results in lower efficiency. Therefore, the usual firewall solutions on the market are a combination of the two. And since we all need to access through the port controlled by the firewall, the efficiency of the firewall has become the most important control over how much data users can access. Poor configuration may even become a bottleneck for traffic.
2: The history and working principle of iptables
1.Development of iptables:
The predecessor of iptables is called ipfirewall (kernel 1.x era). This is a simple access control tool that the author transplanted from freeBSD and can work in the kernel to detect data packets. However, the working function of ipfirewall is extremely limited (it needs to put all the rules into the kernel so that the rules can run, and putting it into the kernel is generally extremely difficult). When the kernel developed to the 2. Access control functions.
They are tools that work in user space and define rules, and are not firewalls themselves. The rules they define can be read by netfilter in the kernel space and allow the firewall to work. The place where it is put into the kernel must be a specific location, where the tcp/ip protocol stack passes. The place where this tcp/ip protocol stack must pass and where the reading rules can be implemented is called netfilter. (Network filter)
The author selected a total of 5 locations in the kernel space,
1. In the kernel space: coming in from one network interface and going to another network interface
2. Data packets flow from the kernel to the user space
3. Data packets flow out from user space
4. Enter/leave the external network interface of this machine
5. Enter/leave the local network interface
2. Working mechanism of iptables
From the above development, we know that the author chose 5 locations as places of control, but have you discovered that in fact, the first three locations can basically completely block the path, but why are they already in and out? After setting the level in the mouth, what happens if it still gets stuck internally? Since routing decisions have not yet been made for data packets and it is not yet known where the data is going, there is no way to implement data filtering at the import and export. Therefore, it is necessary to set the forwarding level in the kernel space, the level for entering user space, and the level for exiting from user space. So, if they are of no use, why do we place them? Because when we do NAT and DNAT, the target address translation must be translated before routing. Therefore, we must set the checkpoint at the interface of the external network and then the internal network.
These five positions are also called five hook functions, also called five rule chains.
1.PREROUTING (before routing)
2.INPUT (packet flow entry)
3.FORWARD (Forwarding Card)
4.OUTPUT(data packet export)
5.POSTROUTING (after routing)
These are the five rule chains specified by NetFilter. Any data packet that passes through this machine must pass through one of these five chains.
3. Firewall strategy
Firewall policies are generally divided into two types, one is called the "pass" policy, and the other is called the "blocking" policy. In the pass policy, the door is closed by default, and it is necessary to define who can enter. The blocking strategy is that the door is open, but you must have identity authentication, otherwise you cannot enter. So we have to define, let those who come in come in, and let those who go out go out, so to open means to allow all, and to block is to choose. When we define the policy, we need to define multiple functions respectively, including: defining the policies that are allowed or not allowed in the data packet, the filter function, and the nat option that defines the address translation function. In order to allow these functions to work alternately, we formulated the definition of "table" to define and distinguish various working functions and processing methods.
We currently use three functions:
1.filter defines what is allowed or not allowed
2.nat defines address translation
3.mangle function: modify the original data of the message
We modify the original data of the message to modify the TTL. It is possible to disassemble the metadata of the data packet and mark/modify the content inside. Firewall tags are actually implemented by mangle.
Small extension:
Generally speaking, filters can only be used on three chains: INPUT, FORWARD, and OUTPUT
Generally speaking, NAT can only be used on three chains: PREROUTING, OUTPUT, POSTROUTING
And mangle can do 5 chains: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING
iptables/netfilter (this software) works in user space. It can make rules take effect. It is not a service itself, and the rules take effect immediately. And our iptables is now made into a service, which can be started and stopped. If started, the rules will take effect directly; if stopped, the rules will be revoked.
iptables also supports defining your own chain. But the chain you define must be associated with a specific chain. In a level setting, specify that when there is data, go to a specific chain for processing, and return after that chain is processed. Then continue checking in the specific chain.
Note: The order of the rules is very critical. The stricter the rules, the higher they should be placed. When checking the rules, they are checked from top to bottom.
three. Rule writing:
The way iptables defines rules is more complicated:
Format: iptables [-t table] COMMAND chain CRETIRIA -j ACTION
-t table: 3 filter nat mangle
COMMAND: Define how to manage the rules
chain: Specify which chain your next rule will operate on. This can be omitted when defining the policy
CRETIRIA:Specify matching criteria
-j ACTION: Specify how to process
For example: 172.16.0.0/24 is not allowed to access.
iptables -t filter -A INPUT -s 172.16.0.0/16 -p udp --dport 53 -j DROP
Of course, if you want to refuse more thoroughly:
iptables -t filter -R INPUT 1 -s 172.16.0.0/16 -p udp --dport 53 -j REJECT
iptables -L -n -v #View detailed information about defined rules
Four: Detailed explanation COMMAND:
1.Chain management commands (these are effective immediately)
-P: Set the default policy (set whether the default door is closed or open)
There are generally only two default strategies
iptables -P INPUT (DROP|ACCEPT) The default is off/the default is on
for example:
iptables -P INPUT DROP This rejects the default rule. And no action is defined, so all rules about external connections, including Xshell connections, and remote connections are rejected.
-F: FLASH, clear the rule chain (note the management permissions of each chain)
iptables -t nat -F PREROUTING
iptables -t nat -F Clear all chains in the nat table
-N:NEW supports users to create a new chain
iptables -N inbound_tcp_web indicates that it is attached to the tcp table for checking the web.
-X: Used to delete user-defined empty links
The usage method is the same as -N, but the chain inside must be cleared before deletion
-E: Used to Rename chain, mainly used to rename user-defined chains
-E oldname newname
-Z: Clear the chain and the counters of the default rules in the chain (there are two counters, how many packets and bytes are matched)
iptables -Z : Clear
2. Rule management commands
-A: Append, add a new rule at the end of the current chain
-I num: Insert, insert the current rule into which number.
-I 3: Insert as the third item
-R num: Which rule does Replays replace/modify
Format: iptables -R 3…………
-D num: Delete, clearly specify which rule to delete
3. View the management command “-L”
Append subcommands
-n: Display the ip in numerical form. It will display the ip directly. If -n is not added, the ip will be reversely resolved into the host name.
-v: Show detailed information
-vv
-vvv: The more, the more detailed
-x: Display the exact value on the counter without unit conversion
--line-numbers: Display the line numbers of the rules
-t nat: Display information about all levels
5: Detailed explanation of matching criteria
1. Universal matching: matching of source address and target address
-s: Specify as the source address to match, the host name cannot be specified here, it must be IP
IP | IP/MASK | 0.0.0.0/0.0.0.0
And the address can be inverted, add a "!" to indicate except which IP
-d: Indicates matching target address
-p: used to match protocols (there are usually 3 protocols here, TCP/UDP/ICMP)
-i eth0: Data flowing in from this network card
Inflow is generally used for INPUT and PREROUTING
-o eth0: Data flowing out from this network card
Outflow is usually on OUTPUT and POSTROUTING
2.Extended matching
2.1 Implicit extension: extension to the protocol
-p tcp: An extension of the TCP protocol. There are generally three types of extensions
--dport XX-XX: Specify the target port. Multiple non-consecutive ports cannot be specified. Only a single port can be specified, such as
--dport 21 or --dport 21-23 (this means 21,22,23)
--sport: Specify source port
--tcp-fiags: TCP flags (SYN, ACK, FIN, PSH, RST, URG)
For it, it generally needs to be followed by two parameters:
1. Check flag
2. Flag bit that must be 1
--tcpflags syn,ack,fin,rst syn = --syn
means checking these 4 bits, syn must be 1 among these 4 bits, and the others must be 0. So this means it is used to detect the first packet of the three-way handshake. For this kind of packet that specifically matches the first packet whose SYN is 1, there is also an abbreviation called --syn
-p udp: extension of UDP protocol
--dport
--sport
-p icmp: extension of icmp data message
--icmp-type:
echo-request (request echo), usually represented by 8
So --icmp-type 8 matches request echo packets
echo-reply (response data packet) is generally represented by 0
2.2 Explicit expansion (-m)
Expand various modules
-m multiport: Indicates enabling multi-port extension
After that we can enable, for example, --dports 21,23,80
6: Detailed explanation-j ACTION
Commonly used ACTION:
DROP:Discard quietly
Generally we use DROP to hide our identity and hide our linked list
REJECT:Explicitly refuse
ACCEPT:Accept
custom_chain: switch to a custom chain
DNAT
SNAT
MASQUERADE:Source address masquerading
REDIRECT: redirection: mainly used to implement port redirection
MARK:
marked by firewallRETURN:Return
Use return after the custom chain is executed to return to the original rule chain.
Exercise 1:
As long as it comes from the 172.16.0.0/16 network segment, it is allowed to access the SSHD service of my local 172.16.100.1
Analysis: First of all, it must be defined in the allow table. Because there is no need to do NAT address translation and the like, then check our SSHD service. On port 22, the processing mechanism is acceptance. For this table, there need to be two rules, one back and forth, whether we allow it or reject it. , for accessing local services, it is best to define it on the INPUT chain, and then define OUTPUT. (The initial end of the session is defined first), so the rules are:
Definition comes in: iptables -t filter -A INPUT -s 172.16.0.0/16 -d 172.16.100.1 -p tcp --dport 22 -j ACCEPT
Defined: iptables -t filter -A OUTPUT -s 172.16.100.1 -d 172.16.0.0/16 -p tcp --dport 22 -j ACCEPT
Change the default policy to DROP:
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
Seven: Status detection:
is an explicit extension used to detect the connection relationship between sessions. With detection, we can realize the expansion of inter-session functions
What is status detection? For the entire TCP protocol, it is a connection protocol. In the three-way handshake, the first handshake is called a NEW connection. From the second handshake onwards, the ack is 1, which is normal data transmission. , and the second and third handshake of tcp are called established connections (ESTABLISHED). There is also a state that is quite strange, such as: SYN=1 ACK=1 RST=1. For this kind of thing that we cannot recognize, we all Call it INVALID unrecognized. There is also a fourth type, an ancient feature of FTP. Each port is independent. Ports 21 and 20 both go and come back. There is a relationship between them. We call this relationship for RELATED.
So we have four states in total:
NEW
ESTABLISHED
RELATED
INVALID
So we can add status detection to the exercise questions just now. For example, only those in the status of NEW and ESTABLISHED are allowed to come in, and only the status of ESTABLISHED is allowed to go out. This can provide a good control mechanism for the more common rebound Trojans.
Extensions to practice questions:
Those who come in refuse permission to go out, those who come in only allow ESTABLISHED to come in, and those who go out only allow ESTABLISHED to go out. The default rules all use deny
iptables -L -n --line-number: View the line where the previous rule is located
Rewrite INPUT
iptables -R INPUT 2 -s 172.16.0.0/16 -d 172.16.100.1 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -R OUTPUT 1 -m state --state ESTABLISHED -j ACCEPT
If you want to release another 80 port at this time, how can you release it?
iptables -A INPUT -d 172.16.100.1 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -R INPUT 1 -d 172.16.100.1 -p udp --dport 53 -j ACCEPT
Exercise 2:
What if we allow ourselves to ping others, but others cannot ping us?
Analysis: For the ping protocol, what comes in is 8 (ping) and what goes out is 0 (response). In order to achieve our goal, we need 8 to go out and allow 0 to come in
On the outgoing port: iptables -A OUTPUT -p icmp --icmp-type 8 -j ACCEPT
On the incoming port: iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT
Small extension: 127.0.0.1 is special, we need to define it clearly
iptables -A INPUT -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
iptables -A OUTPUT -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
Eight: Implementation of SNAT and DNAT
Since our IP addresses are now in short supply and have been allocated, we must perform address translation to save our remaining IP resources. So how to implement NAT address translation through iptables?
1. SNAT conversion based on original address
Conversion based on the original address is generally used when many of our internal network users access the Internet through an external network port. At this time, we convert our internal network address to an external network IP, and we can connect to other The function of external network IP.
So we have to define how to convert in iptables:
Defined style:
For example, we now need to convert all IP addresses in the 192.168.10.0 network segment into the assumed external network address of 172.16.100.1:
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j SNAT --to-source 172.16.100.1
In this way, anyone from the local network who tries to access the network through the network card will be converted to the IP of 172.16.100.1.
So, what if 172.16.100.1 is not fixed?
We all know that when we use China Unicom or China Telecom to access the Internet, it will generally randomly generate an external IP address every time you turn on the computer, which means that the external network address is dynamically changed. At this time, we need to change the external network address to MASQUERADE (dynamic camouflage): it can automatically find the external network address and automatically change it to the correct external network address. Therefore, we need to set it like this:
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j MASQUERADE
Note here: Address masquerading does not apply to all places.
2.DNAT target address translation
For target address translation, the data flow direction is from outside to inside, the outside is the client, and the inside is the server side through target address translation. We can let the outside IP access our server through our external external network IP. server, but our services are placed on different servers within the intranet server.
How to do target address conversion? :
iptables -t nat -A PREROUTING -d 192.168.10.18 -p tcp --dport 80 -j DNAT --todestination 172.16.100.2
The target address translation needs to be done before reaching the network card, so it needs to be done at the PREROUTING position
9: Storage and opening of control rules
Note: All the content you define will become invalid when you restart. If we want it to take effect, we need to use a command to save it
1.service iptables save command
It will be saved in the file /etc/sysconfig/iptables
2.iptables-save command
iptables-save > /etc/sysconfig/iptables
3.iptables-restore command
When booting, it will automatically load /etc/sysconfig/iptabels
If it cannot be loaded or is not loaded at boot, and you want a self-written configuration file (assumed to be iptables.2) to take effect manually:
iptables-restore /etc/sysconfig/iptables.2
This completes the manual validation of the rules defined in iptables
Ten: Summary
Iptables is a very important tool. It is an almost necessary setting on every firewall. It is also something we must set for many reasons when we build a large network. Learning Iptables well can give us a deeper understanding of the structure of the entire network. At the same time, we can also have a thorough grasp of the direction of data in the kernel space and the security of Linux. When we are learning, we try to combine various projects and experiments to complete it. This will be very helpful for you to deepen the configuration of iptables and various techniques.
The above is the detailed content of In-depth analysis of how to use iptables under CentOS. For more information, please follow other related articles on the PHP Chinese website!