Featured image of post Debian 网关 [Episode 03]: DHCP 与 DNS 服务

Debian 网关 [Episode 03]: DHCP 与 DNS 服务

使用 dnsmasq 为内网分配 IP 及域名分流解析

安装 dnsmasq

1sudo apt install -y dnsmasq

配置 dnsmasq

删除原有配置

反正本身也没啥配置

  • 先关闭 dnsmasq
1sudo systemctl stop dnsmasq
  • 再删除
1sudo rm -vf /etc/dnsmasq.conf
2# sudo rm -vf /etc/dnsmasq.d/*

基础配置

 1export DOMAIN="example.com"
 2export IP_POOL_S="192.168.64.32"
 3export IP_POOL_E="192.168.64.254"
 4
 5sudo tee /etc/dnsmasq.conf > /dev/null <<EOF
 6port=53
 7server=1.1.1.1
 8server=1.0.0.1
 9no-resolv
10all-servers
11cache-size=8192
12conf-dir=/etc/dnsmasq.d
13domain-needed
14local=/${DOMAIN}/
15domain=${DOMAIN}
16bind-interfaces
17
18interface=br-lan
19dhcp-range=${IP_POOL_S},${IP_POOL_E},8h
20dhcp-option=option:domain-name,${DOMAIN}
21dhcp-option=option:domain-search,${DOMAIN}
22EOF
  • 说明:
    • line 1: example.com 替换为自己的本地域域名
    • line 2: 192.168.64.32 以下预留给一些服务
    • 静态绑定: (在 line 21 之后追加,${} 变量自行替换)
      • 基于 MAC 地址: dhcp-host=${MAC_ADDRESS},${IP_ADDRESS},infinite
      • 基于主机名: dhcp-host=${IP_ADDRESS},${HOSTNAME},infinite

分流配置

规则来源: https://github.com/felixonmars/dnsmasq-china-list

  • 切换到配置目录
1cd /etc/dnsmasq.d
  • 下载配置
1sudo curl -fLO "https://raw.kgithub.com/felixonmars/dnsmasq-china-list/master/accelerated-domains.china.conf"
2sudo curl -fLO "https://raw.kgithub.com/felixonmars/dnsmasq-china-list/master/apple.china.conf"
3sudo curl -fLO "https://raw.kgithub.com/felixonmars/dnsmasq-china-list/master/bogus-nxdomain.china.conf"
4sudo curl -fLO "https://raw.kgithub.com/felixonmars/dnsmasq-china-list/master/google.china.conf"

启动 dnsmasq

1sudo systemctl start dnsmasq

[选] 设置本机 DNS

将本机 DNS 设置为 127.0.0.1 可 ping 通内网主机

1sudo tee /etc/resolv.conf > /dev/null <<EOF
2nameserver 127.0.0.1
3EOF

解决 DNS 污染问题

方案一:DoH

安装 cloudflared

1curl -fLO "https://kgithub.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb"
2sudo apt install ./cloudflared-linux-amd64.deb

写入 service 文件

 1sudo tee /etc/systemd/system/cloudflared-proxy-dns.service > /dev/null <<EOF
 2[Unit]
 3Description=DNS over HTTPS (DoH) proxy client
 4Wants=network-online.target nss-lookup.target
 5Before=nss-lookup.target
 6
 7[Service]
 8AmbientCapabilities=CAP_NET_BIND_SERVICE
 9CapabilityBoundingSet=CAP_NET_BIND_SERVICE
10DynamicUser=yes
11ExecStart=/usr/local/bin/cloudflared proxy-dns --port 5053
12
13[Install]
14WantedBy=multi-user.target
15EOF

启用 cloudflared

1sudo systemctl enable --now cloudflared-proxy-dns

修改 dnsmasq 配置

  • 修改 /etc/dnsmasq.conf,仅保留一个 server
1server=127.0.0.1#5053
  • 随后重启 dnsmasq

方案二:将 DNS 流量代理出去

dnsmasq 没有代理选项,需要用到透明代理技术,参见之后的透明代理

CC BY-NC-SA 4.0 转载或引用本文时请遵守许可协议,注明出处、不得用于商业用途!
最后更新于 Apr 29, 2023 01:18 +0800
人最重要的特点是会思考,写博客的初衷是保存思维的电子快照。 当然各种文档工具亦或是简单的文本编辑器也能随时记录点滴,选择建个人网站无非是想满足技术爱好者的偏执。
Built with Hugo
主题 StackJimmy 设计