使用 dpkt 库从 DNS 响应数据包中提取域名 [英] Extracting domain name from a DNS Response packet using dpkt library
问题描述
我正在尝试使用可用的 dpkt 库从 pcap 文件生成所有域名及其相应 IP 地址的列表 这里
I'm trying to generate a list of all domain names and their corresponding IP addresses from a pcap file, using dpkt library available here
我的代码主要基于 这个
filename = raw_input('Type filename of pcap file (without extention): ')
path = 'c:/temp/PcapParser/' + filename + '.pcap'
f = open(path, 'rb')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
#make sure we are dealing with IP traffic
try:
eth = dpkt.ethernet.Ethernet(buf)
except:
continue
if eth.type != 2048:
continue
#make sure we are dealing with UDP protocol
try:
ip = eth.data
except:
continue
if ip.p != 17:
continue
#filter on UDP assigned ports for DNS
try:
udp = ip.data
except:
continue
if udp.sport != 53 and udp.dport != 53:
continue
#make the dns object out of the udp data and
#check for it being a RR (answer) and for opcode QUERY
try:
dns = dpkt.dns.DNS(udp.data)
except:
continue
if dns.qr != dpkt.dns.DNS_R:
continue
if dns.opcode != dpkt.dns.DNS_QUERY:
continue
if dns.rcode != dpkt.dns.DNS_RCODE_NOERR:
continue
if len(dns.an) < 1:
continue
#process and print responses based on record type
for answer in dns.an:
if answer.type == 1: #DNS_A
print 'Domain Name: ', answer.name, '\tIP Address: ', socket.inet_ntoa(answer.rdata)
问题是 answer.name 对我来说不够好,因为我需要请求的原始域名,而不是它的 CNAME 表示.例如,原始 DNS 请求之一是针对 www.paypal.com
,但它的 CNAME 表示是 paypal.112.2o7.net
.
The problem is that answer.name is not good enough for me, because I need the original domain name requested, and not its' CNAME representation. For example, one of the original DNS requests was for www.paypal.com
, but the CNAME representation of it is paypal.112.2o7.net
.
我仔细查看了代码并意识到我实际上是从 DNS 响应(而不是查询)中提取信息.然后我查看了wireshark中的响应包,看到原始域在那里,在'queries'和'answers'下,所以我的问题是如何提取它?
I looked closely at the code and realized I'm actually extracting the information from the DNS Response (and not the query). Then I looked at the response packet in wireshark and saw that the original domain is there, under 'queries' and under 'answers', so my question is how can I extract it?
谢谢!
推荐答案
为了从 DNS 响应的Questions"部分获取名称,通过 dns.qd
对象,由dpkt.dns
,我需要做的就是:
In order to acquire the name from the "Questions" section of the DNS response, via the dns.qd
object, provided by dpkt.dns
, all I needed to do was simply this:
for qname in dns.qd: print qname.name
这篇关于使用 dpkt 库从 DNS 响应数据包中提取域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!