Detailed explanation of Linux iptables command

Time:2021-10-21

Iptables is an important part of Linux firewall system. The main function of iptables is to control the access and forwarding of network packets. Iptables can be used to control when data packets need to enter the device, flow out of the device, or be forwarded and routed by the device. The following Liangxu Xiaobian will be from several aspectsLinux iptables commandIn detail, I hope it will be helpful to you.

Linux命令

Introduction to iptables

Iptables is a packet filtering firewall system integrated into the Linux kernel. Iptables can be used to add and delete specific filtering rules. Iptables maintains 4 tables and 5 chains by default, and all firewall policy rules are written to these tables and chains respectively.

“Four tables” refer to the functions of iptables. The default IPtable s rule tables include filter table, NAT table, mangle table and raw table

  1. Filter table: controls whether data packets are allowed to enter, exit and forward. The links that can be controlled include input, forward and output.
  2. Nat table: controls the address translation in the data packet. The links that can be controlled include preouting, input, output and postrouting.
  3. Mangle: modify the original data in the packet. The links that can be controlled include preouting, input, output, forward and postrouting.
  4. Raw: controls the enabling status of the connection tracking mechanism in the NAT table. The links that can be controlled include preouting and output.

“Five chains” refers to the five rule chains defined by Netfilter that controls the network in the kernel. Each rule table contains multiple data chains: input (inbound data filtering), output (outbound data filtering), forward (forwarding data filtering), pre routing (pre routing filtering) and post routing (post routing filtering). Firewall rules need to be written into these specific data chains.

The filtering framework of Linux firewall is shown in Figure 1.

Linux命令

It can be seen that if an external host sends data packets to the firewall, the data will pass through the provisioning chain and input chain; If the firewall sends data packets to the external host, the data will pass through the output chain and postrouting chain; If the firewall is responsible for forwarding data as a route, the data will pass through the preceding chain, forward chain and postrouting chain.

Iptables syntax format

The basic syntax format of iptables command is as follows:

[[email protected] ~]# iptables [-t table] COMMAND [chain] CRETIRIA -j ACTION

The meaning of each parameter is:

  • -t: Specify the firewall rule table filter, NAT, mangle, or raw to maintain. When – t is not used, the filter table is used by default.
  • Command: a subcommand that defines the management of rules.
  • Chain: indicates the linked list.
  • Cretiria: match parameters.
  • Action: trigger action.

The common options and functions of iptables command are shown in Table 2

Options Function
-A Add firewall rule
-D Delete firewall rule
-I Insert firewall rule
-F Clear firewall rules
-L List add firewall rules
-R Replace firewall rule
-Z Clear firewall data table statistics
-P Set chain default rules

The common matching parameters and functions of iptables command are shown in Table 3.

Parameters Function
[!]-p Match protocol,! Indicates negation
[!]-s Match source address
[!]-d Match destination address
[!]-i Match inbound network card interface
[!]-o Match outbound network card interface
[!]–sport Match source port
[!]–dport Match target port
[!]–src-range Match source address range
[!]–dst-range Match target address range
[!]–limit Four configuration data table rate
[!]–mac-source Match source MAC address
[!]–sports Match source port
[!]–dports Match target port
[!]–stste Matching status (invalid, established, new, retired)
[!]–string Match application layer string

The iptables command trigger action and their respective functions are shown in Table 4.

Trigger action Function
ACCEPT Allow packets to pass
DROP Drop packets
REJECT Reject packet pass
LOG Record packet information to syslog log log
DNAT Destination address translation
SNAT Source address translation
MASQUERADE Address spoofing
REDIRECT redirect

The kernel will check iptables firewall rules in order. If a matching rule directory is found, it will immediately perform relevant actions and stop looking down the rule directory; If all firewall rules fail to match successfully, the default policy is followed. Adding a firewall rule with the – a option will append the rule to the end of the whole chain, while the firewall rule added with the – I option will be inserted into the chain as the first rule by default.

Note that iptables is installed by default in Linux CentOS system. If there is no iptables tool in the system, you can install it first.

Viewing and clearing rules

Use iptables command to view, add, modify and delete specific rules

1) View rules

To view rules, you need to use the following commands:

[[email protected] ~]# iptables -nvL

The meaning of each parameter is:

  • -L means to view all rules of the current table. The filter table is viewed by default. If you want to view the NAT table, you can add the – t NAT parameter.
  • -N means that the IP address will not be backqueried. With this parameter, the display speed will be accelerated.
  • -V represents the output details, including the number of packets passing through the rule, the total number of bytes and the corresponding network interface.

[example 1] view rules.
First, you need to use the Su command to switch the current user to the root user. Then enter the following command on the terminal page:

[[email protected] ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere           
ACCEPT     all  --  anywhere             anywhere           
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited

2) Add rule

The two parameters for adding a rule are – A and – I. Where – A is added to the end of the rule- I can be inserted into the specified location. If there is no specified location, it will be inserted into the header of the rule by default.

[example 2] view the current rule. First, use the Su command to switch the current user to the root user, and then enter the command on the terminal page as follows:

[[email protected] ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
......

[example 3] add a rule to the tail.
First, use the Su command to switch the current user to the root user, and then enter the following command on the terminal page:

[[email protected] ~]# iptables -A INPUT -s 192.168.1.5 -j DROP
[[email protected] ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
6    DROP       all  --  192.168.1.5          0.0.0.0/0

3) Modify rules

The – R parameter is required when modifying rules.
[example 4] modify the drop added to the rule in line 6 to accept. First, use the Su command to switch the current user to the root user, and then enter the following command on the terminal page:

[[email protected] ~]# iptables -R INPUT 6 -s 194.168.1.5 -j ACCEPT
[[email protected] ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
6    ACCEPT     all  --  194.168.1.5          0.0.0.0/0

The comparison shows that the target of the rule in line 6 has been modified to accept.

4) Delete rule

There are two ways to delete a rule, but both must use the – D parameter.
[example 5] delete the added rule in line 6. First, use the Su command to switch the current user to the root user, and then enter the following command on the terminal page:

[[email protected] ~]# iptables -D INPUT 6 -s 194.168.1.5 -j ACCEPT

or

[[email protected] ~]# iptables -D INPUT 6

Note that sometimes the rule to be deleted is long, and a large string of code needs to be written during deletion, which is easy to make mistakes. At this time, you can use – line number to find the line number of the rule, and then delete the rule through the line number.

Backup and restore of firewall

The default iptables firewall rules will take effect immediately, but if they are not saved, all rules will be lost after the computer restarts, so it is very necessary to save the firewall rules in time.

Iptables package provides two very useful tools that we can use to deal with a large number of firewall rules. The two tools are iptables save and iptables restore, which can save and restore firewall rules. The biggest advantage of these two tools is that they are very fast when dealing with large rule sets.

The firewall rules in the CentOS 7 system are saved in the / etc / sysconfig / iptables file by default. You can save the firewall rules in this file by using iptables save. The rules in this file will be loaded automatically after the computer restarts. If you use iptables save to save rules to other locations, you can backup firewall rules. When the firewall rules need to be restored, you can use iptables restore to import the backup files directly into the current firewall rules.

1. Iptables Save command

Iptables Save command is used to batch export Linux firewall rules. The syntax is as follows:

Save in default folder (save firewall rules):
[[email protected] ~]# iptables-save > /etc/sysconfig/iptables

Save in another location (backup firewall rules):
[ [email protected] ~]#Iptables save > file name

  1. Directly execute iptables Save command: all currently enabled rules are displayed in the order of raw, mangle, NAT and filter tables, as shown below:

[[email protected] ~]# iptables-save
# Generated by iptables-save v1.4.7 on Thu Aug 27 07:06:36 2020
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [602:39026]
…….
COMMIT
# Completed on Thu Aug 27 07:06:36 2020

Of which:

  • Notes beginning with “#”;
  • “* filter” indicates the table;
  • “: chain name default policy” indicates the corresponding chain and default policy. The command name “iptables” is omitted in the specific rules;
  • At the end, “commit” means to commit the previous rule settings.
  1. Back up to another file. For example, the file: text is as follows:

[[email protected] ~]# iptables-save > test
[[email protected] ~]# ls
test
[[email protected] ~]# cat test
# Generated by iptables-save v1.4.7 on Thu Aug 27 07:09:47 2020
*filter
……

  1. List the rule contents of NAT table. The command is as follows:

[[email protected] ~]# iptables-save -t nat

“-t table name”: indicates that a table is listed.

2. Iptables restore command

Iptables restore command can import Linux firewall rules in batches. At the same time, it also needs to specify the location of backup files in combination with redirection input. The command is as follows:

[ [email protected] ~]#Iptables restore < file name

Note that the imported file must be exported using iptables save tool.

First use the iptables restore command to restore the text file, and then use the iptables – t NAT – NVL command to check whether the empty rule has been restored, as shown below:

[[email protected] ~]# iptables-restore < test
[[email protected] ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

The above isLiangxu tutorial networkDetailed explanation of Linux iptables command shared by all friends.

This article is composed of blog one article multi posting platformOpenWriterelease!

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]