- OpenWrt 防火墙基础过滤--域名过滤
- 域名过滤
- 直接劫持ip
- uci 自定义域
- dnsmasq+ipset+iptables
前文提到了在 openwrt 系统中,IP过滤和mac 过滤的大概实现,这里再简单介绍下域名过滤的实现。 域名过滤
域名过滤主要是建立在dns服务器基础上。前期我也考虑过通过域名劫持的方式将访问转接到其他地址
直接劫持ip比如:在openwrt系统中,我们可以通过修改 dnsmasq.conf 文件进行实现。
# vi /etc/dnsmasq.conf address=/testdomain.com/10.10.254.62 //在文本最后添加一行实现testdomain.com域名劫持到ip地址10.10.254.62 # /etc/init.d/dnsmasq restart
这样,我们访问网页的时候就会跳到10.10.254.62的地址上
#ping baidu.com PING baidu.com (10.10.254.62): 56 data bytes ping: sendto: Network is unreachable
但是,在实际应用中会出现很多问题,就比如一个很实际的问题,怎么实现黑白名单,我们不可能每次都会对后台进行修改。
uci 自定义域这时,我又考虑到第二种方式,也就是
通过openwrt系统自带的 uci 工具实现自定义域,建立dhcp域名池 来进行拦截
#uci add dhcp domain #uci set dhcp.@domain[-1].name="baidu.com" #uci set dhcp.@domain[-1].ip="127.0.0.1" uci commit dhcp /etc/init.d/dnsmasq restart
#ping baidu.com PING baidu.com (127.0.0.1): 56 data bytes ping: sendto: Network is unreachable
这种方式一度让我觉得可行,我可以通过 uci 工具对要过滤的 dns 进行直接的 拦截与开放,但是在后续的测试过程中,我发现了 这种方式的不足。
在测试拦截的有效性时,我发现是能够满足我对对应域名的拦截,但是,这种方式的拦截对精确度要求太高,我不能拦截到它的别名域名。
就比如:我在我的dhcp 域名池中添加的是 baidu.com ,那么就不能拦截到 www.baidu.com 这个域名的访问链接。这种方式被我放弃了。
dnsmasq+ipset+iptables最后,我采用了这种方式。利用ipset 创建ip集,将域名所对应的ip 储存到ip集中,对整个ip集利用iptables 进行操作,这样就完美的实现了域名的拦截和黑白名单操作。
openwrt的默认dnsmasq并不支持ipset,需要安装dnsmasq-full版本。而 ipset是为了支持对域名的转发代理
1.配置
iptables + ipset + dnsmasq-full
vi /etc/dnsmasq.conf
末尾添加:
server=/.com/127.0.0.1#53
server=/.com/127.0.0.1#53 server=/.cn/127.0.0.1#53 server=/.net/127.0.0.1#53 conf-dir=/etc/dnsmasq.d
新建文件夹
mkdir /etc/dnsmasq.d cd /etc/dnsmasq.d touch domain.conf
在domain.conf中添加内容,例如:
ipset=/baidu.com/domain ipset=/qq.com/domain ...
创建一个ipset,禁用URL接触出的IP地址存储在该ipset中。鉴于ipset保存在内存中,重启后需要重新设置
ipset -N domain iphash
操作–>将规则写入到开机自启动的firewall文件路径中,在openwrt中文件一般为firewall.user.
黑名单:
iptables -t filter -I 规则链 -m set --match-set domain dst -j REJECT iptables -t filter -I 规则链 -m set --match-set domain src -j REJECT
白名单:
iptables -t filter -I 规则链 -m set --match-set domain dst -j ACCEPT
iptables -t filter -I 规则链 -m set --match-set domain src -j ACCEPT
iptables -t filter -A 规则链 -j REJECT
注:ipset每次重启后失效,因此需要把ipset写入开机自启动文件中,在openwrt系统中,uci支持ipset, 我们用uci 设置firewall
config ipset
option name 'domain'
option match 'ip'
option storage 'hash'
option enabled '1'
作用等同于:ipset -N domain iphash
在我的openwrt 系统中,iptables 没有安装 string 模块,这个也可以使用 iptables 中的 string 模块进行实现,但是精确性不高,且效率低



