import requests
import re
import subprocess
import os
import json
from multiprocessing.dummy import Pool
import threading
import socket
import time
import sys
# import http.client
import xml.etree.ElementTree as ET
from colorama import Fore,Back,init
import sys

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
import random

init()

red  = '\033[91m'
blue  = '\033[94m'
green = '\033[92m'
movv    = '\033[95m'
lasfar  = '\033[93m'
ramadi  = '\033[90m'
blid    = '\033[1m'
star    = '\033[4m'
bigas   = '\033[07m'
bigbbs  = '\033[27m'
hell    = '\033[05m'
saker   = '\033[25m'
labyadh = '\033[00m'
cyan    = '\033[0;96m'

class Yuyu:
	def __init__(self, url,timeout):
		self.subdomains = []
		self.link = []
		self.reverse = []
		self.livehost = []
		self.ips = []
		self.file = []
		self.port = []
		self.url = url
		self.timeout = timeout

		self.pwd = os.getcwd()
		try:
			os.mkdir(self.pwd+"/output")
			os.mkdir(self.pwd+"/output/"+self.url)
		except:
			pass

		self.logo()

		print(labyadh+"["+red+"!"+labyadh+"] Yuyu will pinch the subdomain from the source")
		print("-------------------------------------------------------\n")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting WebArchive!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting ThreadCrowd!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting URLScan!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting RapidDNS!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting AlienVault!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting DNSDumpster!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting CRT!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting ThreatMiner!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting CERTSPOTTER!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting HackerTarget!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting Riddler!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting CommonCrawl!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Starting ReverseIP!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Extracting Link Pages!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Checking Live Host!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Convert Domain to IP!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Checking files!")
		print(labyadh+"\t["+blue+"!"+labyadh+"] Top 10 Port Scanner!\n")
		print(labyadh+"["+cyan+"!"+labyadh+"] Starting ...\n")





	def logo(self):

	        clear = "\x1b[0m"
	        colors = [36, 32, 34, 35, 31, 37  ]

	        x = """ 

	
     ,__,
(/__/\oo/\__(/
  _/\/__\/\_
   _/    \_   
Yuyu is a web Reconnaissance & Web Analysis Scanner by @justakazh
------------------------------------------------------------------------------------------------------------"""
	        for N, line in enumerate(x.split("\n")):
	            sys.stdout.write("\x1b[1;%dm%s%s\n" % (random.choice(colors), line, clear))
	            time.sleep(0.05)
	        print(red+"""
[!] Usage of Instagram Hacking Tool for attacking targets without prior mutual consent is illegal. 
It's the end user's responsibility to obey all applicable local, state and federal laws. 
Developers assume no liability and are not responsible for any misuse or damage caused by this program. 
Only use for educational purposes.




	        	""")



	def worker(self):
		threading.Thread(target=self.ReverseIP).start()
		time.sleep(10)
		# self.extractlinks()
		self.checklivehost()
		self.domaintoip()


	def scan_domain(self, url):
		# webarchive
		if "web.archive.org" in url:
			try:
				r = self.req(url)
				pecah = r.split("\n")
				for i in pecah:
					self.link += [i]
					url = i.split("\r")
					for ii in url:
						try:
							domain = ii.split("/")
							if domain[2] not in self.subdomains:
									self.subdomains += [domain[2]]
						except:
							pass
			except:
				pass
			print(labyadh+"\t["+green+"+"+labyadh+"] WebArchive")

		# threatcrowd
		elif "threatcrowd.org" in url:
			try:
				r = self.req(url)
				de = json.loads(r)
				lis = de['subdomains']
				for domain in lis:
					try:
						if domain not in self.subdomains:
							self.subdomains += [domain]
					except:
						pass
			except:
				pass
			print(labyadh+"\t["+green+"+"+labyadh+"] ThreadCrowd")

		# urlscan
		elif "urlscan.io" in url:
			try:
				r = self.req(url)
				de = json.loads(r)
				for i in de['results']:
					try:
						if i['task']['domain'] not in self.subdomains:
							self.subdomains += [i['task']['domain']]
					except:
						pass
			except:
				pass
			print(labyadh+"\t["+green+"+"+labyadh+"] URLScan")

		elif "rapiddns.io" in url:
			try:
				r = self.req(url)
				rex = re.findall('<td><a href="http(.*?)" target="_blank">(.*?)</a></td>', r)
				for i in rex:
					try:
						if i[1] not in self.subdomains:
							# print(i[1])
							self.subdomains += [i[1]]
					except:
						pass
			except:
				pass
			print(labyadh+"\t["+green+"+"+labyadh+"] RapidDNS")


		elif "alienvault.com" in url:
			try:
				r = self.req(url)
				de = json.loads(r)
				for i in de['passive_dns']:
					try:
						if i['hostname'] not in self.subdomains:
							self.subdomains += [i['hostname']]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] AlienVault")
			except:
				pass

		elif "dnsdumpster.com" in url:
			try:
				r = self.req("https://dnsdumpster.com/")
				rex = re.findall('value="(.*?)"', r)
				csrf = rex[0]
				data = {
				"csrfmiddlewaretoken": csrf,
				"targetip": self.url
				}
				rr = requests.post("https://dnsdumpster.com/", data=data, headers={
					"content-type": "application/x-www-form-urlencoded",
					"cookie": "csrftoken="+csrf+"; _ga=GA1.2.1216996729.1609624762; _gid=GA1.2.1247250058.1609624762; _gat=1",
					"origin": "https://dnsdumpster.com",
					"referer": "https://dnsdumpster.com/",
					"sec-ch-ua": '"Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"',
					"sec-ch-ua-mobile": "?0",
					"sec-fetch-dest": "document",
					"sec-fetch-mode": "navigate",
					"sec-fetch-site": "same-origin",
					"sec-fetch-user": "?1",
					"upgrade-insecure-requests": "1",
					"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"

					}).text
			except:
				pass
			try:
				rex2 = re.findall('<tr><td class="col-md-4">(.*?)<br>', rr)
				for i in rex2:
					try:
						if i not in self.subdomains:
							if self.url in i:
								self.subdomains += [i]
					except:
						pass
			except:
				pass
			print(labyadh+"\t["+green+"+"+labyadh+"] DNSDumpster")



		elif "crt.sh" in url:
			try:
				r = self.req(url)
				de = json.loads(r)
				for i in de:
					try:
						if i['common_name'] not in self.subdomains:
							self.subdomains += [i['common_name']]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] CRT")
			except:
				pass


		elif "threatminer.org" in url:
			try:
				r = self.req(url)
				print(r)
				de = json.loads(r)
				for i in de['results']:
					try:
						if i not in self.subdomains:
							self.subdomains += [i]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] ThreatMiner")
			except:
				pass


		elif "certspotter.com" in url:
			try:
				r = self.req(url)
				de = json.loads(r)
				for i in de:
					try:
						if "*" not in i['dns_names'][0]:
							if i['dns_names'][0] not in self.subdomains:
								self.subdomains += [i['dns_names'][0]]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] CERTSPOTTER")
			except:
				pass

		elif "hackertarget.com" in url:
			try:
				r = self.req(url)
				pecah = r.split("\n")
				for i in pecah:
					try:
						domain = i.split(",")
						if domain[0] not in self.subdomains:
							self.subdomains += [domain[0]]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] HackerTarget")
			except:
				pass


		elif "riddler.io" in url:
			try:
				r = self.req(url)
				rex = re.findall(",(.*?),", r)
				for i in rex:
					try:
						if i in self.url:
							if i not in self.subdomains:
								self.subdomains += [i]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] Riddler")
			except:
				pass

		elif "commoncrawl.org" in url:
			try:
				r = self.req("http://index.commoncrawl.org/CC-MAIN-2020-50-index?url=*."+self.url+"&output=json")
				rex = re.findall(', "url": "(.*?)",',r)
				for i in rex:
					try:
						url = i.split("/")
						domain = url[2].lower()
						if domain not in self.subdomains:
							self.subdomains += [domain]
					except:
						pass
				print(labyadh+"\t["+green+"+"+labyadh+"] commoncrawl")
			except:
				pass
				# print("fail commoncrawl")
				


	def scan_port(self,ip):
		try:
			if "*." not in ip:
				if ":" not in ip:
					cmd = subprocess.getoutput("nmap -F --top-ports 10 "+ip)
					self.port += [{'url':ip, 'result':cmd}]
		except:
			pass
		# print(self.port)


	def scan_IP(self, url):
		try:
			ip = socket.gethostbyname(url)
			if ip not in self.ips:
				self.ips += [ip]
		except:
			pass

	def get_port(self):
		Y = Pool(int(len(self.livehost)))
		Y.map(self.scan_port, self.livehost)


	def get_IP(self):
		Y = Pool(int(len(self.livehost)))
		Y.map(self.scan_IP, self.subdomains)



	def scan_livehost(self, url):
		try:
			time.sleep(1)
			cmd = subprocess.getoutput("curl -Is "+url)
			if cmd:
				self.livehost += [url]
		except:
			pass



	def get_livehost(self):
		liss = [i.strip() for i in self.subdomains]
		p = Pool(int(len(self.subdomains)))
		p.map(self.scan_livehost,liss)

	def get_domain(self):
		api = [
		"http://web.archive.org/cdx/search/cdx?url=*."+self.url+"/&output=text&fl=original&collapse=urlkey",
		"https://threatcrowd.org/searchApi/v2/domain/report/?domain="+self.url,
		"https://urlscan.io/api/v1/search/?q="+self.url,
		"https://rapiddns.io/subdomain/"+self.url,
		"https://otx.alienvault.com/api/v1/indicators/domain/"+self.url+"/passive_dns",
		"https://dnsdumpster.com/",
		"https://crt.sh/?q="+self.url+"&output=json",
		"https://api.threatminer.org/v2/domain.php?q="+self.url+"&rt=5",
		"https://api.certspotter.com/v1/issuances?domain="+self.url+"&include_subdomains=true&expand=dns_names",
		"https://api.hackertarget.com/hostsearch/?q="+self.url,
		"https://riddler.io/search/exportcsv?q=pld:"+self.url,
		"http://index.commoncrawl.org/CC-MAIN-2020-50-index?url=*."+self.url+"&output=json",
		]
		Y = Pool(12)
		Y.map(self.scan_domain, api)

		

	def req(self, url):
		r = requests.get(url, headers={
			'user-agent':'mozilla'
			}, timeout=self.timeout).text
		return r


	def checklivehost(self, urls):
		if urls in self.url:
			try:
				conn = http.client.HTTPConnection(urls)
				conn.request("HEAD", "/")
				res = conn.getresponse().status
				self.livehost += [urls+" | "+str(res)]
			except:
				pass
		print(labyadh+"\t["+green+"+"+labyadh+"] checklivehost")


	def ReverseIP(self):
		try:
			r = self.req("https://api.hackertarget.com/reverseiplookup/?q="+self.url)
			x = r.split("\n")
			for i in x:
				try:
					self.reverse += [i]
				except:
					pass
			print(labyadh+"\t["+green+"+"+labyadh+"] reverseip")
		except:
			pass
	def domaintoip(self):
		for i in self.subdomains:
			try:
				ip = socket.gethostbyname(i)
				if ip not in self.ips:
					self.ips += [ip]
			except:
				pass
		print(labyadh+"\t["+green+"+"+labyadh+"] domaintoip")

