Skip to content

Instantly share code, notes, and snippets.

@hahastudio
Created November 20, 2012 14:21
Show Gist options
  • Save hahastudio/4118209 to your computer and use it in GitHub Desktop.
Save hahastudio/4118209 to your computer and use it in GitHub Desktop.
import dpkt, socket
f = open('t.cap', 'rb')
pcap = dpkt.pcap.Reader(f)
c = 0
for ts, buf in pcap:
# make sure we are dealing with IP traffic
# ref: http://www.iana.org/assignments/ethernet-numbers
c += 1
try:
if pcap.datalink() == dpkt.pcap.DLT_LINUX_SLL:
eth = dpkt.sll.SLL(buf)
else:
eth = dpkt.ethernet.Ethernet(buf)
except:
print 'eth, %d' % c
continue
#if eth.type != 2048:
#print 'eth.type, %d' % c
#continue
# make sure we are dealing with UDP
# ref: http://www.iana.org/assignments/protocol-numbers/
try:
ip = eth.data
except:
print 'ip, %d' % c
continue
if ip.p != 17:
print 'ip.p, %d' % c
continue
# filter on UDP assigned ports for DNS
# ref: http://www.iana.org/assignments/port-numbers
try:
udp = ip.data
except:
print 'udp: %s %d' % (ip, c)
continue
if udp.sport != 53 and udp.dport != 53:
print 'udp.port, %d' % c
continue
# make the dns object out of the udp data and check for it being a RR (answer)
# and for opcode QUERY (I know, counter-intuitive)
try:
dns = dpkt.dns.DNS(udp.data)
except:
print 'dns, %d' % c
continue
print 'Yeah!'
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
# now we're going to process and spit out responses based on record type
# ref: http://en.wikipedia.org/wiki/List_of_DNS_record_types
for answer in dns.an:
if answer.type == 5:
print "CNAME request", answer.name, "\tresponse", answer.cname
elif answer.type == 1:
print "A request", answer.name, "\tresponse", socket.inet_ntoa(answer.rdata)
elif answer.type == 12:
print "PTR request", answer.name, "\tresponse", answer.ptrname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment