iptables of linux Firewall

preface

Firewall of Linux system - netfilter/iptables: IP packet filtering system, which is actually composed of two components, netfilter and iptables.
It mainly works at the network layer for IP packets. It is reflected in the processing of IP address, port and other information in the packet.

1, Relationship between netfilter and iptables

(1)netfilter

netfilter: it belongs to the firewall functional system of "Kernel Space" (also known as Kernel Space). It is a part of the kernel and consists of some packet filtering tables. These tables contain the rule set used by the kernel to control packet filtering processing.

(2)iptables

Iptables: firewall management system belonging to "User Space" (also known as User Space). Is a command program used to manage the Linux firewall. It makes it easy to insert, modify and delete the rules in the packet filtering table. It is usually located in the / sbin/iptables directory.

netfilter/iptables is later referred to as iptables. Iptables is a kernel based firewall, which has built-in four rule tables: raw, mangle, nat and filter. After all the rules in the table are configured, they will take effect immediately without restarting the service.

2, Four tables and five chains

Function of rule table: to accommodate various rule chains
Role of rule chain: to accommodate various firewall rules
There are chains in the outside and rules in the chain

(1) Four tables

raw table: determines whether to track the status of the packet. It contains two rule chains, OUTPUT and preouting.
mangle table: modify the content of the data packet, use it for traffic shaping, and set a flag for the data packet. It contains five rule chains: INPUT, OUTPUT, FORWARD, preouting and POSTROUTING.
nat table: it is responsible for network address translation and is used to modify the source, destination IP address or port in the packet. It contains three rule chains: OUTPUT, preouting and POSTROUTING.
filter table: it is responsible for filtering the data packet and determining whether to release the data packet (filtering). It contains three rule chains: INPUT, FORWARD and OUTPUT.
#Among the four rule tables of iptables, mangle table and raw table are relatively less used.

(2) Five chains

INPUT: process inbound packets and match the packets whose target IP is local.
OUTPUT: Processing outbound packets. Generally, it is not configured on this chain.
FORWARD: process and FORWARD packets and match the packets flowing through the machine.
Preouting chain: process packets before routing, which is used to modify the destination address and make DNAT. It is equivalent to mapping port 80 in the intranet to the router's extranet port.
POSTROUTING chain: processing packets after routing, which is used to modify the source address and make SNAT. It is equivalent to that the intranet host accesses the Internet through a public IP address through the NAT conversion function of the router.

(3) The priority between rule tables when packets arrive at the firewall

When the packet arrives at the firewall, the priority between the rule tables:
raw > mangle > nat > filter

(4) Matching order between rule chains

1. Host firewall

Inbound data (packets from the outside, and the destination address is firewall native): preouting -- > Input -- > native application
Outbound data (packets sent from the firewall to external addresses): native application -- > output -- > postrouting

2. Network firewall

Forwarding data (packets that need to be forwarded through the firewall): forwarding -- > forward -- > postrouting

3. Matching order within the rule chain:

Check in order from top to bottom, and stop when you find the matching rule (LOG policy exception, which means recording relevant logs)
If no matching rule is found in the chain, it will be handled according to the default policy of the chain (if it is not modified, the default policy is allowed)

3, Installation of iptables

CentOS 7 Default use firewalld Firewall, not installed iptables´╝îIf you want to use iptables Firewall. Must be closed first firewalld Firewall, reinstall iptables
systemctl stop firewalld.service
systemctl disable firewalld.service

yum -y install iptables iptables-services
systemctl start iptables.service

(1) Configuration method of iptables firewall

1,use iptables Command line.
2,use system-config-firewall  (Desktop environment)

(2) iptables command line configuration method

Command format:

iptables [-t Table name] Management options [Chain name] [Matching conditions] [-j control type]

matters needing attention:
When the table name is not specified, it refers to the filter table by default
When the chain name is not specified, it refers to all chains in the table by default
You must specify matching criteria unless you set the default policy for the chain
Options, chain names and control types use uppercase letters, and the rest are lowercase

Common control types:
ACCEPT: allow packets to pass.
DROP: directly discard the data packet without giving any response information.
REJECT: if the packet is rejected, a response message will be sent to the data sender.
SNAT: modify the source address of the packet.
DNAT: modify the destination address of the packet.
MASQUERADE: disguised as a non fixed public IP address.
LOG: record the LOG information in the / var/log/messages file, and then pass the packet to the next rule. LOG is only an auxiliary action and does not really process data packets.

Common management options:
-A: Append (– append) a new rule to the end of the specified chain
-1: Insert (– insert) a new rule at the beginning of the specified chain. If no sequence number is specified, it will be the first rule by default
-R: Modify, replace (– replace) specifies a rule in the chain. You can specify the sequence number or specific content of the rule
-P: Set the default policy for the specified chain (– Policy)
-D: Delete (– delete) a rule in the specified chain. You can specify the sequence number or specific content of the rule
-F: Clear (– flush) all rules in the specified chain. If no chain name is specified, all chains in the table will be cleared
-50: L ist (– list) all rules in the specified chain. If no chain name is specified, all chains in the table will be listed
-n: Display the output in numeric form (– numeric), such as IP address instead of host name
-v: Displays details, including the number of matching packets and bytes per rule
– line numbers: displays the sequence number of the rule when viewing the rule

Add a new rule:
iptables -t filter -A INPUT -p icmp -j REJECT
iptables -I INPUT 2 -p tcp --dport 22 -j ACCEPT

To view a list of rules:
iptables [-t table name] - n -L [chain name] [– line numbers]
or
iptables -[vn]L # note: it cannot be written as - Ln
iptables -n -L --line-numbers

Set default policy:
iptables [-t table name] - P < chain name > < control type >
iptables -P INPUT DROP
iptables -P FORWARD DROP
#Generally, when setting network firewall and host firewall in the production environment, the default rule should be DROP and the white list should be set

Delete rule:
iptables -D INPUT 2
iptables -t filter -D INPUT -p icmp -j REJECT

be careful:
1. If there are multiple identical rules in the rule list, only the one with the smallest serial number will be deleted according to the content matching
2. When matching and deleting by number, ensure that the rule number is less than or equal to the number of existing rules, otherwise an error will be reported
3. When matching the deletion number according to the content, ensure that the rule exists, otherwise an error will be reported

Empty rule:
iptables [-t table name] - F [chain name]
iptables -F INPUT
iptables -F

be careful:
1.-F only clears the rules in the chain and does not affect the default rules set by - P. the default rules need to be modified manually
2. When DROP is set for - P, be careful when using - F!
#Prevent the host from being unable to connect remotely after clearing the relevant rules that allow remote connection. If the rules are not saved, restart the host
3. If the table name and chain name are not written, all rules in all chains in the filter table will be cleared by default

(3) Rule matching

1. General matching

It can be used directly without relying on other conditions or extensions, including network protocol, IP address, network interface and other conditions.

Agreement matching:-p Protocol name
 Address match:-s Source address-d Destination address	#Can be IP, network segment, domain name, empty (any address)
Interface matching:-i Inbound network card-o Outbound network card
Example:
iptables -A FORWARD ! -p icmp -j ACCEPT 
iptables -A INPUT -s 192.168.80.11 -j DROP
iptables -I INPUT -i ens33 -s 192.168.80.0/24 -j DROP

2. Implicit matching

Specific protocol matching is required as the premise, including port, TCP tag, ICMP type and other conditions.

Port matching:--sport Source port--dport Destination port
#It can be individual port or port range
--sport 1000			Packet with matching source port of 1000
--sport 1000:3000		The matching source port is 1000-3000 Data packet
--sport :3000			Packets with matching source ports of 3000 and below
--sport 1000:			Packets with matching source ports of 1000 and above
 be careful:--sport and --dport Must cooperate -p <Protocol type> use
Example:
iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT
iptables -I FORWARD -d 192.168.80.0/24 -p tcp --dport 24500:24600 -j DROP

TCP tag matching

TCP Mark match:--tcp-flags TCP sign
iptables -I INPUT -i ens33 -p tcp --tcp-flags SYN,RST,ACK SYN -j ACCEPT
#Discard the SYN request package and release other packages

ICMP type matching

ICMP Type matching:--icmp-type ICMP type		
#Can be string, numeric code, target unreachable
"Echo-Request"(Code 8) indicates a request
"Echo-Reply"(Code 0) indicates echo
"Destination-Unreachable"(Code 3) indicates that the target is unreachable
 About other available ICMP Protocol type, executable“ iptables -p icmp -h"Command, view help information
iptables -A INPUT -p icmp --icmp-type 8 -j DROP		#Prohibit other hosts from ping ing this machine
iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT	#Allow this machine to ping other hosts

iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT	#When the local machine cannot ping other hosts, it will prompt that the target is unreachable
#At this time, other hosts need to configure the control type of icmp Protocol as REJECT
iptables -A INPUT -p icmp -j REJECT					

3. Explicit matching

It is required to specify the type in the form of "- m expansion module", including multi port, MAC address, IP range, packet status and other conditions.

Multi port matching

Multi port matching:-m multiport --sports Source port list
-m multiport --dports Destination port list
Example:
iptables -A INPUT -p tcp -m multiport --dport 80,22,21,20,53 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dport 53 -j ACCEPT

MAC address matching

MAC Address match:-m mac --mac-source MAC address
iptables -A FORWARD -m mac --mac-source xx:xx:xx:xx:xx:xx -j DROP
#Prohibit packets from a MAC address from being forwarded locally

IP range matching

IP Range matching:-m iprange --src-range IP Range
iptables -A FORWARD -p udp -m iprange --src-range 192.168.80.100-192.168.80.200 -j DROP			
#It is forbidden to forward udp packets whose source addresses are 192.168.80.100-192.168.80.200

State matching

Status matching:-m state --state Connection status
 Common connection states:
NEW : It has nothing to do with any connection. The connection has not started yet
ESTABLISHED : In response to a request or a connection has been established, the connection status is
RELATED : Related to existing connections (e.g FTP Data connection of active and passive mode), derivative ecology, generally with ESTABLISHED Use together
INVALID : It cannot be recognized which connection it belongs to or has no state
iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP
#Forwarding of non --syn request packets (such as forged network attack packets) unrelated to normal TCP connection is prohibited

4. Host type firewall is required

iptables -I INPUT -p tcp -m multiport --dport 80,22,21,20,53 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dport 53 -j ACCEPT			
iptables -I INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -P INPUT DROP 

4, SNAT principle and Application

1. SNAT application environment

LAN hosts share a single public IP address to access the Internet (private can not be earlier than normal routing in the Internet)

2. SNAT principle

Modify the source address of the packet.

3. SNAT conversion prerequisites

Each host of LAN has correctly set IP address, subnet mask and default gateway address

Linux gateway turns on IP routing forwarding

4. Open mode

(1) Temporary opening (restart failure)

echo 1 > /proc/sys/net/ipv4/ip_forward
 or
sysctl -w net.ipv4.ip_forward=1

(2) Permanently open

vim /etc/sysctl.conf
net.ipv4.ip_forward = 1 		#Write this line to the configuration file

sysctl -p 						#Read the modified configuration

5. SNAT conversion

(1) SNAT conversion ---- fixed public IP address

iptables -t nat -A POSTROUTING -s 192.168.80.0/24 -o ens33 -j SNAT --to 12.0.0.1
 or
iptables -t nat -A POSTROUTING -s 192.168.80.0/24 -o ens33 -j SNAT --to-source 12.0.0.1-12.0.0.10
									Intranet IP	     Outbound extranet card                 Extranet IP Or address pool	

(2) SNAT conversion ---- non fixed public IP address (shared dynamic IP address)

iptables -t nat -A POSTROUTING -s 192.168.80.0/24 -o ens33 -j MASQUERADE

Small knowledge expansion:
SNAT conversion of an IP address can generally enable 100 to 200 hosts in the intranet to access the Internet.

5, Principle and application of DNAT

1. DNAT application environment

Publish servers located in a local area network on the Internet

2. DNAT principle

Modify the destination address of the packet

3. Prerequisites for DNAT conversion

LAN servers can access the Internet
The gateway's Internet address has the correct DNS resolution record
Linux gateway turns on IP routing forwarding

4. Opening mode of DNAT

vim /etc/sysctl.conf
net.ipv4.ip_forward = 1 	

sysctl -p 			

5. Conversion of DNAT

(1) DNAT conversion ---- publish Web services of Intranet

#The destination address of the packet coming in from ens33 to access the web service is converted to 192.168.80.10
iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 80 -j DNAT --to 192.168.80.10
 or
iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 80 -j DNAT --to-destination 192.168.80.10
                             Inbound external network card IP											   Intranet server IP
 iptables -t nat -A PREROUTING -i ens33 -p tcp --dport 80 -j DNAT --to 192.168.80.10-192.168.80.20

(2) DNAT conversion 2 ------ modify the target port when publishing

#Publish the OpenSSH server inside the LAN, and the external network host needs to use port 250 for connection
iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 250 -j DNAT --to 192.168.80.10:22

#Using SSH test in extranet environment
ssh -p 250 root@12.0.0.1

yum -y install net-tools 		#If there is no ifconfig command, you can use yum to install it in advance
ifconfig ens33


Note: use DNAT At the same time, there is cooperation SNAT The correct return of the response packet can only be realized by using

Small knowledge expansion:
Host firewalls mainly use INPUT and OUTPUT chains. When setting rules, it is generally necessary to specify the ports in detail
The network firewall mainly uses the FORWARD chain. When setting rules, it is rarely specified to the port. Generally, it can be specified to the IP address or to the network segment

6, Backup and restore of firewall rules

1. Rules for exporting (backing up) all tables

iptables-save > /opt/ipt.txt

2. Import (restore) Rules

iptables-restore < /opt/ipt.txt

Save the iptables rule file in / etc/sysconfig/iptables. When the iptables service starts, the rules will be restored automatically

iptables-save > /etc/sysconfig/iptables
systemctl stop iptables						#Stopping iptables service will clear the rules of all tables
systemctl start iptables					#Starting iptables service will automatically restore the rules in / etc/sysconfig/iptables

Tags: Linux

Posted by wolfrat on Sat, 16 Apr 2022 00:57:03 +0930