Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?

Release: 2023-08-01 17:36:23
forward
1496 people have browsed it

Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?

Connection tracking (conntrack)

Connection tracking is the basis of many network applications. For example, Kubernetes Service, ServiceMesh sidecar, software four-layer load balancer LVS/IPVS, Docker network, OVS, iptables host firewall, etc., all rely on the connection tracking function.
Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
Connection tracking, as the name suggests, is to track (and record) the status of the connection. For example, Figure 1.1 is a Linux machine with an IP address of 10.1.1.2. We can see that there are three connections on this machine:
  • The connection for the machine to access the external HTTP service (destination port 80)
  • The connection for the external access to the FTP service within the machine (destination port 21)
  • The connection of the machine to access the external DNS service (destination port 53)
What connection tracking does is to discover and Track the status of these connections, including:
  • Extract tuple information from the data packet, identify the data flow (flow) and the corresponding connection ( connection).
  • #Maintain a status database (conntrack table) for all connections, such as the creation time of the connection, the number of packets sent, the number of bytes sent, etc.
  • #Recycle expired connections (GC).
  • # Provide services for higher-level functions (such as NAT).
It should be noted that the concept of "connection" in connection tracking is the same as the concept of "connection oriented" in the TCP/IP protocol. "Connection" is not exactly the same. To put it simply:
  • In the TCP/IP protocol, connection is a Layer 4 concept. TCP is connection-oriented, and all packets sent require a response (ACK) from the peer, and there is a retransmission mechanism. UDP is connectionless, and the packets sent do not require a response from the peer, and there is no retransmission mechanism.
  • In conntrack(CT), a data flow (flow) defined by a tuple (tuple) represents a connection (connection). We will see later that three-layer protocols such as UDP and even ICMP also have connection records in CT, but not all protocols will be connected.

Netfilter

Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
##Linux Connection tracking is implemented in Netfilter.
Netfilter is a framework in the Linux kernel for controlling, modifying, and filtering data packets (manipulation and filtering). It sets several hook points in the kernel protocol stack to intercept, filter or otherwise process data packets.
Now when it comes to connection tracking (conntrack), you may first think of Netfilter. Netfilter is just a connection tracking implementation in the Linux kernel. In other words, as long as you have the hook capability and can intercept every packet entering and exiting the host, you can implement a set of connection tracking on your own based on this.
Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
The cloud native network solution Cilium has implemented such an independent connection tracking and NAT mechanism in version 1.7.4 (Full functionality requires Kernel 4.19). The basic principle is:
  • Implement the packet interception function based on BPF hook (equivalent to the hook mechanism in netfilter)
  • Based on BPF hook, implement a new set of conntrack and NAT. Therefore, even if Netfilter is uninstalled, it will not affect Cilium's support for Kubernetes ClusterIP, NodePort, ExternalIPs and LoadBalancer. . Since this connection tracking mechanism is independent of Netfilter, its conntrack and NAT information are not stored in the kernel (that is, Netfilter's) conntrack table and NAT table.Therefore, conventional conntrack/netstats/ss/lsof and other tools cannot be seen. You must use Cilium commands, for example:
  • ##
    $ cilium bpf nat list$ cilium bpf ct list global
    Copy after login

Iptables

Iptables is a user space tool for configuring Netfilter filtering function. Netfilter is the real security framework of the firewall, and netfilter is located in the kernel space. iptables is actually a command line tool located in user space. We use this tool to operate the real framework. Iptable processes data packets according to the methods defined by rules, such as accept, reject, drop, etc.
For example, when the client accesses the server's web service, the client sends a message to the network card, and the tcp/ip protocol stack is part of the kernel, so the client's information will pass through The kernel's TCP protocol is transmitted to the web service in user space. At this time, the target endpoint of the client message is the socket (IP:Port) monitored by the web service. When the web service needs to respond to the client request , the target destination of the response message sent by the web service is the client. At this time, the IP and port monitored by the web service become the origin. We have said that netfilter is the real firewall, and it is part of the kernel. Therefore, if we want the firewall to achieve the purpose of "fire prevention", we need to set up checkpoints in the kernel. All incoming and outgoing messages must pass through these checkpoints. After inspection, only those that meet the release conditions can be released, and those that meet the blocking conditions can be released. needs to be blocked.
Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
iptables contains 4 tables and 5 chains. The table is distinguished according to the operation on the data packet (filtering, NAT, etc.), and the chain is distinguished according to different Hook points. The table and chain are actually the two dimensions of netfilter.
The four tables of iptables are filter, mangle, nat, and raw. The default table is filter.
  • filter table: used to filter data packets. Specific rule requirements determine how to process a data packet.
  • nat table: mainly used to modify the IP address and port number information of data packets.
  • mangle table: Mainly used to modify the service type and life cycle of data packets, set tags for data packets, and implement traffic shaping, policy routing, etc.
  • #raw table: Mainly used to decide whether to perform status tracking on data packets.
The five chains of iptables are PREROUTING, INPUT, FORWARD, OUTPUT, and POSTROUTING.
  • input chain: The rules in this chain will be applied when a packet is received that accesses the local address.
  • output chain: When the machine sends a packet out, the rules in this chain will be applied.
  • forward chain: When receiving a data packet that needs to be forwarded to other addresses, the rules in this chain will be applied. Note that if you need to implement forward forwarding, you need to enable it. The ip_forward function in the Linux kernel.
  • prerouting chain: The rules in this chain will be applied before routing packets.
  • postrouting chain: The rules in this chain will be applied after routing the packet.
The corresponding relationship between the table and the chain is as shown below:
We can imagine some common scenarios , the flow direction of the message:
  • The message to a certain process of the local machine: PREROUTING –> INPUT.
  • Messages forwarded by this machine: PREROUTING –> FORWARD –> POSTROUTING.
  • A message (usually a response message) is sent by a process on the local machine: OUTPUT –> POSTROUTING.
We can summarize the process of data packets passing through the firewall as follows:

Query rules

  • -t: Table name
  • -n: Do not resolve IP address
  • -v: Will display counter information, the number and size of packets
  • -x: Options Represents the exact value of the display counter
  • ##--line-numbers: The serial number of the display rule (abbreviated as --line)
  • In addition, when searching for public accounts on Linux, this is how you should learn to reply "monkey" in the background to get a surprise gift package.
  • -L:链名
#iptables -t filter -nvxL DOCKER  --lineChain DOCKER (1 references)num      pkts      bytes target     prot opt in     out     source               destination1        5076   321478 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:84432       37233 54082508 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:223        1712   255195 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.3           tcp dpt:90004           0        0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.3           tcp dpt:80005       40224  6343104 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.4           tcp dpt:34436       21034  2227009 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.5           tcp dpt:33067          58     5459 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.6           tcp dpt:808         826    70081 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.6           tcp dpt:4439    10306905 1063612492 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.9           tcp dpt:330610     159775 12297727 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.7           tcp dpt:11111
Copy after login

增加规则

在指定表的指定链的尾部添加一条规则,-A 选项表示在对应链的末尾添加规则,省略 -t 选项时,表示默认操作 filter 表中的规则:
命令语法:iptables -t 表名 -A 链名 匹配条件 -j 动作示例:iptables -t filter -A INPUT -s 192.168.1.146 -j DROP
Copy after login
在指定表的指定链的首部添加一条规则,-I 选型表示在对应链的开头添加规则:
命令语法:iptables -t 表名 -I 链名 匹配条件 -j 动作示例:iptables -t filter -I INPUT -s 192.168.1.146 -j ACCEPT
Copy after login
在指定表的指定链的指定位置添加一条规则:
命令语法:iptables -t 表名 -I 链名 规则序号 匹配条件 -j 动作示例:iptables -t filter -I INPUT 5 -s 192.168.1.146 -j REJECT
Copy after login

删除规则

按照规则序号删除规则,删除指定表的指定链的指定规则,-D 选项表示删除对应链中的规则。示例表示删除filter表中INPUT链中序号为3的规则。:
命令语法:iptables -t 表名 -D 链名 规则序号示例:iptables -t filter -D INPUT 3
Copy after login
按照具体的匹配条件与动作删除规则,删除指定表的指定链的指定规则。示例表示删除filter表中INPUT链中源地址为192.168.1.146并且动作为DROP的规则。:
命令语法:iptables -t 表名 -D 链名 匹配条件 -j 动作示例:iptables -t filter -D INPUT -s 192.168.1.146 -j DROP
Copy after login
删除指定表的指定链中的所有规则,-F选项表示清空对应链中的规则:
命令语法:iptables -t 表名 -F 链名示例:iptables -t filter -F INPUT
Copy after login

修改规则

修改指定表中指定链的指定规则,-R 选项表示修改对应链中的规则,使用 -R 选项时要同时指定对应的链以及规则对应的序号,并且规则中原本的匹配条件不可省略。示例表示修改filter表中INPUT链的第3条规则,将这条规则的动作修改为ACCEPT, -s 192.168.1.146为这条规则中原本的匹配条件,如果省略此匹配条件,修改后的规则中的源地址可能会变为0.0.0.0/0:
命令语法:iptables -t 表名 -R 链名 规则序号 规则原本的匹配条件 -j 动作示例:iptables -t filter -R INPUT 3 -s 192.168.1.146 -j ACCEPT
Copy after login
设置指定表的指定链的默认策略(默认动作):
命令语法:iptables -t 表名 -P 链名 动作示例:iptables -t filter -P FORWARD ACCEPT
Copy after login

保存规则

方式一

当我们对规则进行了修改以后,如果想要修改永久生效,必须使用下面命令保存规则:
service iptables save
Copy after login
当然,如果你误操作了规则,但是并没有保存,那么使用 service iptables restart 命令重启 iptables 以后,规则会再次回到上次保存 /etc/sysconfig/iptables 文件时的模样。
centos7 中,已经不再使用 init 风格的脚本启动服务,而是使用 unit 文件,所以,在 centos7 中已经不能再使用类似 service iptables start 这样的命令了,所以 service iptables save 也无法执行,同时,在 centos7中,使用 firewall 替代了原来的 iptables service,不过不用担心,我们只要通过 yum 源安装 iptables与iptables-services 即可(iptables 一般会被默认安装,但是iptables-services 在 centos7 中一般不会被默认安装),在centos7 中安装完 iptables-services 后,即可像 centos6 中一样,通过 service iptables save 命令保存规则了,规则同样保存在 /etc/sysconfig/iptables 文件中。此处给出 centos7 中配置 iptables-service 的步骤:
#配置好yum源以后安装iptables-serviceyum install -y iptables-services#停止firewalldsystemctl stop firewalld#禁止firewalld自动启动systemctl disable firewalld#启动iptablessystemctl start iptables#将iptables设置为开机自动启动,以后即可通过iptables-service控制iptables服务systemctl enable iptables
Copy after login
上述配置过程只需一次,以后即可在 centos7 中使用 service iptables save 命令保存 iptables 规则了。

方式二

还可以使用另一种方法保存 iptables 规则,就是使用 iptables-save 命令。使用 iptables-save 并不能保存当前的 iptables 规则,但是可以将当前的 iptables 规则以”保存后的格式”输出到屏幕上。
所以,我们可以使用 iptables-save 命令,再配合重定向,将规则重定向到 /etc/sysconfig/iptables 文件中即可。
iptables-save > /etc/sysconfig/iptables
Copy after login

加载规则

我们也可以将 /etc/sysconfig/iptables 中的规则重新载入为当前的iptables 规则,但是注意,未保存入 /etc/sysconfig/iptables 文件中的修改将会丢失或者被覆盖。
使用 iptables-restore 命令可以从指定文件中重载规则,示例如下
iptables-restore < /etc/sysconfig/iptables
Copy after login

匹配条件

当规则中同时存在多个匹配条件时,多个条件之间默认存在”与”的关系,即报文必须同时满足所有条件,才能被规则匹配。
-s 用于匹配报文的源地址,可以同时指定多个源地址,每个IP之间用逗号隔开,也可以指定为一个网段。
#示例如下iptables -t filter -I INPUT -s 192.168.1.111,192.168.1.118 -j DROPiptables -t filter -I INPUT -s 192.168.1.0/24 -j ACCEPTiptables -t filter -I INPUT ! -s 192.168.1.0/24 -j ACCEPT
Copy after login
-d 用于匹配报文的目标地址,可以同时指定多个目标地址,每个 IP 之间用逗号隔开,也可以指定为一个网段。
#示例如下iptables -t filter -I OUTPUT -d 192.168.1.111,192.168.1.118 -j DROPiptables -t filter -I INPUT -d 192.168.1.0/24 -j ACCEPTiptables -t filter -I INPUT ! -d 192.168.1.0/24 -j ACCEPT
Copy after login
-p 用于匹配报文的协议类型,可以匹配的协议类型 tcp、udp、udplite、icmp、esp、ah、sctp 等(centos7 中还支持 icmpv6、mh)。
#示例如下iptables -t filter -I INPUT -p tcp -s 192.168.1.146 -j ACCEPTiptables -t filter -I INPUT ! -p udp -s 192.168.1.146 -j ACCEPT
Copy after login
-i 用于匹配报文是从哪个网卡接口流入本机的,由于匹配条件只是用于匹配报文流入的网卡,所以在 OUTPUT 链与 POSTROUTING 链中不能使用此选项。
#示例如下iptables -t filter -I INPUT -p icmp -i eth4 -j DROPiptables -t filter -I INPUT -p icmp ! -i eth4 -j DROP
Copy after login
-o 用于匹配报文将要从哪个网卡接口流出本机,于匹配条件只是用于匹配报文流出的网卡,所以在 INPUT 链与 PREROUTING 链中不能使用此选项。
#示例如下iptables -t filter -I OUTPUT -p icmp -o eth4 -j DROPiptables -t filter -I OUTPUT -p icmp ! -o eth4 -j DROP
Copy after login

扩展匹配条件

tcp扩展模块

常用的扩展匹配条件如下:
  • –sport:用于匹配 tcp 协议报文的源端口,可以使用冒号指定一个连续的端口范围。
  • –dport:用于匹配 tcp 协议报文的目标端口,可以使用冒号指定一个连续的端口范围。
  • –tcp-flags:用于匹配报文的tcp头的标志位。
  • –syn:用于匹配 tcp 新建连接的请求报文,相当于使用 <span style="outline: 0px;font-size: 17px;">–tcp-flags SYN,RST,ACK,FIN SYN</span>
注意,-p tcp与 -m tcp 并不冲突,-p 用于匹配报文的协议,-m 用于指定扩展模块的名称,正好,这个扩展模块也叫 tcp。
#示例如下iptables -t filter -I OUTPUT -d 192.168.1.146 -p tcp -m tcp --sport 22 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m tcp --dport 22:25 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m tcp --dport :22 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m tcp --dport 80: -j REJECTiptables -t filter -I OUTPUT -d 192.168.1.146 -p tcp -m tcp ! --sport 22 -j ACCEPTiptables -t filter -I INPUT -p tcp -m tcp --dport 22 --tcp-flags SYN,ACK,FIN,RST,URG,PSH SYN -j REJECTiptables -t filter -I OUTPUT -p tcp -m tcp --sport 22 --tcp-flags SYN,ACK,FIN,RST,URG,PSH SYN,ACK -j REJECTiptables -t filter -I INPUT -p tcp -m tcp --dport 22 --tcp-flags ALL SYN -j REJECTiptables -t filter -I OUTPUT -p tcp -m tcp --sport 22 --tcp-flags ALL SYN,ACK -j REJECTiptables -t filter -I INPUT -p tcp -m tcp --dport 22 --syn -j REJECT
Copy after login

udp 扩展模块

常用的扩展匹配条件:
  • –sport:匹配udp报文的源地址。
  • –dport:匹配udp报文的目标地址。
#示例iptables -t filter -I INPUT -p udp -m udp --dport 137 -j ACCEPTiptables -t filter -I INPUT -p udp -m udp --dport 137:157 -j ACCEPT
Copy after login

icmp 扩展模块

常用的扩展匹配条件:
  • –icmp-type:匹配icmp报文的具体类型。
#示例iptables -t filter -I INPUT -p icmp -m icmp --icmp-type 8/0 -j REJECTiptables -t filter -I INPUT -p icmp --icmp-type 8 -j REJECTiptables -t filter -I OUTPUT -p icmp -m icmp --icmp-type 0/0 -j REJECTiptables -t filter -I OUTPUT -p icmp --icmp-type 0 -j REJECTiptables -t filter -I INPUT -p icmp --icmp-type "echo-request" -j REJECT
Copy after login

multiport 扩展模块

常用的扩展匹配条件如下:
  • -p tcp -m multiport –sports 用于匹配报文的源端口,可以指定离散的多个端口号,端口之间用”逗号”隔开。
  • -p udp -m multiport –dports 用于匹配报文的目标端口,可以指定离散的多个端口号,端口之间用”逗号”隔开。
#示例如下iptables -t filter -I OUTPUT -d 192.168.1.146 -p udp -m multiport --sports 137,138 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m multiport --dports 22,80 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m multiport ! --dports 22,80 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m multiport --dports 80:88 -j REJECTiptables -t filter -I INPUT -s 192.168.1.146 -p tcp -m multiport --dports 22,80:88 -j REJECT
Copy after login

iprange 模块

包含的扩展匹配条件如下:
  • –src-range:指定连续的源地址范围。
  • –dst-range:指定连续的目标地址范围。
#示例iptables -t filter -I INPUT -m iprange --src-range 192.168.1.127-192.168.1.146 -j DROPiptables -t filter -I OUTPUT -m iprange --dst-range 192.168.1.127-192.168.1.146 -j DROPiptables -t filter -I INPUT -m iprange ! --src-range 192.168.1.127-192.168.1.146 -j DROP
Copy after login
牛逼啊!接私活必备的 N 个开源项目!赶快收藏
Copy after login

string 模块

常用扩展匹配条件如下:
  • –algo:指定对应的匹配算法,可用算法为bm、kmp,此选项为必需选项。
  • –string:指定需要匹配的字符串
我们想要达到的目的是,如果报文中包含”OOXX”字符,我们就拒绝报文进入本机:
#示例
iptables -t filter -I INPUT -m string --algo bm --string "OOXX" -j REJECT
Copy after login

time 模块

常用扩展匹配条件如下:
  • –timestart:用于指定时间范围的开始时间,不可取反。
  • –timestop:用于指定时间范围的结束时间,不可取反。
  • –weekdays:用于指定”星期几”,可取反。
  • –monthdays:用于指定”几号”,可取反。
  • –datestart:用于指定日期范围的开始日期,不可取反。
  • –datestop:用于指定日期范围的结束时间,不可取反。
#示例
iptables -t filter -I OUTPUT -p tcp --dport 80 -m time --timestart 09:00:00 --timestop 19:00:00 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 443 -m time --timestart 09:00:00 --timestop 19:00:00 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time --weekdays 6,7 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time --monthdays 22,23 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time ! --monthdays 22,23 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time --timestart 09:00:00 --timestop 18:00:00 --weekdays 6,7 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time --weekdays 5 --monthdays 22,23,24,25,26,27,28 -j REJECT
iptables -t filter -I OUTPUT -p tcp --dport 80  -m time --datestart 2017-12-24 --datestop 2017-12-27 -j REJECT
Copy after login

connlimit 模块

常用的扩展匹配条件如下:
  • –connlimit-above:单独使用此选项时,表示限制每个IP的链接数量。
  • –connlimit-mask:此选项不能单独使用,在使用–connlimit-above选项时,配合此选项,则可以针对”某类IP段内的一定数量的IP”进行连接数量的限制,如果不明白可以参考上文的详细解释。
#示例
iptables -I INPUT -p tcp --dport 22 -m connlimit --connlimit-above 2 -j REJECT
iptables -I INPUT -p tcp --dport 22 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j REJECT
iptables -I INPUT -p tcp --dport 22 -m connlimit --connlimit-above 10 --connlimit-mask 27 -j REJECT
Copy after login

limit 模块

connlimit 模块是对连接数量进行限制的,limit 模块是对”报文到达速率”进行限制的。用大白话说就是,如果我想要限制单位时间内流入的包的数量,就能用 limit 模块。我们可以以秒为单位进行限制,也可以以分钟、小时、天作为单位进行限制。常用的扩展匹配条件如下:
  • –limit-burst:类比”令牌桶”算法,此选项用于指定令牌桶中令牌的最大数量。
  • –limit:类比”令牌桶”算法,此选项用于指定令牌桶中生成新令牌的频率,可用时间单位有second、minute 、hour、day。
示例表示限制外部主机对本机进行ping操作时,本机最多每6秒中放行一个ping包
#示例,注意,如下两条规则需配合使用
#令牌桶中最多能存放3个令牌,每分钟生成10个令牌(即6秒钟生成一个令牌)。
iptables -t filter -I INPUT -p icmp -m limit --limit-burst 3 --limit 10/minute -j ACCEPT
#默认将icmp包丢弃
iptables -t filter -A INPUT -p icmp -j REJECT
Copy after login

state 扩展模块

当我们通过 http 的 url 访问某个网站的网页时,客户端向服务端的 80 端口发起请求,服务端再通过 80 端口响应我们的请求,于是,作为客户端,我们似乎应该理所应当的放行 80 端口,以便服务端回应我们的报文可以进入客户端主机,于是,我们在客户端放行了 80 端口,同理,当我们通过 ssh 工具远程连接到某台服务器时,客户端向服务端的 22 号端口发起请求,服务端再通过 22 号端口响应我们的请求,于是我们理所应当的放行了所有 22 号端口,以便远程主机的响应请求能够通过防火墙,但是,作为客户端,如果我们并没有主动向 80 端口发起请求,也没有主动向 22 号端口发起请求,那么其他主机通过 80 端口或者 22 号端口向我们发送数据时,我们可以接收到吗?应该是可以的,因为我们为了收到 http 与 ssh 的响应报文,已经放行了 80 端口与 22 号端口,所以,不管是”响应”我们的报文,还是”主动发送”给我们的报文,应该都是可以通过这两个端口的,那么仔细想想,这样是不是不太安全呢?此时 state 扩展模块就派上用场了。
For the connection of the state module, the messages in the "connection" can be divided into 5 states, which are:
  • NEW: The status of the first packet in the connection is NEW. We can understand that the status of the first packet in the new connection is NEW.
  • ESTABLISHED: We can understand the status of the packet after the NEW status packet as ESTABLISHED, indicating that the connection has been established.
  • RELATED: Literally understood, RELATED is translated as relationship, but this is still not easy to understand. Let’s give an example. For example, in the FTP service, the FTP server will create two processes, one command process and one data process. The command process is responsible for command transmission between the server and the client (we can understand this transmission process as a so-called "connection" in state, temporarily called "command connection"). The data process is responsible for data transmission between the server and the client (we temporarily call this process "data connection"). However, the specific data to be transmitted is controlled by the command. Therefore, the messages in the "data connection" are "related" to the "command connection". Then, the packets in the "data connection" may be in the RELATED state, because these packets are related to the packets in the "command connection". (Note: If you want to perform connection tracking for ftp, you need to load the corresponding kernel module nf_conntrack_ftp separately. If you want to load it automatically, you can configure the /etc/sysconfig/iptables-config file)
  • INVALID: If a packet cannot be identified, or the packet does not have any status, then the status of the packet is INVALID. We can actively block messages with INVALID status.
  • UNTRACKED: When the status of the packet is untracked, it means that the packet has not been tracked. When the status of the packet is Untracked, it usually means that the relevant connection cannot be found. .
刚才举例中的问题即可使用 state 扩展模块解决,我们只要放行状态为 ESTABLISHED 的报文即可,因为如果报文的状态为 ESTABLISHED,那么报文肯定是之前发出的报文的回应,这样,就表示只有回应我们的报文能够通过防火墙,如果是别人主动发送过来的新的报文,则无法通过防火墙:
iptables -t filter -I INPUT -m state --state ESTABLISHED -j ACCEPT
Copy after login

mangle 表

mangle 表的主要功能是根据规则修改数据包的一些标志位,以便其他规则或程序可以利用这种标志对数据包进行过滤或策略路由。mangle 表主要有以下 3 种操作:
  • TOS:用来设置或改变数据包的服务类型域。这常用来设置网络上的数据包如何被路由等策略。注意这个操作并不完善,有时得不所愿。它在Internet 上还不能使用,而且很多路由器不会注意到这个域值。换句话说,不要设置发往 Internet 的包,除非你打算依靠 TOS 来路由,比如用 iproute2。
  • TTL:用来改变数据包的生存时间域,我们可以让所有数据包只有一个特殊的 TTL。它的存在有 一个很好的理由,那就是我们可以欺骗一些ISP。为什么要欺骗他们呢?因为他们不愿意让我们共享一个连接。那些 ISP 会查找一台单独的计算机是否使用不同的 TTL,并且以此作为判断连接是否被共享的标志。
  • MARK 用来给包设置特殊的标记。iproute 2能识别这些标记,并根据不同的标记(或没有标记) 决定不同的路由。用这些标记我们可以做带宽限制和基于请求的分类。
例如内网的客户端通过 Linux 主机连入 Internet,而 Linux 主机与Internet 连接时有两条线路,它们的网关如图所示。现要求对内网进行策略路由,所有通过 TCP 协议访问 80 端口的数据包都从 ChinaNet 线路出去,而所有访问 UDP 协议 53 号端口的数据包都从 Cernet 线路出去。
Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
这是一个策略路由的问题,为了达到目的,在对数据包进行路由前,要先根据数据包的协议和目的端口给数据包做上一种标志,然后再指定相应规则,根据数据包的标志进行策略路由。为了给特定的数据包做上标志,需要使用mangle 表,mangle 表共有 5 条链,由于需要在路由选择前做标志,因此应该使用 PREROUTING 链,下面是具体的命令:
iptables -t mangle -A PREROUTING -i eth0 -p tcp --dport 80 -j MARK --set-mark 1;
iptables -t mangle -A PREROUTING -i eth0 -p udp --dprot 53 -j MARK --set-mark 2;
Copy after login
数据包经过 PREROUTING 链后,将要进入路由选择模块,为了对其进行策略路由,执行以下两条命令,添加相应的规则:
ip rule add from all fwmark 1 table 10
ip rule add from all fwmark 2 table 20
Copy after login
以上两条命令表示所有标志是1的数据包使用路由表 10 进行路由,而所有标志是 2 的数据包使用路由表 20 进行路由。路由表 10 和 20 分别使用了 ChinaNet 和 Cernet 线路上的网关作为默认网关,具体设置命令如下所示:
ip route add default via 10.10.1.1 dev eth1 table 10
ip route add default via 10.10.2.1 dev eth2 table 20
Copy after login
以上两条命令在路由表 10 和 20 上分别指定了 10.10.1.1 和 10.10.2.1 作为默认网关,它们分别位于 ChinaNet 和 Cernet 线路上。于是,使用路由表 10 的数据包将通过 ChinaNet 线路出去,而使用路由表20的数据包将通过 Cernet 线路出去。

Custom chain

When there are too many rules in the default chain, it is inconvenient for us to manage. Imagine if there are 200 rules stored in the INPUT chain. Some of these 200 rules are for httpd service, some are for sshd service, some are for private network IP, and some are for public network IP. If we suddenly want to modify Regarding the rules related to the httpd service, do we have to read these 200 rules from the beginning to find out which rules are specific to httpd? This is obviously unreasonable.
So, in iptables, you can customize the chain, and the above problems can be solved by customizing the chain. Suppose we customize a chain named IN_WEB. We can write all inbound rules for port 80 into this custom chain. When we want to modify the inbound rules for web services in the future, we can Just modify the rules in the IN_WEB chain directly. Even if there are more rules in the default chain, we will not be afraid, because we know that all inbound rules for port 80 are stored in the IN_WEB chain.

创建自定义链

#在filter表中创建IN_WEB自定义链
iptables -t filter -N IN_WEB
Copy after login

引用自定义链

#在INPUT链中引用刚才创建的自定义链
iptables -t filter -I INPUT -p tcp --dport 80 -j IN_WEB
Copy after login

重命名自定义链

#将IN_WEB自定义链重命名为WEB
iptables -E IN_WEB WEB
Copy after login

删除自定义链

删除自定义链需要满足两个条件:
  • 1、自定义链没有被引用。
  • 2、自定义链中没有任何规则。
#第一步:清除自定义链中的规则
iptables -t filter -F WEB
#第二步:删除自定义链
iptables -t filter -X WEB
Copy after login

LOG 动作

LOG 动作默认会将报文的相关信息记录在/var/log/message文件中,当然,我们也可以将相关信息记录在指定的文件中,以防止 iptables 的相关信息与其他日志信息相混淆,修改 /etc/rsyslog.conf 文件(或者 /etc/syslog.conf),在 rsyslog 配置文件中添加如下配置即可:
kern.warning /var/log/iptables.log
Copy after login
完成上述配置后,重启rsyslog服务(或者syslogd):
service rsyslog restart
Copy after login
LOG 动作也有自己的选项,常用选项如下:
  • –log-level 选项可以指定记录日志的日志级别,可用级别有 emerg,alert,crit,error,warning,notice,info,debug。
  • –log-prefix 选项可以给记录到的相关信息添加”标签”之类的信息,以便区分各种记录到的报文信息,方便在分析时进行过滤。–log-prefix 对应的值不能超过 29 个字符。
比如,我想要将主动连接22号端口的报文的相关信息都记录到日志中,并且把这类记录命名为”want-in-from-port-22″,则可以使用如下命令:
iptables -I INPUT -p tcp --dport 22 -m state --state NEW -j LOG --log-prefix "want-in-from-port-22"
Copy after login
完成上述配置后,我在IP地址为 192.168.1.98 的客户端机上,尝试使用 ssh 工具连接上例中的主机,然后查看对应的日志文件(已经将日志文件设置为 /var/log/iptables.log):
Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?
如上图所示,ssh 连接操作的报文的相关信息已经被记录到了 iptables.log 日志文件中,而且这条日志中包含”标签”:want-in-from-port-22,如果有很多日志记录,我们就能通过这个”标签”进行筛选了,这样方便我们查看日志,同时,从上述记录中还能够得知报文的源IP与目标IP,源端口与目标端口等信息,从上述日志我们能够看出,192.168.1.98 这个 IP 想要在 14点11分 连接到 192.168.1.139(当前主机的 IP)的22号端口,报文由eth4网卡进入,eth4 网卡的 MAC 地址为 00:0c:29:b7:f4:d1,客户端网卡的 MAC 地址为 f4:8e:38:82:b1:29。

Reference link

  • https://www.zsythink.net/archives/category/Operation and maintenance related/ iptables/
  • ##https://my.oschina.net/mojiewhy/blog/3039897
  • https://www.frozentux.net/iptables-tutorial/cn/iptables-tutorial-cn-1.1.19.html#MARKTARGET
  • https://mp.weixin.qq.com/s/NOxY4ZC7Cay4LCWlMkVx8A

##

The above is the detailed content of Don't know how to use Linux firewall software IPtables! What kind of operation and maintenance person are you?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Linux中文社区
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!