iptables的基本用法
source link: https://bajie.dev/posts/20221024-iptables/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Iptables的基本用法
面试的时候经常会被问到 iptables 的问题,那么下面就运维角度来总结一下基本的用法。
看晕了吧,不要紧,我们关注上面的5个红色,5个链条,然后继续看下面的表,详细解释了上面的流程:
两张图结合起来看,意思就是整个 iptables 可以动手的地方太多了。
我们完全没必要关注那么多的细节,常用的地方就2个:
一、最后的出口nat postrouting
iptables -t nat -A POSTROUTING -s 10.11.0.0/16 -j SNAT --to 172.16.8.1
上面是做 openvpn 时常用的,一定记得不要乱用 MASQUERADE,而要指定 特定网段(10.11.0.0/16) 从 特定IP(172.16.8.1) 出去。
二、filter表
filter表是 iptables 缺省不带参数查看的表,用于过滤数据包,这是我们操作的最多的地方
iptables -I INPUT -s 185.207.178.236/32 -p tcp --dport 12530 -j ACCEPT
iptables -A INPUT -p tcp --dport 12530 -j DROP
上面就只开放了一个IP 185.207.178.236可以访问本机的12530端口,其余的统统封掉,这是最常用的脚本了。
OK,以上两点是最常用的。其余的端口转发之类的,最好中间用haproxy和nginx进行代理,否则查看 iptables 系统的架构就变得不清晰了。
下面贴上常用的参数:
-p tcp/udp/icmp/all 匹配协议,all会匹配所有协议
-s addr[/mask] 匹配源地址
-d addr[/mask] 匹配目标地址
--sport 匹配源端口(可指定连续的端口)如--sport80
--dport 匹配目的端口(可指定连续的端口)如--dport80
-o interface 匹配出口网卡,只适用于FORWARD、POSTROUTING、OUTPUT(例:iptables -A FORWARD -o eth0)
-i interface 匹配入口网卡,只适用于PREROUTING、INPUT、FORWARD
--icmp-type 匹配icmp类型(使用iptables -p icmp -h可查看可用的icmp类型)
--tcp-flags mask comp 匹配TCP标记,mask表示检查范围,comp表示匹配mask中的哪些标记(例:iptables -A FORWARD -p tcp --tcp-flags ALL SYN,ACK -j ACCEPT 表示匹配SYN和ACK标记的数据包)
-j DROP/ACCEPT/REJECT/LOG 拒绝/允许/拒绝并发出消息/在/var/log/messages中登记分组匹配的记录
-m mac -mac 绑定MAC地址
-m limit -limit 1/s 1/m 设置时间策略
-s 192.168.1.153或192.168.1.0/24 指定源地址或地址段
-d 192.168.1.153或192.168.1.0/24 指定目标地址或地址段
-s ! 192.168.1.0 指定源地址以外的
基本的2个用法足够满足日常运维的需要了。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK