This is the 14th day of my participation in the More text Challenge. For more details, see more text Challenge


A lifelong learner, practitioner, and sharer committed to the path of technology, an original blogger who is busy and sometimes lazy, and a teenager who is occasionally boring and sometimes humorous.

Welcome to search “Jge’s IT Journey” on wechat!

The original link: iptables firewall rules (3) – export/import, use firewall script | (system mind map attached)

1. Backup and restore firewall rules

The commands iptables-save and iptables-restore are used to save and restore firewall rules in batches.

The iptables – save command

The iptables-save command: you can export Linux firewall rules in batches.

If you run the iptables-save command, all the currently enabled rules are displayed.

# iptables-save # Generated by iptables-save v1.4.7 on Mon Oct 7 20:09:30 2019 * NAT :PREROUTING ACCEPT [134:12724] :POSTROUTING ACCEPT [10:645] :OUTPUT ACCEPT [10:645] -A PREROUTING -d 192.168.1.4/32 -i eth2 -p TCP -m TCP --dport 80 -j DNAT --to-destination 192.168.3.112 COMMIT # Completed on Mon Oct 7 20:09:30 2019 # Generated by iptables-save v1.4.7 on Mon Oct 7 20:09:30 2019 *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [257:22057] -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 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT # Completed on Mon Oct 7 20:09:30 2019Copy the code

Meanings of the above outputs:

  • Anything that begins with a # sign is a comment;
  • * Table name: indicates the table; Such as:*nat
  • : Chain name Default policy: indicates the corresponding chain and default policy. The specific rules are omittediptablesThe command name.
  • COMMIT: commits the previous rule Settings.

The iptables-save command is used to output the rules to the screen. When the rules need to be saved as fixed files, the operation of redirection output is used to complete the backup.

Run the following command to back up all firewall rules to the iptables_beifen. TXT file. After the backup is complete, check whether the file exists in the backup path.

# iptables - save > / root/iptables_beifen. TXT # ll | grep iptables_beifen. TXT - rw - r - r -. 1 root root on October 7, 782 strip iptables_beifen.txtCopy the code

The iptables – restore command

The iptables-restore command: you can import Linux firewall rules in batches, and use the iptables-save command to redirect input to specify the location of backup files.

# iptables-restore < /root/iptables_beifen.txt
Copy the code

2. Use the iptables service

The rule files used by the iptables service are in the /etc/sysconfig/iptables file.

Using the iptables system service, you can quickly enable and clear firewall rules.

The firewall rules are automatically enabled

The default rule configuration file /etc/sysconfig/iptables is backed up with iptables-save and can then be invoked from the iptables service.

Saves the current firewall rules and automatically rebuilds the firewall rules after each startup.

# iptables-save > /etc/sysconfig/iptables # chkconfig --level 2345 iptables on # chkconfig --list iptables iptables 0: disable 1: disabled 2: enabled 3: enabled 4: enabled 5: enabled 6: disabledCopy the code

To enable the rule setting in the /etc/sysconfig/iptables file, you only need to start the iptables service.

# service iptables start
Copy the code

Clear all firewall rules

During the debugging of various firewall rules, you need to clear the rules in some tables to eliminate interference from other rules.

Disabling the iptables service is the best way to do this when you need to clear the rules for all tables in sequence.

ACCEPT: NAT filter: [confirm] iptables: clear firewall rules: [confirm] iptables: uninstalling modules: [Confirm] # service iptables status iptables: The firewall is not running.Copy the code

3. Composition of firewall scripts

Some of you might be wondering, firewalls and scripting? What do they consist of? And so on;

The advantages of firewall script: easy to use Shell variables, program control logic, as an independent file in need of reuse, transplantation use more convenient;

Defining basic variables

The network adapter, IP address, LAN segment, and iptables command path of the firewall are defined as variables, facilitating maintenance and migration of script programs.

When there are many rules, once there is a problem in the network environment, it can be used only by modifying the variable value.

# vi /opt/myiptables.sh #! /bin/bash #### 3.1 Define the basic variable INET_IF="eth1" # Extranet interface INET_IP="192.168.3.111" # Extranet interface address LAN_IF="eth2" # Intranet interface LAN_NET="192.168.1.0/24" # Internal network segment LAN_WWW_IP="192.168.3.112" # Internal address of the web server IPT="/sbin/iptables" # iptables command path MOD="/sbin/modprobe" # modprobe command path CTL="/sbin/sysctl" # sysctl command pathCopy the code

Once the variable is set, you can refer to it directly, except to add the necessary comments. It is best to use a string with some meaning for the variable name.

Loading a kernel module

Modules of the iptables command can be dynamically loaded into the kernel on demand, and some need to be manually loaded.

When the number of rules to be enabled is large, the efficiency of rule setting is improved, the stability of the firewall is maintained, and modules are loaded into the kernel in advance.

#### 3.2 Load the necessary kernel modules $MOD ip_tables # Iptables basic module $MOD ip_conntrack # Connection tracing module $MOD ipt_REJECT # Reject operation module $MOD ipt_LOG # Logging module $MOD ipt_iprange # Supports IP range matching $MOD xt_state # Supports state matching $MOD xt_multiport # Supports multi-port matching $MOD xT_MAC # Supports MAC address matching $MOD $MOD ip_conntrack_ftp # Supports FTP connection trackingCopy the code

Adjust the /proc parameter

/proc is a pseudo-file system mechanism on Linux or UNIX systems that provides real-time data for accessing kernel running structures and changing kernel Settings.

The data in /proc is stored in memory rather than on hard disk.

/proc/sys holds system-specific controllable parameters that can be used to change the behavior of the kernel as a real-time entry point for Linux kernel tuning.

You can run the echo and sysctl commands to modify related parameters or write them to the /etc/sysctl.conf file. (Sysctl -p takes effect after the command is executed.) The parameters include whether to enable IP forwarding, whether to respond to ICMP broadcast, and whether to set TCP response timeout.

The following are the most common /proc parameter adjustments

Icmp related parameters: Enable the host to ignore ping tests of other hosts.

TCP related parameters: can properly improve the resistance of the machine DOS attack ability;

#### 3.3 Linux kernel control and tuning $CTL -w net.ipv4.ip_forward=1 # Enable the routing and forwarding function $CTL -w net.ipv4. ip_default_TTL =128 # Modify ICMP response timeout $CTL Icmp_echo_ignore_all =1 # Reject ICMP broadcasts $CTL -w net.ipv4. icMP_ECHO_ignore_all =1 # Reject ICMP broadcasts $CTL -w net.ipv4 Net.ipv4. tcp_syncookies=1 # Enable SYN Cookie mechanism $CTL -w net.ipv4.tcp_syn_retries=3 # Maximum number of SYN request attempts $CTL -w Tcp_synack_retries =3 # Maximum retry times $CTL -w net.ipv4.tcp_fin_timeout=60 # TCP connection wait timeout $CTL -w Net.ipv4. tcp_max_syn_backlog=3200 # Queue length for SYN requestsCopy the code

Set specific iptables rules

Clean up existing rules

To avoid interference caused by existing firewall rules, you need to delete all user-defined chains in all tables and clear all rules in the chain.

$ipt-t filter -x $ipt-t filter -f $ipt-t filter -f $ipt-t filter -f $ipt-t filter -f $ipt-t filter -f $ipt-t filter -f $ipt-t filter -fCopy the code
Set the default policy for the rule chain

In the actual environment, the firewall filtering rules must adopt the default deny policy to improve security.

During the learning process, you are advised to use the default policy. Change the DROP in the default policy to ACCEPT.

$IPT -P INPUT DROP
$IPT -P FORWARD DROP
$IPT -P OUTPUT ACCEPT
Copy the code
Set the rules in the NAT table

The NAT table is mainly used on Linux gateway servers. You need to write SNAT and DNAT rules based on the actual situation.

$IPT -t nat -A POSTROUTING -s $LAN_NET -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_IPCopy the code
Set the rules in the filter table

The filter table is used to filter data packets.

The main firewall uses INPUT and OUTPUT chains.

Network firewalls mainly use FORWARD chains.

To enable shared Internet access, set SNAT policies and allow Intranet PCS to communicate with Internet services such as DNS and HTTPD.

Note: In actual work, it is recommended that you set the corresponding rules according to the actual network situation and test them in the test environment to ensure that the rules are correct and avoid network communication failure.

$IPT -A FOEWARD -s $LAN_NET -o $INET_IF -p udp 53 -j ACCEPT
$IPT -A FOEWARD -s $LAN_NET -o $INET_IF -p udp 80 -j ACCEPT
$IPT -A FOEWARD -d $LAN_NET -i $INET_IF -m state ESTABLISHED,RELATED -j ACCEPT
Copy the code

Adding execute Permission

# chmod +x /opt/myiptables.sh
Copy the code

Run the /opt/myiptables.sh script

# /opt/myiptables.sh 
net.ipv4.ip_forward = 1
net.ipv4.ip_default_ttl = 128
net.ipv4.icmp_echo_ignore_all = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
net.ipv4.tcp_fin_timeout = 60
net.ipv4.tcp_max_syn_backlog = 3200
Copy the code

Viewing Firewall Rules

# iptables -nL FORWARD
Copy the code

The /opt/myiptables.sh script is automatically executed upon startup

# vi /etc/rc.local
/opt/myiptables.sh
Copy the code

Recommended reading

Iptables firewall (a) | 4 table / 5 chain, packet matching process, write the iptables rules

The iptables firewall (2) | SNAT/DNAT strategy and application


Original is not easy, if you think this article is a little useful to you, please give me a like, comment or forward for this article, because this will be my power to output more quality articles, thanks!

See you next time!