The understanding and use of iptables in Linux

1 Introduction

        iptables is a firewall software for the Linux operating system that controls network communications by filtering, modifying, and redirecting network traffic. iptables is a subsystem in the Linux kernel, which can configure network firewalls by entering rules on the command line. iptables can control inbound and outbound traffic, allowing or blocking specific IP addresses, protocols, and ports. It is one of the most commonly used network security and firewall software for Linux systems.       

 Linux's iptables is very useful in enterprise applications, examples are as follows:

1. Small and medium-sized enterprises and Internet cafes have iptables as the NAT router of the enterprise, which can be used to replace traditional routers and save costs.

2. The IDC computer room generally does not have a hardware firewall, and the server in the IDC computer room can use a Linux firewall instead of a hardware firewall.

3. iptables can be combined with squid as a transparent proxy for enterprise internal Internet access. The traditional proxy needs to configure the proxy server information in the browser, but the transparent proxy of iptables+squid can redirect the client's request to the port of the proxy server. The client does not need to make any settings, but does not feel the existence of the agent.

4. When using iptables as an enterprise NAT router, you can use the extension module of iptables to shield P2P traffic, and you can also prohibit illegal web pages.

5.iptables can be used to map external network IP to internal network IP.

6.iptables can easily prevent lightweight DOS attacks, such as ping attacks and SYN flood attacks.

        Therefore, Iptables mainly has two application modes: host firewall and NAT router .

2. netfilter and iptables

        Netfilter is a Linux 2.4 kernel firewall framework proposed by Rusty Russell. This framework is concise and flexible, and can realize many functions in the application of security policies, such as packet filtering, packet processing, address masquerade, transparent proxy, dynamic network address translation ( Network Address Translation, NAT), and user and media access control (Media Access Control, MAC) address-based filtering and state-based filtering, packet rate limiting, etc. These rules of Iptables/Netfilter can be combined flexibly to form a lot of functions and cover all aspects, all thanks to its excellent design ideas.

  Netfilter is a packet processing module inside the core layer of the Linux operating system. It has the following functions:

1. Network Address Translate

2. Modification of data packet content

3. Packet filtering firewall

The Netfilter platform has formulated five mount points for data packets (Hook Point, we can understand it as a callback function point, when the data packet arrives at these locations, it will actively call our function, so that we have the opportunity to Change their direction, content), these five mount points are PRE_ROUTING, INPUT, OUTPUT, FORWARD, respectively POST_ROUTING.

 

The rules set by Netfilter are stored in the kernel memory, and iptables is an application layer application, which modifies the XXtables (Netfilter configuration table) stored in the kernel memory through the interface released by Netfilter. This XXtables consists of tables tables, chains chains, and rules rules, and iptables is responsible for modifying this rule file at the application layer. A similar application is firewalld.

3. Basic components of iptables

3.1 Table of Rule 4

The rule four tables are: filter table, nat table, mangle table, raw table.

3.1.1  filter table

It is mainly used to filter data packets, and decide whether to release the data packets according to specific rules (such as DROP, ACCEPT, REJECT, LOG). The kernel module corresponding to the filter table is iptable_filter, which contains three rule chains:

INPUTchain: INPUT for packets whose destination is local

FORWARDChain: FORWARD filters all the ones that are not generated locally and the destination is not local (that is, the local machine is only responsible for forwarding)

OUTPUTchain: OUTPUT is used to filter all locally generated packages    

3.1.2 nat table

It is mainly used to modify the IP address, port number and other information of the data packet (network address translation, such as SNAT, DNAT, MASQUERADE, REDIRECT). Packets belonging to a flow (data that may be split into multiple packets due to packet size limitations) will only go through this table once. If the first packet is allowed to be NAT or Masqueraded, then the rest of the packets will be automatically do the same, that is, the rest of the packets will not pass through this table. The kernel module corresponding to the table is iptable_nat, which contains three rule chains:

PREROUTINGChain: The function is to change the destination address of the packet when it just reaches the firewall

OUTPUTchain: change the destination address of a locally generated packet

POSTROUTINGChaining: changing the source address of a packet just before it leaves the firewall

3.1.3 mangle table

It is mainly used to modify the TOS (Type Of Service, service type), TTL (Time To Live, life cycle) index of the data packet and set the Mark mark for the data packet to realize Qos (Quality Of Service, service quality) adjustment and policy routing And other applications, due to the need for corresponding routing equipment support, so the application is not extensive. Contains five rule chains - PREROUTING, POSTROUTING, INPUT, OUTPUT, FORWARD

3.1.4 raw table

It is a newly added table of iptables since version 1.2.9. It is mainly used to determine whether the data packet is processed by the state tracking mechanism. When matching packets, the rules of the raw table take precedence over other tables. Contains two rule chains - OUTPUT, PREROUTING.

3.2 Five chains of rules

When processing various data packets, according to different intervention timings of firewall rules, iptables provides 5 default rule chains, and understands these chains from the perspective of application time

INPUTChain: Apply the rules in this chain when a packet is received (inbound) for the firewall's native address.

OUTPUTChain: Rules in this chain are applied when the firewall natively sends packets out (outbound).

FORWARDChain: Rules in this chain are applied when packets are received that need to be sent to other addresses through the firewall (forwarding).

PREROUTINGChain: Apply the rules in this chain, such as DNAT, before routing the packet.

POSTROUTINGChain: Apply the rules in this chain, such as SNAT, after routing the packet.

The INPUT and OUTPUT chains are mainly used in the "host firewall", which is mainly aimed at the security control of the incoming and outgoing data of the server itself.

The chains of FORWARD , PREROUTING and POSTROUTING are mainly applied in "network firewall", especially when the firewall server is used as a gateway.

4. The principle of data packet routing

How does this Xtables table work in the packet routing of the kernel protocol stack?

work process:

The network port data packet is received by the underlying network card NIC, and after unpacking through the data link layer (removing the data link frame header), it enters the TCP/IP protocol stack (essentially a kernel driver that processes network data packets) and Netfilter mixed packet processing flow. The receiving, processing, and forwarding process of data packets constitutes a finite state vector machine, which passes through a series of kernel processing functions and Netfilter Hook points, and is finally forwarded or digested by the upper-layer application.

Found a good picture, as follows:

From the figure above, we can conclude the following rules

1. When a data packet enters the network card, the data packet first enters the PREROUTING chain . In the PREROUTING chain, we have the opportunity to modify the DestIP (destination IP) of the data packet, and then the "routing module" of the kernel according to the "data packet destination IP" and " The routing table in the kernel" determines whether it needs to be forwarded (note that the DestIP of the data packet may have been modified by us at this time)

2. If the data packet enters the machine (that is, the destination IP of the data packet is the network port IP of the machine), the data packet will move down along the graph and reach the INPUT chain . After a packet reaches the INPUT chain, any process will - receive it

3. The program running on this machine can also send data packets, these data packets go through the OUTPUT chain, and then reach the output of the POSTROTING chain (note that the SrcIP of the data packet may have been modified by us at this time)

4. If the data packet is to be forwarded (that is, the destination IP address is no longer in the current subnet), and the kernel allows forwarding, the data packet will move to the right, pass through the FORWARD chain , and then reach the output of the POSTROUTING chain (select the corresponding subnet network port to send out)

         When writing iptables rules, you can flexibly configure the rules according to the routing sequence diagram and according to the different Hook points.

5.iptables writing rules

 Command format:

 Example:

iptables -I INPUT -s 0/0 -d 192.168.42.153 -p tcp -m multiport --dports 22,80,3306 -j ACCEPT
iptables -t filter -I INPUT -d 192.168.42.153 -p tcp --dport 80 -j ACCEPT 

5.1 table + command

[-t 表名]: Which table is operated by the rule, you can use filter, nat, etc., if not specified, the default is filter

    • -A: Add a new rule to the last line of the rule chain list
    • -I: Insert a rule, the original rule at this position will move backward sequentially, if no number is specified, it will be 1
    • -D: Delete a rule from the rule chain, either enter the complete rule, or specify the rule number to delete
    • -R: Replace a certain rule, rule replacement will not change the order, and the number must be specified.
    • -P: Set the default action of a rule chain
    • -nL: -L, -nto view the list of currently running firewall rules

5.2 chain + parameter

chain名: Specifies which chain of the rule table, such as INPUT, OUPUT, FORWARD, PREROUTING, etc.

    • [规则编号]: Used when inserting, deleting, and replacing rules, --line-numbersdisplaying the number
    • [-i|o 网卡名称]: i specifies which network card the data packet enters from, and o specifies which network card the data packet outputs from
    • [-p 协议类型]: You can specify the protocol that the rule applies to, including tcp, udp, and icmp, etc.
    • [-s 源IP地址]: IP address or subnet address of the source host
    • [--sport 源端口号]: The source port number of the IP of the packet
    • [-d目标IP地址]: IP address or subnet address of the target host
    • [--dport目标端口号]: The destination port number of the IP of the packet

5.2.1 -m

-m: extend matches, this option is used to provide more matching parameters, such as:

    • -m state --state ESTABLISHED,RELATED
    • -m tcp --dport 22
    • -m multiport --dports 80,8080
    • -m icmp --icmp-type 8

5.3 target

<-j 动作>: Actions to process data packets, including ACCEPT, DROP, REJECT, etc.

    • ACCEPT: Allow packets to pass through
    • DROP: directly discard the data packet without giving any response information
    • REJECT: Reject the data packet, if necessary, it will send a response message to the data sender.

    • SNAT: Source address translation. After entering the route at the routing level and before exiting the local network stack, the source address is rewritten, the destination address remains unchanged, and a NAT entry is established on the local machine. When the data returns, the destination address data is rewritten as data according to the NAT table and sent out When the source address, and sent to the host. Solve the problem that intranet users use the same public address to access the Internet.
      MASQUERADE, is a special form of SNAT, suitable for temporary changing ip like adsl

    • DNAT: Destination address translation. Contrary to SNAT, before the IP packet passes through the route, the destination address is re-modified, the source address remains unchanged, and a NAT entry is established on the local machine. When the data is returned, the source address is modified to the destination address when the data is sent according to the NAT table, and concurrently to the remote host. The real address of the backend server can be hidden. (Thanks to the netizen for suggesting that this place and SNAT were reversed)
      REDIRECT: It is a special form of DNAT, which forwards network packets to the local host (regardless of the target address specified in the IP header), which is convenient for port forwarding on the local machine .

    • LOG: Record the log information in the /var/log/messages file, and then pass the packet to the next rule

        Excluding the last one LOG, after the first 3 rules match the data packet, the data packet will not continue to match, so the order of the rules written is extremely critical.

5.3.1 SNAT and DNAT

        Linux firewalls are often responsible for connecting the internal and external networks of the enterprise. In addition to providing packet filtering functions, sometimes they also need to provide some basic gateway applications. Before configuring SNAT and DNAT, you need to enable the address forwarding function in the Linux system, otherwise the data cannot be forwarded through the firewall.

修改/etc/sysctl.conf配置文件件,将ip_forward的值设置为1即可。

[root@localhost /]#vim /etc/sysctl.conf
......//省略部分内容
net.ipv4.ip_forwaed=1 //将此行中的0改为1

[root@localhost /]#sysctl -p //重新读取修改后的配置

也可以开启临时的路由转发,可以执行以下操作。
[root@localhost /]#echo 1> /proc/sys/net/ipv4/ip_forward
或者
[root@localhost /]#sysctl -w net.ipv4.ip_forward=1

5.3.1.1 SNAT strategy and application

SNAT: Source Address Translation is an address translation operation of the Linux firewall and a packet control type in the iptables command. Its function is to modify the source IP address of the packet according to the specified conditions.
The SNAT strategy can only be used in the POSTROUTING chain of the nat table. When using the iptables command to write the SNAT strategy, you need to combine the "--to-source IP address" option to specify the modified source IP address.

Scenario example: The Linux gateway server is connected to the Internet and the LAN through eth0 and eth1 respectively, where the IP address of eth0 is 218.29.30.31, and the IP address of eth1 is 192.168.1.1. Now it is required to configure rules on the Linux gateway server, so that all users in the LAN can access the Internet through sharing. You can do the following:

1) Turn on routing and forwarding, see the previous section.
2) Write SNAT rules in POSTROUTING of iptables.

[root@localhost /]#iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 218.29.30.31


3) In some cases, the external network IP address of the gateway may not be fixed. For example, when ADSL broadband access is used, iptables provides a data packet control type called MASQUERASE (masquerading), MASQUERADE is equivalent to a special case of SNAT. It also modifies the source IP address of the data packet, but it can automatically obtain the IP address of the external network interface.
Referring to the previous SNAT case, if you want to use the MASQUERADE masquerading strategy, you only need to remove the "--to-source IP address" in the SNAT strategy. Instead, "-j MASQUERADE" specifies the control type of the packet. For ADSL broadband connections, the connection names are usually ppp0, ppp1, etc. The operation is as follows

[root@localhost /]#iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ppp0 -j MASQUERADE


4) Test the result of SNAT shared access
Same as the above configuration, now the IP address used by the internal LAN to access the Internet is the external network interface address of the gateway server. We can execute "tcpdump -i eth0" on the external client to monitor and access the local data stream, then ping the external network client on the internal network, and then check the monitoring status of the external network client. We will find that the access to the external network client The IP address is the external network interface address of the gateway server, not the internal LAN address.

5.3.1.2 DNAT strategy and application

DNAT: Destination address translation is another address translation operation of the Linux firewall. It is also a packet control type in the iptables command. Its function is to modify the destination IP address and destination port of the data packet according to the specified conditions.

The DNAT strategy is very similar to the SNAT strategy, but the application direction is reversed.

SNAT is used to modify the source address IP, while DNAT is used to modify the target IP address and target port;

SNAT can only be used in the POSTROUTING chain of the nat table, and DNAT can only be used in the PREROUTING chain and OUTPUT chain of the nat table.

Example 1: With the help of the above network environment, a web server is set up in the company's internal LAN with an IP address of 192.168.1.7. Now it needs to be published on the Internet, hoping to access the web server through the Internet. Then we can do the following

[root@localhost /]#iptables -t nat -A PREROUTING -i eth0 -d 218.29.30.31 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.7:80

Example 2: The company's web server 192.168.1.7 needs to be managed remotely through the Internet. Due to security concerns, the administrator does not want to use the default port for access. At this time, we can use DNAT to modify the default port of the service. The operation is as follows

[root@localhost /]#iptables -t nat -A PREROUTING -i eth0 -d 218.29.30.31 -p tcp --dport 2346 -j DNAT --to-destination 192.168.1.7:22

After doing this, access the external network interface of the gateway server in the browser of the external network client, and you can find that the web page accessed is actually the web server of the internal network 192.168.1.7. When using sshd to connect to port 2346, it is possible to remotely connect to the 192.168.1.7 server.

6. Examples

6.1 Configuration method of a requirement

need:

1. The network port at0 (10.0.0.1) is a fake AP network port. After the target client connects to the fake AP network port at0, it will
   initiate on at0 will respond
   and assign 10.0 to the client. .0.100 IP address, and set the default gateway of the client to 10.0.0.1 (that is, the IP address of at0), and the
   default DNS server to 10.0.0.1 (that is,
the IP address of at0). The ingress traffic is drawn to the network card interface
   eth0 (192.168.159.254) that is actually connected to the external network , and a NAT service
is performed. 3. The DHCP traffic (broadcast data packets with destination port 67) of the network port at0 (10.0.0.1) is released,
   Because we need to assume a DHCP server on the server where the fake AP is located
4. Let the DNS traffic (destination port 53) of the network port at0 (10.0.0.1) be released,
   because we need to assume a DNS server on the server where the fake AP is located

Configuration idea:

Turn on the Linux routing and forwarding switch, because the machine forwards the data packets

echo "1" > /proc/sys/net/ipv4/ip_forward

NAT the client's HTTP traffic and change the SrcIP of the data packet

Note that it is POSTROUTING (modification before the data packet is about to be sent out)

iptables -t nat -A POSTROUTING -p tcp -s 10.0.0.0/24 --dport 80 -j SNAT --to-source 192.168.159.254

Perform NAT on the HTTP traffic returned by the remote WEB server, and redirect it back to the client. Note that it is in PREROUTING (the data packet is modified immediately after entering the protocol stack)

iptables -t nat -A PREROUTING -p tcp -d 192.168.159.254 -j DNAT --to 10.0.0.100

We specify in the DHCP server that the client's default DNS server is 10.0.0.1 (this machine), which is a pseudo-DNS, but I haven't set up DNS on this machine yet, so I still need to NAT the DNS data packets on port 53. Traction to Google's DNS: 8.8.8.8

iptables -t nat -A PREROUTING -p udp -s 10.0.0.0/24 --dport 53 -j DNAT --to 8.8.8.8
iptables -t nat -A POSTROUTING -p udp -s 10.0.0.0/24 --dport 53 -j SNAT --to-source 192.168.159.254
iptables -t nat -A PREROUTING -p udp -d 192.168.159.254 --sport 53 -j DNAT --to 10.0.0.100
iptables -t nat -A POSTROUTING -p udp -s 8.8.8.8 --sport 53 -j SNAT --to-source 10.0.0.1

6.2 Write iptables to reject packets passing icmp (protocol matching)

iptables -A INPUT -p icmp -j DROP

6.3 Write iptables to refuse to forward packets from 192.168.1.0/24 to 202.106.123.0/24 (address match)

When writing iptables rules, specify in the form of "-s source address" or "-d destination address", which is used to check the source address or destination address of the data packet.

iptables -A FORWARD -s 192.168.1.0/24 -d 202.106.123.0/24 -j DROP

6.4 Refuse to ping the firewall host from the eth1 NIC interface of the firewall (the network interface matches)

When writing iptables rules, use the forms of "-i interface name" and "-o interface name", which are used to check which interface the data packet enters or sends out from the firewall, corresponding to the inbound network card (--in-interface), and the outbound network card (--in-interface) respectively. Station NIC (--out-interface).

iptables -A INPUT -i eth1 -p icmp -j DROP

6.5 Write iptables rules to allow FTP packets to pass (port matching)

When writing iptable rules, use the form of "--sport source port" or "--dport". The target protocol is TCP or UDP, which is used to check the source port or destination port of the data packet. A single port or a range of ports separated by ":" are acceptable, but multiple discontinuous port numbers are not supported.

[root@localhost /]#iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT
[root@localhost /]#iptables -A INPUT -p tcp --dport 24500:24600 -j ACCEPT

6.6 Deny the TCP request of the external network card interface (eth1) to directly access the firewall itself, but the TCP response data packets sent by other hosts to the firewall should be allowed (TCP flag matching)

When writing iptables rules, use the form of "--tcp-flags check range is set flag", the protocol for TCP is used to check the flag bit of the data packet. Among them, the "inspection range" indicates the flag bits that need to be inspected in the data packet, and the "set flag" clearly matches the flag with a corresponding value of 1, and multiple flags are separated by commas.

[root@localhost /]#iptables -A INPUT -i eth1 -p tcp --tcp-flags SYN,RST,ACK SYN -j DROP

6.7 It is forbidden to ping the firewall from other hosts, but allow the firewall to ping other hosts (ICMP type matches)

When writing iptables rules, use the form of "--icmp-type ICMP type", and the target protocol is ICMP, which is used to check the type of ICMP data packets. The ICMP type is represented by a string or a numeric code, such as "Echo-quest" (code 8), "Echo-Reply" (code 0), and "Destination-Unreachable" (code 3), corresponding to ICMP protocol requests , it is displayed that the target is unreachable.

[root@localhost /]#iptables -A INPUT -p icmp --icmp-type 8 -j DROP
[root@localhost /]#iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT
[root@localhost /]#iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT

6.8 Allow the machine to open ports such as 25, 80, 110, 143, etc., in order to provide email services (multi-port matching)

When writing iptables rules, use the form of "-m multiport --dport port list" or "-m multiport --sport port list" to check the source port and destination port of the data packet, and multiple ports are separated by commas.

[root@localhost /]#iptables -A INPUT -p tcp -m multiport --dport 25,80,110,143 -j ACCEPT

6.9 Allow forwarding of TCP packets whose source IP is between 192.168.4.21 and 192.168.4.28 (IP address range matching)

When writing iptables rules, use the form of "-m iprange --src-range IP range" and "-m -iprange --dst-range IP address range" to check the source address, destination address, and IP range of the data packet It is expressed in the form of "start address-end address".

[root@localhost /]#iptables -A FORWARD -p tcp -m iprange --src-range 192.168.4.21-192.168.4.28 -j ACCEPT

6.10 Block the host according to the MAC address, prohibiting it from accessing any application on the machine (MAC address matching)

When writing iptables rules, use the form of "-m mac --mac-source MAC address" to check the source MAC address of the data packet. Due to the limitations of the MAC address itself, such matching conditions are generally only applicable to internal networks.

[root@localhost /]#iptables -A INPUT -m mac --mac-source 00:0c:29:c0:55:3f -j DROP

6.11 Only port 80 of the local machine is opened, and the TCP response data packets sent to the local machine are allowed, and other inbound data packets are rejected (status matching)

When writing iptables rules, use the form of "-m state --state connection state", and the state tracking mechanism based on iptables is used to check the connection state of data packets. Common connection states include NEW (as irrelevant to any connection), ESTABLISHED (corresponding to a request or a connection is established), RELATED (related to an existing connection, such as an FTP data connection).

[root@localhost /]#iptables -A INPUT -p tcp -m multiport --dport 80 -j ACCEPT
[root@localhost /]#iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT

6.12 A Complete Example

We assume that interface ppp0 leads to the Internet and interface eth0 leads to the internal network.
The IP address of ppp0 is 128.138.101.4, the IP address of eth0 is 10.1.1.1, and the subnet mask of both interfaces is 255.255.255.0.
This example uses stateless packet filtering to protect a web server with IP address 10.1.1.2, which is the standard way to protect Internet servers.
Later in this example, we will show how to use stateful filtering mechanisms to protect desktop users.
Before you use iptables, you must enable IP forwarding (IP forwarding) function, and ensure that each iptables module has been loaded in the kernel. See section 5.3.1 of this article for configuration.
All distributions with iptables also have a startup script that does the enabling and loading.

1. The first set of rules is to initialize the filter table.
First, flush all chains from the table,
then set the default target of the INPUT and FORWARD chains to DROP.
As with any other network firewall, the safest policy is to drop any packets that you do not explicitly allow.

# iptables -F
# iptables -P INPUT DROP       // 如果是用SSH连接进行设置,不要用这条命令,会导致SSH断开;
# iptables -P FORWARD DROP

2. Rules are matched in the order they appear in the chain, so we put the most used rules first.
The first three rules in the FORWARD chain allow connections to the web service on 10.1.1.2 to pass through the firewall.
Specifically, we allow SSH (port 22), HTTP (port 80), and HTTPS (port 443) to our web server.
The first rule allows all connections from trusted networks through the firewall.

# iptables -A FORWARD -i eth0 -p ANY -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p tcp --dport 22  -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p tcp --dport 80  -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p tcp --dport 443 -j ACCEPT

3. The only TCP traffic we allow to the firewall host (10.1.1.1) is SSH, which is used to manage the firewall.
The second rule listed below allows loopback traffic, which remains local to the firewall host.
Our sysadmins get nervous when they can't ping the default route,
so the third rule here allows ICMP ECHO_REQUEST packets from internal IP addresses.

# iptables -A INPUT -i eth0 -d 10.1.1.1  -p tcp --dport 22     -j ACCEPT
# iptables -A INPUT -i lo   -d 127.0.0.1 -p ANY                -j ACCEPT
# iptables -A INPUT -i eth0 -d 10.1.1.1  -p icmp --icmp-type 8 -j ACCEPT 

4. In order for any TCP/IP host to work properly on the Internet, certain types of ICMP packets must be allowed to pass through the firewall.
The following 8 rules are the minimum set that allows ICMP packets to be sent to both the firewall host and the network behind it.

# iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT
# iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT
# iptables -A INPUT -p icmp --icmp-type 5 -j ACCEPT
# iptables -A INPUT -p icmp --icmp-type 11 -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p icmp --icmp-type 0 -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p icmp --icmp-type 3 -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p icmp --icmp-type 5 -j ACCEPT
# iptables -A FORWARD -d 10.1.1.2 -p icmp --icmp-type 11 -j ACCEPT

5. Next, add rules to the PREROUTING chain of the NAT table. Although the purpose of the NAT table is not for packet filtering,
its PREROUTING chain is especially useful for anti-IP spoofing filtering.
If we add DROP items in the PREROUTING chain, they don't need to appear in the INPUT and FORWARD chains,
because the PREROUTING chain will be applied to all packets entering the firewall host.
Putting controls in one place is much more organized than duplicating them.

# iptables -t nat -A PREROUTING -i ppp0 -s 10.0.0.0/8 -j DROP
# iptables -t nat -A PREROUTING -i ppp0 -s 172.16.0.0/12 -j DROP
# iptables -t nat -A PREROUTING -i ppp0 -s 192.168.0.0/16 -j DROP
# iptables -t nat -A PREROUTING -i ppp0 -s 127.0.0.0/8 -j DROP
# iptables -t nat -A PREROUTING -i ppp0 -s 224.0.0.0/8 -j DROP

6. Finally, we end the INPUT and FORWARD chains with a rule that disallows all packages that are not explicitly permitted.
While we've done this before with the iptables -P command, the LOG target lets us see who's knocking on our door from the Internet.

# iptables -A INPUT -i ppp0 -j LOG
# iptables -A FORWARD -i ppp0 -j LOG

7. We can also set up IP NAT to disguise the private address space used in the internal network.

8. One of the most powerful functions that Netfilter brings to the Linux firewall is the stateful packet filtering mechanism.
Instead of allowing specific incoming services, a firewall for a client computer connected to the Internet allows incoming responses based on the client's request.
The simple stateful FORWARD chain below allows all traffic leaving our network, but only incoming traffic related to connections initiated by our host.

# iptables -A FORWARD -i eth0 -p ANY -j ACCEPT
# iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

To track complex network sessions, such as FTP and IRC, certain kernel modules must be loaded to enable iptables.
If these modules are not loaded, iptables will simply disallow those connections. Although stateful packet filters can improve the security of a site,
they also increase the complexity of the network. So make sure you really need stateful functionality before implementing it on your firewall.

7. Export, import and scripting of rules

These iptables rules are only temporarily effective. When the firewall is closed or the server is shut down, all the rules will be cleared after restarting. Therefore, I need to save the written iptables rules, so that after the firewall is closed or the system is restarted, the iptables rules can still be used without writing again.

Batch backup and restoration of iptables rules requires two commands iptables-save and iptables-restore, which are used to save and restore respectively.

7.1 Backup and save iptables rules

The iptables-save command is used to export iptables firewall rules in batches. When iptables-save is executed directly, all currently enabled rules will be displayed, listed in order of raw, mangle, nat, and filter tables; if you only want to display a certain table, you should add "-t table name" as a command option, and then combine redirection input ">" to redirect the output to a file.
For example: the rules for backing up all tables, the operation is as follows:

[root@localhost /]#iptables-save > /opt/iprules_all.txt

or

[root@localhost /]#service iptables save

The latter saves all rules to the "/etc/sysconfig/iptables" file by default.

7.2 Restoring iptables rules

The iptables-retore command is used to import Linux firewall rules in batches. If there is already a backup file exported using the iptable-save command, the process of restoring the rules is just a matter of moments. As opposed to the iptables-save command, the iptables-restore command should combine redirection input to specify the location of the backup file.
For example: to restore the backup rules above to iptables, the operation is as follows:

[root@localhost /]#iptables-restore < /opt/iprules_all.txt

or

[root@localhost /]#service iptables start

The latter loads the contents of the "/etc/sysconfig/iptables" file into iptables by default, that is, if the backup uses "service iptables save", then "service iptables start" should be used for recovery.

7.3 Using iptables service


To enable or disable the iptables service use the following command

[root@localhost /]#service iptables start //开启iptables服务
[root@localhost /]#service iptables stop //关闭iptables服务


The former enables the iptables service and loads the rules in "/etc/sysconfig/iptables" by default, while the latter disables the iptables service and clears all iptables rules by default.

7.4 Examples of scripting

In a production environment, I rarely write iptables rules one by one. The most common way is to write them into shell scripts for one-time processing. Common firewall scripts usually include multiple parts such as variable definition, module loading, /proc adjustment, rule setting, etc. Some simple firewall scripts may only include the rule setting part. Let's learn how to write a script through a "network-type" firewall script example.

[root@loaclhost /]#vim /opt/myipfw.sh
#!/bin/bash
# 1.定义基本变量
INET_IF="eth0" //外网接口
INET_IP="218.29.30.31" //外网接口地址
LAN_IF="eth1" //内网接口
LAN_IP="192.168.1.1" //内网接口地址
LAN_NET="192.168.1.0/24" //内网网段
LAN_WWW_IP="192.168.1.7" //网站服务器的内部地址
IPT="/sbin/iptables" //iptables命令的路径
MOD="/sbin/modprobe" //modprode命令的路径
CTL="/sbin/sysctl" //sysctl命令的路径

# 2.加载内核模块
$MOD ip_tables //iptables基本模块
$MOD ip_conntrack //连接跟踪模块
$MOD ipt_REJECT //拒绝操作模块
$MOD ipt_LOG //日志记录模块
$MOD ipt_iprange //支持IP范围匹配
$MOD xt_tcpudp //支持tcp、udp协议
$MOD xt_state //支持状态匹配
$MOD xt_multiport //支持多端口匹配
$MOD xt_mac //支持MAC地址匹配
$MOD ip_nat_ftp //支持TFP地址转换
$MOD ip_conntrack_ftp //支持TFP连接跟踪 

# 3.调整/porc参数
$CTL -w net.ipv4.ip_forward=1 //打开路由转发功能
$CTL -w net.ipv4.ip_default_ttl=128 //修改ICMP响应超时
$CTL -w net.ipv4.icmp_echo_ignore_all=1 //拒绝响应ICMP请求
$CTL -w net.ipv4.icmp_echo_ignore_broadcasts //拒绝响应ICMP广播
$CTL -w net.ipv4.tcp_syncookies=1 //启用SYN Cookie机制
$CTL -w net.ipv4.tcp_syn_retries=3 //最大SYN请求重试次数
$CTL -w net.ipv4.tcp_synack_retries=3 //最大ACK确认重试次数
$CTL -w net.ipv4.tcp_fin_timeout=60 //TCP连接等待超时
$CTL -w net.ipv4.tcp_max_syn_backlog=3200 //SYN请求的队列长度

# 4.设置具体的防火墙规则
# 4.1删除自定义链、清空已有规则
$IPT -t filter -X //清空各表中定义的链
$IPT -t nat -X
$IPT -t mangel -X
$IPT -t raw -X
$IPT -t filter -F //清空各表中已有的规则
$IPT -t nat -F
$IPT -t mangel -F
$IPT -t raw -F

# 4.2定义默认规则
$IPT -P INPUT DROP
$IPT -P FORWARD DROP
$IPT -P OUTPUT ACCETP

# 4.3设置nat表中的各种策略
$IPT -t nat -A POSTROUTING -s $LAN_NAT -o $INET_IF -j SNAT --to-source $INET_IP
$IPT -t nat -A PREROUTING -i $INET_IF -d $INET_IP -p tcp --dport 80 -j DNAT --to-destination $LAN_WWW_IP

# 4.4设置filter表中的各种规则
$IPT -A INPUT -m state ESTABLISHED,RELATED -j ACCEPT
$IPT -A FORWARD -s $LAN_NET -o $INET_IF -p udp --dport 53 -j ACCEPT
$IPT -A FORWARD -s $LAN_NET -o $INET_IF -p tcp -m multiport --dport 20,21,25,80,110,143,443 -j ACCEPT
$IPT -A FORWARD -d $LAN_NET -i $INET_IF -m state ESTABLISHED,RELATED -j ACCEPT
$IPT -A FORWARD -d $LAN_WWW_IP -p tcp --dport 80 -j ACCEPT
$IPT -A FORWARD -d $LAN_WWW_IP -p tcp --sport 80 -j ACCEPT

8. Finally

References:

https://www.cnblogs.com/zllong/p/7236881.html

Firewall_http://192.168.52.14/_Catch the Thief First Capture the King's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_33163046/article/details/131993878