[Tool] Iptables 简介

最近发生了两次比较尴尬的问题排查,最终结论都是iptables配置错误,影响服务(kafkaspark)组件之间的通信。使用Ambari安装HDP集群的时候,曾强列建议关闭网络防火墙,但是运维的同学感觉完全关闭,服务于裸奔无异,果断还是保留着 iptables 的配置,只是将规则放宽到内网全部端口可用。下边总结一下 iptables 的基本原理以及常见用法。

有问题找男人,先看一下 iptablesman page

Iptables and ip6tables are used to set up, maintain, and inspect the tables of IPv4 and IPv6 packet filter rules in the Linux kernel. Several different tables may be defined. Each table contains a number of built-in chains and may also contain user-defined chains. Several different tables may be defined. Each table contains a number of built-in chains and may also contain user-defined chains. Each chain is a list of rules which can match a set of packets. Each rule specifies what to do with a packet that matches. This is called a target, which may be a jump to a user- defined chain in the same table.

可见 iptables 本身并不是防火墙,只是提供了对 linux kernal 的管理配置功能。

chainiptables 管理的主要对象, chain 初始一共有5条(预定义的):

  • PREROUTING
  • INPUT
  • FORWARD
  • OUTPUT
  • POSTROUTING

每条对应一中场景, 一般关注的是 INPUT 这条 chain, 因为 INPUT 代表的是流入的 package, 对系统威胁较大. 一般会配置为默认丢弃所有的包, 只接受部分符合预期的, 如: 80 http 服务默认端口, 来自内网的 22 端口(内网 ssh 请求).

chain 里的对象是 rule, rule 描述了针对包的匹配规则, 包的目标以及处理方式. 针对每一个包(package)对每个规则进行匹配, 匹配成功就执行响应的动作, 匹配失败就交给下一条规则继续匹配.

下边举个栗子:

$ sudo iptables -L
# 对于INPUTpackage, 默认全部丢弃
Chain INPUT (policy DROP)
target     prot opt source               destination
# 对来自 10.0.0.0/8 网段, 开放 ssh(22)端口
ACCEPT     tcp  --  10.0.0.0/8           anywhere             tcp dpt:ssh
# 响应所有的 ping 请求
ACCEPT     icmp --  anywhere             anywhere             icmp echo-request
# 接受已经建立连接的所有请求
ACCEPT     tcp  --  anywhere             anywhere             state NEW
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED

# 对FROWARD和OUTPUT请求, 全部接受 
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

管理可以通过 iptables 配合参数直接进行修改, 如增加一条接受 eth0 网卡的所有 INPUT 请求的规则: iptables -A INPUT -i eth0 -j ACCEPT

直接用命令修改的规则会及时生效, 但不会做保存, 在机器重启之后, 这些规则会被清除, 如果想要永久保存这些规则, 需要使用 iptables-saveiptables-restore 配合, 先将现有的配置使用 iptables-save 命令保存, 修改之后使用 iptables-restore 保存.

Categories: