Basic use of iptables firewall

Source: Internet
Author: User
Tags types of extensions
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 a network. Our task is to define how the firewall works. this is the firewall policy and rules to achieve first:
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 a 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: Iptables.
1. 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 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 the user control
4. access/exit the local internet interface
5. access/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 (data packet inbound port)
3. FORWARD (forwarding manager)
4. OUTPUT (data 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 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 of the following features:
1. the filter definition is allowed or not allowed.
2. nat defines the 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 scale
Filters can only be performed on three chains:
INPUT, FORWARD, OUTPUT
Nat can only be implemented on three links:
PREROUTING, OUTPUT, POSTROUTING
Mangle can do the following for five chains:
PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING
Iptables/netfilter (this software) works in the user space. it enables 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.
The order of rules is critical. the stricter the rules, the more advanced the rules should be. when checking rules, they should be checked from top to bottom.

3. how to write rules?
The iptables rule definition method is complex.
Format: iptables [-ttable] COMMAND chain CRETIRIA-j ACTION
-T table: 3 filternat mangle
COMMAND: defines how to manage rules
Chain: specifies the chain on which your next rule is operated. when defining a policy, it can be omitted.
CRETIRIA: specify matching criteria
-J ACTION: specifies 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
Of course, if you want to reject it more thoroughly:
Iptables-t filter-r input 1-s 172.16.0.0/16-p udp -- dport 53-j REJECT
Iptables-L-n-v

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)
There are generally only two default policies.
Iptables-p input (DROP | ACCEPT) is disabled by default/is enabled by default
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 PREROUTING
Iptables-t nat-F clear all links in the nat table
-N: NEW supports creating a chain.
Iptables-N inbound_tcp_web indicates that the web is checked on the tcp table.
-X: used to delete custom empty chains.
The method is the same as-N, but you must clear the chain before deleting it.
-E: Renamechain is mainly used to rename a custom chain.
-E oldname newname
-Z: clears 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 at the end of the current chain.
-I num: Insert the number of the current rule.
-I 3: Insert the third entry
-Rnum: the number of rules to be replaced/modified by Replays.
Format: iptables-R 3 ............
-Dnum: Delete. specify the rules to delete.
3. view the management command "-L"
Additional sub-commands
-N: the ip address is displayed in numbers. the ip address is displayed directly. if-n is not added, the ip address is resolved to the host name.
-V: displays 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.
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 must be an IP address.
IP | IP/MASK | 0.0.0.0/0.0.0.0
In addition, the address can be reversed by adding "!". Indicates the IP address other
-D: indicates matching the target address.
-P: used to match the Protocol (TCP/UDP/ICMP)
-Ieth0: data inflows from this Nic
Inbound traffic is generally used on INPUT and PREROUTING.
-Oeth0: data outflow from this Nic
The outbound traffic is generally on the OUTPUT and POSTROUTING.
2. Extended matching
2.1 implicit extension: protocol extension
-P tcp: TCP protocol extension. Generally, there are three types of extensions.
-- Dport XX-XX: specifies the target Port, cannot specify multiple non-continuous ports, can only specify a single port, such
-- Dport 21 or -- dport 21-23 (at this time, 23)
-- Sport: specifies 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 flag space
2. the flag must be 1
-- Tcpflags syn, ack, fin, rst syn = -- syn
Indicates checking the four digits. the syn must be 1 in the four digits, 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: extension of icmp data packets
-- Icmp-type:
Echo-request (request echo), usually expressed in 8
So -- icmp-type 8 matches the request Echo Packet
Echo-reply (response packet) is generally expressed as 0.
2.2 explicit scaling (-m)
Extended modules
-M multiport: enables multi-port extension.
Then we can enable -- dports, 80

6. Explanation-j ACTION
Common actions:
DROP: quietly discarded
Generally, we use DROP to hide our identity and our linked list.
REJECT: explicitly deny
ACCEPT: ACCEPT
Custom_chain: switch to a custom chain
DNAT
SNAT
MASQUERADE: source address disguise
REDIRECT: redirection: mainly used for port redirection
MARK: marked by the firewall
RETURN: RETURN
Return the original rule chain after the custom chain is executed.
Exercise Question 1:
Any CIDR block from 172.16.0.0/16 is allowed to access the SSHD service of 172.16.100.1 on my local machine.
Analysis: 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 addition rule is:
Defined in: iptables-tfilter-a input-s 172.16.0.0/16-d 172.16.100.1-p tcp -- dport 22-j ACCEPT
Defined: iptables-tfilter-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 function extension 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 = 1ACK = 1RST = 1. we call INVALID unidentifiable for such unidentifiable information. 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
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:
When the request is rejected, only ESTABLISHED is allowed. when the request is rejected, only ESTABLISHED is allowed. Reject all default rules
Iptables-L-n -- line-number: check the row 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 -- dport22-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
One rule allows all
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 the incoming value 0.
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: For 127.0.0.1, we need to clearly define it
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 address
The 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, we need to define how to convert in iptables:
Defined style:
For example, we want to convert all the IP addresses in the 192.168.10.0 CIDR block to the internet address of 172.16.100.1:
Iptables-t nat-APOSTROUTING-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 it as follows:
Iptables-t nat-APOSTROUTING-s 192.168.10.0/24-j MASQUERADE
Note: address disguise does not apply to all places.
2. DNAT target address translation
For destination address translation, the data flow is from the external to the client, and the external is the server.
Through the target address translation, 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 server.
How do I convert the target address? :
Iptables-t nat-a prerouting-d 192.168.10.18-p tcp -- dport 80-jDNAT -- todestination 172.16.100.2
The destination address translation must be performed before it reaches the NIC, so it must be performed at the PREROUTING location.

9. storage and activation of control rules
Note: All the content you define will expire when you restart it. to make it take effect, you need to use a command to save it.
1. service iptablessave command
It will be saved in the/etc/sysconfig/iptables file.
2. iptables-save command
Iptables-save>/etc/sysconfig/iptables
3. iptables-restore command
It automatically loads/etc/sysconfig/iptabels at startup.
If you cannot load or do not load a configuration file that you have written (assuming iptables.2:
Iptables-restore </etc/sysconfig/iptables.2
The rules defined in iptables are manually activated.

10: conclusion.
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.
Author "For The Dream"
Related Article

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.