如何选择防火墙

一般来讲:
rhel7或以下,选择iptables;
rhel8或以上,可以采用firewalld,使用iptables也是可以的,但两者选其一即可。
如果有docker、k8s等紧密依赖iptables的环境,建议采用iptables,禁用firewalld,请把这个配置写入新系统初始配置中。
ubuntu22仍然可保持采用iptables。
iptables

禁用firewalld

#停止firewalld服务
systemctl stop firewalld
#禁用firewalld服务
systemctl mask firewalld

启用iptables

yum install -y iptables
yum install -y iptables-services

systemctl enable iptables.service
systemctl start iptables.service

保存经验

默认保存位置:/etc/sysconfig/iptables

两种常见保存方式:

  • 方式一
    service iptables save #安装了iptables套件后才有效,默认保存位置:/etc/sysconfig/iptables,iptables套件配置文件是/etc/sysconfig/iptables-config
  • 方式二
    iptables-save -c > /etc/sysconfig/iptables #没有安装iptables套件也可执行,参数-c是保存计数

保存为不同版本的示例

iptables-save > ipt.v1.0     #版本保存
iptables-restore < ipt.v1.0  #恢复

datetime=$(date +%Y%m%d-%H%M%S)
iptables-save -c > /etc/sysconfig/iptables_${datetime} #以时间为版本保存
iptables-restore -c < /etc/sysconfig/iptables_${datetime}

在多人管理的工作环境中,采用同一脚本去管理iptables是非常推荐的做法,但如果确实混乱不堪,维护好/etc/sysconfig/iptables是最好的选择。参考常规简易配置综合脚本范例

在iptables和firewalld共存的系统,比如rhel7系列,但又没有安装iptables套件,或采用了firewalld和iptables共同管理防火墙,造成了iptables策略混乱,这时候可用iptables-save命令保存策略,不过这时可能更应该考虑采用firewalld去管理iptables

2024年实践中发现,k8s的网络插件calico管理的iptables策略可能造成iptables-save命令也无法完整保存策略,这需要根据生产场景来制定应对方案,以避免重启后策略丢失。

通过自定义链并写入开机启动的解决案例

#!/bin/bash
###################################
# function iptables防火墙因服务不正常而采用的临时处置
#
# 参考创建或使用示例: mkdir -p /root/sh/log; touch /root/sh/iptables\_for\_tmp.sh; chmod a+x /root/sh/iptables\_for\_tmp.sh
#
# if (! grep -q iptables\_for\_tmp /etc/rc.local); then echo '/root/sh/iptables\_for\_tmp.sh >> /root/sh/log/iptables\_for\_tmp.log 2>&1' >> /etc/rc.local; else echo "This script already exists in /etc/rc.local"; fi; chmod a+x /etc/rc.d/rc.local
#
# Change History:
# date author note
# 20240105 N k8s的calico导致防火墙iptables服务无法恢复运行,改用脚本
#
###################################

export LANG=C
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin


# 22端口处理 ###
iptables -F FOR_TMP > /dev/null 2>&1
iptables -D INPUT -j FOR_TMP > /dev/null 2>&1
iptables -X FOR_TMP > /dev/null 2>&1
iptables -N FOR_TMP
iptables -I INPUT -j FOR_TMP

#放通
iptables -I FOR_TMP -s 1.2.3.4 -p tcp --dport 22 -j ACCEPT

#限制
iptables -A FOR_TMP -p tcp --dport 22 -j DROP

#保存
iptables-save -c > /etc/sysconfig/iptables # 执行后保存

if (! grep -q iptables_for_tmp /etc/rc.local); then echo '/root/sh/iptables\_for\_tmp.sh >> /root/sh/log/iptables\_for\_tmp.log 2>&1' >> /etc/rc.local; else echo "This script already exists in /etc/rc.local"; fi; chmod a+x /etc/rc.d/rc.local


该脚本可以反复执行,不会产生冗余策略。

加载内核模块

在早期版本的Linux内核,iptables的NAT,一般不能使用FTP的20端口,可以使用下面命令加载模块
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_conntrack_ftp.ko
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_nat_ftp.ko
或使用modprobe命令加载(推荐modprobe,因为insmod不解决依赖关系)
允许NAT转换FTP的跟踪连接,如下:
modprobe ip_nat_ftp
允许本机FTP的跟踪连接,这样就不必设置允许20和被动端口了
modprobe ip_conntrack_ftp

脚本中常用配置:

modules="ip\_conntrack\_ftp ip\_conntrack\_irc ip\_nat\_pptp ip\_gre ip\_conntrack\_pptp ip\_conntrack\_proto\_gre"
for mod in $modules
do
    testmod=`lsmod | grep "${mod}"`
    if [ "$testmod" == "" ]; then
        modprobe $mod
    fi
done

基于近些年Linux内核版本的系统,比如rhel6+,还未仔细分析过是否默认支持上述模块,没有的话,可以根据业务场景选择是否加载。

基本操作

iptables规则执行顺序是从上到下,前面的匹配后就不再看后面的。
基本语法:
iptables [-t table] -[AD] chain rule-specification [options]
iptables [-t table] -I chain [rulenum] rule-specification [options]
iptables [-t table] -R chain rulenum rule-specification [options]
iptables [-t table] -D chain rulenum [options]
iptables [-t table] -[LFZ] [chain] [options]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target [options]
iptables [-t table] -E old-chain-name new-chain-name

iptables -A 添加一条规则到末尾
iptables -D 删除
iptables -I 插入一条规则到最前面
iptables -R 替换
iptables -vnL 列表
iptables -vnL --line-numbers 列表时同时显示策略号,方便更新局部策略,而不需要重新配置所有策略。

常用模块和参数

iprange

–src-range ip-ip Match source IP in the specified range.
–dst-range ip-ip
例:
-m iprange --src-range 192.168.10.2-192.168.10.6
iptables -I INPUT -m iprange --src-range 192.168.10.2-192.168.10.6 -p tcp --dport 22 -j ACCEPT

icmp

-p icmp --icmp-type 类型 ping: type 8 pong: type 0

sport和dport

-p tcp
-p udp
–sport 和–dport 必须配合-p 参数使用

multiport

   This  module  matches  a set of source or destination ports.  Up to 15 ports can be specified.  A port range (port:port) counts as two
   ports.  It can only be used in conjunction with -p tcp or -p udp.

   --source-ports [!] port[,port[,port:port...]]
          Match if the source port is one of the given ports.  The flag --sports is a convenient alias for this option.

   --destination-ports [!] port[,port[,port:port...]]
          Match if the destination port is one of the given ports.  The flag --dports is a convenient alias for this option.

   --ports [!] port[,port[,port:port...]]
          Match if either the source or destination ports are equal to one of the given ports.

例:
-p tcp -m multiport --dports 20,21,22

state

-m state --state 状态 状态:NEW、RELATED、ESTABLISHED、INVALID
NEW:有别于tcp 的syn
ESTABLISHED:连接态
RELATED:衍生态,与conntrack 关联(比如FTP常用)
INVALID:不能被识别属于哪个连接或没有任何状态

mac

mac --mac-source [!] address
        Match source MAC address.  It must be of the form XX:XX:XX:XX:XX:XX.  Note that this only makes sense for packets  coming  from
        an Ethernet device and entering the PREROUTING, FORWARD or INPUT chains.

line-numbers

--line-numbers
              When listing rules, add line numbers to the beginning of each rule, corresponding to that rule's position in the chain.

limit

   This module matches at a limited rate using a token bucket filter.  A rule using this extension will match until this limit is reached
   (unless the flag is used).  It can be used in combination with the LOG target to give limited logging, for example.

   --limit rate
          Maximum average matching rate: specified as a number, with an optional second minute hour or day suffix;  the
          default is 3/hour.
   注意:
   limit 英语上看是限制的意思,但实际上只是按一定速率去匹配而已,要想限制的话后面要再跟一条DROP,但使用下面这条就不必了。

   --limit-burst number
          Maximum  initial  number  of  packets  to  match: this number gets recharged by one every time the limit specified above is not
          reached, up to this number; the default is 5.

comment

   Allows you to add comments (up to 256 characters) to any rule.
   --comment comment
   Example:
          iptables -A INPUT -s 192.168.0.0/16 -m comment --comment "A privatized IP block"

-j 动作

-j有如下动作:
DROP 丢弃
ACCEPT 接受
LOG 记入日志,默认是message
–log-tcp-options :记录tcp header的相关资讯
–log-ip-options :记录ip header的相关资讯
RETURN 返回父链,例:假设一个包进入了INPUT 链,匹配了某条target 为–jump EXAMPLE_CHAIN 规则,然后进入了子链EXAMPLE_CHAIN。在子链中又匹配了某条规则,恰巧target 是–jump RETURN,那包就返回INPUT 链了。如果在INPUT链里又遇到了–jump RETURN,那这个包就要交由缺省的策略来处理了。
SNAT 更换源地址,NAT
DNAT 更换目的地址,NAT
MASQUERADE 伪装为-o选项指定的网卡上的IP,比SNAT和DNAT负载稍高

SNAT示例

通常用于客户端上外网
iptables -t nat -A POSTROUTING -s 192.168.0.0/255.255.255.0 -d 1.2.3.0/255.255.255.0 -j SNAT --to-source 192.168.1.2
特别注意192.168.1.2是本系统的出站网口IP,通过ip a可以查看到

DNAT示例

通常用于服务器端口的发布
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to X.X.X.X:8080

应用案例

通过iptables实现跨地域转发端口

iptables端口代理,做到像nginx,haproxy一样转发TCP请求,但是它不能关心应用层的东西,比机主机头,没有超时时间限制,除非网络不稳定

开启系统路由

echo "1" > /proc/sys/net/ipv4/ip_forward

或者修改/etc/sysctl.conf
net.ipv4.ip_forward = 1
然后执行sysctl -p 永久生效

添加nat策略到转发服务器iptables主脚本(假设通过脚本管理iptables且有一个主脚本),在转发服务器添加,示例如下

iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
iptables -t nat -F PREROUTING
iptables -t nat -F POSTROUTING
iptables -t nat -A PREROUTING -i eth0 -d 转发服务器本机系统ip -p tcp -m multiport --dport 80,8080 -j DNAT --to-destination 目标服务器公网ip
iptables -t nat -A POSTROUTING -o eth0 -d 目标服务器公网ip -p tcp -m multiport --dport 80,8080 -j SNAT --to-source 转发服务器本机系统ip

运行防火墙主脚本

LOG示例

iptables -A INPUT -s x.x.x.x -j LOG --log-tcp-options --log-ip-options --log-prefix '[IPTABLES IMLOG] : ’

调节MTU

iptables -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1400:1536 -j TCPMSS --clamp-mss-to-pmtu

简单限速

最全的Linux教程,Linux从入门到精通

======================

  1. linux从入门到精通(第2版)

  2. Linux系统移植

  3. Linux驱动开发入门与实战

  4. LINUX 系统移植 第2版

  5. Linux开源网络全栈详解 从DPDK到OpenFlow

华为18级工程师呕心沥血撰写3000页Linux学习笔记教程

第一份《Linux从入门到精通》466页

====================

内容简介

====

本书是获得了很多读者好评的Linux经典畅销书**《Linux从入门到精通》的第2版**。本书第1版出版后曾经多次印刷,并被51CTO读书频道评为“最受读者喜爱的原创IT技术图书奖”。本书第﹖版以最新的Ubuntu 12.04为版本,循序渐进地向读者介绍了Linux 的基础应用、系统管理、网络应用、娱乐和办公、程序开发、服务器配置、系统安全等。本书附带1张光盘,内容为本书配套多媒体教学视频。另外,本书还为读者提供了大量的Linux学习资料和Ubuntu安装镜像文件,供读者免费下载。

华为18级工程师呕心沥血撰写3000页Linux学习笔记教程

本书适合广大Linux初中级用户、开源软件爱好者和大专院校的学生阅读,同时也非常适合准备从事Linux平台开发的各类人员。

需要《Linux入门到精通》、《linux系统移植》、《Linux驱动开发入门实战》、《Linux开源网络全栈》电子书籍及教程的工程师朋友们劳烦您转发+评论

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以点击这里获取!

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐