Iptables usage instructions, iptables usage

Source: Internet
Author: User

Iptables usage instructions, iptables usage
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: 1. In the kernel space: from one network interface to another
2. Data Packets flow from the kernel to the user space
3. data packets flow out of user space
4. Access/exit the local Internet interface
5. enter/exit the Local intranet interface 2. iptables's working mechanism from the above development, we know that the author has chosen five locations for control, but have you found that, in fact, the path has basically been completely blocked in the first three locations, but why is it still necessary to enable the internal card after the entrance and exit ports have been 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 (packet egress) 5. POSTROUTING (after routing)

This is the five rule chains specified by NetFilter. Any data packet that passes through the local machine will pass through one of these five chains.
3. firewall policies 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, you must define who can enter. 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 of the following features:
1. filter defines 2.nat that is allowed or not allowed to define address translation 3. mangle function: Modify original packet data

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 Syntax: iptables [-t table] COMMAND chain CRETIRIA-j ACTION-t table: table is one of the three filters nat mangle, if this parameter is omitted, filter is used. COMMAND: defines how to manage the chain of rules: Specifies the chain on which the next rule is operated. CRETIRIA can be omitted when a policy is defined: 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/24-p udp -- dport 53-j DROP
Of course, if you want to REJECT it more thoroughly: iptables-t filter-r input 1-s 172.16.0.0/24-p udp -- dport 53-j REJECT
Iptables-L-n-v # view detailed information about the rule Definition
4. Details about COMMAND1. chain management commands (these are effective immediately)-P: Set the Default policy (set whether the default door is closed or open) the default policy generally only has two types of iptables-p input (DROP | ACCEPT). The default policy is off (data packets are discarded directly)/the Default policy is on (data packet receipt)
For example, iptables-p input drop rejects the default rule. 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 PREROUTINGiptables-t nat-F clear all the chains in the nat table
-N: NEW. You can create a chain iptables-N inbound_tcp_web, which indicates that the chain 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, number of matched packets and number of bytes) iptables-Z: Empty 2. rule Management command-A: append, add A rule at the end of the current chain
-I num: insert the number of the current rule. -I 3: insert the third entry
-R num: Replays replace/modify the rule format: iptables-R 3 ............
-D num: delete. specify the number of rules to be deleted. 3. view the management command "-L" appended sub-command-n: display the ip address in a number, it will display the ip address directly, if not added-n, it will reverse resolve the ip address to the host name.
-V: Show Details-vv-vvv: more details
-X: displays the exact value on the counter, not in unit conversion.
-- Line-numbers: displays the row number of the rule.
-T nat: displays information about all levels. 5. Detailed Description: matching Standard 1. common match: Source Address and target address match-s: Specifies the source address match. The host name cannot be specified here. It must be IPIP | IP/MASK | 0.0.0.0/0.0.0.0 and the address can be reversed, add a "!" Indicates the IP address other
-D: match the target address-p: Used to match the Protocol (here there are usually three protocols, TCP/UDP/ICMP)-I eth0: data flowing from this network card, inbound traffic is generally used on INPUT and PREROUTING-o eth0: the data that flows out from this Nic, And the outbound traffic is generally on OUTPUT and POSTROUTING. extended matching 2.1 implicit Extension: Extended protocol-p tcp: Extended TCP. 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: TCP flag (SYN, ACK, FIN, PSH, RST, URG)
For this parameter, it is generally followed by two parameters: 1. Check the flag 2. It must be a flag of 1
-- Tcpflags syn, ack, fin, rst syn = -- syn indicates to check the four digits. The syn in these four digits must be 1, and the other digits must be 0. So this is the first packet used to detect the three-way handshake. For a packet that specifically matches the first packet with a SYN of 1, there is also a shorthand method called -- syn
-P udp: UDP protocol extension -- dport -- sport-p icmp: icmp data packet extension -- icmp-type:
Echo-request (request echo), usually expressed in 8, so -- icmp-type 8 matches the request echo packet
Echo-reply (response packet) generally uses 0 to represent 2.2 explicit expansion (-m) Expansion of various modules-m multiport: it means that after multi-port extension is enabled, we can enable it, for example, -- 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: turn to a custom chain DNATSNATMASQUERADE: Source Address disguise
REDIRECT: Redirection: Mainly used for port redirection. MARK: firewall-marked RETURN: RETURN
Return the original rule chain after the custom chain is executed. Exercise Question 1: as long as the SSHD service analysis from 172.16.0.0/16 CIDR blocks allow access to my local machine's 172.16.100.1: first, it must be defined in the allow 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 addition rule is:
Defined 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 DROPiptables-p output DROPiptables-p forward drop 7: status detection: an explicit extension used to detect connections between sessions, with the detection, we can extend the function of the session.
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, there are four statuses: NEW, ESTABLISHED, RELATED, and INVALID. Therefore, we can add status detection for the exercise questions we just learned. 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. Deny iptables-L-n -- line-number is used for all default rules: Check the row where the previous rule is located
Rewrite INPUTiptables-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 how can I achieve ping failure by others? 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 ACCEPTiptables-a output-s 127.0.0.1-d 127.0.0.1-j ACCEPT eight: the implementation of SNAT and DNAT is very tight and allocated. As a result, we must perform address conversion to save only a few IP resources. So how does iptables implement NAT address translation?
1. SNAT based on the original address Conversion Based on the original address conversion is generally used when many of our Intranet users access the Internet through an Internet port, in this case, we can convert our Intranet address to an Internet IP address so that we can connect to other Internet IP addresses. Therefore, we need to define how to convert in iptables:
Defined style: for example, we want to convert all the IP addresses of the 192.168.10.0 CIDR block into 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, any attempt from a local network to access the network through the network card will be converted to 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. for DNAT target address translation, the data flow is from the external to the external, and the external is the client, which is the server through the target address conversion, 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 need to go to the PREROUTING position 9: control rule storage and enabling. Note: all the content you define will expire when you restart. If we want 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. iptables-restore command 1) when it is started, it will automatically load/etc/sysconfig/iptabels. If it cannot be loaded or not loaded, and you want to have a configuration file (assuming iptables.
2) if it takes effect manually: iptables-restore </etc/sysconfig/iptables.2 completes the manual effectiveness of the rules defined in iptables
10: iptables 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.
We recommend an article titled netfilter/iptables.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.