#!/usr/bin/env python2

#Covered by GPL V2.0:w
import time
import string
import httplib,sys
from socket import *
import re
import getopt

print "\n*************************************"
print "*Subdomainer Ver. 1.2	            *"
print "*Coded by Christian Martorella      *"
print "*Edge-Security Research             *"
print "*laramies2k@yahoo.com.ar            *"
print "*************************************\n\n"

#Cheers to Trompeti, Pluf, Dani, Javi, al3x and all s21sec crew.

global word
global w
global limit
global result
result =[]


def usage():
 print "usage: subdomainer.py  options \n"
 print "		-d: domain to search"
 print "		-l: limit of results to work with. (msn and yahoo goes in 10 to 10"
 print "		    google in 100's, and pgp does not need this option)"
 print "		-m: data source (msn, yahoo, google, pgp)\n"
 print "		-o: output to html file. (optional, good for long lists.)\n"
 print "Example:"
 print "		subdomainer.py -d microsoft.com -l 200 -m google\n"
 sys.exit()



def howmanyahoo(w):
	 h = httplib.HTTP('search.yahoo.com')
	 h.putrequest('GET',"/search?ei=UTF-8&fr=FP-tab-web-t&p="+w)
      	 h.putheader('Host', 'search.yahoo.com')
	 h.putheader('User-agent', 'Internet Explorer 6.0 ')
	 h.endheaders()
	 returncode, returnmsg, headers = h.getreply()
	 data=h.getfile().read()
	 #r1 = re.compile('about <strong>[0123456789,]*</strong> for')
	 r1 = re.compile('<span id="infototal">[0123456789,]*</span>')
	 result = r1.findall(data)
	 if result == []:
		print "No results were found.\n"
		sys.exit()
	 for x in result:
	 	clean = re.sub('<span id="infototal">','',x)
		clean = re.sub('</span>','',clean)
		clean = re.sub('about','',clean)
		clean = re.sub('for','',clean)
		clean = re.sub(',','',clean)
	 print clean
	 return clean

def howmanmsn(w):
	h = httplib.HTTP('search.msn.com')
	h.putrequest('GET',"/results.aspx?q=%40"+w+"&FORM=QBHP")
	h.putheader('Host', 'search.msn.com')
	h.putheader('User-agent', 'Internet Explorer 6.0 ')
	h.endheaders()
	returncode, returnmsg, headers = h.getreply()
	data=h.getfile().read()
	r1 = re.compile('of [0123456789,]* results')
	result = r1.findall(data)
	if result ==[]:
		print "No results were found.\n"
		sys.exit()
	for x in result:
		clean = re.sub('of','',x)
		clean = re.sub('results','',clean)
		clean = re.sub(',','',clean)
		return clean

def howmanygoo(w):
	 h = httplib.HTTP('www.google.com')
	 h.putrequest('GET',"/search?num=10&hl=en&btnG=B%C3%BAsqueda+en+Google&meta=&q=\""+w+"\"")
      	 h.putheader('Host', 'www.google.com')
	 h.putheader('User-agent', 'Internet Explorer 6.0 ')
	 h.endheaders()
	 returncode, returnmsg, headers = h.getreply()
	 data=h.getfile().read()
	 r1 = re.compile('about <b>[0123456789,]*</b> for')
	 result = r1.findall(data)
	 if result == []:
		print "No results were found.\n"
		sys.exit()
	 for x in result:
	 	clean = re.sub(' <b>','',x)
		clean = re.sub('</b> ','',clean)
		clean = re.sub('about','',clean)
		clean = re.sub('for','',clean)
		clean = re.sub(',','',clean)
	 return clean


def run(w,i,metho):
	if metho == 'yahoo':
		h = httplib.HTTP('search.yahoo.com')
		h.putrequest('GET',"/search?ei=UTF-8&fr=FP-tab-web-t&p="+w+"&b="+str(i))
		h.putheader('Host', 'search.yahoo.com')
		h.putheader('Cookie','B=0nplklt3gvg45&b=3&s=a8; sB=nw=&vl=&n=100&mfs=')
	elif metho == 'msn':
		h = httplib.HTTP('search.msn.com')
		h.putrequest('GET',"/results.aspx?q="+w+"&FORM=QBHP&first="+str(i))
		h.putheader('Host', 'search.msn.com')
	elif metho == 'google':
		 h = httplib.HTTP('www.google.com')
		 h.putrequest('GET',"/search?num=100&start="+str(i)+"&hl=es&btnG=B%C3%BAsqueda+en+Google&meta=&q=\""+w+"\"")
      		 h.putheader('Host', 'www.google.com')
	elif metho == 'pgp':
		h = httplib.HTTP('pgp.rediris.es:11371')
		h.putrequest('GET',"/pks/lookup?search="+w+"&op=index")
	h.putheader('User-agent', 'Internet Explorer 6.0 ')
	h.endheaders()
	returncode, returnmsg, headers = h.getreply()
	data=h.getfile().read()
	data = re.sub('<b>','',data)
	data = re.sub('<\b>','',data)
	for e in ('>',':','=','<','/','\\',';','@','F','%'):
		 data = string.replace(data,e,' ')
	r1 = re.compile('[a-zA-Z0-9.-_]*\.'+w)
	res = r1.findall(data)
	return res

def test(argv):
    ofil='a'
    if len(sys.argv) < 4:
	    usage()
    try :
           opts, args = getopt.getopt(argv,"l:d:m:o:")
    except getopt.GetoptError:
            usage()
    for opt,arg in opts :
	if opt == '-l' :
		limit = int(arg)
	elif opt == '-d':
		word = str(arg)
	elif opt == '-m':
		meth = str(arg)
	elif opt == '-o':
		ofil = str(arg)

    print "Searching for " + word + " in " + meth
    print "======================================="

    if meth == 'yahoo':
        total = int(howmanyahoo(word))
        limit0 = 100
    elif meth == 'msn':
        total = int(howmanmsn(word))
        limit0 = 10
    elif meth == 'google':
        total =int(howmanygoo(word))
        limit0 = 100
    if meth != 'pgp':
        print "Total results: ",total
        if limit =='':
	        limit=limit0

        cant = 0
        if total < limit:
    	    limit=total
        print "Limit: ",int(limit)
        while cant < limit:
            print "Searching results: " + str(cant) +"\r"
            res = run(word,cant,meth)
            result=[]
            for x in res:
                if result.count(x) == 0:
                    result.append(x)
	    if meth =='msn':
		    cant+=10
	    else:
	   	    cant+=100
    else:
        res=run(word,0,meth)
        result=[]
        for x in res:
            if result.count(x) == 0:
                result.append(x)
    print "Subdomains founded:"
    print "====================\n"
    t=0
    for x in result:
	print x
	t+=1
    print "\nTotal results: ",t
    if x != []:
	print "Going for extra check:\n"
    	if ofil !='a':
		fil = open(ofil,'w')
		fil.write("<center><h3>Subdomains for: "+ word + "</center><br>")
		fil.write("<table border=1>")
		fil.write("<tr>")
		fil.write("<td bgcolor=#FFCCFF>Subdomain</td>")
		fil.write("<td bgcolor=#FFCCFF>IP</td>")
		fil.write("</tr>")
    	else:
		for x in result:
			try:
				g=gethostbyname(x)
				if ofil !='a':
					fil.write("<tr>")
					fil.write("<td>"+x+"</td>")
					fil.write("<td>"+g+"</td>")
					fil.write("</tr>")
				else:
					print  x + " ====> "+ g
			except:
				pass
    	if ofil !='a':
   		 	fil.write('</table>')
	print "\n"

if __name__ == "__main__":
        try: test(sys.argv[1:])
	except KeyboardInterrupt:
		print "Search interrupted by user.."
	except:
		sys.exit()
