Detailed explanation of iptables, a commonly used firewall software on Linux

iptables

Commonly used firewall software on Linux
recommends Linux command online tools: linux command online query tool

Supplementary Note

The iptables command is commonly used firewall software on Linux and is part of the netfilter project. Can be configured directly or through a number of frontends and graphical interfaces.

grammar

iptables(选项)(参数)

options

-t, --table table 对指定的表 table 进行操作, table 必须是 raw, nat,filter,mangle 中的一个。如果不指定此选项,默认的是 filter 表。

# 通用匹配:源地址目标地址的匹配
-p:指定要匹配的数据包协议类型;
-s, --source [!] address[/mask] :把指定的一个/一组地址作为源地址,按此规则进行过滤。当后面没有 mask 时,address 是一个地址,比如:192.168.1.1;当 mask 指定时,可以表示一组范围内的地址,比如:192.168.1.0/255.255.255.0。
-d, --destination [!] address[/mask] :地址格式同上,但这里是指定地址为目的地址,按此进行过滤。
-i, --in-interface [!] <网络接口name> :指定数据包的来自来自网络接口,比如最常见的 eth0 。注意:它只对 INPUT,FORWARD,PREROUTING 这三个链起作用。如果没有指定此选项, 说明可以来自任何一个网络接口。同前面类似,"!" 表示取反。
-o, --out-interface [!] <网络接口name> :指定数据包出去的网络接口。只对 OUTPUT,FORWARD,POSTROUTING 三个链起作用。

# 查看管理命令
-L, --list [chain] 列出链 chain 上面的所有规则,如果没有指定链,列出表上所有链的所有规则。

# 规则管理命令
-A, --append chain rule-specification 在指定链 chain 的末尾插入指定的规则,也就是说,这条规则会被放到最后,最后才会被执行。规则是由后面的匹配来指定。
-I, --insert chain [rulenum] rule-specification 在链 chain 中的指定位置插入一条或多条规则。如果指定的规则号是1,则在链的头部插入。这也是默认的情况,如果没有指定规则号。
-D, --delete chain rule-specification -D, --delete chain rulenum 在指定的链 chain 中删除一个或多个指定规则。
-R num:Replays替换/修改第几条规则

# 链管理命令(这都是立即生效的)
-P, --policy chain target :为指定的链 chain 设置策略 target。注意,只有内置的链才允许有策略,用户自定义的是不允许的。
-F, --flush [chain] 清空指定链 chain 上面的所有规则。如果没有指定链,清空该表上所有链的所有规则。
-N, --new-chain chain 用指定的名字创建一个新的链。
-X, --delete-chain [chain] :删除指定的链,这个链必须没有被其它任何规则引用,而且这条上必须没有任何规则。如果没有指定链名,则会删除该表中所有非内置的链。
-E, --rename-chain old-chain new-chain :用指定的新名字去重命名指定的链。这并不会对链内部造成任何影响。
-Z, --zero [chain] :把指定链,或者表中的所有链上的所有计数器清零。

-j, --jump target <指定目标> :即满足某条件时该执行什么样的动作。target 可以是内置的目标,比如 ACCEPT,也可以是用户自定义的链。
-h:显示帮助信息;

Basic parameters

parameter effect
-P Set the default policy: iptables -P INPUT (DROP
-F clear rule chain
-L View rule chain
-A Add new rules at the end of the rule chain
-I num add a new rule at the head of the rule chain
-D num delete a rule
-s Match the source address IP/MASK, adding an exclamation mark "!" indicates that this IP is excluded.
-d match target address
-i The network card name matches the data flowing from this network card
-o The network card name matches the data flowing from this network card
-p Matching protocols, such as tcp, udp, icmp
–dport number Match destination port number
–sport num Match source port number

Command option input order

iptables -t 表名 <-A/I/D/R> 规则链名 [规则号] <-i/o 网卡名> -p 协议名 <-s 源IP/源子网> --sport 源端口 <-d 目标IP/目标子网> --dport 目标端口 -j 动作

Working Mechanism

The rule chain names include (also known as five hook functions):

  • INPUT chain : process input packets.
  • OUTPUT chain : handle output packets.
  • FORWARD chain : handle forwarding packets.
  • PREROUTING chain : used for destination address translation (DNAT).
  • POSTOUTING chain : used for source address translation (SNAT).

firewall policy

Firewall policies are generally divided into two types, one is called policy, the other is called policy, through policy, the default door is closed, and it is necessary to define who can enter. The blocking strategy is that the door is open, but you must have identity authentication, otherwise you cannot enter. So we have to define, let what comes in, let what goes out, 所以通,是要全通,而堵,则是要选择. When we define a policy, we need to define multiple functions separately, among which: define the policy that is allowed or not allowed in the data packet, the function of filter filtering, and the function of defining the address translation is the nat option. In order to allow these functions to work alternately, we have formulated the definition of "table" to define and distinguish various work functions and processing methods.

We now use three functions for comparing multiple functions:

  1. The filter defines whether it is allowed or not, and it can only be done on 3 chains: INPUT, FORWARD, OUTPUT
  2. Nat defines address translation, and it can only be done on three chains: PREROUTING, OUTPUT, POSTROUTING
  3. Mangle function: modify the original data of the message, which can be done in 5 chains: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING

We modify the original data of the message to modify the TTL. It is possible to disassemble the metadata of the data packet and mark/modify the content inside. The firewall mark is actually realized by mangle.

Small extension:

  • For filters, generally only three chains can be used: INPUT, FORWARD, OUTPUT
  • For nat, it can only be done on three chains: PREROUTING, OUTPUT, POSTROUTING
  • And mangle can do 5 chains: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING

iptables/netfilter (this software) works in user space, it can make the rules take effect, it is not a service itself, and the rules take effect immediately. And our iptables is now made into a service that can be started and stopped. If it is started, the rule will be directly effective, and if it is stopped, the rule will be revoked.

iptables also supports self-defined chains. But the chain you define must be associated with a specific chain. In a level setting, specify that when there is data, go to a specific chain for processing, and return after that chain is processed. Then continue checking in the specific chain.

Note: The order of the rules is very critical, 谁的规则越严格,应该放的越靠前and when checking the rules, it is checked from top to bottom.

Table names include:

  • raw : Advanced functions, such as URL filtering.
  • mangle : packet modification (QOS), used to implement quality of service.
  • nat : address translation, used for gateway routers.
  • filter : Packet filtering, used for firewall rules.

Actions include:

  • ACCEPT : Receive a packet.
  • DROP : Drop the packet.
  • REDIRECT : Redirection, mapping, transparent proxying.
  • SNAT : Source Address Translation.
  • DNAT : Destination Address Translation.
  • MASQUERADE : IP masquerading (NAT), used for ADSL.
  • LOG : log records.
  • SEMARK : Add SEMARK mark for mandatory access control (MAC) within domain
                             ┏╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┓
 ┌───────────────┐           ┃    Network    ┃
 │ table: filter │           ┗━━━━━━━┳━━━━━━━┛
 │ chain: INPUT  │◀────┐             │
 └───────┬───────┘     │             ▼
         │             │   ┌───────────────────┐
  ┌      ▼      ┐      │   │ table: nat        │
  │local process│      │   │ chain: PREROUTING │
  └             ┘      │   └─────────┬─────────┘
         │             │             │
         ▼             │             ▼              ┌─────────────────┐
┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅    │     ┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅      │table: nat       │
 Routing decision      └───── outing decision ─────▶│chain: PREROUTING│
┅┅┅┅┅┅┅┅┅┳┅┅┅┅┅┅┅┅┅          ┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅      └────────┬────────┘
         │                                                   │
         ▼                                                   │
 ┌───────────────┐                                           │
 │ table: nat    │           ┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅               │
 │ chain: OUTPUT │    ┌─────▶ outing decision ◀──────────────┘
 └───────┬───────┘    │      ┅┅┅┅┅┅┅┅┳┅┅┅┅┅┅┅┅
         │            │              │
         ▼            │              ▼
 ┌───────────────┐    │   ┌────────────────────┐
 │ table: filter │    │   │ chain: POSTROUTING │
 │ chain: OUTPUT ├────┘   └──────────┬─────────┘
 └───────────────┘                   │
                             ┏╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┓
                             ┃    Network    ┃
                             ┗━━━━━━━━━━━━━━━┛

example

Clear all current rules and counts

iptables -F  # 清空所有的防火墙规则
iptables -X  # 删除用户自定义的空链
iptables -Z  # 清空计数

Configure to allow ssh port connections

iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT
# 22为你的ssh端口, -s 192.168.1.0/24表示允许这个网段的机器来连接,其它网段的ip地址是登陆不了你的机器的。 -j ACCEPT表示接受这样的请求

Allow the local loopback address to be used normally

iptables -A INPUT -i lo -j ACCEPT
#本地圆环地址就是那个127.0.0.1,是本机上使用的,它进与出都设置为允许
iptables -A OUTPUT -o lo -j ACCEPT

set default rules

iptables -P INPUT DROP # 配置默认的不让进
iptables -P FORWARD DROP # 默认的不允许转发
iptables -P OUTPUT ACCEPT # 默认的可以出去

Configure whitelist

iptables -A INPUT -p all -s 192.168.1.0/24 -j ACCEPT  # 允许机房内网机器可以访问
iptables -A INPUT -p all -s 192.168.140.0/24 -j ACCEPT  # 允许机房内网机器可以访问
iptables -A INPUT -p tcp -s 183.121.3.7 --dport 3380 -j ACCEPT # 允许183.121.3.7访问本机的3380端口

Open the corresponding service port

iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 开启80端口,因为web对外都是这个端口
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT # 允许被ping
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 已经建立的连接得让它进来

Save the rules to the configuration file

cp /etc/sysconfig/iptables /etc/sysconfig/iptables.bak # 任何改动之前先备份,请保持这一优秀的习惯
iptables-save > /etc/sysconfig/iptables
cat /etc/sysconfig/iptables

List the rules that have been set

iptables -L [-t table name] [chain name]

  • Four table names raw, nat, filter,mangle
  • Five rule chain names INPUT, OUTPUT, FORWARD, PREROUTING,POSTROUTING
  • The filter table contains INPUT, OUTPUT, FORWARDthree rule chains
iptables -L -t nat                  # 列出 nat 上面的所有规则
#            ^ -t 参数指定,必须是 raw, nat,filter,mangle 中的一个
iptables -L -t nat  --line-numbers  # 规则带编号
iptables -L INPUT

iptables -L -nv  # 查看,这个列表看起来更详细

clear existing rules

iptables -F INPUT  # 清空指定链 INPUT 上面的所有规则
iptables -X INPUT  # 删除指定的链,这个链必须没有被其它任何规则引用,而且这条上必须没有任何规则。
                   # 如果没有指定链名,则会删除该表中所有非内置的链。
iptables -Z INPUT  # 把指定链,或者表中的所有链上的所有计数器清零。

delete added rule

# 添加一条规则
iptables -A INPUT -s 192.168.1.5 -j DROP

To display all iptables with sequence numbers, execute:

iptables -L -n --line-numbers

For example, to delete the rule whose serial number is 8 in INPUT, execute:

iptables -D INPUT 8

Open the specified port

iptables -A INPUT -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT               #允许本地回环接口(即运行本机访问本机)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT    #允许已建立的或相关连的通行
iptables -A OUTPUT -j ACCEPT         #允许所有本机向外的访问
iptables -A INPUT -p tcp --dport 22 -j ACCEPT    #允许访问22端口
iptables -A INPUT -p tcp --dport 80 -j ACCEPT    #允许访问80端口
iptables -A INPUT -p tcp --dport 21 -j ACCEPT    #允许ftp服务的21端口
iptables -A INPUT -p tcp --dport 20 -j ACCEPT    #允许FTP服务的20端口
iptables -A INPUT -j reject       #禁止其他未允许的规则访问
iptables -A FORWARD -j REJECT     #禁止其他未允许的规则访问

Shield IP

iptables -A INPUT -p tcp -m tcp -s 192.168.0.8 -j DROP  # 屏蔽恶意主机(比如,192.168.0.8
iptables -I INPUT -s 123.45.6.7 -j DROP       #屏蔽单个IP的命令
iptables -I INPUT -s 123.0.0.0/8 -j DROP      #封整个段即从123.0.0.1到123.255.255.254的命令
iptables -I INPUT -s 124.45.0.0/16 -j DROP    #封IP段即从123.45.0.1到123.45.255.254的命令
iptables -I INPUT -s 123.45.6.0/24 -j DROP    #封IP段即从123.45.6.1到123.45.6.254的命令是

Specifies the network interface from which packets are sent out

Only works for OUTPUT, FORWARD, POSTROUTING three chains.

iptables -A FORWARD -o eth0

View added rules

iptables -L -n -v
Chain INPUT (policy DROP 48106 packets, 2690K bytes)
 pkts bytes target     prot opt in     out     source               destination
 5075  589K ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
 191K   90M ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:22
1499K  133M ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:80
4364K 6351M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
 6256  327K ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 3382K packets, 1819M bytes)
 pkts bytes target     prot opt in     out     source               destination
 5075  589K ACCEPT     all  --  *      lo      0.0.0.0/0            0.0.0.0/0

Start network forwarding rules

The public network 210.14.67.7allows the intranet 192.168.188.0/24to access the Internet

iptables -t nat -A POSTROUTING -s 192.168.188.0/24 -j SNAT --to-source 210.14.67.127

Port Mapping

Port 2222 of this machine is mapped to port 22 of the intranet virtual machine

iptables -t nat -A PREROUTING -d 210.14.67.127 -p tcp --dport 2222  -j DNAT --to-dest 192.168.188.115:22

string match

For example, if we want to filter all strings in a TCP connection testand terminate the connection once it appears, we can do this:

iptables -A INPUT -p tcp -m string --algo kmp --string "test" -j REJECT --reject-with tcp-reset
iptables -L

# Chain INPUT (policy ACCEPT)
# target     prot opt source               destination
# REJECT     tcp  --  anywhere             anywhere            STRING match "test" ALGO name kmp TO 65535 reject-with tcp-reset
#
# Chain FORWARD (policy ACCEPT)
# target     prot opt source               destination
#
# Chain OUTPUT (policy ACCEPT)
# target     prot opt source               destination

Stopping Windows Worm Attacks

iptables -I INPUT -j DROP -p tcp -s 0.0.0.0/0 -m string --algo kmp --string "cmd.exe"

Prevent SYN flood attacks

iptables -A INPUT -p tcp --syn -m limit --limit 5/second -j ACCEPT

Add SECMARK record

iptables -t mangle -A INPUT -p tcp --src 192.168.1.2 --dport 443 -j SECMARK --selctx system_u:object_r:myauth_packet_t
# 向从 192.168.1.2:443 以TCP方式发出到本机的包添加MAC安全上下文 system_u:object_r:myauth_packet_t

more examples

Build a powerful security shield with iptables http://www.imooc.com/learn/389

iptables: application layer firewall tool under linux

iptables 5 chain: corresponding to Hook point
netfilter: a data packet processing module inside the core layer of the linux operating system
Hook point: the mount point of data packets in netfilter;PRE_ROUTING / INPUT / OUTPUT / FORWARD / POST_ROUTING

iptables & netfilter
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-stZEWRWs-1682768669213)(http://7xq89b.com1.z0.glb.clouddn.com/ netfilter&iptables.jpg)]

iptables 4 table 5 links
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7l0oglDb-1682768669214) (http://7xq89b.com1.z0.glb.clouddn. com/iptables-data-stream.jpg)]

iptables rules
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-28PmmPJe-1682768669214)(http://7xq89b.com1.z0.glb.clouddn.com/iptables -rules.jpg)]

  • 4 tables

filter : access control / rule matching
nat : address forwarding
mangle / raw

  • rule

Data access control: ACCEPT / DROP / REJECT
Packet rewriting (nat -> address translation): snat / dnat
information record: log

Example of usage scenarios

  • scene one

Open tcp 10-22/80 port,
open icmp,
and other unallowed ports are prohibited from accessing

Existing problems: This machine cannot access this machine; This machine cannot access other hosts

  • scene two

ftp: default passive mode (the server generates a random port to inform the client, and the client actively connects to this port to pull data) vsftpd
: enables ftp to support active mode (the client generates a random port to notify the server, and the server actively connects to this port to send data)

  • scene three

Allow Internet access:
web
http -> 80/tcp; https -> 443/tcp
mail
smtp -> 25/tcp; smtps -> 465/tcp
pop3 -> 110/tcp; pop3s -> 995/tcp
imap -> 143 /tcp

内部使用:
file
nfs -> 123/udp
samba -> 137/138/139/445/tcp
ftp -> 20/21/tcp
remote
ssh -> 22/tcp
sql
mysql -> 3306/tcp
oracle -> 1521/tcp

  • scene four

nat forwarding

  • scene five

Anti CC attack

iptables -L -F -A -D # list flush append delete
# 场景一
iptables -I INPUT -p tcp --dport 80 -j ACCEPT # 允许 tcp 80 端口
iptables -I INPUT -p tcp --dport 10:22 -j ACCEPT # 允许 tcp 10-22 端口
iptables -I INPUT -p icmp -j ACCEPT # 允许 icmp
iptables -A INPUT -j REJECT # 添加一条规则, 不允许所有

# 优化场景一
iptables -I INPUT -i lo -j ACCEPT # 允许本机访问
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 允许访问外网
iptables -I INPUT -p tcp --dport 80 -s 10.10.188.233 -j ACCEPT # 只允许固定ip访问80

# 场景二
vi /etc/vsftpd/vsftpd.conf # 使用 vsftpd 开启 ftp 主动模式
port_enable=yes
connect_from_port_20=YES
iptables -I INPUT -p tcp --dport 21 -j ACCEPT

vi /etc/vsftpd/vsftpd.conf # 建议使用 ftp 被动模式
pasv_min_port=50000
pasv_max_port=60000
iptables -I INPUT -p tcp --dport 21 -j ACCEPT
iptables -I INPUT -p tcp --dport 50000:60000 -j ACCEPT

# 还可以使用 iptables 模块追踪来自动开发对应的端口

# 场景三
iptables -I INPUT -i lo -j ACCEPT # 允许本机访问
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 允许访问外网
iptables -I INPUT -s 10.10.155.0/24 -j ACCEPT # 允许内网访问
iptables -I INPUT -p tcp -m multiport --dports 80,1723 -j ACCEPT # 允许端口, 80 -> http, 1723 -> vpn
iptables -A INPUT -j REJECT # 添加一条规则, 不允许所有

iptables-save # 保存设置到配置文件

# 场景四
iptables -t nat -L # 查看 nat 配置

iptables -t nat -A POST_ROUTING -s 10.10.177.0/24 -j SNAT --to 10.10.188.232 # SNAT
vi /etc/sysconfig/network # 配置网关

iptables -t nat -A POST_ROUTING -d 10.10.188.232 -p tcp --dport 80 -j DNAT --to 10.10.177.232:80 # DNAT

#场景五
iptables -I INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 100 -j REJECT # 限制并发连接访问数
iptables -I INPUT -m limit --limit 3/hour --limit-burst 10 -j ACCEPT # limit模块; --limit-burst 默认为5

Guess you like

Origin blog.csdn.net/u011837804/article/details/130443175