Basic instructions on using iptables commands

Source: Internet
Author: User
Tags 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 that it is actually very simple

IptablesA firewall can be used to create filters and NAT rules. All Linux distributions can useIptablesTherefore, understanding how to configure iptables will help you manage the Linux firewall more effectively. If you contact iptables for the first time, you will think it is very complicated, but once you understand how iptables works, you will find it very simple.

Figure: IPTables Table, Chain, and Rule Structure

I. iptables tables and links

Iptables has four built-in tables: Filter, NAT, Mangle, and Raw:

1. Filter table

Filter 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 data that is sent out.

FORWARD chain? Forward data to other Nic devices on the local machine.

2. NAT table

A nat table has three built-in links:

PREROUTING chain? Process the packets that have just arrived at the local machine and are forwarded by the route. It will convert the destination IP address (destination ipaddress) 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 (sourceNAT ).

OUTPUT chain? Processes data packets generated by the local machine.

3. Mangle table

The 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 table

The Raw table is used to handle exceptions. It has two built-in links:

PREROUTING chain

OUTPUT chain

5. Summary

Three 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 packets

DROP? Firewall discard package

QUEUE? The firewall transfers data packets to the user space.

RETURN? The firewall stops executing the subsequent Rules in the current chain and returns it to the call chain (thecalling 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 RAW table:

# Iptables-t raw? List

! Note: If you do not specify-TOnly the defaultFilterTable. 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? The special value of target mentioned above
Prot? Protocol: tcp, udp, icmp, etc.
Source? Source IP address of the data packet
Destination? Destination IP address of the data packet

III. clear all iptables rules

Before configuring iptables, do you usually need iptables? You can run the list command or the iptables-save command to check whether there are any existing rules, because you sometimes need to delete the existing iptables rules:

Iptables? Flush
Or
Iptables-F

The two commands 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 on some linux distributions, this command does not clear the rules in the NAT table. in this case, you can only manually clear the rules:

Iptables-t NAT-F

IV. permanent effect

After 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. Ubuntu

First, 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

In this way, the iptables rule is automatically loaded 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 rules

You can use the iptables-A command to append the new rule.-IndicatesAppend. 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. Syntax

Iptables-A chain firewall-rule

-A chain? Chain of the rule to be appended

Firewall-rule? Specific rule parameters

2. describe the basic parameters of the rule

The 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!-Ieth0, then allInterfaces other than eth0Incoming data packet

If-ieth 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!-Oeth0:Interfaces other than eth0Output

If-ieth appears+, Then onlyInterfaces starting with ethOutput

You can also use? Out-interfaceParameters

3. description of the extended parameters of the rule

After 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, such "? Sport ″

You can also use "? Source-port"

? -Dport destination port (destination port) for-p tcp or-pudp

Parameter and? Sport is similar

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 policy

The 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 havePolicyACCEPTAnnotation, 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 tcp dpt: ssh
DROP all? 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. At this time, although the server can receive data, it cannot send data:

# Iptables-L
Chain INPUT (Policy DROP)
Target prot opt source destination
ACCEPT tcp? Anywhere tcp dpt: ssh
DROP all? Anywhere

Chain FORWARD(Policy DROP)
Target prot opt source destination

Chain OUTPUT(Policy DROP)
Target prot opt source destination

7. configure application rules

Although Section 5.4 has introduced how to restrict connections other than SSH, it is implemented when the chain's default policy is ACCEPT and there is no limit on the output data packets. 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-mstate 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? StateNEW, ESTABLISHED-j ACCEPT

#2. allow sending SSH responses to local hosts
Iptables-a output-o eth0-p tcp? Sport 22-m state? StateESTABLISHED-j ACCEPT

-M state:State matchingmodule)

? -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.

? Sport22: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.

? Dport22: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? StateNEW, 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? StateESTABLISHED-j ACCEPT

2. HTTP

The HTTP configuration is similar to that of SSH:

#1. allow receiving HTTP requests from remote hosts
Iptables-a input-I eth0-p tcp? Dport 80-m state? StateNEW, ESTABLISHED-j ACCEPT

#1. allow sending HTTP responses to local hosts
Iptables-a output-o eth0-p tcp? Sport 80-m state? StateESTABLISHED-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? StateNEW, ESTABLISHED-j ACCEPT
Iptables-a output-o eth0-p tcp? Sport 22-m state? StateESTABLISHED-j ACCEPT

#4. allow SSH connection to the local host
Iptables-a output-o eth0-p tcp? Dport 22-m state? StateNEW, ESTABLISHED-j ACCEPT
Iptables-a input-I eth0-p tcp? Sport 22-m state? StateESTABLISHED-j ACCEPT

#5. allow HTTP requests
Iptables-a input-I eth0-p tcp? Dport 80-m state? StateNEW, ESTABLISHED-j ACCEPT
Iptables-a output-o eth0-p tcp? Sport 80-m state? StateESTABLISHED-j ACCEPT

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: 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.