【Linux】记录所有 DNS 查询

Posted by 西维蜀黍 on 2022-04-03, Last Modified on 2023-05-02

[Recommend] Via DNS Sniffer

# If ubuntu
$ sudo apt-get install python3-scapy; 
# If OpenWrt
$ opkg install scapy
# If macOS
$ brew install libpcap; sudo pip3 install scapy -i https://pypi.python.org/simple

$ git clone git@github.com:Oros42/DNS_sniffer.git; cd DNS_sniffer

# For a specific interface
$ sudo python3 dns_sniffer.py -i eth0

# Write to a DB
$ sudo python3 dns_sniffer.py -i en0 -d db.sqlite

Demo

在一个 session运行

$ dig google.com

...

这次 DNS query即可被捕捉到

$ sudo python3 dns_sniffer.py -i tun0
IP source       | DNS server      | Count DNS request | Query
10.22.56.25
                  8.8.8.8
                                    1                   google.com.

Ref

Via tcpdump

$ sudo tcpdump --list-interfaces

$ sudo tcpdump udp port 53 --interface <pickone>


# To show and save to file all the A DNS requests, run this:
$ script -q -c "sudo tcpdump -l port 53 2>/dev/null | grep --line-buffered ' A? ' | cut -d' ' -f8" | tee dns.log

Via a Local DNS Server

Install Bind locally. Most distros default install of Bind will be non-autoritative caching-only.

Simply add a logging {} config block (as described in the Bind 9 Configuration Reference) then set your system to use 127.0.0.1 or ::1 as the DNS resolver.

Reference