`iptables` forms the backbone of Linux firewalls for packet filtering on Linux platforms. Like most Linux software, this packet filtering firewall is free and serves as a cost-effective alternative to expensive commercial firewall solutions. It can perform functions such as packet filtering, packet redirection, and Network Address Translation (NAT). In everyday Linux operations and maintenance, `iptables` firewall rules are often configured to improve service security. Below is a comprehensive summary of how to use `iptables` rules:
Understanding iptables:
1) Concept of Rules:
Rules are predefined conditions set by network administrators. Generally, a rule is defined as “if the packet header meets specific conditions, then handle this packet in a specified manner.” These rules are stored in the kernel space’s packet filtering table, specifying criteria such as source address, destination address, transmission protocol (like TCP, UDP, ICMP), and service types (such as HTTP, FTP, and SMTP).
When a data packet matches a rule, iptables processes the packet according to the method defined by the rule, such as accept, reject, or drop. The main tasks in configuring a firewall are adding, modifying, and deleting rules.
Definitions:
– Match: Criteria that needs to be met, such as specified IP addresses and ports.
– Drop: When a packet arrives, it is simply discarded without any further processing.
– Accept: Opposite of drop; the packet is allowed to pass through.
– Reject: Similar to drop, but it sends an error message back to the source host of the packet. This error message can be specified or generated automatically.
– Target: Specifies the action to take on a packet, such as drop, accept, or reject.
– Jump: Similar to target, but instead of specifying a specific action, it points to another chain, indicating a jump to that chain.
– Rule: One or more matches and their corresponding target.
2) Relationship between iptables and netfilter:
The relationship between iptables and netfilter is often a source of confusion. Many are familiar with iptables without knowing about netfilter. In fact, iptables is merely a management tool for the Linux firewall, located at /sbin/iptables. The actual implementation of firewall capabilities is through netfilter, which is an internal structure within the Linux kernel that performs packet filtering.
3) iptables Rules and Chains
Tables: These offer specific functionalities, and iptables has four built-in tables: the filter table, the nat table, the mangle table, and the raw table. These are respectively used for packet filtering, network address translation, packet alteration (modification), and data tracking.
Chains: These are the pathways for data packet traversal. Each chain essentially serves as a checklist of rules. A chain can contain one or multiple rules. When a packet arrives at a chain, iptables begins checking from the first rule to determine if the packet meets the conditions specified by the rule. If it does, the system processes the packet according to the rule’s definition. If not, iptables proceeds to check the next rule. Should the packet not match any rule within the chain, iptables will process the packet according to the chain’s predefined default policy.
Iptables employs a hierarchical structure of “tables” and “chains.” In Linux, there are currently four tables and five chains. Below, I list these four tables and five chains (make sure you clearly understand the relationship and functions of these tables and chains).
Rule Table:
1) Filter Table—Three Chains: INPUT, FORWARD, OUTPUT
Purpose: Filters packets
Kernel Module: iptables_filter.
2) NAT Table—Three Chains: PREROUTING, POSTROUTING, OUTPUT
Purpose: Network Address Translation (IP, port)
Kernel Module: iptable_nat
3) Mangle Table—Five Chains: PREROUTING, POSTROUTING, INPUT, OUTPUT, FORWARD
Purpose: Modifies service type, TTL of packets, and can be configured for route implementation of QoS
Kernel Module: iptable_mangle (Despite its complexity, we rarely use it when setting policies)
4) Raw Table—Two Chains: OUTPUT, PREROUTING
Purpose: Determines whether packets are handled by connection tracking
Kernel Module: iptable_raw
Rule Chains:
1) INPUT – The policies within this rule chain are applied to incoming packets.
2) OUTPUT – The policies within this rule chain are applied to outgoing packets.
3) FORWARD – Apply the policies within this rule chain when forwarding packets.
4) PREROUTING – Apply the rules within this chain before packet routing decisions are made.
(Remember! All incoming packets are handled by this chain first)
5) POSTROUTING – Apply the rules within this chain after packet routing decisions are made.
(All outgoing packets are processed by this chain first)
Managing and Configuring iptables Rules:
4) The process of iptables in packet transmission
1) When a packet enters the network interface card, it first reaches the PREROUTING chain. The kernel determines whether it needs to forward the packet based on its destination IP address.
2) If the packet is destined for the local machine, it will move downwards to the INPUT chain as per the diagram. Once the packet reaches the INPUT chain, any process on the machine can receive it. Programs running on the local machine can send packets, which will pass through the OUTPUT chain and then reach the POSTROUTING chain before being sent out.
3) If the packet is to be forwarded, and the kernel permits forwarding, it will move to the right as shown in the diagram, passing through the FORWARD chain, and then reaching the POSTROUTING chain before being sent out.
If you’re still unclear about the basic flow of a data packet through iptables, take a look at the more detailed flowchart below:
The handling process of iptables packet processing can be categorized into three types based on the illustration:
1) Packets Destined for the Local Machine
When packets are addressed to the local machine, they traverse iptables as follows:
1. The packet moves from the network to the network interface card (NIC).
2. After being received by the NIC, the packet enters the `PREROUTING` chain of the `raw` table. This chain processes the packet before connection tracking and allows marking a connection to bypass connection tracking. (Note: Avoid adding other rules in the `raw` table.)
3. If connection tracking is set, it processes the packet on this connection.
4. After `raw` processing, it enters the `PREROUTING` chain of the `mangle` table, primarily modifying the packet’s TOS, TTL, and applying special `MARKs`. (Note: Avoid using the `mangle` table for filtering/NAT/masquerading.)
5. The packet moves into the `PREROUTING` chain of the `nat` table, used mainly for DNAT. Avoid filtering in this chain to prevent packet drops. (Note: This is solely for source/destination address translation.)
6. The packet enters routing decisions to determine handling, like forwarding or processing locally. (Note: Here it’s assumed the packet will be handled by the local machine.)
7. The packet enters the `INPUT` chain of the `mangle` table, allowing further modifications post-routing.
8. In the `INPUT` chain of the `filter` table, all packets destined for the local machine are filtered, regardless of incoming interfaces or destinations.
9. After filtering, packets are handled by local processes or applications, like servers or client programs.
2) Packets Originating from the Local Machine
When packets originate from the local machine, they follow this sequence in iptables:
1. Local processes or applications (e.g., servers or client programs) issue packets.
2. Routing decisions determine the source address and the interface, alongside other vital details.
3. The packet enters the `OUTPUT` chain of the `raw` table for processing before connection tracking takes effect, allowing connections to be marked to bypass connection tracking.
4. Connection tracking processes the local packet.
5. It enters the `OUTPUT` chain of the `mangle` table, enabling modifications without filtering to avoid side effects.
6. The packet enters the `OUTPUT` chain of the `nat` table to allow DNAT on firewall-originated packets.
7. In the `OUTPUT` chain of the `filter` table, outgoing local packets can be filtered.
8. Re-routing decisions are made, considering potential modifications from previous `mangle` and `nat` table processing.
9. Enter the `POSTROUTING` chain of the `mangle` table, passed through by forwarded and local packets.
10. The packet progresses to the `POSTROUTING` chain of the `nat` table for SNAT. Avoid filtering here due to side effects, even with default policies, as some packets might slip through.
11. Finally, the packet exits through the network interface.
3) Forwarded Packets
When packets enter iptables for forwarding, they go through:
1. The packet moves from the network to the NIC.
2. After NIC receipt, the packet enters the `PREROUTING` chain of the `raw` table, processing before connection tracking to mark and bypass connections as needed. (Note: Avoid additional rules in the `raw` table.)
3. Connection tracking is applied if set.
4. Post `raw` processing, the packet enters the `PREROUTING` chain of the `mangle` table for modifying TOS, TTL, and applying `MARKs`. (Note: Avoid filtering/NAT/masquerading here.)
5. It enters the `PREROUTING` chain of the `nat` table for DNAT. Avoid filtering to prevent packet drops. (Note: Used exclusively for address translation.)
6. Routing decisions determine the packet’s next step, such as forwarding. (Note: Here, it’s assumed the packet will be forwarded.)
7. The packet enters the `FORWARD` chain of the `mangle` table for potential modifications between routing decisions.
8. In the `FORWARD` chain of the `filter` table, forwarding packets are filtered. Note these packets move in both directions.
9. Enter the `POSTROUTING` chain of the `mangle` table for final local host modifications post-routing decisions.
10. Progress to the `POSTROUTING` chain of the `nat` table mostly for SNAT, avoiding filtering.
11. Finally, the packet exits through the network interface.
Let’s talk about the usage of setting iptables rules.
1) Basic Syntax Format of iptables
iptables [-t table_name] command_options [chain_name] [condition_match] [-j target_action_or_jump]
Explanation:
– Table Name, Chain Name: Used to specify the table and chain that the iptables command operates on.
– Command Options: Used to specify the method of managing iptables rules (e.g., insert, append, delete, view).
– Condition Match: Specifies the conditions under which packets are processed.
– Target Action or Jump: Used to specify how the packet should be handled (e.g., allow, reject, drop, jump to another chain for processing).
2) Management and Control Options for the iptables Command
-A Append a new rule at the end of the specified chain
-D Delete a specific rule in the chain; can be deleted by rule number or content
-I Insert a new rule in the specified chain, by default added at the first line
-R Modify or replace a specific rule in the chain; can be replaced by rule number or content
-L List all rules in the specified chain for viewing (default is the filter table; to list rules in the nat table, add -t, i.e., `iptables -t nat -L`)
-E Rename user-defined chains without altering the chain itself
-F Flush all rules
-N Create a new user-defined rule chain
-X Delete a user-defined rule chain in the specified table
-P Set the default policy for a specified chain
-Z Zero all byte and packet counters for all chains in all tables
-n Display numeric output results
-v View detailed information of the rules table (verbose information)
-V View version information
-h Get help information
3) Four Methods of Packet Handling by Firewalls
ACCEPT: Allows packets to pass through.
DROP: Discards packets directly without providing any response information.
REJECT: Denies packet passage, and when necessary, sends a response back to the sender.
LOG: Records log information in the /var/log/messages file and then passes the packet to the next rule.
4) Saving and Restoring iptables Firewall Rules
To preserve the iptables rules, use `iptables-save` to store them in a file. The script located under the rc.d directory (`/etc/rc.d/init.d/iptables`) automatically loads these rules.
Use the command `iptables-save` to save the rules:
Typically, you would execute:
iptables-save > /etc/sysconfig/iptables
This generates a file `/etc/sysconfig/iptables` containing the saved rules. Alternatively, you can use:
service iptables save
This command automatically saves the rules to `/etc/sysconfig/iptables`.
Upon system startup, the script in the rc.d directory will invoke this file using the `iptables-restore` command, thereby automatically restoring the rules.
5) Common Strategies for iptables Firewall Configuration
Setting Default Chain Policies
The filter table in iptables contains three chains: INPUT, FORWARD, and OUTPUT.
The default chain policy is ACCEPT, but you can configure them to DROP as shown in the following commands, which will reject all packets:
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
—————————————————————————————————————————
In fact, the two most commonly used rules in operations and maintenance work are the whitelist rule and NAT forwarding rule:
1) Whitelist rule
When operating in the Linux terminal command line, if it is not the default filter table, you need to specify the table;
If setting in the /etc/sysconfig/iptables file, configure it within the corresponding table’s configuration area;
The outcome is the same with both methods of setting!
For example, to open the local machine’s port 22 and allow access from servers in the 192.168.1.0 network segment (the `-t filter` table configuration can be omitted as it’s the default table configuration):
[root@linux-node1 ~]# iptables -A INPUT -s 192.168.1.0/24 -p tcp -m state –state NEW -m tcp –dport 22 -j ACCEPT
or
[root@linux-node1 ~]# iptables -t filter -A INPUT -s 192.168.1.0/24 -p tcp -m state –state NEW -m tcp –dport 22 -j ACCEPT
To open port 80 on this machine and only allow access from machine 192.168.1.150 (a 32-bit mask indicates a single machine, and a mask can be omitted when specifying a single machine), execute the following command:
[root@linux-node1 ~]# iptables -t filter -A INPUT -s 192.168.1.150/32 -p tcp -m state –state NEW -m tcp –dport 80 -j ACCEPT
Make sure to execute this with administrative privileges. This command modifies the firewall rules to permit incoming TCP traffic specifically from the IP address 192.168.1.150 on port 80.
Then save the rules and restart iptables.
[root@linux-node1 ~]# service iptables save
[root@linux-node1 ~]# service iptables restart
Or configure the `/etc/sysconfig/iptables` file as follows (in fact, after setting, saving, and restarting the firewall in the terminal command line, the rules will automatically be saved to the `/etc/sysconfig/iptables` file):
plaintext
[root@bastion-IDC ~]# cat /etc/sysconfig/iptables
……
*filter
:INPUT ACCEPT [442620:173026884]
:FORWARD ACCEPT [118911:23993940]
:OUTPUT ACCEPT [8215384:539509656]
-A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -s 192.168.1.0/24 -p tcp -m state –state NEW -m tcp –dport 22 -j ACCEPT
-A INPUT -s 192.168.1.150/32 -p tcp -m state –state NEW -m tcp –dport 80 -j ACCEPT
This configuration allows incoming SSH connections from the `192.168.1.0/24` network, and incoming HTTP connections from `192.168.1.150`.
[root@bastion-IDC ~]# service iptables restart
2) NAT Forwarding Configuration For example, forward access requests from port 8088 on the local machine (192.168.1.7) to port 80 on 192.168.1.160; forward access requests from port 33066 on the local machine to port 3306 on 192.168.1.161. Preparatory Steps: Enable the IP forwarding route function on the local machine; ensure that the internal network gateways for 192.168.1.160/161 match the local machine’s gateway! If there’s no internal network gateway, set the gateway to the local machine’s internal IP, and disable the firewall (if the firewall is active, configure it to allow the local machine to access the relevant ports). [root@kvm-server conf]# iptables -t nat -A PREROUTING -p tcp -m tcp –dport 8088 -j DNAT –to-destination 192.168.1.160:80 [root@kvm-server conf]# iptables -t nat -A POSTROUTING -d 192.168.1.160/32 -p tcp -m tcp –sport 80 -j SNAT –to-source 192.168.1.7 [root@kvm-server conf]# iptables -t filter -A INPUT -p tcp -m state –state NEW -m tcp –dport 8088 -j ACCEPT
[root@kvm-server conf]# iptables -t nat -A PREROUTING -p tcp -m tcp –dport 33066 -j DNAT –to-destination 192.168.1.161:3306
[root@kvm-server conf]# iptables -t nat -A POSTROUTING -d 192.168.1.161/32 -p tcp -m tcp –sport 3306 -j SNAT –to-source 192.168.1.7
[root@kvm-server conf]# iptables -t filter -A INPUT -p tcp -m state –state NEW -m tcp –dport 33066 -j ACCEPT
[root@kvm-server conf]# service iptables save
[root@kvm-server conf]# service iptables restart
Or set the following in the /etc/sysconfig/iptables file:
[root@bastion-IDC ~]# cat /etc/sysconfig/iptables
……
*nat
:PREROUTING ACCEPT [60:4250]
:INPUT ACCEPT [31:1973]
:OUTPUT ACCEPT [3:220]
:POSTROUTING ACCEPT [3:220]
-A PREROUTING -p tcp -m tcp –dport 8088 -j DNAT –to-destination 192.168.1.160:80 // Place PREROUTING rules above
-A PREROUTING -p tcp -m tcp –dport 33066 -j DNAT –to-destination 192.168.1.161:3306
-A POSTROUTING -d 192.168.1.160/32 -p tcp -m tcp –sport 80 -j SNAT –to-source 192.168.1.7 // Place POSTROUTING rules below
-A POSTROUTING -d 192.168.1.161/32 -p tcp -m tcp –sport 3306 -j SNAT –to-source 192.168.1.7
…..
*filter
:INPUT ACCEPT [16:7159]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [715:147195]
-A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state –state NEW -m tcp –dport 8088 -j ACCEPT
-A INPUT -p tcp -m state –state NEW -m tcp –dport 33066 -j ACCEPT
…..
[root@bastion-IDC ~]# service iptables restart
[root@bastion-IDC ~]# iptables -L // Lists the set rules; by default, it displays the rules under the filter table
[root@bastion-IDC ~]# iptables -L -t nat // If you want to list the rules under the nat table, add the -t parameter
————————————————————————————————————————–
Delete the first rule in the INPUT chain
iptables -D INPUT 1
Reject all ICMP packets at the firewall.
shell
iptables -I INPUT -p icmp -j REJECT
Allow the firewall to forward all packets except ICMP.
shell
iptables -A FORWARD -p ! icmp -j ACCEPT
Explanation: Using “!” can negate the condition.
Reject forwarding packets from host 192.168.1.11, allow forwarding from the 192.168.0.0/24 subnet.
shell
iptables -A FORWARD -s 192.168.1.11 -j REJECT
iptables -A FORWARD -s 192.168.0.0/24 -j ACCEPT
Instructions: Make sure to place the denial part first; otherwise, it won’t be effective!Discard packets with a source address in a private network entering the firewall through the external network interface (eth1):
iptables -A INPUT -i eth1 -s 192.168.0.0/16 -j DROP
iptables -A INPUT -i eth1 -s 172.16.0.0/12 -j DROP
iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP
Block the network segment (192.168.1.0/24), and lift the blockage after two hours:
# iptables -I INPUT -s 10.20.30.0/24 -j DROP
# iptables -I FORWARD -s 10.20.30.0/24 -j DROP
# at now + 2 hours
at> iptables -D INPUT 1
at> iptables -D FORWARD 1
Note: This strategy can be excellently achieved using cron scheduled tasks.
Only allow administrators to use SSH remote login to the firewall host from the 202.13.0.0/16 subnet
`iptables -A INPUT -s 202.13.0.0/16 -p tcp -m tcp -m state –state NEW –dport 22 -j ACCEPT`
Explanation: This method is more suitable for remote management of devices, such as when an SQL server located in a branch office needs to be managed by administrators from the headquarters.
Typically, server access to certain service ports is restricted by a whitelist, for instance (configuration for other ports is similar to the following):
Allow access to the local machine’s 3306 port (MySQL service):
shell
iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 3306 -j ACCEPT
Or allow only devices from the 192.168.1.0/24 subnet to access the local machine’s 3306 port:
shell
iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp -m state –state NEW –dport 3306 -j ACCEPT
Allow the local machine to provide application services from TCP ports 20-1024
`iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 20:1024 -j ACCEPT`
Allow forwarding of DNS query packets from the 192.168.0.0/24 local network segment
iptables -A FORWARD -s 192.168.0.0/24 -p udp –dport 53 -j ACCEPT
iptables -A FORWARD -d 192.168.0.0/24 -p udp –sport 53 -j ACCEPT
Blocking a Specified IP Address
The following rule will block access to the localhost from the IP address specified by BLOCK_THIS_IP:
BLOCK_THIS_IP=”x.x.x.x”
`iptables -A INPUT -i eth0 -s “$BLOCK_THIS_IP” -j DROP`
(Alternatively, to block only TCP packets from this IP)
`iptables -A INPUT -i eth0 -p tcp -s “$BLOCK_THIS_IP” -j DROP`
Block Loopback Access
iptables -A INPUT -i lo -j DROP
iptables -A OUTPUT -o lo -j DROP
Block incoming pings from external sources, i.e., prevent external machines from pinging the local machine
`iptables -A INPUT -p icmp –icmp-type echo-request -j DROP`
`iptables -A OUTPUT -p icmp –icmp-type echo-reply -j DROP`
Block the Local Machine from Pinging External Hosts, Prohibit the Local Machine from Pinging External Machines
iptables -A OUTPUT -p icmp –icmp-type echo-request -j DROP
iptables -A INPUT -p icmp –icmp-type echo-reply -j DROP
Block other hosts from pinging this machine while allowing this machine to ping others (You can also use `echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all` to forbid ping):
`iptables -I INPUT -p icmp –icmp-type echo-request -j DROP`
`iptables -I INPUT -p icmp –icmp-type echo-reply -j ACCEPT`
`iptables -I INPUT -p icmp –icmp-type destination-Unreachable -j ACCEPT`
Prohibit forwarding packets coming from the host with MAC address 00:0C:29:27:55:3F
iptables -A FORWARD -m mac –mac-source 00:0c:29:27:55:3F -j DROP
Explanation: In iptables, the form “-m module keyword” is used to invoke explicit matching. Here, we use “-m mac –mac-source” to specify the source MAC address of the packet.
Allow the firewall to open TCP ports 20, 21, 25, 110, and passive mode FTP ports 1250-1280 to the external network.
plaintext
iptables -A INPUT -p tcp -m multiport –dport 20,21,25,110,1250:1280 -j ACCEPT
Note: Use `“-m multiport –dport”` here to specify multiple destination ports.
plaintext
iptables -A INPUT -p tcp -m tcp -m multiport –dports 22,80,443,1250-1280 -m state –state NEW -j ACCEPT
You can also set these ports individually on separate lines:
plaintext
iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 22 -j ACCEPT
iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 443 -j ACCEPT
iptables -A INPUT -p tcp -m tcp -m state –state NEW –dport 1250:1280 -j ACCEPT
Prohibit forwarding of TCP packets originating from IP addresses ranging from 192.168.1.20 to 192.168.1.99.
iptables -A FORWARD -p tcp -m iprange –src-range 192.168.1.20-192.168.1.99 -j DROP
Explanation:
Here, `”-m iprange –src-range”` specifies the IP address range.
1) To filter a range of source addresses:
iptables -A INPUT -m iprange –src-range 192.168.1.2-192.168.1.7 -j DROP
2) To filter a range of destination addresses:
iptables -A INPUT -m iprange –dst-range 192.168.1.2-192.168.1.7 -j DROP
3) Filtering based on port access. The following rule means that only IPs in the range of 192.168.1.5 to 192.168.1.10 are allowed to access port 80 on the machine at 192.168.1.67, while all other IPs are denied access.
iptables -A INPUT -d 192.168.1.67 -p tcp –dport 80 -m iprange –src-range 192.168.1.5-192.168.1.10 -j ACCEPT
Prohibit forwarding non–syn request packets unrelated to normal TCP connections
`iptables -A FORWARD -m state –state NEW -p tcp ! –syn -j DROP`
Explanation: “`-m state`” indicates the connection state of the packet, and “`NEW`” signifies that it is unrelated to any existing connection.
Deny new packets accessed by the firewall, but allow packets that are response connections or related to existing connections.
iptables -A INPUT -p tcp -m state –state NEW -j DROP
iptables -A INPUT -p tcp -m state –state ESTABLISHED,RELATED -j ACCEPT
Explanation: “ESTABLISHED” refers to packets that have been acknowledged or have an established connection, while “RELATED” refers to packets related to an established connection, like FTP data connections, etc.
防止DoS攻击
`iptables -A INPUT -p tcp –dport 80 -m limit –limit 25/minute –limit-burst 100 -j ACCEPT`
`-m limit`: Enable the limit extension to control the rate.
`–limit 25/minute`: Allow up to a maximum of 25 connections per minute.
`–limit-burst 100`: The 25/minute limit will only activate after 100 connections have been reached.
–icmp-type 8 indicates an Echo request (Ping request). The following command denotes the rate-limiting settings when the local machine pings the host 192.168.1.109:
iptables -I INPUT -d 192.168.1.109 -p icmp –icmp-type 8 -m limit –limit 3/minute –limit-burst 5 -j ACCEPT
Allow Routing
If the localhost has two network cards, one connected to the internal network (eth0) and the other to the external network (eth1), you can use the following rule to route data from eth0 to eth1:
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
In IPtables, you can flexibly perform various types of Network Address Translation (NAT).
There are mainly two types of Network Address Translation: SNAT and DNAT.
1) SNAT stands for Source Network Address Translation, which refers to the conversion of source addresses.
For example, multiple PCs use an ADSL router to share internet access, with each PC configured with a private IP. When a PC accesses the external network, the router replaces the source address in the packet header with the router’s IP. When an external network server, such as a web server, receives the access request, the IP address logged is the router’s IP, not the private IP of the PC. This is because the “source address” in the packet header received by the server has already been replaced. Therefore, it is called SNAT, which is address translation based on the source address.
2) DNAT stands for destination network address translation. It refers to converting the destination address in network packets.
A typical use case involves a web server located within an internal network, which is assigned a private IP address. A firewall with a public IP address is configured at the front end, allowing internet users to access the website using the public IP address.
When an access request is made, the client sends a data packet wherein the packet header contains the firewall’s public IP address as the destination. The firewall then rewrites the packet header, changing the destination address to the web server’s private IP address, before forwarding the packet to the web server within the internal network. With this method, the data packet penetrates the firewall, effectively transforming a public IP access into an internal network address access. This process exemplifies DNAT, which is network address translation based on the destination address.
The following rules will forward traffic originating from port 422 on the local machine at 192.168.1.17 to port 22. This means that SSH connection requests from port 422 are equivalent to those from port 22.
1) Enable DNAT forwarding
iptables -t nat -A PREROUTING -p tcp -d 192.168.1.17 –dport 422 -j DNAT –to-destination 192.168.1.17:22
2) Allow requests to connect to port 422
iptables -t filter -A INPUT -p tcp -m tcp -m state –state NEW –dport 422 -j ACCEPT
3) Save the rules
# service iptables save
# service iptables restart
Assuming the current external gateway is 58.68.250.1, the rule below forwards HTTP requests to an internal server at port 8888, IP 192.168.1.20:
iptables -t nat -A PREROUTING -p tcp -i eth0 -d 58.68.250.1 –dport 8888 -j DNAT –to 192.168.1.20:80
iptables -A FORWARD -p tcp -i eth0 -d 192.168.0.2 –dport 80 -j ACCEPT
iptables -t filter -A INPUT -p tcp -m state –state NEW -m tcp –dport 80 -j ACCEPT
service iptables save
service iptables restart
These iptables rules will allow the redirection to port 80 on the internal server and manage the necessary packet forwarding and input acceptance to ensure proper traffic flow.
If the local machine’s internal network IP is 192.168.1.10, and you want to forward HTTP requests to an internal server at 192.168.1.20 on port 8888, you can set up the rules as follows:
Preparation: Enable the `ip_forward` routing forwarding feature on the local machine. Make sure the internal network gateway of 192.168.1.20 matches the local machine’s gateway! If there’s no internal network gateway, set the gateway address to the local machine’s internal IP, and disable the firewall (if the firewall is enabled, configure the respective port to grant access to the local machine).
iptables -t nat -A PREROUTING -p tcp -m tcp –dport 20022 -j DNAT –to-destination 192.168.1.150:22
iptables -t nat -A POSTROUTING -d 192.168.1.150/32 -p tcp -m tcp –sport 22 -j SNAT –to-source 192.168.1.8
iptables -t filter -A INPUT -p tcp -m state –state NEW -m tcp –dport 20022 -j ACCEPT
service iptables save
service iptables restart
This configuration helps redirect traffic from port 20022 on the local machine to another destination. Remember to keep security practices in mind when modifying firewall and network settings to prevent unauthorized access.
MASQUERADE, or IP address masquerading, in iptables provides an effect similar to SNAT (Source Network Address Translation), but there are distinctions:
1. When using SNAT, the range of the outgoing IP address can be one or more. For example:
1) The following command indicates that all packets from the 10.8.0.0 network segment are to be SNATed to the IP address 192.168.5.3 before being sent out:
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j SNAT –to-source 192.168.5.3
2) The following command indicates that all packets from the 10.8.0.0 network segment are to be SNATed to IP addresses such as 192.168.5.3, 192.168.5.4, or 192.168.5.5, among others, before being sent out:
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j SNAT –to-source 192.168.5.3-192.168.5.5
This showcases how SNAT can be employed, either to NAT to a single address or multiple addresses. However, with SNAT, regardless of the number of addresses, you must explicitly specify the IP you wish to SNAT!
If the current system utilizes an ADSL dynamic dialing method, each dial will lead to a change in the outgoing IP 192.168.5.3, and this change can be substantial, not necessarily within the range of 192.168.5.3 to 192.168.5.5. In this scenario, configuring iptables with the current method can present issues. Every time a redial occurs, the server address changes, yet the IP in the iptables rule won’t automatically adjust. Hence, each address change requires manually modifying iptables and updating the fixed IP in the rule to the new IP, which is highly impractical!
2) MASQUERADE is designed specifically for the aforementioned scenario. Its function is to automatically obtain the current IP address from the server’s network interface card (NIC) to perform NAT.
For example, consider the following command:
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j MASQUERADE
With this configuration, there is no need to specify the target IP for SNAT. Regardless of what dynamic IP is acquired by the eth0 interface, MASQUERADE will automatically read the current IP address of eth0 and then perform SNAT. This achieves efficient dynamic SNAT address translation.
Let’s take a look at a few examples of operational setup:
1) Restrict access to the local web server on Mondays;
New request rate cannot exceed 100 requests per second;
Web pages containing the “admin” string are not allowed to be accessed;
The web server is allowed to respond to requests leaving the host only;
Settings are as follows:
Access not allowed on Monday
iptables -A INPUT -p tcp –dport 80 -m time ! –weekdays Mon -j ACCEPT
iptables -A OUTPUT -p tcp –dport 80 -m state –state ESTABLISHED -j ACCEPT
The maximum request rate cannot exceed 100 per second.
iptables -A INPUT -p tcp –dport 80 -m limit –limit 100/s -j ACCEPT
Pages containing the “admin” string are not allowed to be accessed, source port: dport
iptables -A INPUT -p tcp –dport 80 -m string –algo bm –string ‘admin’ -j REJECT
The web server only permits response packets to leave the host, allowing the port (destination port): sport.
iptables -A OUTPUT -p tcp –dport 80 -m state –state ESTABLISHED -j ACCEPT
2) During work hours, which are Monday to Friday from 8:30 AM to 6:00 PM, allow FTP service on this machine to be accessed by hosts in the 192.168.1.0 network.
The number of data download requests should not exceed 5 per minute.
Configuration is as follows:
iptables -A INPUT -p tcp –dport 21 -s 192.168.1.0/24 -m time ! –weekdays 6,7 -m time –timestart 8:30 –timestop 18:00 -m connlimit –connlimit-above 5 -j ACCEPT
3) Allow SSH access from hosts within the range 192.168.1.1-192.168.1.100 to this machine;
The rate of new connection establishment must not exceed two per minute;
Only allow response packets to leave this machine through its service port;
Configuration is as follows:
iptables -A INPUT -p tcp –dport 22 -m iprange –src-range 192.168.1.1-192.168.1.100 -m limit –limit 2/m -j ACCEPT
iptables -A OUTPUT -p tcp –sport 22 -m iprange –dst-range 192.168.1.1-192.168.1.100 -m state –state ESTABLISHED -j ACCEPT
4) Deny packets with TCP flag bits set to all 1s and all 0s from accessing the local machine;
iptables -A INPUT -p tcp –tcp-flags ALL ALL -j DROP
5) Allow the local machine to ping other hosts; but do not allow other hosts to ping the local machine:
iptables -I INPUT -p icmp –icmp-type echo-request -j DROP
iptables -I INPUT -p icmp –icmp-type echo-reply -j ACCEPT
iptables -I INPUT -p icmp –icmp-type destination-unreachable -j ACCEPT
Alternatively, disable ping with the following operation:
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all