使用 iptables 将传出的 dns 查询重定向到本地主机

使用 iptables 将传出的 dns 查询重定向到本地主机

问题

有些传出TCP我无法控制我的 Ubuntu 服务器中的 DNS 请求由 127.0.0.1:53 上的 Unbound 解析,它使用 208.67.222.222 来解析所有请求,我看到那些 TCP DNS 数据包最终从我的公共 IP 地址传输到著名的 DNS 服务器,例如 8.8.8.8 和 1.1.1.1。

我做了什么

ipset -N myipset iphash
ipset -A myipset 127.0.0.1
ipset -A myipset 208.67.222.222

iptables -t nat -D OUTPUT -m udp -p udp --dport 53 -m set ! --match-set myipset -j DNAT --to 127.0.0.1:53
iptables -t nat -D OUTPUT -m tcp -p tcp --dport 53 -m set ! --match-set myipset -j DNAT --to 127.0.0.1:53

我使用 OUTPUT 是因为我相信 PREROUTING 不会影响它们,因为它们是本地生成的,并且在发送之前重定向它们。但是当我运行这些命令时,这些 TCP 数据包的 DNS 根本不起作用,但dnslookup -vc使用 Unbound 可以。

我的问题

我应该做一些特别的事情来让这些规则发挥作用吗?我遗漏了什么吗?也许是一些 sysctl.conf 的东西?

/etc/sysctl.conf

net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
net.ipv4.conf.all.route_localnet = 1
net.ipv4.conf.ens3.route_localnet = 1

/etc/unbound/unbound.conf

server:
  port: 53
  cache-min-ttl: 600
  rrset-cache-size: 64m
  msg-cache-size: 32m
  prefetch: yes
  serve-expired: yes
  serve-expired-ttl: 86400
  do-not-query-localhost: no
  tcp-upstream: yes
  outgoing-num-tcp: 2000
  incoming-num-tcp: 2000

remote-control:
  control-enable: yes

forward-zone:
  name: "."
  forward-addr: 208.67.222.222

Unbound 在 TCP 和 UDP 端口 53 上运行。

答案1

一个新手错误。iptables规则没问题。问题出在unbound的配置上(实际上我不知道它是如何工作的!),我不得不添加它access-control,以便它接受来自我服务器的公共 IP 地址的 TCP 请求:

server:
  ...
  access-control: <server public ip address>/24 allow_snoop

然后重新启动unbound。到目前为止一切正常。

相关内容