Http:// OS .51cto.com/art/201108/285352.htm
This document is intended for beginners of iptables. If you have just learned the principles and basic syntax of iptables, but you still do not know how to actually use this tool in the online server environment, read this article.
Two main work modes of iptables
For iptables data packets, there are several flows:
Prerouting → forward → postrouting
Prerouting → input → local → output → postrouting
You can pay attention to the two main flows of data packets (in fact, they are also the two working modes of iptables): one is as a NAT router, and the other is as a host firewall.
For details about iptables data inflows and outflows, refer:
Figure iptables flowchart of inbound and outbound data packets
Iptables uses different rule tables based on different data packet processing functions. It includes the following three tables: filter, Nat, and mangle.
- Filter is the default table that contains the real firewall filter rules. The built-in rule chains include input, output, and forward.
- The NAT table contains the rules used for source and destination address and port conversion. The built-in rule chains include prerouting, output, and postrouting.
- The mangle table contains rules used to set special packet routing labels, which are subsequently checked by the rules in the filter table. The built-in rule chains include prerouting, input, forward, postrouting, and output.
The related rule chain functions of the table are as follows:
- Input chain: when a data packet is determined as a local Linux system by the route calculation in the kernel, it will pass the input chain check.
- Output chain: the data packet generated by the system.
- Forward chain: data packets routed through the Linux system (that is, when the iptables firewall is used to connect two networks, data packets between the two networks must flow through the firewall ).
- Prerouting chain: used to modify the destination address (DNAT ).
- Postrouting chain: used to modify the source address (SNAT ).
The detailed Syntax of iptables is as follows:
Iptables [-T table name] <-A | I | d | r> chain name [Rule number] [-I | o Nic name] [-P protocol type] [-S source IP address | source subnet] [-- Sport source port number] [-D destination IP address | destination subnet] [-- dport destination port number] <-J action>
Note: This syntax rule is detailed and logic is clear. We recommend that you use this formula to remember it. When writing iptables rules at the beginning, we should develop good habits and use formulas to standardize scripts, which will be of great help to our future work.
In this section, we compile a simple iptables syntax rule for mail host protection. The network topology is very simple. the IP address of the iptables machine is 192.168.1.101/24, and the IP address of the other machine is 192.168.1.102.
Common email host protection script
The normal mail host protection script is easy to implement. The mail host mainly opens two ports: 80 and 25, while the other ports are closed. In addition, because there is not much function involved here, the module loading is very simple, only the filter table is involved, the initialization of the script is also very simple.
We can write scripts in the order of iptables writing. The script content is as follows:
(Note: This server is placed in its own data center. Therefore, port 22 is not open. You can directly debug the server in the data center. For remote operations, open port 22 .)
#/Bin/bashiptables-fiptables-xiptables-Z modprobe cannot exceed your own iptables-P input dropiptables-P forward acceptiptables-P output accept iptables-A input-I lo-J accept iptables -A output-O lo-J accept iptables-A input-p tcp-M multiport -- dports 25, 80-J acceptiptables-A input-M state -- state related, established-J accept
Note:
You can initialize iptables in the first three items.
Modprobe is the process of manually Loading modules. Generally, if you use service iptables start to start iptables, many unnecessary modules will be loaded, so here we use manual loading. The ip_conntrack module can be enabled in the usual test and learning environment to track the flow of data packets. However, in the production environment, I do not recommend that you enable this module to increase the server load.
The two ports below the default rule are used to enable the system loop port to avoid unnecessary troubles. What are the specific troubles? You can think about it first. The answer will be provided at the end of this article.
The last one is to allow connections in the related and established statuses to pass through iptables. The reason for this setting will also be answered at the end of the article.
After the iptables script is enabled, run the following command to view the result:
Iptables-Nv-l
The command displays the following results:
Chain input (Policy drop 13539 packets, 763 K bytes) pkts bytes target prot opt in out source destination 0 0 accept all -- lo * 0.0.0.0/0 0.0.0.0/0 480 32744 accept TCP -- ** 0.0.0.0/0 0.0.0.0/0 multiport dports 25, 80 13 1411 accept all -- ** 0.0.0.0/0 0.0.0.0/0 state related, established chain forward (Policy accept 0 packets, 0 bytes) Pkts bytes target prot opt in out source destination chain output (Policy accept 472 packets, 52779 bytes) pkts bytes target prot opt in out source destination 0 0 accept all -- * lo 0.0.0.0/0 0.0.0.0/0
Port 80 and port 25 are hidden by iptables. For example, we try NMAP to scan this server on another machine:
If not, you need:
Yum install NMAPNow!
NMAP-ST 192.168.1.101
The command displays the following results:
Starting NMAP 4.11 (http://www.insecure.org/nmap/) at cstinteresting ports on 192.168.1.101: not shown: 1678 filtered portsport state service25/tcp open ssh80/tcp open httpmac address: 00: E0: 62: 12: 7b: 65 (host engineering) NMAP finished: 1 IP address (1 host up) scanned in 37.721 seconds
The result indicates that iptables takes effect.
In addition, I would like to provide a suggestion to my friends who have just learned iptables. One easy mistake to make when you start playing iptables is to lock yourself out of the server. In this case, we can compile a crontab scheduled task to close the firewall every five minutes and close the crontab task after the complete debugging:
Vim/etc/crontab */5 *****/etc/init. d/iptables stop
The above is only a preliminary protection script. As for other SYN and Ping attacks and other attacks, you can add them on the basis of this script after you are familiar with the principles.
The following are the answers to the two questions mentioned above:
I. Why do I need to enable the system loop interface?
By default, a Linux system will have a loopback network interface named Lo, and the real Nic is generally recognized by the Linux system as a network interface such as eth0 and eth1.
Generally, the IP address of the LO interface is 127.0.0.1.
When you send data packets to yourself from a Linux host, the actual data packets are sent and accepted through the Virtual lo interface, rather than through your physical Nic eth0/eth1.
If the lo interface is blocked, Ping/Telnet/ssh Local Machine (local domain name, localhost and 127.0.0.1) may fail, which may cause some trouble for debugging.
2. Why should I set related and established status detection?
Compared with pure IP address filtering, status firewalls are more intelligent and more efficient. This is suitable for FTP servers. For more information about the status mechanism of iptables, seeArticle: Http:// OS .51cto.com/art/201108/285209.htm
Http:// OS .51cto.com/art/201111/301918.htm
On our web server, the system's default policy is that input is drop, output; forward chain is accept, and drop is relatively loose, because we know that the outgoing packets are safer.
Preparations
To verify the versatility of the script, I checked the kernel and iptables version of the server:
# Uname-alinux ud50041 2.6.9-34. elsmp #1 SMP Fri Feb 24 16:54:53 est 2006 i686 i686 i386 GNU/Linux # iptables-viptables v1.2.11 # lsb_release-alsb version: core-3.0-ia32: core-3.0-noarch: graphics-3.0-ia32: graphics-3.0-noarchDistributor ID: redhatenterpriseasdescription: red Hat Enterprise Linux as Release 4 (nahant Update 3) Release: 4 codename: nahantupdate3
We can find that the system, kernel, and iptables versions of this server are relatively old. The script described in this article involves the recent security module, which requires the system kernel (the recent module is also frequently used in host protection scripts ). Therefore, if you want to use iptables as the host firewall, we recommend that you use centos 5.6 x86_64 or a more advanced version. Otherwise, the system will prompt the following error message:
Iptables: Unknown error 18446744073709551615 iptables: invalid argument
The following error message is prompted during tail-F/var/log/messages:
Ip_tables: connlimit match: Invalid size 32! = 16ip_tables: connlimit match: Invalid size 32! = 24
In addition, before debugging the iptables script in the production environment, we strongly recommend that you write a crontab task and close the iptables script every five minutes to prevent improper operations and lock your SSH client out:
*/5 * root/etc/init. d/iptables stop
These are the preparations. The following is the iptables script content.
Script content
#! /Bin/sh
#
# This script will be executed * after * all the other init scripts.
# You can put your own initialization stuff in here if you don't
# Want to do the full sys V style init stuff.
Touch/var/lock/subsys/local
# Start memcached
/Usr/local/bin/memcached-D-M 1024-u root-P 11211-C 256-P/tmp/memcached. PID
# Configuring a firewall
/Sbin/iptables-F
/Sbin/iptables-x
/Sbin/iptables-z
/Sbin/modprobe ip_tables
/Sbin/modprobe iptable_nat
/Sbin/modprobe ip_nat_ftp
#/Sbin/modprobe ip_conntrack
/Sbin/iptables-P input drop
/Sbin/iptables-P forward accept
/Sbin/iptables-P output accept
# Up to 100 new connections are allowed per second
/Sbin/iptables-A input-F-m limit -- limit 100/sec -- limit-burst 100-J accept
# Prevent Ping flood attacks. The maximum number of Ping packets per second is 10.
/Sbin/iptables-a forward-p icmp -- ICMP-type echo-request-m limit -- limit 1/s -- limit-burst 10-J accept
# Prevent various port scans and limit SYN and ack syn to no more than 200 per second, so as not to exhaust the bandwidth of the server
/Sbin/iptables-A input-p tcp-m tcp -- TCP-flags SYN, RST, Ack syn-m limit -- Limit 20/sec -- limit-burst 200-J accept
# Open Access to a specified host, such as the IP address of the host for Intrusion Detection
#/Sbin/iptables-A input-s 122.70.x.x-J accept
# Loop data must be released
/Sbin/iptables-A input-I lo-J accept
/Sbin/iptables-A output-O lo-J accept
# Self-sent users can collect
/Sbin/iptables-A input-M state -- State established, related-J accept
# Open ports 80 and 22, not explained
/Sbin/iptables-A input-p tcp-M multiport -- dport 80, 22-J accept
Save the script file and use
# Sh iptables. Sh
Run the script. After running the script, check the following:
# Iptables-Nv-l
Script description
Because the Web server is placed behind the Server Load balancer, we need to allow the data source address to pass through the Load balancer packet:
Iptables-A input-s 122.70.x.x-J accept
If monitoring systems such as Nagios are configured, add them here. If neither monitoring nor lb is done, skip this line.
In addition, this script is also deployed on many small lnmp-based websites. Because the web service and MySQL database are installed on one machine at the same time, port 3306 is not enabled.
In this script, we have configured some security measures to prevent external Ping and SYN flood attacks, and considering that the external crazy Port Scan software may affect the server's entry bandwidth, therefore, the following restrictions are also imposed:
Iptables-A input-p tcp -- syn-m limit -- limit 100/s -- limit-burst 100-J accept
The preceding command allows up to 100 new connections per second. Note that the new connection refers to the data packet whose state is new. Later, we also configure the data that is allowed to pass in the state of established and related. In addition, 100 this threshold value should be adjusted based on the actual situation of the server. If it is a server with a small number of concurrent requests, it should be adjusted to a smaller value. If it is a server with a large access volume and a large number of concurrent requests, this value needs to be increased.
Iptables-A input-p icmp -- ICMP-type echo-request-m limit -- limit 1/S-limit-burst 10-J accept
To prevent Ping flood attacks, a maximum of 10 ping packets per second are allowed.
Iptables-A input-p tcp-m tcp -- TCP-flags SYN, RST, Ack syn-m limit -- Limit 20/sec -- limit-burst 200-J accept
The above command prevents various port scans and limits SYN and ack syn to no more than 200 per second, so as not to exhaust the bandwidth of the server.
Subsequent reinforcement work
After the iptables firewall is running, run the Nmap tool for scanning:
# NMAP-P0-SS 211.143.6.xstarting NMAP 4.11 (http://www.insecure.org/nmap/) at cstinteresting ports on 211.143.6.x: not shown: 1668 closed portsport state service22/tcp open ssh25/tcp open smtp80/tcp open http110/tcp open pop3111/tcp open rpcbind143/tcp open imap443/tcp open https465/tcp open smtps587/tcp open submission993/tcp open imaps995/tcp open pop3s1014/tcp open unknown
Here, we found that a 1014 terminal was opened by a process and it was opened by rpc. statd through lsof-I: 1014. This service uses different ports every time! If rpc. statd cannot correctly process the sigpid signal, remote attackers can use this vulnerability to close the process and initiate a Denial-of-Service attack. We found that rpc. statd is enabled by the nfslock service. Further query shows that it is an optional process, which allows the NFS client to lock files on the server. This process corresponds to the nfslock service, so we disable this service:
Service nfslock stopchkconfig nfslock off
Finally, if there is no hardware firewall protection, try to deploy the iptables firewall on every machine with a public IP address!