Wechat official account: Operation and maintenance development story, author: Wanger

“There is only one true heroism in the world, which is to love life after recognizing the truth of life.”

This article is my iptables learning notes, on and off for several days, today finally finished writing, I can use virtual machine or docker container operation, the following text:


The firewall system of Iptables Linux mainly works at the network layer and filters and restricts TCP/IP packets. It is a typical packet filtering firewall (also called network layer firewall). Iptables is a command-line firewall utility that uses policy chains to allow or block traffic. When a connection tries to establish itself on your system, Iptables looks for a rule in its list to match it. If not, the default operation is used. The NetFilter/Iptables filter firewall system is a powerful tool for adding, editing, and removing rules that the firewall follows and consists of when making packet filtering decisions. These rules are stored in dedicated packet filtering tables that are integrated into the Linux kernel. In packet filtering tables, rules are grouped in what we call chains. Although the NetFilter/Iptables packet filtering system is referred to as a single entity, it actually consists of two components, NetFilter and Iptables. The NetFilter component, also known as kernelspace, is the part of the kernel that consists of packet filtering tables containing the set of rules that the kernel uses to control packet filtering processing. The Iptables component is a tool, also known as userspace, that makes it easy to insert, modify, and remove rules from packet filtering tables.

Iptables controls data packets based on iptables rules. There are five chains defined in Iptables, and multiple rules can be defined for each chain. When a data packet reaches a chain, Iptables checks the first rule. See if the packet meets the conditions defined by the rule. If yes, the system processes the packet according to the method defined in this rule. Otherwise iptables moves on to the next rule, and if the packet doesn’t match any of the rules in the chain, Iptables will process packet 1 according to the default policy predefined for that chain. When a packet enters a network card, it first enters the PREROUTING chain, and the kernel determines whether to forward the packet based on the destination IP address. 2. If the packet is coming into the native machine, it moves up the graph to the INPUT chain. Once the packet reaches the INPUT chain, any process will receive it. The program running on this machine can send data packets, which go through the OUTPUT chain and then to the POSTROUTING chain OUTPUT. 3. If the packet is to be forwarded out, and the kernel allows forwarding, the packet will move to the right as shown in the figure, through the FORWARD chain, and then to the output of the POSTROUTING chain.

Iptables Filtering process The firewall is configured with layers of filtering. In fact, filtering is performed from top to bottom and from front to back based on the configuration rule sequence. If the rule is matched, that is, if the table is blocked or passed, the packet will no longer match the new rule down. If there is no clear rule to block or pass the packet, that is, no new rule is matched, the match is executed until the default matching rule is clearly organized or the default matching rule through the firewall is executed all the rules of the corresponding chain. Iptables Rules are predefined conditions defined by network administrators on Iptables. Rules are generally defined as “if the data packet header meets such conditions, the data packet will be processed”. Rules are stored in the packet filtering table in the kernel space. These rules specify the source address, destination address, transport protocol (such as TCP, UDP, and ICMP), and service type (such as HTTP, FTP, and SMTP). When the packets match the rules, Iptables processes the packets according to methods defined by the rules, such as accept, reject, and drop. The main task of configuring a firewall is to add, modify, and delete these rules. Iptables chain The iptables chain is made up of many rules. Kernel check, according to the order in the chain, check one by one, can be compared to a checkpoint chain, each packet to pass through the checkpoint, it will check whether the packet conforms to the rules of the checkpoint, if there is a rule that meets the conditions, the corresponding action of the rule will be executed. Iptables defines five default rule chains, which are INPUT, OUTPUT, FORWARD, PREROUTING, and POSTROUTING. The corresponding application time points are as follows: INPUT chain: The destination is the host after passing through the routing table, and the rules in this chain are applied. OUTPUT chain: generated by the local machine, the rules in this chain are applied when forwarding outward. FORWARD chain: After passing through the routing table, the rules in this chain apply to packets (forwarding) that need to be sent through the firewall to other addresses. PREROUTING chain: The rules in this chain are applied before routing packets. POSTROUTING chain: After routing packets, the rules in this chain are applied. Iptables tables are a set of rules that have the same functions. Therefore, rules with different functions can be managed in tables with different functions. Four tables are defined in iptables, each table has different functions. If no Filter table is specified, iptables uses the Filter table by default to execute all commands. Nat: Network address translation (port mapping, address mapping, etc.) The NAT table can be used for LAN sharing. Managle: Used to modify specific data packets (the service type and TTL of the data packets can be changed, and routes can be configured for QOS) Raw: Determines whether the data packets are processed by the status tracing mechanism. The processing priority of the highest Raw table is as follows: A list is a set of rules that have the same function. A chain is a set of rules that have the same function. Some chains have no rules that have the same function. The rules for the POstrouting chain only exist in the Managle and NAT tables. Here is the mapping between the IPtables tables and the chain:

Iptables Command Operation iptables Command format iptables [-t table] [- Command parameter chain] [- Matching condition {extended matching}] [-j action] Parameters of the iptables command

-p -policy < chain name > Sets the default policy for the specified chain

-l — list < chain name > lists all rules in the selected chain. If no chain is selected, all chains are listed. -a — append < chain name > appends one or more rules to the end of the selected chain. -I — insert < chain name > inserts 1 rule at the specified position. If no rule number is specified, the top of the chain is inserted by default. -D — delete < chain name > deletes one or more rules from the selected chain. -r — replace < chain name > replaces the rules in the selected chain. -f — flush < chain name > Deletes all rules in the table. -Z — zero < chain name > zeros packets and byte counters in all chains, either for a given chain or for a given rule in a given chain. -x -delete-chain < chain name > Deletes a user-defined chain. If no parameter is given, -v — verbose < chain name > Used with the -l other command to display more detailed information -c — check < chain name > Checking chain rules – specification Checking whether there are rules matching the specification in the selected chain. This command uses the same logic as -d to find matches, but does not change the existing iptables configuration and uses its exit code to indicate success or failure. -n — new-chain < chain name > Create a user-defined rule chain. -e — -rename-chain < Old chain name > < New chain name > Renames the user-defined chain. – line-numbers: displays the line numbers of the rules

Iptables matching rules

! The match rule is preceded by! -p # specifies the protocol type. Udplite types can be TCP, udp, icmp, icmpv6, esp, SCTP or special keyword “all” – sport # # specify the source port or port range — dport specified target port or port range – s – SRC # specify the packet source address or the source segment – d – DST # Specifies the destination IP address or destination network segment of the packet. -i # Specifies the nic for which the packet is sent. -o # Specifies the nic for which the packet is sent

Iptables extension module

– # m state – the state matching state (state, including the NEW ESTABLISHED, RELATED, INVALID) – m multiport – dports | — – sports # means to match multiple discrete port, using dports specify the target port, Sports Specifies the source port number. -m iprange — src-range 192.168.0.2-192.168.0.20# Specifies a continuous IP address segment. -m limit — limit 3/minute # Specifies the request rate within a specified period of time – limit – into 3 # at the same time allows the number of requests – m string – algo bm | KMP – string “XXXX” # use string string matching, algo said set character match query algorithm, Generally, bm algorithm is used by default. -m time – timestart 8:00 – timestop12:00 # Indicates a time period. -m time – datestART 2018-5-28T8:00 – datestOP2018-5-29T8:00 # define an absolute time scale – m time – weekdays | monthdays6, 20, 21 # 7 | specify several weeks or a month of the date of every week – m – icmp -type icmp type [/ code] # match different types of icmp protocol, You can run the iptables -m icmp -h command to view all types of ICMP protocols. You can run the iptables -m extension module -h command to view the module help

The iptables action

ACCEPT # Block the packet by dropping the packet REJECT # REJECT # Block the packet and return the packet notification. You can use the -reject -with option to set the prompt message. The information that can be set includes ICMP-net-unreachable, ICMP-host-unreachable, ICMP-proto-unreachable, ICMP-port-unreachable, ICMP-net-prohibited, and IC For example, for mp-host-prohibited, ICMP-admin-prohibited, tcp-reset LOG, for example, SNAT, for Intranet shared Internet access, for Intranet HIDDEN IP address DNAT, for mp-host-prohibited, ICMP-admin-prohibited, tcp-reset LOG MASQUERADE can be configured for extranet access to Intranet services. Unlike SNAT, it does not need to specify the mapped IP address. It automatically maps the source IP address to the IP address REDIRECT available on the extranet card. The port of the local machine can be mapped to another port to MARK packets, which can be used as the basis for judging the conditions of subsequent filtering

The iptables instance

Viewing iptables detailed rules iptables -nvl Deny all access to port22 iptables -a INPUT -p TCP -dport22 -j DROP Allow only the network segment 173.168.16.0 to access port22 iptables -i Input-s173.168.16.0/24 -p TCP -dport 22 -j ACCEPT Allows the associated state packets to pass iptables -a INPUT -m state -stateEstablished,RELATED -j ACCEPT Udp ports 137 and 138 that are allowed to access the Samba service iptables -a INPUT -p udp -dport 137 -j ACCEPT iptables -a INPUT -p udp -dport138 -j ACCEPT Forbid others to ping the host iptables -a INPUT -p icmp-micmp -icmp-type 8 -j REJECT iptables -a OUTPUT -p icmp-micmp – ICmp-type 0 -j REJECT 8 indicates that the type of icmp packets is 8, that is, echo-request. 0 indicates that the type of ICMP packets is 0, that is, echo-reply. You can use ‘iptables -m icmp -h’ to view more ICMP packet types and formats. You can use ‘iptables -i INPUT -p icmp -j REJECT’ to REJECT all ICMP packets. Iptables -p INPUT DROP Forward port 220 to port 22 iptables -t nat-aprerouting -p TCP -dport 220 -j redirect-to-ports 22 Delete rule 2 in the INPUT chain iptables -d INPUT 2 Accept IP addresses on network segment 173.168.16.0/24 to access ports 22 and 80 iptables -a INPUT -s173.168.16.0/24 -p TCP -m multiport -dports 22,80 -j ACCEPT when the number of packets with source IP address 173.168.16.8 exceeds 10, the packet matching rate is set to one every five seconds. Iptables -a INPUT -s173.168.16.8 -p TCP -m limit -limit 12/minute -limit-burst 10 -j ACCEPT iptables -a Input-s173.168.16.8 -p TCP -j DROP input-s173.168.16.8 -p TCP -j DROP input-s173.168.16.8 -p TCP -j DROP The default ACCEPT rule of the INPUT chain will be matched, so the speed limit is completely useless, so we need to add a rule to discard packets that are not matched

Iptables uses NAT tables as LAN sharing instances

In A LAN, only one computer can access the Internet, and none of the other computers can. Now, you need to use the NAT table of Iptables to map the IP address in the LAN to the computer that can access the Internet. Environment Host A External IP :60.205.177.173 Internal IP :173.168.16.1 Internal IP of host B: 173.168.16.2 gateway: 173.168.16.1 Change the gateway of host B to the IP address of host A that can access the Internet. Enable the kernel forwarding function of host A. Temporarily enable the kernel forwarding function of host A. echo 1 >/proc/sys/net/ipv4/ip_forward Permanently enable [root@localhost ~]# vim /etc/sysctl.conf net.ipv4.ip_forward = 1 [root@localhost ~]# sysctl-p # Reloading kernel parameters Add rules for host A as follows: iptables-t NAT -a POSTROUTING -o eth0 -s 173.168.16.0/24 -jsnat-to-source 60.205.177.173 If the external IP address is dynamic, you can use the MASQUERADE action, which is similar to the SNAT action. Iptables -t NAT -a POSTROUTING -o eth0 -s 173.168.16.0/24 -j MASQUERADE

Iptables Uses NAT tables to configure the access from the Internet to Intranet service instances

There is a Web server on the Intranet, but the Internet cannot directly access the Intranet. The IP address must be mapped to the Intranet. The environment configuration remains unchanged. Iptables -t NAT – A PREROUTING – d60.205.177.173 -i eth0 -p TCP — dport 800 – j DNAT – to – destination173.168.16.2:80 This allows you to access the Web service on 173.168.16.2 by accessing port 800 on 60.205.177.173. If this is not possible, try configuring the corresponding SNAT rules

If you have any mistakes or additions, please leave a comment below


Refer to the link

Blog.csdn.net/reyleon/art…

www.zsythink.net/archives/17…

www.zhsir.org/article/145…

This article uses the article synchronization assistant to synchronize