Linux firewall-iptables firewall with four tables and five chains with SNAT and DNAT

iptables overview

  • The firewall
    IP information packet filtering system of the Linux system is actually composed of two components, netfilter and iptables, which
    mainly work at the network layer and target ip data packets. Reflected in the processing of the ip address, port and other information in the packet
  • netfilter/iptables relationship
    • netfilter: a firewall function system that belongs to the " kernel mode ". It
      is a part of the kernel and consists of some data backpack filtering tables. These tables contain the rule set used by the kernel to control the processing of data packet filtering.
    • iptables: firewall management system belonging to " user mode "
      is a command program used to manage Linux firewalls. It makes it easy to insert, modify and delete rules in the packet filtering table, usually located in the /sbin/iptables directory
    • netfilter/iptables was later referred to as iptables for short. iptables is a kernel-based firewall with four built-in 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 . Attention should be paid when setting up, in case a default rejection is set, then ssh will be disconnected and can only be changed in the computer room.

Four watches and five chains

  • The role of the rule table: to accommodate various rule chains

  • The role of the rule chain: to accommodate various firewall rules

  • Summary: There are chains in the table, and rules in the chain
    Insert picture description here

  • Four tables:

    • raw table : Determine whether to track the status of the packet. Contains two rule chains, OUTPUT , PREROUTING
    • Mangle table : modify the content of the data packet, which is used for traffic shaping, and set a mark for the data packet. Contains five rule chains, INPUT , OUTPUT , FORWARD , PREROUTING , POSTROUTING
    • nat table : responsible for network address translation , used to modify the source and destination IP addresses or ports in data packets. Contains three rule chains, OUTPUT , PREROUTING , POSTROUTING
    • Filter table : Responsible for filtering data packets and determining whether to pass the data packets (filtering). Contains three rule chains, INPUT , FORWARD , OUTPUT
    • Among the four rule tables of iptables, the mangle table and raw table are relatively less used
  • Five chains:

    • INPUT : Process inbound data packets, match the data packets of the target IP to this machine
    • OUTPUT .: Process outbound data packets, generally do not configure on this chain
    • FORWARD : Process and forward data packets, matching data packets flowing through the machine
    • PREROUTING chain : Process data packets before routing, used to modify the destination address, and used for DNAT . It is equivalent to mapping the IP and port of the internal network server to the external IP and port of the router
    • POSTROUTING chain : Process data packets after routing selection, used to modify the source address, and used for SNAT . It is equivalent to the internal network through the router NAT conversion function to realize the internal network host through a public IP address to access the Internet

Rule chain matching order

Insert picture description here

When packets arrive at the firewall, the order of priority between the rule tables :
raw> mangle> nat> filter

  • Matching order between rule chains:
    • Host-based firewall: Inbound data (data packets from the outside world, and the destination address is the firewall's local machine): PREROUTING ··> INPUT··> native application
    • Outbound data (data packets sent from the firewall to the external address of the machine): the machine's application··> OUTPUT ··> POSTROUTING
    • Network type firewall: Forwarding data (data packets that need to be forwarded through the firewall): PREROUTING ··> FORWARD ··> POSTROUTING
  • Matching order in the rule chain:
    • Check sequentially from top to bottom, and stop when a matching rule is found (except for the LOG policy, which means to record related logs)
    • If no matching rule is found in the chain, it will be processed according to the default policy of the chain (unmodified, the default policy is allowed)

iptables installation

  • CentOS 7 uses firewalld firewall by default, iptables is not installed, if you want to use iptables firewall. You must turn off the firewalld firewall before installing iptables
    • systemctl stop firewalldTurn off firewalld firewall
    • systemctl disable firewalldTurn off auto start
    • yum install iptables iptables-servicesinstallation
    • systemctl start iptablesStart the iptables service

# system-config-firewallCentos6 and previous versions can start the graphical interface, of course, the computer room is not graphical

iptables command line configuration method

  • Command format
    iptables [-t 表名] 管理选项 [链名] [匹配条件] [-j 控制类型]

Note: 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. Unless the default policy of the chain is set, the matching conditions must be formulated. The
control type uses uppercase letters, and the rest are lowercase.

Commonly used control types

  • ACCEPT: Allow data packets to pass
  • DROP: Drop the data packet directly without giving any response information
  • REJECT: Reject the data packet to pass, a response message will be sent to the data sender
  • SNAT: modify the source address of the data packet
  • MASQUERADE: disguised as a non-fixed public IP
  • LOG: Record log information in the /var/log/messages file, and then pass the data packet to the next cabinet. LOG is just an auxiliary action, and does not actually process data packets

Common management options

  • -A: Append a new rule at the end of the specified chain
  • -I: Insert a new cabinet at the beginning of the specified chain. If the serial number is not specified, it will default to the first rule
  • -R: modify or replace a certain rule in the specified chain, and specify the sequence number or specific content of the rule
  • -P: Set the default policy of the specified chain
  • -D: Delete a rule in the specified chain, you can specify the rule number or specific content
  • -F: Specify all the rules in the chain, if the chain name is not specified, all the chains in the table are cleared
  • -L: List all the rules in the specified chain, if the chain name is not specified, all the chains in the table are listed
  • -n: Display output results in digital form, such as displaying IP address instead of host name
  • -v: Display detailed information, including the number of matched packets and the number of matched bytes for each rule
  • --line-numbers: When viewing rules, display the sequence numbers of the rules

Add new rule

iptables -t filter -A INPUT -p icmp -j REJECT-t指定表名filter,-A在表中添加链-p指定协议,-j控制类型为拒绝
Insert picture description here
此时别的客户机ping本机会ping不通且会收到响应,而本机ping别的客户机将无法返回包而DROP则直接丢弃没有响应
iptables -F清空
iptables -I INPUT 2 -p tcp --dport 22 -j ACCEPT默认以filter表中在以有的规则中插入后面跟的2则是指定规则序号不添加默认添加为第一条规则,-p指定为tcp协议–dport位22端口-j为控制类型
Insert picture description here

查看规则列表

iptables [-t 表名] -n -L [链名] [--line-numbers]
iptables -[vn]L不可以合写为-Ln,v代表可以查看字节数和包
iptables -n -L --line-numbers–line-numbers表示把规则序号显示出来
Insert picture description here

删除规则列表

iptables -D INPUT 2删除INPUT链中第二条规则
iptables -t filter -D INPUT -P icmp -j REJECT删除指定表指定链指定规则
注意:
1.若规则列表中有多条相同的规则时,按内容匹配只删除的序号最小的一条
2.按号码匹配删除是,确保规则号码小于等于已有规则数,否则报错
3.按内容匹配删除数时,确保规则存在,否则报错

设置默认策略

iptables [-t 表名] -P <链名> <控制类型>

iptables -P INPUT DROP远程设置时先放通ssh的22号端口以免被拒绝无法连接
iptables -P FORWARD DROP
Insert picture description here

一般在生产环境中设置网络型防火墙、主机型防火墙时都要设置默认规则为DROP,并设置白名单

清空规则

iptables [-t 表名] -F [链名]
iptables -F INPUT删除指定链名的规则
iptables -F删除所有链规则
注意:
1.-F 仅仅是清空链中的规则,并不影响-P设置默认规则,默认规则需要手动进行修改
2.-P 设置DROP后,使用 -F 一定要小心
Insert picture description here

#防止把允许远程连接的相关规则清除后导致无法远程连接初级,此情况如果没有保存规则可重启主机解决
3.如果不写表名和链名,默认清空filter表中所有链里的所有规则

规则的匹配

  • 通用匹配
    • 可直接使用,不依赖于其他条件或扩展,包括网络协议、IP地址、网络接口等条件
      • 协议匹配:-p 协议名
      • 地址匹配:-s 源地址、-d 目的地址 #可以是IP、网段、域名、空(任何地址)
      • 接口匹配:-i 入站网卡、-o 出站网卡
      • 实例
        iptables -A FORWARD ! -p icmp -j ACCEPTFORWARD链添加一条!取反代表除了icmp以外都放通
        iptables -A INPUT -s 192.168.150.10 -j DROPINPUT链添加一条丢弃源地址为150.10的主机所发送的包
        iptables -I INPUT -i ens33 -s 192.168.150.0/24 -j DROPINPUT链插入一条丢弃所有入站ens33网卡的150.0/24网段的包
  • 隐含匹配
    • 要求以特定的协议匹配作为前提,包括端口、TCP标记、ICMP类型等条件

    • 端口匹配:- -sport 源端口、- -dport 目的端口

      • 可以是个别端口也可以是端口范围
        --sport 1000 匹配源端口是1000的数据包
        --sport 1000:3000 匹配源端口是1000-3000的数据包
        --sport :3000 匹配源端口是3000及以下的数据包
        --sport 1000: 匹配源端口是1000及以上的数据包
        注意:–sport 和 --dport 必须配合 -p <协议类型> 使用
        例如:
        iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT
        iptables -I FORWARD -d 192.168.150.0/24 -p tcp --dport 24500:24600 -j DROP
    • TCP标记匹配:

      • iptables -I INPUT -i ens33 -p tcp --tcp-flags SYN,RST,ACK SYN -j ACCEPT
        丢弃SYN请求包,放行其他包
    • ICMP类型匹配:–icmp-type ICMP类型

      • #可以是字符串、数字代码
        “Echo-Request”(代码为 8)表示 请求
        “Echo-Reply”(代码为 0)表示 回显
        “Destination-Unreachable”(代码为 3)表示 目标不可达
        关于其它可用的 ICMP 协议类型,可以执行“iptables -p icmp -h”命令,查看帮助信息
      • 实例:
        iptables -A INPUT -p icmp --icmp-type 8 -j DROP 禁止其它主机ping 本机
        iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT 允许本机ping 其它主机
        iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT 当本机ping 不通其它主机时提示目标不可达
        此时其它主机需要配置关于icmp协议的控制类型为 REJECT
        iptables -A INPUT -p icmp -j REJECT
  • 显式匹配
    • 要求以“-m 扩展模块”的形式明确指出类型,包括多端口、MAC地址、IP范围、数据包状态等条件
    • 多端口匹配:
      • -m multiport --sport 源端口列表
        -m multiport --dport 目的端口列表
      • 实例:
        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地址匹配
      • MAC地址匹配:-m mac --mac-source MAC地址
        iptables -A FORWARD -m mac --mac-source xx:xx:xx:xx:xx:xx -j DROP禁止来自某MAC 地址的数据包通过本机转发
    • IP范围匹配
      • IP范围匹配:-m iprange --src-range IP范围
        iptables -A FORWARD -p udp -m iprange --src-range 192.168.150.100-192.168.150.200 -j DROP 禁止转发源地址位于192.168.150.100-192.168.150.200的udp数据包
    • 状态匹配
      • 状态匹配:-m state --state 连接状态
        常见的连接状态:
        NEW :与任何连接无关的,还没开始连接
        ESTABLISHED :响应请求或者已建立连接的,连接态
        RELATED :与已有连接有相关性的(如FTP 主被动模式的数据连接),衍生态,一般与ESTABLISHED 配合使用
        INVALID :不能被识别属于哪个连接或没有任何状态
        iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP禁止转发与正常 TCP 连接无关的非- -syn 请求数据包(如伪造的网络攻击数据包)
      • 实例:
        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 -A INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
        #对进来的包的状态进行检测。已经建立tcp连接的包以及该连接相关的包允许通过。
        #比如我和你做生意,我们谈成了生意,到了支付的时候,就可以直接调用与这笔生意相关的支付功能
        iptables -P INPUT DROP

iptables语法总结图

Insert picture description here

SNAT原理与应用

  • SNAT 应用环境:局域网主机共享单个公网IP地址接入Internet(私有IP不能在Internet中正常路由)
  • SNAT原理:修改数据包的源地址
  • SNAT转换前提条件:
    • 局域网各主机已正确设置IP地址、子网掩码、默认网关地址
    • Linux网关开启IP路由转发
  • 临时打开
    • echo 1 > /proc/sys/net/ipv4/ip_forward
    • sysctl -w net.ipv4.ip_forward=1两种方法
  • 永久打开
    • vim /etc/sysctl.conf
      net.ipv4.ip_forward = 1 将此行写入配置文件
      sysctl -p 读取修改后的配置
  • SNAT转换1:固定的公网IP地址
    • iptables -t nat -A POSTROUTING -s 192.168.150.0/24 -o ens33 -j SNAT --to 12.0.0.1
    • ptables -t nat -A POSTROUTING -s 192.168.150.0/24 -o ens33 -j SNAT --to-source 12.0.0.1-12.0.0.10两种
    • 192.168.150.0/24内网ip , -o 出站外网网卡ens33 ,12.0.0.1-12.0.0.10外网ip或地址池
  • SNAT转换2:非固定的公网IP地址(共享动态ip地址)
    • iptables -t nat -A POSTROUTING -s 192.168.80.0/24 -o ens33 -j MASQUERADE
  • 小知识扩展:
    一个ip地址做SNAT转换,一般可以让内网100到200台主机实现上网

DNAT原理与应用

  • DNAT 应用环境
    • 在Internet中发布位于局域网内的服务器
  • .DNAT原理
    • 修改数据包的目的地址
  • DNAT转换前提条件
    • 局域网的服务器能够访问Internet
    • 网关的外网地址有正确的DNS解析记录
    • Linux网关开启IP路由转发
  • 打开DNAT
    • vim /etc/sysctl.conf
      net.ipv4.ip_forward = 1
      sysctl -p
  • DNAT转换
    • 发布内网的Web服务
      把从ens33进来的要访问web服务的数据包目的地址转换为 192.168.80.11
      iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 80 -j DNAT --to 192.168.80.11或者
      iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 80 -j DNAT --to-destination 192.168.80.11
      iptables -t nat -A PREROUTING -i ens33 -p tcp --dport 80 -j DNAT --to 192.168.80.11-192.168.80.20
  • 发布时修改目标端口
    • #发布局域网内部的OpenSSH服务器,外网主机需使用250端口进行连接
      iptables -t nat -A PREROUTING -i ens33 -d 12.0.0.1 -p tcp --dport 250 -j DNAT --to 192.168.80.11:22
    • #在外网环境中使用SSH测试
      ssh -p 250 [email protected]
    • yum -y install net-tools 若没有 ifconfig 命令可提前使用 yum 进行安装
      ifconfig ens33
    • 注意:使用DNAT时,同时还有配合SNAT使用,才能实现响应数据包的正确返回

防火墙规则的备份和还原

  • 导出(备份)所有表的规则

    • iptables-save > /opt/iptables.txt
      Insert picture description here
      Insert picture description here
  • 导入(还原)规则

    • iptables-restore < /opt/iptables.txt备份好的文件进行还原
  • Save the iptables rules file in /etc/sysconfig/iptables, the rules will be restored automatically when the iptables service starts

    • iptables-save > /etc/sysconfig/iptables
    • systemctl stop iptablesStop the iptables service will clear the rules of all tables
    • systemctl start iptablesStarting the iptables service will automatically restore the rules in /etc/sysconfig/iptables

Guess you like

Origin blog.csdn.net/weixin_53496398/article/details/114929063