CentOS使用dnsmasq实现DNS域名拦截

dns域名拦截

具体描述:笔记本这边访问www.baidu.com,服务器将其拦截到自己的服务中,返回自定义内容。

  1. 防火墙开放53端口
    firewall-cmd --add-service=dns --permanent
    firewall-cmd --add-port=53/tcp --zone=public --permanent
    firewall-cmd --add-port=53/udp --zone=public --permanent
    firewall-cmd --reload
    systemctl restart firewalld
    
  2. 修改dnsmasq配置(没有安装的话可以通过yum安装)
    1. 修改/etc/dnsmasq.conf
    resolv-file=/etc/resolv.dnsmasq.conf    # dnsmasq 会从这个文件中寻找上游dns服务器
    strict-order            
    interface=eth1                        # 监听网卡eth1
    listen-address=0.0.0.0                # 监听所有地址
    address=/baidu.com/192.168.0.145      # 域名解析
    no-hosts                              # 取消解析默认的hosts文件
    
    1. 修改/etc/resolv.conf
    echo 'nameserver 127.0.0.1' > /etc/resolv.conf
    
    1. 创建resolv.dnsmasq.conf文件并添加上游dns服务器的地址
    touch /etc/resolv.dnsmasq.conf
    # 添加上游的DNS服务器,也就是公网DNS,这里添加114.114.114
    echo 'nameserver 114.114.114.114' > /etc/resolv.dnsmasq.conf
    
    
    1. 创建dnsmasq.hosts文件
    cp /etc/hosts /etc/dnsmasq.hosts
    # 在这个目里面添加记录
    echo 'addn-hosts=/etc/dnsmasq.hosts' >> /etc/dnsmasq.conf
    
  3. 修改内网主机DNS服务器为服务器eth1的ip

shell脚本

dns-cfg.sh

#!/bin/sh
# 配置dnsmasq的dns劫持,将内网主机的域名请求解析成指定的ip

echo "# 防火墙配置"
firewall-cmd --add-service=dns --permanent
firewall-cmd --add-port=53/tcp --zone=public --permanent
firewall-cmd --add-port=53/udp --zone=public --permanent
firewall-cmd --reload
systemctl restart firewalld

echo "# 修改dnsmasq配置"
# dnsmasq 会从这个文件中寻找上游dns服务器, 默认是从hosts文件中寻找
echo 'resolv-file=/etc/resolv.dnsmasq.conf' >> /etc/dnsmasq.conf
# 表示严格按照resolv-file文件中的顺序从上到下进行DNS解析,直到第一个解析成功为止
echo 'strict-order' >> /etc/dnsmasq.conf
# 监听网卡eth1
echo 'interface=eth1' >> /etc/dnsmasq.conf
# 域名解析
ip=$(awk -F "=" '/^IPADDR/{print $2}' /etc/sysconfig/network-scripts/ifcfg-eth0)
echo "address=/baidu.com/${ip}" >> /etc/dnsmasq.conf
# 取消解析默认的hosts文件
echo 'no-hosts' >> /etc/dnsmasq.conf
# 修改/etc/resolv.conf
echo 'nameserver 127.0.0.1' > /etc/resolv.conf
# 创建resolv.dnsmasq.conf文件并添加上游dns服务器的地址
touch /etc/resolv.dnsmasq.conf
echo 'nameserver 114.114.114.114' > /etc/resolv.dnsmasq.conf

# 创建dnsmasq.hosts文件
cp /etc/hosts /etc/dnsmasq.hosts
echo 'addn-hosts=/etc/dnsmasq.hosts' >> /etc/dnsmasq.conf

echo "# 启动dnsmasq"
systemctl enable dnsmasq
systemctl start dnsmasq

你可能感兴趣的:(CentOS使用dnsmasq实现DNS域名拦截)