Tips for using the iptables command in linux: linuxiptables
Tips for using the iptables command in linux: iptables advanced network
Iptables commandIs a common firewall software on Linux and is part of the netfilter project. It can be configured directly or through many front-end and graphical interfaces.
Syntax
Iptables (option) (parameter)
Option
-T <Table>: Specifies the table to be manipulated.-A: adds an entry to the rule chain.-D: deletes an entry from the rule chain.-I: insert entries into the rule chain.-R: Replace the entries in the Rule chain.-L: display the existing entries in the Rule chain.-F: Clear the existing entries in the Rule chain; -Z: clears the data packet calculator and byte counter in the Rule chain.-N: Creates a custom rule chain.-P: defines the default target in the Rule chain.-h: displays help information.-p: Specifies the protocol type of the data packet to be matched.-s: Specifies the source IP address of the data packet to be matched.-j <target>: Specifies the target to be redirected; -I <Network Interface>: Specifies the network interface for the data packet to enter the local machine;-o <Network Interface>: Specifies the network interface used by the local machine to exit the data packet.
Iptables Command Option input sequence:
Iptables-t table name <-A/I/D/R> rule chain name [Rule number] <-I/o Nic Name>-p protocol name <-s source IP address/ source subnet> -- sport source port <-d target IP Address/target subnet> -- dport target port-j action
Table names include:
Raw: Advanced features, such as URL filtering.
Mangle: Packet modification (QOS), used to achieve service quality.
Net: Address translation, used for Gateway Router.
Filter: Packet filtering, used for firewall rules.
Rule chain names include:
INPUT chain: Process input data packets.
OUTPUT chain: Process output data packets.
PORWARD chain: Process forwarded data packets.
PREROUTING chain: Used for destination address translation (DNAT ).
POSTOUTING chain: Used for SNAT conversion ).
Actions include:
Accept: Receives data packets.
DROP: Discard data packets.
REDIRECT: Redirection, ing, and transparent proxy.
SNAT: Source address conversion.
DNAT: Destination Address conversion.
MASQUERADE: NAT, used for ADSL.
LOG: Log record. Instance
Clear existing iptables rules
iptables -Fiptables -Xiptables -Z
Open the specified port
Iptables-a input-s 127.0.0.1-d 127.0.0.1-j ACCEPT # Allow the local loopback interface (that is, run the local machine to access the local machine) iptables-a input-m state -- state ESTABLISHED, RELATED-j ACCEPT # Allow established or connected access iptables-a output-j ACCEPT # Allow all hosts to access iptables-a input-p tcp -- dport 22-j ACCEPT # Allow access to port 22 iptables-a input-p tcp -- dport 80-j ACCEPT # Allow access to port 80 iptables-a input-p tcp -- dport 21-j ACCEPT # allow ftp port 21 of the Service iptables-a input-p tcp -- dport 20-j ACCEPT # Allow Port 20 of the FTP service iptables-a input-j reject # prohibit other unpermitted rules from accessing iptables -a forward-j REJECT # prohibit access by other unpermitted rules
Blocked IP Address
Iptables-I input-s 123.45.6.7-j DROP # command iptables-I INPUT-s 123.0.0.0/8-j DROP # command iptables from 123.0.0.1 to 123.20.254 -I input-s 124.45.0.0/16-j DROP # an IP address segment is the command iptables-I INPUT-s 123.45.6.0/24-j DROP # an IP address segment from 123.45.0.1 to 123.45.254. the command from 123.45.6.1 to 123.45.6.254 is
View added iptables rules
iptables -L -n -vChain INPUT (policy DROP 48106 packets, 2690K bytes) pkts bytes target prot opt in out source destination 5075 589K ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0 191K 90M ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:221499K 133M ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:804364K 6351M ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 6256 327K ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0 Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 3382K packets, 1819M bytes) pkts bytes target prot opt in out source destination 5075 589K ACCEPT all -- * lo 0.0.0.0/0 0.0.0.0/0
Delete an added iptables rule
Display All iptables with serial numbers. Run the following command:
iptables -L -n --line-numbers
For example, to delete the rule with serial number 8 in INPUT, execute:
iptables -D INPUT 8
I. Preface
The firewall is actually used to implement access control in Linux. It can be divided into two types: hardware or software firewalls. In any network, the firewall must work on the edge of the network. Our task is to define how the firewall works. This is the firewall policy and rules, so that it can detect inbound and outbound IP addresses and data.
Currently, layer-3 and layer-4 firewalls are common on the market, such as network layer firewalls and layer-7 firewalls, which are actually proxy layer gateways.
For the layer-7 TCP/IP model, we know that the layer-3 is the network layer, and the layer-3 firewall will detect the source and target addresses on this layer. However, for a layer-7 firewall, no matter what your source port or target port, source address or target address is, all your items will be checked. Therefore, for the design principle, the layer-7 firewall is more secure, but this brings lower efficiency. Therefore, the common firewall solutions on the market are both combined. However, because we all need to access the port controlled by the firewall, the working efficiency of the firewall has become the most important control over how much data users can access, poor configuration may even cause traffic bottlenecks.
Ii. History and working principles of iptables
1. The development of iptables:
The predecessor of iptables is 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, ipfirewall has extremely limited functions (it needs to put all the rules into the kernel so that the rules can run and put them into the kernel, which is generally extremely difficult ). When the kernel develops to 2. in the x Series, the software changed its name to ipchains. It can define multiple rules and concatenate them to work together. Now, it is called iptables, which can form a list of rules, implement absolutely detailed access control.
They are all tools that work in user space and define rules. They are not firewalls themselves. The rules they define can be read by netfilter in the kernel space, and the firewall can work. The place where the kernel is placed must be a specific location, and must be where the TCP/IP protocol stack passes. The TCP/IP protocol stack must pass through the netfilter where the read rules can be implemented)
The author selects five locations in the kernel space. in kernel space: 2. 3. the number of data packets that flow out from the user space. access/exit the local Internet interface 5. enter/exit the Local intranet Interface
2. iptables Working Mechanism
From the above development, we know that the author has chosen five locations for control, but have you found that the paths have basically been completely blocked in the first three locations, but why should I enable the internal card even after the entry and exit ports are set? Because data packets have not yet been routed and do not know where the data is going, there is no way to filter data during import and export. Therefore, you need to set the forwarding level in the kernel space to enter the level of the user space and to go out of the user space. So, since they are useless, why should we place them? Because when we are doing NAT and DNAT, the destination address must be converted before the route. Therefore, we must set the level at the Internet and then the Intranet interface.
These five locations are also called five hook functions and five rule chains. 1. PREROUTING (before routing) 2. INPUT (packet inbound port) 3. FORWARD (forwarding manager) 4. OUTPUT (data packet egress) 5. POSTROUTING (after routing) is the five rule chains specified by NetFilter. Any data packet that passes through the local machine will pass through one of the five chains.
3. Firewall Policy
Firewall policies are generally divided into two types: one is "pass", the other is "Block", and the other is "pass". By default, the door is closed and you must define who can enter the firewall. The blocking policy is that the door is open, but you must have identity authentication; otherwise, you cannot enter. Therefore, we need to define how to allow incoming traffic to allow outgoing traffic. Therefore, we need to allow full access, while blocking means selecting. When defining a policy, we need to define multiple features, including: policies that are allowed or not allowed in data packets, and filter functions, the nat option is used to define the address translation function. To make these functions work in turn, we have developed a "table" definition to define and differentiate different work functions and processing methods.
We now use three more functions: 1. filter defines the allowed or not allowed 2.nat defines the address translation 3. mangle function: modify the original data of the message
We modify the original data of the message to modify the TTL. The data package metadata can be split and marked/modified in it. The firewall tag is actually implemented by mangle. Small Extension: For filters, it can only be performed on three chains: INPUT, FORWARD, and OUTPUT. For nat, it can only be performed on three chains: PREROUTING, OUTPUT, POSTROUTING and mangle can work in five chains: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING iptables/netfilter (this software, it allows the rule to take effect. It is not a service and the rule takes effect immediately. Iptables is now a service that can be started and stopped. Start, the rule takes effect directly, and stop, then the rule is revoked. Iptables also supports custom chains. However, a custom chain must be associated with a specific chain. In a level setting, specify to find a specific chain for processing when there is data, and then return after the chain is processed. Check the link.
Note: The order of rules is critical. The stricter the rules, the more advanced the rules should be placed. When checking rules, they should be checked from top to bottom.
III. Rule writing:
The iptables rule definition method is complex: Format: iptables [-t table] COMMAND chain CRETIRIA-j ACTION-t table: 3 filters nat mangle COMMAND: define how to manage a rule chain: Specify the chain on which the rule you want to operate. CRETIRIA can be omitted when defining a policy: specify matching standard-j ACTION: specify how to process
For example, access from 172.16.0.0/24 is not allowed. Iptables-t filter-a input-s 172.16.0.0/16-p udp -- dport 53-j DROP: 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 the rule Definition
4. Explain COMMAND:
1. Chain management commands (these commands take effect immediately)-P: Set the Default policy (set whether the default door is closed or open). Generally, there are only two default policies: iptables-p input (DROP | ACCEPT) the default setting is disabled/the default setting is enabled. For example, iptables-p input drop rejects the default setting. No action is defined. Therefore, all rules for external connections, such as Xshell connections, are rejected. -F: FLASH, clear the rule chain (pay attention to the management permission of each chain) iptables-t nat-f prerouting iptables-t nat-F clear all the chains in the nat table-N: NEW allows you to create a chain iptables-N inbound_tcp_web, which is attached to the tcp table for web check. -X: the method used to delete user-defined empty links is the same as-N. However, you must clear the links in-E before deleting them: rename chain is mainly used to Rename the custom chain-E oldname newname-Z: to clear the chain and the counter of the default rule in the chain (there are two counters, how many packets are matched and how many bytes are matched) iptables-Z: Clear
2. Rule management commands-A: append, add A rule-I num: Insert at the end of the current chain, and insert the current rule as the number. -I 3: insert it to the third entry-R num: Replays to replace/modify the format of the rule: iptables-R 3 ............ -D num: delete. specify the number of rules to be deleted.
3. view the management command "-L"Append sub-command-n: to display the ip address in numbers. It will display the ip address directly. If-n is not added, the ip address will be resolved to the host name in reverse direction. -V: display details-vv-vvv: More details-x: display the exact value on the counter, without converting the unit-line-numbers: display the rule's row number-t nat: display information of all levels
V. Detailed description of matching criteria
1. General match: match the source address and target address-S: Specifies the source address match. The host name cannot be specified here. It must be an IP address | IP/MASK | 0.0.0.0/0.0.0.0 and the address can be reversed by adding "!". Indicates the IP address other than the target IP address-p: Used to match the Protocol (here there are usually three protocols, TCP/UDP/ICMP)-I eth0: the inbound data from this Nic is generally used in INPUT and PREROUTING-o eth0: the outbound data from this Nic is generally in OUTPUT and POSTROUTING.
2. Extended matching2.1 implicit Extension: Protocol extension-p tcp: TCP extension. There are generally three extensions -- dport XX-XX: Specify the target port, you can only specify a single port, such as -- dport 21 or -- dport 21-23, 23) -- sport: Specify the source port -- tcp-fiags: the flag of TCP (SYN, ACK, FIN, PSH, RST, URG). Generally, it must follow two parameters: 1. check flag 2. the flag must be 1-bit -- tcpflags syn, ack, fin, rst syn = -- syn indicates to check the four digits. The syn must be 1 in the four digits, and the others must be 0. So this is the first packet used to detect the three-way handshake. For this type of packet that specifically matches the first packet with SYN 1, there is also a shorthand method called -- syn-p udp: UDP protocol extension -- dport -- sport-p icmp: icmp-type: echo-request (request echo ), generally, 8 is used to represent the echo-reply (response packet) of the -- icmp-type 8 matching request echo packet. Generally, 0 is used to represent the 2.2 explicit extension (-m) extended modules-m multiport: indicates that the multi-port extension can be enabled after -- dports, 80
6. explanation-j ACTION
Common ACTION: DROP: quietly discard generally we use DROP to hide our identity and hide our linked list REJECT: explicitly reject accept: ACCEPT custom_chain: switch to a custom chain dnat snat masquerade: Source Address disguised REDIRECT: Redirection: Mainly used for port redirection MARK: Firewall flag RETURN: RETURN after the custom chain is executed, use the RETURN, to return the original rule chain.
Exercise Question 1:As long as the SSHD service analysis from the 172.16.0.0/16 CIDR Block allows access to my local 172.16.100.1: first, it must be defined in the allowed table. Because you do not need to perform NAT address translation or so, and then check our SSHD service. on port 22, the processing mechanism is accept. For this table, you need to have one or two rules, if we allow or deny access to the local service, we 'd better define the access to the INPUT chain, and define the OUTPUT. (The initial end of the session is defined first), so the rule is: defined: 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
7. Status Detection:
It is an explicit extension used to detect the connection relationship between sessions. With the detection, we can implement the extension of the function between sessions. What is status detection? For the entire TCP protocol, it is a connected protocol. In the three-way handshake, the first handshake is called the NEW connection, and from the second handshake, The ack is 1, this is a normal data transmission, and the second and third handshake with tcp, called the ESTABLISHED connection (ESTABLISHED), there is a status, relatively strange, such: SYN = 1 ACK = 1 RST = 1. We call INVALID unidentifiable for such unidentifiable tasks. There is also the fourth type. FTP is an ancient feature. Each port is independent. ports 21 and 20 are both one-to-one, and there is a relationship between them, this relationship is called RELATED. Therefore, we have four statuses: new established related invalid. Therefore, we can add status detection for the exercise just now. For example, only NEW and ESTABLISHED States are allowed to come in, and ESTABLISHED States are allowed to go out. This provides a good control mechanism for common bounce Trojans. Extended exercise questions: if you are not allowed to exit, you can only allow ESTABLISHED to come in. If you want to exit, you can only allow ESTABLISHED to go out. The default rules all use the deny iptables-L-n -- line-number: check the row where the previous rule is located to rewrite the 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 how can I allow another port 80? 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 Question 2:If we allow ourselves to ping others, but others cannot ping ourselves, how can we achieve this? Analysis: For the ping protocol, the incoming value is 8 (ping), and the outgoing value is 0 (response ). to achieve this goal, we need to exit 8 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: Special for 127.0.0.1, we need to clearly define 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
8. Implementation of SNAT and DNAT
As the IP address is very tight and allocated, we must perform address conversion to save only a few IP resources. So how does iptables implement NAT address translation?
1. SNAT Conversion Based on the original addressThe Conversion Based on the original address is generally used when many of our Intranet users access the Internet through an Internet port. At this time, we convert our Intranet address into an Internet IP address, we can connect to other Internet IP addresses. Therefore, in iptables, we need to define how to convert: The Defined style: for example, we want to convert all the IP addresses of the 192.168.10.0 network segment to the Internet 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, as long as A local network tries to access the network through the network card, all are converted to the IP address 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 generate a random Internet IP address every time you start the system, which means that the Internet address is dynamically changed. In this case, we need to replace the Internet address with the MASQUERADE (Dynamic disguise): It can automatically find the Internet address and change it to the correct Internet address. Therefore, we need to set iptables-t nat-a postrouting-s 192.168.10.0/24-j MASQUERADE as follows: Address disguise does not apply to all places.
2. DNAT target address translationFor target address translation, the data flow is from the external to the external, and the external is the client, where the server side is converted through the target address, we can allow external ip addresses to access different servers on our servers through our external internet ip addresses, while our services are placed on different servers on the Intranet servers.
How do I convert the target address? : Iptables-t nat-a prerouting-d 192.168.10.18-p tcp -- dport 80-j DNAT -- todestination 172.16.100.2 the destination address must be converted before it reaches the NIC, so we have to go to the position of PREROUTING: control the storage and enabling of rules.
Note: All the content you define will expire when you restart it. To take effect, you need to use a command to save it. the service iptables save command is saved in the/etc/sysconfig/iptables file. iptables-save command iptables-save>/etc/sysconfig/iptables 3. when the iptables-restore command is started, it automatically loads/etc/sysconfig/iptabels, iptables-restore </etc/sysconfig/iptables.2 manually takes effect for a self-written configuration file (assuming iptables.2 ).
10. SummaryIptables is a very important tool. It is almost essential for every firewall. It is also required for many reasons when we are working on a large network. Learning Iptables well can give us a deep understanding of the entire network structure. At the same time, we can thoroughly understand the data trend in the kernel space and linux security. When we are learning, we try to combine various projects and experiments. This will be of great help for you to deepen the configuration of iptables and various techniques.