Created
November 21, 2012 06:53
-
-
Save hahastudio/4123472 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import dpkt, socket | |
f = open('t.cap', 'rb') | |
pcap = dpkt.pcap.Reader(f) | |
c = 0 | |
ptr_c = 0 | |
log = open('4-seg-ip-dns-filter','w') | |
dic = {} | |
for ts, buf in pcap: | |
# make sure we are dealing with IP traffic | |
# ref: http://www.iana.org/assignments/ethernet-numbers | |
c += 1 | |
try: | |
#check if it has a Linux cooked capture | |
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 | |
try: | |
ip = eth.data | |
except: | |
#print 'ip, %d' % c | |
continue | |
# make sure we are dealing with UDP | |
# ref: http://www.iana.org/assignments/protocol-numbers/ | |
try: | |
if ip.p != 17: | |
continue | |
except AttributeError: | |
#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 | |
try: | |
if dns.qd[0].type == dpkt.dns.DNS_PTR: | |
ptr_c += 1 | |
if dns.qr == dpkt.dns.DNS_Q: | |
ip_addr = socket.inet_ntoa(ip.src) | |
if dic.has_key(ip_addr): | |
dic[ip_addr] += 1 | |
else: | |
dic[ip_addr] = 1 | |
except : | |
pass | |
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: | |
pass#print "CNAME request", answer.name, "\tresponse", answer.cname | |
elif answer.type == 1: | |
pass#print "A request", answer.name, "\tresponse", socket.inet_ntoa(answer.rdata) | |
elif answer.type == 12: | |
print "PTR request", answer.name, "\tresponse", answer.ptrname | |
sorted_dict = sorted(dic.iteritems(), key=lambda x:x[1], reverse=True) | |
for i in sorted_dict: | |
log.write(i[0] + ' ' + str(i[1]) + '\n') | |
print ptr_c, c | |
f.close() | |
log.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment