iptables实现针对域名匹配规则

iptables 一般都是基于 IP、端口、协议 来实现数据包过滤
本文主要记录如何借助于 dnsmasq 以及 ipset, “曲线救国”地实现 iptables 针对域名做规则匹配

概述

本文实现方法为:

  • dnsmasq 后期版本支持将解析域名的结果添加到 ipset
  • iptables 使用 -m set 模块可以基于 ipset 做地址匹配

实现

一、dnsmasq

1. 确认 dnsmasq 支持 ipset

使用 dnsmasq -v 确认当前版本是否支持 ipset 🤖 没有的可以直接关闭本文了
image

2. 配置 dnsmasqipset 相关

  1. 编辑 /etc/dnsmasq.conf
conf-dir=/etc/dnsmasq.d
  1. /etc/dnsmasq.d/ 目录下建立 ipset 配置文件 domain.conf🤖 名字随意
ipset=/.baidu.com/myddns
  1. 建立对应的 ipset
    ipset create myddns hash:ip

  2. 重启 dnsmasq

二、iptables

在对应的规则中使用上文的 ipset 即可
iptables -I FORWARD -m set --match-set myddns src -j ACCEPT


额外的尝试

iptables 其实也有字符串匹配模块 -m string
但是我实际尝试并没有生效, 也许是配置有问题?

posted @ 2023-03-29 16:38  tfel-ypoc  阅读(440)  评论(0编辑  收藏  举报