Basic iptables knowledge

Source: Internet
Author: User
Tags ssh example ssh server
The iptables firewall can be used to create filters and Nat rules. All Linux distributions can use iptables. Therefore, understanding how to configure iptables will help you manage Linux firewalls more effectively. If you contact iptables for the first time, you will think it is very complicated, but once you understand the working principle of iptables, you will find it very simple.

First, we will introduce the structure of iptables: iptables-> tables-> chains-> rules. In short, tables consists of chains, which are also composed of rules. As shown in. Figure: iptables table, chain, and rule Structure I. iptables tables and linksIptables has four built-in tables: filter, Nat, mangle, and raw: 1. Filter tableFilter indicates the default table of iptables. Therefore, if you do not have a custom table, the filter table is used by default. It has the following three built-in links:
  • Input chain-Process external data.
  • Output chain-Process the data that is sent out.
  • Forward chain-Forward data to other Nic devices on the local machine.
2. NAT tableA nat table has three built-in links:
  • Prerouting chain-Process the data packets that have just arrived at the local machine and are forwarded by the route. It will convert the destination IP address (destination IP address) in the data packet, usually used for DNAT (destination Nat ).
  • Postrouting chain-Process data packets that are about to leave the local machine. It will convert the source IP address in the data packet, which is usually used for SNAT (source Nat ).
  • Output chain-Process the data packets generated by the local machine.
3. mangle tableThe mangle table is used to specify how data packets are processed. It can change the QoS bit in the TCP header. The mangle table has five built-in chains:
  • Prerouting
  • Output
  • Forward
  • Input
  • Postrouting
4. Raw tableThe raw table is used to handle exceptions. It has two built-in links:
  • Prerouting chain
  • Output chain
5. SummaryThree built-in tables of iptables are displayed: Figure: iptables built-in table Ii. iptables rules (Rules)Keep in mind the following three-point key to understanding iptables rules:
  • Rules includes a condition and a target)
  • If conditions are met, the rule or specific value in the target will be executed.
  • If the condition is not met, the next rules is determined.
Target value)The special values you can specify in target are as follows:
  • Accept-Allow the firewall to receive data packets
  • Drop-Firewall discard Packet
  • Queue-The firewall transfers data packets to the user space.
  • Return-The Firewall stops executing subsequent rules in the current chain and returns to the call chain.
If you execute iptables-list, you will see the available rules on the firewall. The following example shows that the system does not define a firewall. As you can see, it displays the default filter table and the default input chain, forward chain, and output chain in the table. # Iptables-T filter-list
Chain input (Policy accept)
Target prot opt source destination

Chain forward (Policy accept)
Target prot opt source destination

Chain output (Policy accept)
Target prot opt source destination

View the mangle table: # iptables-T mangle-list view the NAT table: # iptables-T nat-list view the raw table: # iptables-t Raw-list! Note: If you do not specify -TOnly the default FilterTable. Therefore, the following two command forms mean: # iptables-T filter-list
(Or)
# Iptables-list the following example shows that there are rules in the input chain, forward chain, and output chain of the filter table: # iptables-list
Chain input (Policy accept)
Num target prot opt source destination
1 RH-Firewall-1-INPUT all-0.0.0.0/0 0.0.0.0/0

Chain forward (Policy accept)
Num target prot opt source destination
1 RH-Firewall-1-INPUT all-0.0.0.0/0 0.0.0.0/0

Chain output (Policy accept)
Num target prot opt source destination

Chain RH-Firewall-1-INPUT (2 references)
Num target prot opt source destination
1 accept all-0.0.0.0/0 0.0.0.0/0
2 accept ICMP-0.0.0.0/0 0.0.0.0/0 ICMP Type 255
3 accept ESP-0.0.0.0/0 0.0.0.0/0
4 accept ah-0.0.0.0/0 0.0.0.0/0
5 accept UDP-0.0.0.0/0 224.0.0.20.udp DPT: 5353
6 accept UDP-0.0.0.0/0 0.0.0.0/0 udp dpt: 631
7 accept TCP-0.0.0.0/0 0.0.0.0/0 tcp dpt: 631
8 accept all-0.0.0.0/0 0.0.0.0/0 state related, established
9 accept TCP-0.0.0.0/0 0.0.0.0/0 state New tcp dpt: 22
10 reject all-0.0.0.0/0 0.0.0.0/0 reject-with ICMP-host-prohibited

The preceding output contains the following fields:
  • Num-Rule number in the specified chain
    Target-special value of the target mentioned earlier
    Prot-Protocol: TCP, UDP, ICMP, etc.
    Source-data packet source IP address
    Destination-destination IP address of the Data Packet
Iii. Clear all iptables rulesBefore configuring iptables, you usually need to use the iptables-LIST command or the iptables-save command to check whether there are existing rules, because sometimes you need to delete the existing iptables rule: iptables-flush
Or
The two commands iptables-F are equivalent. However, it is not the case that everything will go well after the execution. You still need to check whether the rules are actually cleared, because in some Linux distributions, this command does not clear the rules in the NAT table. In this case, you can only manually clear: iptables-T nat-F Iv. Permanent EffectAfter you delete or add rules, these changes do not take effect permanently. These Rules may be restored after the system is restarted. In order for the configuration to take effect permanently, the specific operations vary depending on the platform. The following is a brief introduction: 1. UbuntuFirst, save the existing rules: iptables-save>/etc/iptables. Rules, create a bash script, and save it /Etc/Network/if-pre-up.d/Directory :#! /Bin/bash
Iptables-Restore </etc/iptables. rules automatically loads the iptables rules after each system restart. ! Note: do not try to execute the above commands in. bashrc or. Profile, because the user is generally not root, and this can only load iptables rules at login. 2. centos, RedHat# Saving iptables rules
Service iptables save

# Restart the iptables service
Service iptables stop
Service iptables start

View the current rule: CAT/etc/sysconfig/iptables 5. append iptables rulesYou can use the iptables-a command to append the new rule. -Indicates Append. Therefore, The new rule is appended to the end of the chain.Generally, the last rule is used to drop all data packets. If you already have such a rule and use -Adding new rules to parameters is useless. 1. SyntaxIptables-A chain firewall-rule
  • -A chain-specify the chain to append rules
  • Firewall-rule-specific rule parameters
2. Describe the basic parameters of the ruleThe following rule parameters describe the protocol, source address, Destination Address, network interface that is allowed, and how to process these packets. These descriptions are basic descriptions of the rules. -P protocol (Protocol)
  • The Protocol of the specified rule, such as TCP, UDP, and ICMP, can be usedAllTo specify all protocols.
  • If you do not specify-PParameter, the default value isAllValue. This is unwise. always specify the protocol name.
  • You can specify the Protocol by using the Protocol name (such as TCP) or Protocol value (for example, 6 stands for TCP. For the ing relationship, see/Etc/protocols
  • You can also use-ProtocolParameter substitution-PParameters
-S source address (source)
  • Source Address of the specified data packet
  • Parameters enable IP addresses, network addresses, and host names
  • Example:-s 192.168.1.101 specified IP Address
  • For example,-s 192.168.1.10/24 specifies the network address
  • If the-S parameter is not specified, it indicates all addresses.
  • You can also use-SrcOr-Source
-D Destination Address (destination)
  • Destination Address
  • Parameters and-SSame
  • You can also use-DSTOr-Destination
-J: Execution target (jump to target)
  • -JRepresents "Jump to target"
  • -JSpecifies how data packets are processed when matching with Rules (rule ).
  • Possible values: Accept, drop, queue, return
  • You can also specify other chains as the target.
-I input interface)
  • -IInput Interface)
  • -ISpecifies the interface from which data packets are to be processed
  • These packets are about to enter the input, forward, and preroute chains.
  • For example:-I eth0Specifies the packet to be processed through eth0
  • If you do not specify-IParameter, the data packets entering all interfaces will be processed
  • If!-I eth0 will process allInterfaces other than eth0Incoming data packet
  • If-I ETH appears+Will process allInterfaces starting with ETHIncoming data packet
  • You can also use-In-InterfaceParameters
-O output (Out Interface)
  • -O"Output interface"
  • -OSpecifies the interface by which the data packet is output.
  • These packets are about to enter the forward, output, and postrouting chains.
  • If you do not specify-OAll interfaces on the system can be used as output interfaces.
  • If!-O eth0Interfaces other than eth0Output
  • If-I ETH appears+, Then onlyInterfaces starting with ETHOutput
  • You can also use-Out-InterfaceParameters
3. Description of the extended parameters of the ruleAfter a basic description of the rule, we sometimes want to specify the port, TCP flag, ICMP type, and so on. -Sport source port (source port) for-p tcp or-P UDP
  • By default, all ports are matched.
  • You can specify the port number or port name, for example, "-sport 22" and "-sport ssh ".
  • /Etc/servicesThe file describes the mappings.
  • In terms of performance, it is better to use the port number.
  • Use a colon to match the port range, for example, "-sport ″
  • You can also use "-source-port"
-- Destination port of dport (destination port) for-p tcp or-P UDP
  • The parameter is similar to-sport.
  • You can also use "-destination-port"
-- TCP-flags TCP flag for-P TCP
  • Multiple parameters separated by commas can be specified.
  • Valid values: SYN, ack, FIN, RST, URG, and Psh.
  • AvailableAllOrNone
-- ICMP-type ICMP type for-P ICMP
  • -ICMP-type 0 indicates Echo Reply
  • -ICMP-type 8 indicates echo
4. Complete append rule instance: only the SSH service is allowed.In this example, only SSH data packets are allowed to pass through the local computer, and all other connections (including ping) are rejected. #1. Clear all iptables rules
Iptables-F

#2. receive data packets whose destination port is 22
Iptables-A input-I eth0-P TCP-dport 22-J accept

#3. Reject all other data packets
Iptables-A input-J Drop

6. Change the default policyThe preceding example only filters the received data packets, but does not limit the data packets to be sent. This section describes how to change a chain policy to change the behavior of a chain. 1. Default link policy /! \ Warning: Do not test on remotely connected servers or virtual machines! When we use the-L option to verify that the current rule is found, all links have Policy acceptAnnotation, which indicates that the Default policy of the current chain is accept: # iptables-l
Chain input (Policy accept)
Target prot opt source destination
Accept TCP-anywhere Anywhere tcp dpt: SSH
Drop all-anywhere Anywhere

Chain forward (Policy accept)
Target prot opt source destination

Chain output (Policy accept)
Target prot opt source destination

In this case, if the drop rule is not explicitly added, the accept policy is used by default for filtering. Unless: A) Add drop rules for the preceding three links:Iptables-A input-J Drop
Iptables-A output-J Drop
Iptables-a forward-J Drop B) Change the default policy:Iptables-P input drop
Iptables-P output drop
Iptables-P forward drop bad !! If you configure iptables strictly in accordance with the example in the previous section and use SSH to connect, the session may have been terminated! Why? Because we have changed the output chain policy to drop. In this case, although the server can receive data, it cannot send data: # iptables-l
Chain Input (Policy drop)
Target prot opt source destination
Accept TCP-anywhere Anywhere tcp dpt: SSH
Drop all-anywhere Anywhere

Chain forward(Policy drop)
Target prot opt source destination

Chain output(Policy drop)
Target prot opt source destination

7. Configure application rulesAlthough section 5.4 has introduced how to restrict connections other than SSH, it is implemented when the default chain policy is accept and the output packet is not limited. This section describes how to set a firewall when the default link policy is drop based on the port used by SSH and HTTP. Here, we will introduce a new parameter-M state and check the Status field of the data packet. 1. SSH#1. allow receiving SSH requests from remote hosts
Iptables-A input-I eth0-P TCP-dport 22-M State-State new, established-J accept

#2. Allow sending SSH responses to local hosts
Iptables-A output-O eth0-p tcp-sport 22-M State-State established-J accept

  • -M state:State matching Module)
  • -- State:Parameters of the Status matching module. When the first data packet of the SSH client arrives at the server, the Status field is new. After the connection is established, the status fields of the data packet are all established.
  • -Sport 22:Sshd listens to port 22 and also establishes a connection with the client to transmit data. Therefore, for an SSH server, the source port is 22.
  • -Dport 22:The SSH client can establish a connection with port 22 of the SSH server from the random port of the local machine. Therefore, for the SSH client, the destination port is 22.
If the server also needs to use SSH to connect to other remote hosts, add the following configuration: #1. The destination port of the sent data packet is 22.
Iptables-A output-O eth0-p tcp-dport 22-M State-State new, established-J accept

#2. The source port of the received data packet is 22.
Iptables-A input-I eth0-P TCP-sport 22-M State-State established-J accept

2. HTTPThe HTTP configuration is similar to SSH: #1. allows the remote host to receive HTTP requests.
Iptables-A input-I eth0-P TCP-dport 80-M State-State new, established-J accept

#1. Allow sending HTTP responses to local hosts
Iptables-A output-O eth0-p tcp-sport 80-M State-State established-J accept

3. Complete Configuration#1. delete an existing rule
Iptables-F

#2. Configure the default link policy
Iptables-P input drop
Iptables-P forward drop
Iptables-P output drop

#3. Allow SSH connections to remote hosts
Iptables-A input-I eth0-P TCP-dport 22-M State-State new, established-J accept
Iptables-A output-O eth0-p tcp-sport 22-M State-State established-J accept

#4. Allow SSH connection to the local host
Iptables-A output-O eth0-p tcp-dport 22-M State-State new, established-J accept
Iptables-A input-I eth0-P TCP-sport 22-M State-State established-J accept

#5. allow HTTP requests
Iptables-A input-I eth0-P TCP-dport 80-M State-State new, established-J accept
Iptables-A output-O eth0-p tcp-sport 80-M State-State established-J accept

References[1] Linux Firewall Tutorial: iptables tables, chains, rules fundamentals [2] iptables flush: delete/remove all rules on Redhat and centos Linux [3] Linux iptables: how to add firewall rules (with allow SSH example) [4] Linux iptables: incoming and outgoing rule examples (SSH and HTTP) [5] 25 most frequently used Linux iptables rules examples [6] MAN 8 iptables

Basic iptables knowledge

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: info-contact@alibabacloud.com 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.