Linux--iptables Common Commands

Source: Internet
Author: User
Tags syslog vps iptables server port ssh port anchorlink

Iptables is an important means of access control in Linux and is an important part of Linux firewall system. Here are some common operating instructions for iptables firewall rules.

The following operations are based on CentOS and should be similar to different Linux distributions. In CentOS 5.x and 6.x, Iptables is installed by default (if not installed, install Iptables first). If you are not familiar with the Iptables workflow, you can read this iptables workflow in a popular understanding.

Content Directory

    1. Basic operations
      1. View Iptables version
      2. View current iptables rules
      3. View Help
    2. The meaning of each instruction (command) in the iptables rule
      1. –append-a
      2. –delete-d
      3. –insert-i
      4. –replace-r
      5. –list-l
      6. –list-rules-s
      7. –flush-f
      8. –zero-z
      9. –new-n
      10. –delete-chain-x
      11. –policy-p
      12. –rename-chain-e
    3. The meanings of the parameters in the iptables rule
    4. Additional Firewall parameter options
    5. iptables example to allow only inbound SSH connections

The following actions refer to instructions that are entered directly from the Linux command line, and can also be written as a. sh file batch execution.

1. Basic operation¶View IPTABLES version¶
Rpm-q iptables

The result returned here is similar to the iptables-1.4.7-9.el6.i686 .

View current IPTABLES Rules¶
Service Iptables Status



This command displays the currently used Iptables rule in the form of a list, which can be used as a parameter for other operations, such as subsequent delete operations, to be useful. The displayed results are similar to the

# service Iptables Statustable:filterchain INPUT (policy ACCEPT) num target prot opt source Destination1 ACCEPT all--0.0 .0.0/0 State Related,established2 accept ICMP-- Accept All-- Accept TCP-- State NEW TCP dpt:225 REJECT All-- reject-with icmp-host-prohibitedchain F Orward (policy ACCEPT) num target prot opt source Destination1 REJECT All-- reject-with Icmp-host-proh Ibitedchain OUTPUT (policy ACCEPT) num Target prot opt source destination

Shows that there is a table filter in the iptables, where there are 5 rules in INPUT chain, there are 1 rules in FORWARD chain, there are no rules in OUTPUT chain.

View Help¶

The operation instruction is also directly in the terminal input,


You can view the Help information for iptables:

Usage:iptables-[ad] Chain rule-specification [options]iptables-i chain [Rulenum] rule-specification [options]iptables -R chain Rulenum rule-specification [options]iptables-d chain Rulenum [Options]iptables-[ls] [chain [Rulenum]] [options] Iptables-[FZ] [chain] [options]iptables-[nx] chainiptables-e old-chain-name new-chain-nameiptables-p chain Target [opt Ions]iptables-h (Print this Help information)instructionCommands:either Long (Word, with--make leading) or short (letter, case-sensitive, to-do preamble) options is allowed.--append-a chain append to Chain--delete -D chain Delete matching rule from chain--delete-d chain Rulenumdelete rule rulenum (1 = first) from Chain--insert-i Ch Ain [Rulenum]insert in Chain as Rulenum (default 1=first)--replace-r chain Rulenumreplace rule rulenum (1 = first) in Cha in--list-l [Chain [Rulenum]]list the rules in a chain or all chains--list-rules-s [chain] [rulenum]]print the rules in a Chain or all chains--flush-f [chain], Delete all rules in chain or all chains--zero-z [chain [Rulenum]]zero counters in C Hain or all chains--new-n chain Create a new user-defined chain--delete-chain-x [chain] Delete a user-defined Chain--poli Cy-p chain Targetchange policy on chain to TARGET--RENAME-CHAIN-E Old-chain new-chainchange chain name, (moving any refer ences)parameters (Options)options:[!]--proto-p proto protocol:by number or name, eg. ' TCP ' [!]--source-s address[/mask][...] SOURCE specification[!]--destination-d address[/mask][...] Destination specification[!]--in-interface-i input Name[+]network Interface name ([+] for wildcard)--jump-j Targettarge T for rule (could load target extension)--goto-g chainjump to chain with no return--match-m matchextended match (May load extension)--numeric-n numeric output of addresses and ports[!]--out-interface-o output Name[+]network interface name ([  +] for wildcard)--TABLE-T table table to manipulate (default: ' Filter ')--verbose-v verbose mode--line-numbers print Line Numbers when listing--exact-x expand numbers (display exact values) [!]--fragment-f match second or further fragments O  Nly--modprobe= try to insert modules using this command--set-counters pkts BYTES set the counter during Insert/append [!] --VERSION-V Print package version.
2. Meaning of the commands in the Iptables rules¶

The various directives are as follows (the first chunk of content listed in the previous Help information). You can either use a long instruction (word, to-do preamble), or you can use a short instruction letter, case-sensitive, to – do the leading), for example,

Iptables--append Chain Firewall-rule

Equivalent to,

Iptables-a chain Firewall-rule

Various directives are described below. Because the form is the same, the following –append-a for detailed introduction, the other only describes its role. For example, use only short instructions.

In addition, the parameters/options that follow the instruction, if included with [], indicate that the parameter/option can be omitted (with default values).


Instruction form,

Iptables-a chain Firewall-rule
    • -a chain– specifies the name of the chain to which the rule should be added. For example, using input will add the rule to the end of the default INPUT (inbound) chain, and using OUTPUT will add the rule to the end of the outbound chain.
    • firewall-rule– firewall rules with various parameter options, one rule at a time

"-A" means attaching (append), not adding (add) meaning. It is an action instruction that adds rules to the end of an existing firewall chain (chain). This is especially important because the position of the rule in iptables is very important, so remember that-a means adding the rule to the end . Because in general, the last rule in iptables is to discard all packets. If you already have one of these rules, the rules added with the-a parameter will be discarded after the rule, so that the new rule doesn't work at all. If you want to insert into an intermediate position, you need to use the-I directive.

If you do not understand the meaning of chain (chain), it is best to read iptables fundamentals first.


Removes an entry that matches a specified rule or specifies a number from chain.


Iptables-d chain Firewall-rule

Represents the entry that deletes the corresponding rule firewall-rule from chain. This form of deletion rules is cumbersome, usually in the following form

Iptables-d chain Rulenum

Delete the rule that is numbered rulenum in chain. 1 represents the first article.



Iptables-i chain [Rulenum] Firewall-rule

Add firewall-rule as Rule rulenum in chain, and the original section rulenum and subsequent articles need to be +1 in sequence. As above, 1 represents the first of the chain. The default is 1, which is to replace the first rule in the chain if no rulenum is specified.



Iptables-r chain [Rulenum] Firewall-rule

Replace the original Rulenum rule in chain with Firewall-rule. If Rulenum is not specified, the first of the chain is replaced.



iptables-l [Chain [Rulenum]]

Lists the Rulenum rule in chain or all chain (when no chain name is specified) or all rules (when Rulenum is not specified). Note, however, that you cannot take the Rulenum parameter if you do not specify chain.

If you add –line-numbers after-L, the ordinal is displayed before each rule. Such as



iptables-s [Chain [Rulenum]]

Prints the Rulenum rule or all rules (when Rulenum is not specified) in chain or all chain (when no chain name is specified). Note, however, that you cannot take the Rulenum parameter if you do not specify chain.



Iptables-f [Chain]

Clears the rule in chain or all chain (when no chain name is specified).



iptables-z [Chain [Rulenum]]

Clears the chain or all chain (when no chain name is specified) of the packet and byte counters.



--new-n Chain

Create a new chain called chain.



Iptables-x [Chain]

Delete user-defined chain or all user-defined chain (when chain name is not specified). This directive does not affect preset rules (such as INPUT, OUTPUT, FORWARD, and so on).



Iptables-p chain Target

The strategy for changing chain is target.



IPTABLES-E Old-chain New-chain

Change the Old-chain name to New-chain. Doing so invalidates all the rules that refer to Old-chain.

3. The meanings of the parameters in the Iptables rules¶

The various parameters are as follows (the second chunk of content listed in the previous Help information).

-P representative Agreement (PROTOCOL)
    • Indicates the transport protocol for the current rule (such as TCP, UDP, ICMP, and so on)
    • Possible parameter values are: TCP, UDP, ICMP, all
    • Use "All" to indicate that all protocols apply. If you do not specify the-p parameter in the rule, the "all" parameter is used by default. The value "All" is generally not used, either specifying a specific protocol or specifying the-p parameter.
    • The parameter value of-P can be either a name (such as TCP) or a value corresponding to the protocol (for example, 6 for the TCP protocol)
    • All allowed protocol names and corresponding values are included in the/etc/protocols file
    • You can also use a long parameter name –protocol
-S represents the source address
    • Specify the source address of the packet
    • Can be an IP address, or a network address, or host name (hostname)
    • For example:-S indicates a specific IP address
    • For netmask, use/mask. For example, the-S″ indicates that all 192.168.1.x addresses of the netmask are matched for
    • If you do not specify the-s parameter, all source addresses are matched by default
    • You can also use long parameter names –SRC or –source
-D represents the destination address (DESTINATION)
    • Specify the destination address of the packet
    • Use the same way as "-S" above (the difference is only the-s source, and-d means the destination address)
    • You can also use long parameter names –DST or –destination
-j Rep Jump (TARGET)
    • J means "jump" (jumping) to the target
    • Specifies that when a packet satisfies the rule, it jumps to the next processing rule, and no longer executes the subsequent rule judgment
    • Possible values are: accept, drop, queue, return, respectively, receive, discard, enter queue, return (jump, usually from a chain jump back to call the chain upper chain)
    • You can also jump to a custom chain, using the name of the chain as a jump target
-I stands for in INTERFACE (inbound interface)
    • I means "input interface" (input interface, that is, the network card to specify the data processing, the general eth0 is the first wired network card, the external network interface, LO represents the LAN interface)
    • Can be directly understood as "-I" represents an interface. However,-I and-o both represent interfaces,-I represents the interface at input, and-o refers to the interface used for the output.
    • Specifies the interface through which packets enter INPUT, FORWARD, and prerouting chains.
    • For example,-I eth0 indicates that the rule should target packets coming in from the Eth0 interface.
    • If you do not specify the-I parameter, packets entered through all available interfaces on the system can match the rule.
    • You can also use the long parameter –in-interface
-O stands for out INTERFACE (outbound interface)
    • o = "Output interface" (Outbound via interface)
    • Specifies the interface through which packets are sent into the INPUT, FORWARD, and prerouting chains.
    • If you do not specify the-o parameter, packets emitted through all available interfaces in the system can match the rule.
    • You can also use the long parameter –out-interface
4. Other Firewall parameter options¶

Some of the firewall parameters above also have their own parameter options, which can be used with them. Here are some common options.

To use these parameter options, you need to specify parameters such as "-P TCP" (or "-P UDP") in the rule, for example, to use the "–sport" option.

Note: All of these options are preceded by – (2 dashes –).

–sport represents the source port, which is used for-P TCP, or-p UDP
    • All ports are matched by default (when not specifically specified)
    • You can specify a port number (number), or you can specify a name for the ports. For example, the default SSH port number is 22 and the name is SSH, which can be expressed as "–sport 22″ or" –sport ssh.
    • The/etc/services file contains all the allowed port names and the corresponding port numbers.
    • Using a number in a rule is better than using a name (higher efficiency)
    • To match a port range, use the English half-width colon (:), such as 22:100 to match all the port numbers from 22 to 100.
    • You can also use the long name –source-port
–dport = DESTINATION Port (destination port,-p TCP, or-P UDP)
    • Same as –sport usage, except that the object is the destination port
    • You can also use the long name –destination-port
–tcp-flags = TCP FLAGS (for-p TCP)
    • You can specify multiple TCP status IDs by using the English half-width comma (,)
    • Possible values are: SYN, ACK, FIN, RST, URG, PSH. You can use it all or not.
–icmp-type represents ICMP type (ICMP types, for-p ICMP)
    • When using the ICMP protocol "-P ICMP", you can use "–icmp-type" to specifically specify the ICMP type
    • For example, use "–icmp-type 0″ for Echo Reply", "–icmp-type 8″ for Echo."
5. iptables example to allow only inbound SSH connections¶

After understanding the various Iptables parameters and parameter options, take a look at the following example.

In this example, our goal is to allow only SSH to connect to the server, while all other connections are disabled (including ping).

Warning: If you set it incorrectly, you may not be able to access the system over the network, so be careful when playing VPS. However, if it is a Linode VPS, it provides the Lish interface, you can access the same as the local system to operate the VPS, but also do not worry too much, just a bit of trouble. If it's another VPS, I don't know much about it. In short, be careful with everything! It is best to test these things in a local virtual machine, otherwise you will be blocked out of the VPS can not connect to the console via SSH, it is not fun.

1. Delete existing rules

If you already have some rules, you need to back it up, and it's easy to recover later.

Service iptables saveiptables:saving Firewall rules to/etc/sysconfig/iptables:[OK]

The default is save as /etc/sysconfig/iptables . We can back up this file a bit,


Then clear all the rules, start from the beginning,


When we have completed the following settings, we can only connect to the server via SSH, and cannot ping or access other services on the server (such as Web sites). Remember not to play in a production environment.

2. SSH only allowed

The following start setting allows the server to accept only SSH connections (without restricting the location where the connection originated), assuming SSH uses the default port of 22.

Use the following rules to have the server accept all connections that go through Port 22nd.

Iptables-a input-i eth0-p TCP--dport 22-j ACCEPT

The above instruction contains 4 parts:

    • "-A-Input" – Indicates that we want to add the following rule at the end of the INPUT chain. So this rule will be applied to inbound packets.
    • The-I eth0″– means checking packets entered through the Eth0 interface to see if this rule is matched.
    • "-P tcp–dport 22″– The rule is for TCP packets, and the option of the-p parameter is used –dport 22″ to specify that the rule is for packets to be sent to the server port 22nd (that is, the SSH port).
    • "-j accept" – jumps to accept, which accepts the transmission of packets that satisfy these matching rules.

In Mandarin, the above rule is to say: all SSH connections from the Eth0 interface are accepted.

3. Discard all other packages

Once the system can accept a connection, a "discard" rule is usually set to discard all packets that are not intended to be accepted.

Such a rule should be placed at the last position of the INPUT chain.

To discard all packets (because after the rule that accepted the SSH connection, so it doesn't affect the rule just now), add the rule using the following command.

Iptables-a input-j DROP
4. View SSH rules and tests

To view the rule you just added, use the command iptables -L , and give the output of the command at the same time.

# Iptables-lchain INPUT (policy ACCEPT) target     prot opt source               destinationaccept     TCP  -  Anywhere             Anywhere            TCP dpt:sshdrop       all  -  anywhere             anywhere

As you can see from the above results, the rules are arranged in the order we entered them,

    • The first one accepts all incoming SSH connections;
    • The second one discards all the remaining packets (which do not match the first one).

If you do not want to enter these rule commands from the command line, it is a good idea to create a script file (shell script) to contain all the rules and then execute them automatically. For example

# VI iptables.shiptables-a input-i eth0-p TCP--dport 22-j acceptiptables-a input-j drop# sh-x iptable S-a input-i eth0-p tcp--dport 22-j accept+ iptables-a input-j drop# iptables-l inputchain INPUT (policy ACCEPT) tar Get     prot opt source               destinationaccept     TCP  -  anywhere             anywhere            TCP Dpt:sshdrop       all  -  anywhere             anywhere

After looking at the iptables command and its parameters/options above, you should be able to read the iptables settings in my VPS security policy.

The above description is for iptables, which is the firewall for IPV4. IPV6 is similar, but IPv6 's firewall is ip6tables. ©

5. Set Chain policy

For filter table, the default chain policy is accept, and we can modify the chain policy with the following command:

Iptables-p INPUT dropiptables-p FORWARD dropiptables-p OUTPUT DROP

The above command configuration will discard the receive, forward, and emit packets and perform a more rigorous package management. Since both the receive and the package are set to discard, when additional rules are further configured, care should be taken to configure the input and output separately. Of course, if you trust this machine to outsource, the third rule above can not be configured.

6. Block the specified IP

Sometimes we find that an IP is being sent to the server, and we can discard the packets from the specified IP using the following command:

block_this_ip= "x.x.x.x" iptables-a input-i eth0-p tcp-s "$BLOCK _this_ip"-j DROP

The above command sets the TCP packet that will be sent by the x.x.x.x IP to the eth0 network port.

7. Configure Service Items

With Iptables, we can safely manage the service items that we use every day, such as setting up a network via SSH, which can only be connected to the machine via the specified network segment:

Iptables-a input-i eth0-p tcp-s 22-m State--state new,estableshed-j acceptiptables-a OUTP Ut-o eth0-p TCP--sport 22-m State--state established-j ACCEPT

To support connecting to other machines via SSH, the following rules need to be set because the connection is established on the native port:

Iptables-a input-i eth0-p tcp-s 22-m State--state estableshed-j acceptiptables-a OUTPUT- o eth0-p tcp--sport 22-m State--state new,established-j ACCEPT

Similarly, for TCP connection-based services such as HTTP/HTTPS (80/443), POP3 (110), rsync (873), and MySQL (3306), you can also refer to the above command configuration.

For UDP-based DNS services, use the following command to turn on the port service:

Iptables-a output-p udp-o eth0--dport 53-j acceptiptables-a input-p udp-i eth0--sport 53-j ACCEPT

8. Network Port forwarding Configuration

For the server used as a firewall or gateway, a network port connected to the public network, the other network port packet forwarding to the network port to the public network communication, assuming that eth0 connected to the intranet, eth1 connected to the public network, the configuration rules are as follows:

Iptables-a forward-i eth0-o eth1-j ACCEPT

9. Port forwarding Configuration

For ports, we can also use Iptables to complete the forwarding configuration:

Iptables-t nat-a prerouting-p tcp-d 422-j DNAT--to

The above command forwards the 422-port packet to port 22, so SSH connection via 422 port, of course, for 422 ports, we also need to configure the rules that they support for connection establishment as well as the "4. Configure service Items" section above.

10.DoS Attack Prevention

With the extension limit, we can also configure Iptables rules to enable DOS attack prevention:

Iptables-a input-p tcp--dport 80-m limit--limit 25/minute--limit-burst 100-j ACCEPT

--litmit 25/minute indicates a limit of 25 maximum connections per minute

--litmit-burst 100 indicates that the Litmit/minute limit is started when the total number of connections exceeds 100

11. Configure Web Traffic equalization

We can use a server as the front-end server, using iptables for traffic distribution, the configuration method is as follows:

Iptables-a prerouting-i eth0-p TCP--dport 80-m State--state new-m nth--counter 0--every 3--packet 0-j DNAT--to -destination prerouting-i eth0-p TCP--dport 80-m State--state new-m nth--counter 0--ev ery 3--packet 0-j DNAT--to-destination prerouting-i eth0-p TCP--dport 80-m State--stat E new-m nth--counter 0--every 3--packet 0-j DNAT--to-destination

The above configuration rules are used with the nth extension module, which balances 80 port traffic to three servers.

12. Log the Discard package condition

Using the log target and the Syslog service, we can record the packet status under a certain port of a protocol. Examples of packet loss can be achieved in the following ways.

First, customize a chain:

Iptables-n LOGGING

Next, all the receive packages are imported into logging chain:

Iptables-a input-j LOGGING

Then set the log prefix, log level:

Iptables-a logging-m limit--limit 2/min-j LOG--log-prefix "iptables Packet Dropped:"--log-level 7

Finally, the package is dropped to drop, discarding the package:

Iptables-a logging-j DROP

You can also configure the syslog.conf file to specify the log output of the iptables.

Linux--iptables Common Commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.