#!/usr/bin/env python
#
# Copyright (C) Andrea Di Pasquale <andrea.dipasquale@hackingteam.it>
#

import subprocess
import signal
import getopt
import time
import re
import sys
import string
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *

global count2
global count3
global count4

def usage():
	print " "
	print "DNS Query usage:"
	print " "
	print "-d <destination>    : The destination address"
	print "-i <ip>  	   : The ip address"
	print "-n <number>         : The number of query"
	print " "
	sys.exit()

	return

def SIGNAL_handler(signum, frame):
	global count2
	global count3
	global count4

	print " "
	print "Signal caught."
	str1 = "\nSUCCESS(" + str(count2) + ") - FAILED(" + str(count3) + ") - TOTAL(" + str(count2 + count3 + count4) + ")"
	print str1
	sys.exit()

	return

def main():
	global count2
	global count3
	global count4
	
	try:
		opts, args = getopt.getopt(sys.argv[1:],"d:n:i:")
	except:
		usage()
		sys.exit(1)

	dst = None
	num = None

	for o, a in opts:
		if o == '-d':
			dst = a
		elif o == '-n':
			num = a
		elif o == '-i':
			ip = a
			
	if args or not dst or not num:
		usage()
		sys.exit(1)

	signal.signal(signal.SIGINT, SIGNAL_handler)
	signal.signal(signal.SIGTERM, SIGNAL_handler)
	count = 0
	count2 = 0
	count3 = 0
	count4 = 0

	for i in range(1, int(num) + 1):
		subprocess.call('killall netcat 2> /dev/null', shell=True)

		get = 'GET / HTTP/1.1\r\n' \
		      'Host: ' + dst + '\r\n' \
		      'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0\r\n' \
		      'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n' \
		      'Accept-Language: en-us,en;q=0.5\r\n' \
		      'Accept-Encoding: gzip, deflate\r\n' \
		      'Connection: keep-alive\r\n' \
		      '\r\n'
		cmd = 'echo \"' + get + '\" | netcat ' + ip + ' 80'
		try:
			ret = subprocess.check_output(cmd, shell=True).strip()
		except:
			continue

		if string.find(ret, "Location") == - 1:
			count4 += 1
			print ret[:83]
			continue

		index1 = string.find(ret, "Location") + 17
		sito = ret[index1:len(ret)]
		index2 = string.find(sito, "\n") - 1
		sito = sito[0:index2]

		print ""
		print "DNS Query number", i, "to", sito, "..."

		pkt = sr1(IP(dst="192.168.1.1")/UDP()/DNS(rd=1, qd=DNSQR(qname=sito)))

		if pkt.haslayer(DNSRR):
			result = pkt.getlayer(DNSRR).type

			if result == 1 or result == 5 or result == 28:
				print "======================= SUCCESS %s =======================" %(sito)
				count2 = count2 + 1
			else:
				print "======================= FAILED %s ========================" %(sito)
				count3 = count3 + 1

			print ""

	str1 = "\nSUCCESS(" + str(count2) + ") - FAILED(" + str(count3) + ") - NONREDIR(" + str(count4) + ") - TOTAL(" + str(count2 + count3 + count4) + ")"
	print str1
	
	return

if __name__ == "__main__":
	main()
