Iptables understand + Practice

Practice of Iptables

brief introduction

*Netfilter/Iptables (hereinafter referred to as Iptables) is an excellent and open-source completely free firewall tool based on packet filtering in unix/linux. It has very powerful functions and flexible use. It can finely control the data packets flowing into and out of the server. In particular, it can run very well under a very low hardware configuration (I have deployed gateway firewall in the case of Celeron 500HZ cpu 64M memory) providing Internet service for nearly 400 people is no less than enterprise level professional router firewall)*
Iptables is an integrated service in linux 2.4 and 2.6 kernels. Its function and security are much more powerful than its older generation ipfadn and ipchains. Iptables mainly works in the second, third and fourth layers of OSI layer 7. If the kernel is recompiled, iptables can also support layer 7 control (squid agent + iptables).

Name concept:

  • Container: a relationship that contains or belongs to
  • Netfilter/Iptables are containers for tables (four tables)
  • beyond the limits of the visible world
    • Filter: filter packets
    • nat: used for network address translation (IP, port)
    • mangle: modify the service type and TTL of the packet, and configure the route to realize QOS
    • raw table: determines whether the packet is processed by the state tracking mechanism
    • The first three common
  • The table of IP tables is also the container of chain (five chain)
    • INPUT chain: filter packets entering the host
    • OUTPUT chain: process packets sent from the host
    • FORWARD chain: it is responsible for forwarding data packets flowing through the host and plays the role of forwarding, which is closely related to the Nat table
    • Preouting chain: when the external reports of the host enter the location, all data packets are processed by this chain first
    • POSTROUTING chain: the message is forwarded through the route, and all data packets are processed by this chain first
    • Note that the chain name is capitalized
  • chains are containers of rules
  • policy: filter statements one by one

Note: the control of filter table is an important means for us to realize the function of local firewall, especially the control of INPUT chain

Table commonly used in four tables

Nat table

Responsible for network address translation, that is, the conversion of source and destination ip addresses and ports. Application: it has nothing to do with the host itself. It is generally used for LAN sharing, Internet access or special port conversion services
NAT function general enterprise working scenarios:
1) ) used for enterprise routing (zebra) or gateway (iptables), shared Internet access (POSTROUTING)2) internal and external P address one-to-one mapping (dmz), hardware firewall mapping I to internal server, ftp service. (PREROUTING).
3) web, single port mapping, direct mapping of port 80 (provisioning).
This table defines three chains. The nat function is equivalent to the acl control of the network. Similar to network switch acl

Table related chains

  • OUTPUT: related to packets sent by the host
  • INPUT: related to packets entering the host
  • Routing: the rules executed before routing when a packet arrives at the firewall are used to change the destination address and port of the packet. (popular metaphor is to rewrite the recipient's address according to the rules when receiving the message, which looks very unorthodox! Ha ha.) For example: public IP: 124.42 60.113 mapping to LAN 10.0 0.19 on the server. If it is a web service, you can convert 80 to 9000 port on the server of the LAN.
  • POSTROUTING: a rule executed after routing judgment when a packet leaves the firewall. Its function is to change the source address, source port, etc. of the packet. (popular metaphor is to write the sender's address when sending a letter, so that others can have an address to reply to when replying.), For example, our current notebooks and virtual machines are 10.0 0.0/24 means that our enterprise router changed the source address to the public address when we went out of the network. Production application: LAN sharing and Internet access.

Filter table

Emphasis: it is mainly related to the host itself and is really responsible for the firewall function of the host (filtering incoming and outgoing data packets). The filter table is the table used by iptables by default. This table defines three chains: Enterprise work scenario: host firewall.

Table related chains

  • INPUT: it is responsible for filtering all packets whose destination address is the local address. Generally speaking, it is to filter packets entering the host
  • FORWARD: data packets with load flowing through the host are used for forwarding, which is closely related to the nat table
  • OUTPUT: responsible for processing packets sent from the host

Iptables process (writing helps understand)

Flow into the machine: PREROUTING  -->  INPUT  --> PROCESS(process)
After this machine: PREROUTING  --> FORWARD --> POSTROUTING
 Outflow from the machine: PROCESS(process) -->  OUTPUT --> POSTROUTING

Workflow diagram of iptables table and chain

iptables filter graph

iptables works with packet filtering mechanism, so it will analyze the header data of the requested packet and match it according to our preset rules to determine whether it can enter the host.

* The firewall is filtered layer by layer. It is actually filtered from top to bottom and from front to back according to the order of configuration rules
* If the upper rule is matched, that is, it clearly indicates whether to block or pass, the packet will no longer match the new rule downward
* If all rules do not specify whether to block or pass, that is, there is no matching rule, match down until the matching default rule is explicitly blocked or passed
* Firewall default rules are executed only after all the rules in the corresponding chain are executed
* Iptalbes The execution order of firewall rules is from front to back (from top to bottom) by default. In case of matching rules, you will not continue to check downward. Only in case of mismatched rules, you will continue to match downward.
	
# Note: if the reject rule DROP is written on the top layer, the following rules will not be matched for execution, so you can insert a new rule to the top layer with the - I parameter

Iptables installation

  • Check whether iptables: systemctl status iptables is installed
  • Install iptables: yum install iptables* -y
  • Start iptables: systemctl start iptables
  • Turn off the firewall: systemctl disable --now firewalld
  • Close selinux: vim /etc/selinux/config

Iptables command description

Format: iptables [-t table name] [parameter chain name] [parameter protocol] [parameter port] [parameter action]

The parameter table is as follows:

Parameter symbol explain
-t Specifies the table for the operation
-L List current rules
-v Displays packets and packet sizes
-n Do not reverse address
-A Append a rule to the chain
-I Insert a rule to the top
-F empty
-Z Clear counter (number of packets, packet size)
-D Delete rules in the chain
-R Modify rules
-S List all rules
-N Create a custom chain
-X Delete a custom chain
-P Specifies the default policy for the chain

iptables protocol table is as follows:

Condition / agreement name explain
TCP Match according to TCP protocol, and http belongs to TCP
UDP Match by UDP protocol
ICMP Match according to ICMP Protocol, similar to ping
ALL All agreements are OK

👉 [UDP protocol and TCP protocol]( TCP/UDP protocol_ Baidu Encyclopedia (baidu.com))

👉 [ICMP Protocol]( ICMP_ Baidu Encyclopedia (baidu.com))

Port matching parameters

parameter explain
--sport Source port, port to send request
--dport Target port

”The action table is as follows:

"Action name" explain
ACCEPT Release the data packet. After this processing, it will no longer compare other rules and directly jump to the next rule chain
REJECT Block the packet and transmit the packet to notify the other party
DROP The discarded packet will not be processed. After this processing action, the filter program will be directly interrupted without comparing other rules
REDIRECT Redirect the package to another port. After this processing, it will continue to compare other rules

-i. - o, - m, - j, - s, - d parameters, which can specify network card, module, action, protocol and address

parameter explain
-i Incoming network card
-o Outgoing network card
-m Specify module
-j Actions performed (above table)
-p Specify protocol
-s Source address, address to send the request
-d Destination address

Iptables common commands

iptables -h query help

iptables -L -v lists all rules (filter table)

iptables -L -n lists (filter table, default) all rules (difference - v, - n is the version without reverse interpretation)

iptables -L -n -t nat list (nat table) all rules

iptables -F clear (filter table) all rules

iptables -F -t nat clears all rules in (nat table)

service iptables save saves the configuration (iptables must be restarted after saving the configuration)

systemctl restart iptables restart

Iptables common syntax

-A: Append to last rule

-D: Delete record

-1: Add to first rule

-p: (proto) specifies the communication protocol. The common protocols are tcp, udp, icmp and all

-j: (jump) specifies the target to jump. There are three common targets: ACCEPT (receive packet), DROP (DROP packet) and REJECT (redirect). However, redirection is generally not applicable, which will bring security risks

Common cases

Case 1: only port 22 (target port) is allowed to be accessed, and all other ports cannot be accessed
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP
[root@m01 ~]# iptables -L -v
# View (the result is too long to write)
[root@m01 ~]# iptables -L -v

Case 2: only ports 22 and 80443 are allowed to access (target port), and all other ports cannot be accessed. 
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 22  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 80  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 443  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP   -j DROP
# At this time, the response to Baidu timed out. I don't know the curl port
[root@m01 ~]# curl www.baidu.com
curl: (7) Failed connect to www.baidu.com:80; Connection timed out

Case 3: only ports 22 and 80443 are allowed to access, and all other ports cannot be accessed, but this machine can access Baidu. 
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 22  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 80  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 443  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP

Case 4: it is required to be able to link address 192 through port 22 (target port).168.15.81(Destination address), but others can't
# Popular understanding: you can connect to 192.168 through port 22 15.81 address, 192.168 15.81:22
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -d 192.168.15.81 --dport 22  -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP
# You can pass the new window test or the new virtual machine test	

Case 5: address required 192.168.15.71(Source address) allows connection to address 192 through port 22 (target port).168.15.81(Destination address), others can't
[root@m01 ~]# iptables -t filter -A INPUT -p  TCP -s 192.168.15.71  -d 192.168.15.81 --dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP
# You can connect 81 from 71. 81 has been disconnected

Case 6: requirements 192.168.15.71 Invisible to the outside
[root@prometheus ~]# iptables -t filter -A INPUT -p TCP -d 192.168.15.71 -j DROP
# This is equivalent to that the address in the virtual machine is not visible to the outside, and the virtual machine will not be connected

Case 7: required use eth0 All requests from the network card are rejected(Come in the network card and connect the virtual machine)
[root@prometheus ~]# iptables -t filter -A INPUT -p TCP -i etho -j DROP
 Case 8: use eth1 The network card login window does not allow access to Baidu.(Go out of the network card and connect the virtual machine)
[root@prometheus ~]# iptables -t filter -I OUTPUT -p TCP -o eth1 -j DROP

Case 9: request to access port 8080 of the server and forward to port 80
[root@m01 ~]# iptables -t nat -A PREROUTING -p TCP --dport 8080 -j REDIRECT --to-port 80

Case 10: requirement only allowed windows adopt ssh Connection 192.168.15.81,Other rejections
# First check the address under windows: ipconfig > wmnet8 > IPv4 address
[root@m01 ~]# iptables -t filter -I INPUT -p TCP -s 192.168.15.1 -d 192.168.15.81 --dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 22 -j DROP


# IP filtering
# Prohibition 192.168 1.3 all types of data access for IP addresses
iptables -A INPUT ! -s 192.168.1.3 -j DROP

# Open port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT #Open port 80

# Open port range
iptables -I INPUT -p tcp --dport 22:80 -j ACCEPT #Develop ports in the 22-80 range

# Port 80 is not allowed to flow out
iptables -I OUTPUT -p tcp --dport 80 -j DROP

# filter is the default table. It can be unspecified or specified

modular

-m: Specify module

multiport module

Continuously match multiple ports

  • Parameters: - dports means to specify multiple ports (different ports are separated by commas, and consecutive ports are separated by colons)
# Case: all ports between 22, 80443 and 30000-50000 are required to be exposed, and other ports are rejected
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -m multiport --dports 22,80,443,30000:50000 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP

iprange module

Specify a contiguous range of ip addresses

  • Parameters:
    • --SRC range from [- to]: source address range
    • --DST range from [- to]: target address range
# Case: requirement 192.168 15.1 - 192.168. All IP addresses between 15.10 can be connected to 192.168 15.81, other rejections
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -m iprange --src-range 192.168.15.1-192.168.15.10 -j ACCEPT 
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP

string module

Matches the specified string

  • parameter
    • --string pattern: Specifies the string to match
    • --algo {bm|kmp}: matching query algorithm
# Case: it is required to access the data containing HelloWorld in the data package. It is not allowed to pass through
[root@m01 ~]# cd /usr/share/nginx/html/
[root@m01 html]# rm -rf ./*
[root@m01 html]# echo "Helloworld" > index.html
[root@m01 html]# echo "Hello" > demo.html

# rule
[root@m01 html]# iptables -t filter -A INPUT -p TCP -m string --string "Helloworld" --algo kmp -j DROP

[root@m01 html]# curl http://192.168.15.81/demo.html
Hello
[root@m01 html]# curl http://192.168.15.81/index.html


# Helloworld was filtered out

time module

Match packets according to time period

  • Parameters:
  • --timestart hh:mm[:ss]: start time
  • --timestop hh:mm[:ss]: end time
  • --monthdays day[,day...] : Specify a day of the month
  • --weekdays day[,day...] : Specify week or Sunday
# Case: it is required to be between 22 and 23 every day, and access is not allowed
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -m time --timestart 14:00  --timestop 15:00 -j DROP

# Note that the time used here is UTC, remember - 8

icmp module[

ping is forbidden. By default, the machine cannot ping others and others cannot ping itself

  • Parameters: - ICMP type {type [/ code] |typename}
  • Echo request (8)
  • Echo reply (0) response
# It is required that others cannot Ping this machine, but this machine can ping others (optimization common case 3)
[root@m01 ~]# iptables -t filter -A INPUT -p ICMP -m icmp --icmp-type "echo-request" -j DROP
# ping Baidu locally
[root@m01 ~]# ping www.baidu.com
PING www.a.shifen.com (112.80.248.76) 56(84) bytes of data.
64 bytes from 112.80.248.76 (112.80.248.76): icmp_seq=1 ttl=128 time=15.1 ms
# Others cannot ping this machine
[root@m01 ~]# ping 192.168.15.81
PING 192.168.15.81 (192.168.15.81) 56(84) bytes of data.

connlimit module

Limit the number of concurrent connections

  • parameter
    • --Connlimit upto n: match if the number of existing connections is less than or equal to n
    • --Connlimit above n: match if the number of existing connections is greater than n
# A maximum of 2 host connections are required (two windows at most)
[root@m01 ~]# iptables -t filter -A INPUT -p TCP --dport 22 -m connlimit --connlimit-above 2 -j DROP

limit module

Limit the message rate; Seconds, minutes, hours, days.

  • parameter
    • --limit rate[/second|/minute|/hour|/day]: number of messages
    • --Limit burst number: number of messages (default: 5)
# Case: it is required to limit the rate to about 500k/s, about 333 packets per second
# Generate a test file
[root@m01 ~]# dd if=/dev/zero of=a.txt bs=100M count=10
10+0 records in
10+0 records out
1048576000 bytes (1.0 GB) copied, 7.64477 s, 137 MB/s
# Speed limit (control is inaccurate!)
[root@m01 ~]# iptables -t filter -A OUTPUT -p TCP -m limit --limit 333/s -j ACCEPT
[root@m01 ~]# iptables -t filter -A OUTPUT -p TCP -j DROP
	
# transmission
[root@m01 ~]# scp a.txt root@192.168.15.71:/root

Transmission is inaccurate, slowly decreasing until stable!

Supplementary knowledge:

View centos version

cat    /etc/redhat-release       

To view commands occupied by local ports:

Command: netstat -nutlp

[root@m01 ~]# netstat -nutlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1591/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1304/sshd           
tcp6       0      0 :::80                   :::*                    LISTEN      1591/nginx: master  
tcp6       0      0 :::22                   :::*                    LISTEN      1304/sshd 

iptables script settings

!/bin/sh

iptables -P INPUT ACCEPT
iptables -F
iptables -X
iptables -Z
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
service iptables save
systemctl restart iptables.service

## Supplementary cases

> Enterprise case

If the log file`/var/logmessages`appear: kernel: nf_conntrack:table full,droppint packet,The solution is as follows:

```bash
# The above results will make business access very slow
net.nf_conntack_max = 250000000
net.netfilter.nf_conntrack_max = 250000000
# Shorter response time
net.netfilter.nf_conntrack_timeout_established = 170
net.netfilter.nf_conntrack_timeout_wait = 120
net.netfilter.nf_conntrack_timeout_close_wait= 60
net.netfilter.nf_conntrack_timeout_fin_wait = 100

Error prone point

After setting iptables rules, service iptables save sometimes fails to start

When installing iptables in the first step, please use yum install -y iptables. Otherwise, some packages are not available. The packages installed by default are incomplete

When filtering ports, it's easy to kill yourself. Just clear all rules from the virtual machine

[please correct any mistakes, thanks for your correction]

Keywords: Linux

Added by donbonzo on Wed, 29 Dec 2021 21:29:02 +0200