iptables
Basic
-t filter|nat|mangle
指定 table。默认 filter。- ACCEPT, REJECT, DROP are terminating targets. They terminate processing of the packet in the current Netfilter hook. MARK, LOG and many others are non-terminating targets. They create some action based on the packet, and then proceed to the next rule.
Commons
# create new custom chain
iptables -t mangle -N DIVERT
# flush (清空) 某个 chain
iptables -F INPUT
# allow input
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# port range (inclusive)
iptables -A INPUT -p tcp --dport 6000:7000 -j ACCEPT
# multi port
iptables -A INPUT -p tcp -m multiport --dport 80,443 -j ACCEPT
# match NOT certain ports
iptables -A INPUT -p tcp -m multiport ! --dport 80,443 -j ACCEPT
# conntrack 的几种状态:ESTABLISHED,RELATED,NEW,INVALID
# 允许本机主动发起的连接的所有(接收的)数据包
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# 丢弃所有接收的连接状态不合法的包
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# vpn server. must also set net.ipv4.ip_forward=1
iptables -t nat -A POSTROUTING -j MASQUERADE
# 或者,限制仅对 src IP 是内网的数据包 MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.0.0/16 -j MASQUERADE
# MSS CLAMP to fix all MTU related problems
iptables -t mangle -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
# 对属于某个 ipset 的 dst IP 做策略路由,以 "china" 这个 ipset 为例
iptables -t mangle -A PREROUTING -m set --match-set china dst -j MARK --set-mark 0x1/0x1
iptables -t mangle -A OUTPUT -m set --match-set china dst -j MARK --set-mark 0x1/0x1
ip rule add fwmark 0x1/0x1 lookup main prio 1
# 对 PREROUTING 符合特定 mark 比特位的流量做 DNAT
iptables -t nat -A PREROUTING -m mark --mark 0x1/0x1 -j DNAT --to 1.2.3.4:443
# 劫持所有途径本机的udp 53 DNS 流量到本机
# 一般用在路由器上,配合 dnsmasq 使用。
iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-port 53
# 概率匹配。用于做 round robin tcp 负载均衡。通常需要配合(-t nat POSTROUTING) SNAT。
iptables -A PREROUTING -t nat -p tcp -d 192.168.1.1 --dport 27017 -m statistic --mode random --probability 0.33 -j DNAT --to-destination 10.0.0.2:1234
# 另一种负载均衡方式。every(n) +packet(p). The rule will be evaluated every n packet starting at the packet p.
iptables -A PREROUTING -t nat -p tcp -d 192.168.1.1 --dport 27017 -m statistic --mode nth --every 3 --packet 0 -j DNAT --to-destination 10.0.0.2:1234
Others
TTL
# 修改转发的数据包的TTL
iptables -t mangle -A PREROUTING -i eth0 -j TTL --ttl-set 64
Comments
# 添加规则时制定 comment
iptables -m comment --comment "__flag__"
# 移除所有包含某个 comment 的 iptables 规则
iptables-save | grep -v "__flag__" | iptables-restore
DNAT 到 lo 地址
出于安全考虑,内核默认不支持把外部流量 DNAT到本地回环地址 127.0.0.0/8,需要设置:
sysctl net.ipv4.conf.all.route_localnet=1