iptables 学习
uwupu 啦啦啦啦啦

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:网络地址转换

image

使用

查询filter下的规则

1
iptables --table filter --list
1
2
3
4
5
6
7
8
9
Chain INPUT (policy ACCEPT)
target prot opt source destination
REJECT all -- 192.168.3.123 anywhere reject-with icmp-port-unreachable
Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

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 删除链
  • 规则操作
    • -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

ipset

是iptables的一个工具;可以创建一个数据集合,iptables可以通过该集合进行数据包操作。

比如我要屏蔽INDIA的所有IP地址段:ipset创建一个印度IP地址集合,使用iptables可以设定要DROP的ip集合。

Usage

1
2
3
4
5
6
7
8
9
# 创建集合
ipset create <NAME> <TYPE>
ipset create india hash:net
# 为集合添加数据
ipset add <NAME> <VALUE>
ipset add india 192.168.1.0/24
# 列出集合内容
ipset list <NAME>
ipset list india

补充:

  • 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处理这个哈希值即可。

  1. 从ipdeny下载每个国家的所有ip段。zone文件
  2. 使用ipset创建集合
1
ipset create india hash:net
  1. 使用shell向集合添加数据
1
ipset add india <NET>
  1. 添加iptables
1
2
3
4
5
iptables \
--table filter \
--append INPUT \
--match set --match-set india src \
--jump DROP

--match set --match-set <NAME> <src|dst>:匹配指定集合;src来源,dst目标。

SHELL

屏蔽India的所有IP段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ipset create india hash:net -exist
ipset flush india

[ -f 'in-aggregated.zone' ] && rm in-aggregated.zone


wget https://www.ipdeny.com/ipblocks/data/aggregated/in-aggregated.zone

if [ $? -eq 0 ]
then
echo 'Downloaded zone.'
for address in `cat in-aggregated.zone`
do
ipset add india $address
done
else
echo 'Failed to Download zone.'
fi

iptables \
--table filter \
--append INPUT \
--match set --match-set india src \
--jump DROP
 评论