如果我们使用 scapy 发送一个 dns 请求,我们可以得到如下的 dns 响应:
>>> dns.show()
###[ DNS ]###
id= 43223
qr= 1L
opcode= QUERY
aa= 0L
tc= 0L
rd= 1L
ra= 1L
z= 0L
rcode= ok
qdcount= 1
ancount= 3
nscount= 0
arcount= 0
\qd\
|###[ DNS Question Record ]###
| qname= 'search.yahoo.com.'
| qtype= A
| qclass= IN
\an\
|###[ DNS Resource Record ]###
| rrname= 'search.yahoo.com.'
| type= CNAME
| rclass= IN
| ttl= 5
| rdlen= 39
| rdata= 'ds-global.l7.search.ystg1.b.yahoo.com.'
|###[ DNS Resource Record ]###
| rrname= 'ds-global.l7.search.ystg1.b.yahoo.com.'
| type= CNAME
| rclass= IN
| ttl= 96
| rdlen= 43
| rdata= 'ds-any-global.l7.search.ysta1.b.yahoo.com.'
|###[ DNS Resource Record ]###
| rrname= 'ds-any-global.l7.search.ysta1.b.yahoo.com.'
| type= A
| rclass= IN
| ttl= 94
| rdlen= 4
| rdata= '188.125.66.104'
ns= None
ar= None
qdcount - 查询 dns 计数,
ancount - dns 应答计数,
dns.an[0]是第一个 DNSRR,
dns.an[1]是第二个 DNSRR,
...
我们可以用 ancount 解析 DNSRR ,这是我的演示代码:
#!/usr/bin/env python
# -*- coding: utf8 -*-
from scapy.all import *
# disable verbose mode
conf.verb = 0
def parse_dnspkt(pkt):
""" parse dns request / response packet """
if pkt and pkt.haslayer('UDP') and pkt.haslayer('DNS'):
ip = pkt['IP']
udp = pkt['UDP']
dns = pkt['DNS']
# dns query packet
if int(udp.dport) == 53:
qname = dns.qd.qname
print "\n[*] request: %s:%d -> %s:%d : %s" % (
ip.src, udp.sport,
ip.dst, udp.dport,
qname)
# dns reply packet
elif int(udp.sport) == 53:
# dns DNSRR count (answer count)
for i in range(dns.ancount):
dnsrr = dns.an[i]
print "[*] response: %s:%s <- %s:%d : %s - %s" % (
ip.dst, udp.dport,
ip.src, udp.sport,
dnsrr.rrname, dnsrr.rdata)
def sniffer():
sniff(filter="udp port 53", prn=parse_dnspkt)
if __name__ == "__main__":
sniffer()
在你的 shell 中执行nslookup search.yahoo.com和nslookup stackoverflow.com 。
root:scapy/ # python scapy-dns_sniff.py
WARNING: No route found for IPv6 destination :: (no default route?)
[*] request: 192.168.1.108:59199 -> 192.168.1.1:53 : search.yahoo.com.
[*] response: 192.168.1.108:59199 <- 192.168.1.1:53 : search.yahoo.com. - ds-global.l7.search.ystg1.b.yahoo.com.
[*] response: 192.168.1.108:59199 <- 192.168.1.1:53 : ds-global.l7.search.ystg1.b.yahoo.com. - ds-any-global.l7.search.ysta1.b.yahoo.com.
[*] response: 192.168.1.108:59199 <- 192.168.1.1:53 : ds-any-global.l7.search.ysta1.b.yahoo.com. - 188.125.66.104
[*] request: 192.168.1.108:55391 -> 192.168.1.1:53 : stackoverflow.com.
[*] response: 192.168.1.108:55391 <- 192.168.1.1:53 : stackoverflow.com. - 198.252.206.16