iptables 学习

https://www.bilibili.com/video/BV1Jz4y1u7Lz/
iptables
iptables里有多个表,表里有多个链,链里可以设定多个规则。
graph LR R[iptables] --> filter R --> nat R --> mangle R --> raw R --> security filter --> INPUT filter --> FORWARD filter --> OUTPUT nat --> N1[...] mangle --> N2[...] raw --> N3[...] security --> N4[...]
表
filter, nat, mangle, raw, security
- filter: 过滤。
- 可以参与INPUT,FORWARD,OUTPUT链的数据包过滤。
- nat:网络地址转换
链
使用
查询filter下的规则
1 | iptables --table filter --list |
1 | Chain INPUT (policy ACCEPT) |
target 处理方式;prot 协议; opt 操作; source 来源; destination 目标
添加规则
1 | iptables --table TABLE --append 链 --source 来源 --jump 处理方式 |
拒绝来自192.168.3.20的数据包:iptables --table filter --append INPUT --source 192.168.3.20 --jump REJECT
参数
参数
- 基础参数
- –table TABLE
- –line-numbers
- 链操作
- -N, –new-chain ;
-N CHAIN_NAME
创建新链 - -X, –delete-chain ;
-X CHAIN_NAME
删除链
- -N, –new-chain ;
- 规则操作
- -A , –append ;
-A INPUT
添加到INPUT链中 - -I, –insert ;
-I INPUT 1
插入到INPUT链中,为第一条 - -D, –delete ;
-D INPUT 1
删除INPUT中序号为1的规则 - -R, –replace ;
-R INPUT 2
替换INPUT中序号为2的规则 - -L, –list ;
-L INPUT
列出INPUT的所有规则 - -F, –flush ;
-F INPUT
清空INPUT中所有规则 - -P, –policy ;
-P INPUT DROP
为INPUT设定默认策略DROP
- -A , –append ;
ipset
是iptables的一个工具;可以创建一个数据集合,iptables可以通过该集合进行数据包操作。
比如我要屏蔽INDIA的所有IP地址段:ipset创建一个印度IP地址集合
,使用iptables可以设定要DROP的ip集合。
Usage
1 | # 创建集合 |
补充:
- TYPE: IP集合
hash:ip
/ 子网集合hash:net
/ MAC集合hash:mac
/ IP端口组合集合hash:ip,port
/ …
TYPE | hash:ip |
hash:net |
hash:mac |
hash:ip,port |
---|---|---|---|---|
CONTENT | IP集合 | 子网集合 | MAC集合 | IP端口组合集合 |
应用:屏蔽指定国家IP
解释
原理:下载一个国家所有IP段文件zone文件;ipset可以为IP地址集合创建一个哈希值;然后让iptables处理这个哈希值即可。
- 从ipdeny下载每个国家的所有ip段。zone文件
- 使用ipset创建集合
1 | ipset create india hash:net |
- 使用shell向集合添加数据
1 | ipset add india <NET> |
- 添加iptables
1 | iptables \ |
--match set --match-set <NAME> <src|dst>
:匹配指定集合;src来源,dst目标。
SHELL
屏蔽India的所有IP段
1 | ipset create india hash:net -exist |
评论