def bruteforce_worker(target, timeout): for password in target['b_password_list']: username = target['b_username'] try: telnet = Telnet(target['hostname'], target['port'], timeout) banner = telnet.connect() success = False stop = False success = telnet.auth(username, password) if success: Output.write({'target': telnet.url(), 'message': 'Authentication success with credentials %s and password %s' % (username, password)}) stop = True except ConnectionRefusedError: stop = True except Exception as e: stop = True print("%s: %s\n%s" % (type(e), e, traceback.format_exc())) finally: try: telnet.disconnect() except: pass if stop: break
def usage(self): message = 'Usage: {}'.format(self.name) for arg in self.arg_names: message += ' {}'.format(arg) Output.error(message)
def bruteforce_worker(target, timeout): for password in target['b_password_list']: username = target['b_username'] postgresql = PostgreSQL(target['hostname'], target['port'], timeout) success = False stop = False success, _ = postgresql.auth(target['b_username'], password) if success: Output.write({ 'target': postgresql.url(), 'message': 'Authentication success with credentials %s and password %s' % (username, password) }) stop = True try: postgresql.disconnect() except: pass if stop: break
def bruteforce_worker(target, timeout): for password in target['b_password_list']: username = target['b_username'] mongo = Mongo(target['hostname'], target['port'], timeout) success = False stop = False success, _ = mongo.auth(username, password, database=target['database']) if success: Output.write({ 'target': mongo.url(), 'message': 'Authentication success with credentials %s and password %s and database \'%s\'' % (username, password, target['database']) }) stop = True try: mongo.disconnect() except: pass if stop: break
def main(): parser = argparse.ArgumentParser(description='PortScan') parser.add_argument('targets', type=str) parser.add_argument('-p', metavar='ports', type=str_ports, nargs='?', help='target port', default=None, dest='port') parser.add_argument('--top-ports', metavar='top-N', nargs='?', type=top_ports, help='top n ports', default=None, dest='top_ports') parser.add_argument('-p-', action='store_true', help='Scan all ports', dest='all_ports') parser.add_argument('-sV', action='store_true', help='Service scan (nmap)', dest='service_scan') parser.add_argument('--timeout', metavar='timeout', nargs='?', type=int, help='Connect timeout', default=5, dest='timeout') # Dispatcher arguments parser.add_argument('-w', metavar='number worker', nargs='?', type=int, help='Number of concurent workers', default=10, dest='workers') args = parser.parse_args() static_inputs = {} if args.all_ports: static_inputs['port'] = list(range(1, 65536)) else: static_inputs['port'] = [] if args.port: static_inputs['port'] += args.port if args.top_ports: static_inputs['port'] += args.top_ports static_inputs['port'] = list(set(static_inputs['port'])) Output.setup() portscan(args.targets, static_inputs, args.workers, args.service_scan, args.timeout) Output.stop()
def detect(self, cvimg): output = Output(cvimg) self.processed['input'] = cvimg color_corrected = self.color_correct(cvimg) threshImg = self.threshold(color_corrected) self.findContour(threshImg, output) output.processed = self.processed return output
def run(cmd): Output.shell(cmd) status, output = subprocess.getstatusoutput(cmd) for line in output.splitlines(): print(' {}'.format(line)) if status != 0: sys.exit(status)
def ntds_hash(entry): user = '******' % (entry['domain'], entry['username']) Output.write({ 'target': smbscan.url(), 'message': '- %s %s (%s)' % (user.ljust(40), entry['hash'].ljust(70), entry['hash_type']) })
def portscan_worker(target, service_scan, timeout): portscan = PortScan(target['hostname'], target['port'], timeout) is_open = portscan.check_open() if is_open: if service_scan: for output in portscan.service_check(): output["message_type"] = "port_service" output["target"] = "%s:%d" % (target['hostname'], target['port']) Output.write(output) else: Output.write({"target": "%s:%d" % (target['hostname'], target['port']), "message": "open"})
def run(self): client = self.link_cls() client.link() Oval_definition.init_oval(client) for root, dirs, files in os.walk(self.path): for filepath in files: try: if not filepath.endswith('.xml'): continue self.results.update(Oval_definition(root+'/'+filepath).result()) except LinkBase.LinkError, e: Output('Link').error(e) except Exception, e: Output(filepath).error(e)
def __init__(self, arg_names): quiet = False args = [a.strip() for a in sys.argv[1:]] args = [a for a in args if len(a) > 0] if len(args) > 0 and args[0] == '-q': quiet = True args = args[1:] self.name = os.path.basename(sys.argv[0]) self.output = Output(quiet) self.arg_names = arg_names.split() self.arg_values = args self.arg_db = {} self.args_tail = self.arg_values[len(self.arg_names):] required_num = 0 optional_num = 0 for name in self.arg_names: if name[0] == '[' and name[-1] == ']': optional_num += 1 else: required_num += 1 # Optional args are only allowed after all required args if optional_num > 0: self.usage() if len(self.arg_values) < required_num: self.usage() for name, value in zip(self.arg_names, self.arg_values): self.arg_db[name] = value current_dir = os.path.dirname(__file__) self.dir_a2x = os.path.abspath(os.path.join(current_dir, '..', '..')) self.dir_bin = os.path.join(self.dir_a2x, 'bin') self.dir_cfg = os.path.join(os.environ['HOME'], '.config', 'a2x') self.dir_make = os.path.join(self.dir_a2x, 'make') self.dir_src = os.path.join(self.dir_a2x, 'src') if not os.path.exists(self.dir_cfg): os.makedirs(self.dir_cfg) elif not os.path.isdir(self.dir_cfg): self.output.error('{} is not a dir'.format(self.dir_cfg))
def bruteforce_worker(target, timeout): ssh = SSH(target['hostname'], target['port'], timeout) for password in target['b_password_list']: username = target['b_username'] try: success = False stop = False success = ssh.auth(username, password) if success: Output.write({ 'target': ssh.url(), 'message': 'Authentication success with credentials %s and password %s' % (username, password) }) stop = True except paramiko.AuthenticationException as e: pass except ValueError as e: stop = True except paramiko.SSHException as e: Output.write({ 'target': ssh.url(), 'message': 'Server overloaded, try reducing amount of workers' }) stop = True except socket.error: stop = True except Exception as e: stop = True print("%s: %s\n%s" % (type(e), e, traceback.format_exc())) if stop: break try: sshscan.disconnect() except: pass
def main(): parser = argparse.ArgumentParser(description='RSyncScan') parser.add_argument('targets', type=str) parser.add_argument('-p', metavar='ports', type=str_ports, nargs='?', help='target port', default='873', dest='port') parser.add_argument('--timeout', metavar='timeout', nargs='?', type=int, help='Connect timeout', default=5, dest='timeout') # Dispatcher arguments parser.add_argument('-w', metavar='number worker', nargs='?', type=int, help='Number of concurent workers', default=10, dest='workers') args = parser.parse_args() static_inputs = {} static_inputs['port'] = args.port Output.setup() rsyncscan(args.targets, static_inputs, args.workers, args.timeout) Output.stop()
def _parse_nmap_xml(self, xml_output): try: root = ET.parse(xml_output).getroot() for host in root.findall('host'): if not host.find('status').get('state') == 'up': continue addr = host.find('address').get('addr') for port_info in host.findall('ports/port'): if not port_info.find('state').get('state') == 'open': continue protocol = port_info.get('protocol') port = int(port_info.get('portid')) data = { "ip": addr, "port": port, "status": "open", } service_info = port_info.find('service') if service_info != None: service = service_info.get('name') product = service_info.get('product') version = service_info.get('version') if product != None: if version != None: version = "%s %s" % (product, version) else: version = product else: version = "" data["service"] = service data["version"] = version else: data["service"] = "" data["version"] = "" yield data except ET.ParseError: # Unable to parse XML Output.write({"target": "%s:%d" % (target['hostname'], target['port']), "message": "Failed to parse nmap XML output (probably due to nmap core dump)"})
def httpscan_worker(target, useragent, proxy, dir_bruteforce, extensions, dir_bruteforce_workers, timeout, excluded_code=[]): httpscan = HTTPScan(target['method'], target['hostname'], target['port'], useragent, proxy, timeout) output = httpscan.get(target['path']) if output != None and not output['code'] in excluded_code: output['message_type'] = 'http' output['target'] = httpscan.url(target['path']) Output.write(output) if httpscan.method == 'https': names = httpscan.get_cert_hostnames() if len(names) != 0: Output.write({ "target": httpscan.url(target['path']), "message": "certificates names: %s" % ", ".join(names) }) if dir_bruteforce: extension_list = [''] if extensions != None: extension_list += extensions.split(',') extension_list = list(set(extension_list)) gen = dir_bruteforce_generator(target, dir_bruteforce, extension_list) gen_size = dir_file_count(dir_bruteforce) * len(extension_list) args = (useragent, proxy, None, extensions, dir_bruteforce_workers, timeout, [400, 404]) dispatch(gen, gen_size, httpscan_worker, args, workers=dir_bruteforce_workers, process=False, pg_name=httpscan.url(target['path']))
def main(): parser = argparse.ArgumentParser(description='MySQLScan') parser.add_argument('targets', type=str) parser.add_argument('-p', metavar='ports', type=str_ports, nargs='?', help='target port', default='3306', dest='port') parser.add_argument('-u', metavar='username', type=str, nargs='?', help='Username', default=None, dest='username') parser.add_argument('--pass', metavar='password', type=str, nargs='?', help='Password', default=None, dest='password') parser.add_argument('--timeout', metavar='timeout', nargs='?', type=int, help='Connect timeout', default=5, dest='timeout') # Actions parser.add_argument("--dbs", action='store_true', help='List databases') parser.add_argument("--hashes", action='store_true', help='Dump database hashes') parser.add_argument('--sql', metavar='query', type=str, nargs='?', help='Perform a SQL query', default=None, dest='sql') # Bruteforce parser.add_argument("--bruteforce", action='store_true', help='Enable bruteforce') parser.add_argument('-U', metavar='username file', type=str, nargs='?', help='Username file (format username or username:password)', default=None, dest='username_file') parser.add_argument('-P', metavar='password file', type=str, nargs='?', help='Password file', default=None, dest='password_file') parser.add_argument('-W', metavar='number worker', nargs='?', type=int, help='Number of concurent workers for the bruteforce', default=5, dest='bruteforce_workers') # Dispatcher arguments parser.add_argument('-w', metavar='number worker', nargs='?', type=int, help='Number of concurent workers', default=10, dest='workers') args = parser.parse_args() static_inputs = {} if args.port: static_inputs['port'] = args.port creds = {} if args.username: creds['username'] = args.username if args.password: creds['password'] = args.password actions = {} if args.dbs: actions['list_dbs'] = {} if args.hashes: actions['list_hashes'] = {} if args.sql: actions['sql'] = {'query': args.sql} if args.bruteforce: actions['bruteforce'] ={'username_file': args.username_file, 'password_file': args.password_file, 'workers': args.bruteforce_workers} Output.setup() mysqlscan(args.targets, static_inputs, args.workers, actions, creds, args.timeout) Output.stop()
def main(): parser = argparse.ArgumentParser(description='PostGreScan') parser.add_argument('targets', type=str) parser.add_argument('-p', metavar='ports', type=str_ports, nargs='?', help='target port', default='5432', dest='port') parser.add_argument('-u', metavar='username', type=str, nargs='?', help='Username', default=None, dest='username') parser.add_argument('--pass', metavar='password', type=str, nargs='?', help='Password', default=None, dest='password') parser.add_argument('--timeout', metavar='timeout', nargs='?', type=int, help='Connect timeout', default=5, dest='timeout') # Actions parser.add_argument("--dbs", action='store_true', help='List databases') parser.add_argument('--cmd', metavar='command', type=str, nargs='?', help='Execute a command via PostgreSQL RCE techniques', default=None, dest='cmd') # Bruteforce parser.add_argument("--bruteforce", action='store_true', help='Enable bruteforce') parser.add_argument('-U', metavar='username file', type=str, nargs='?', help='Username file (format username or username:password)', default=None, dest='username_file') parser.add_argument('-P', metavar='password file', type=str, nargs='?', help='Password file', default=None, dest='password_file') parser.add_argument('-W', metavar='number worker', nargs='?', type=int, help='Number of concurent workers for the bruteforce', default=5, dest='bruteforce_workers') # Dispatcher arguments parser.add_argument('-w', metavar='number worker', nargs='?', type=int, help='Number of concurent workers', default=10, dest='workers') args = parser.parse_args() static_inputs = {} if args.port: static_inputs['port'] = args.port creds = {} if args.username: creds['username'] = args.username if args.password: creds['password'] = args.password actions = {} if args.dbs: actions['list_dbs'] = {} if args.cmd: actions['cmd'] = {'command': args.cmd} if args.bruteforce: actions['bruteforce'] ={'username_file': args.username_file, 'password_file': args.password_file, 'workers': args.bruteforce_workers} Output.setup() postgrescan(args.targets, static_inputs, args.workers, actions, creds, args.timeout) Output.stop()
def bruteforce_worker(target, timeout): password = target['b_password'] redis = Redis(target['hostname'], target['port'], timeout) success = False stop = False success, _ = redis.auth(password) if success: Output.write({ 'target': redis.url(), 'message': 'Authentication success with password %s' % (password, ) }) try: redis.disconnect() except: pass
def rsyncscan_worker(target, timeout): rsync = RSync(target['hostname'], target['port'], timeout) try: version, welcome = rsync.version() Output.write({ 'target': rsync.url(), 'message': 'RSync server: %s' % version }) shares = rsync.list_shares() output = 'Rsync shares:\n' for share in shares: if share['anon'] == True: output += ' ' * 60 + '- %s %s (Anonymous access !!!)\n' % ( share['name'].ljust(30), share['description'].ljust(60)) else: output += ' ' * 60 + '- %s %s (%s)\n' % ( share['name'].ljust(30), share['description'].ljust(60), share['auth_message']) Output.write({'target': rsync.url(), 'message': output}) except Exception as e: if str(e) == 'Not a rsync server': pass else: Output.write({ 'target': rsync.url(), 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) })
def main(): with codecs.open('data/syntaxTree.json', 'r', 'utf-8') as fin: data = json.load(fin) result = hierarchy(data) if result[0]: file_map = check_file_set(result[2]) root = result[1] print(str_stat(result[2])) output = Output(root, file_map) output.addOutput(Output.DEBUG_LEVEL, 'data/out/debug.txt', tag_iobes) output.addOutput(Output.CHAR_LEVEL, 'data/out/char.txt', tag_iobes) output.addOutput(Output.WORD_LEVEL, 'data/out/word.txt', tag_iobes) output.addOutput(Output.SENTENCE_LEVEL, 'data/out/sentence.txt', tag_iobes) output.generate(100) with codecs.open('data/out/tree.json', 'w', 'utf-8') as fout: root = generate(root) children = root['children'] root['children'] = [data['children'][0]] root['children'].extend(children) fout.write(json.dumps(root, ensure_ascii=False))
def bruteforce_worker(target, timeout): for password in target['b_password_list']: username = target['b_username'] mysqlscan = MySQLScan(target['hostname'], target['port'], timeout) success = False stop = False try: success, _ = mysqlscan.auth(target['b_username'], password) Output.write({'target': mysqlscan.url(), 'message': 'Authentication success with credentials %s and password %s' % (username, password)}) stop = True except AuthFailure as e: pass try: mysqlscan.disconnect() except: pass if stop: break
def dnsscan_worker(target, dn_server, actions, timeout): dnsscan = DNSScan(target['hostname'], dn_server, timeout) resolved = dnsscan.resolve() if resolved: for r in resolved['resolved']: Output.write({"message_type": "dns", "target": target['hostname'], "query_type": resolved["query_type"], "resolved": r}) for action in actions: if action[0] == 'bruteforce': Output.write({"target": target['hostname'], "message": "Starting subdomain bruteforce"}) for resolved in dnsscan.subdomain_bruteforce(action[1]): Output.write({"message_type": "dns", "target": resolved['target'], "query_type": resolved["query_type"], "resolved": resolved['resolved']}) if action[0] == 'axfr': Output.write({"target": target['hostname'], "message": "Starting AXFR check"}) dnsscan.axfr()
def main(): parser = argparse.ArgumentParser(description='DNSScan') parser.add_argument('targets', type=str) parser.add_argument('--dns', metavar='dns_ip', nargs='?', type=str, help='DNS server to send query to', default=None, dest='dns') parser.add_argument('--bruteforce', metavar='file', nargs='?', type=str, help='Bruteforce subdomains', default=None, dest='bruteforce') parser.add_argument('--axfr', action='store_true', help='AXFR check', dest='axfr') parser.add_argument('--timeout', metavar='timeout', nargs='?', type=int, help='Connect timeout', default=5, dest='timeout') # Dispatcher arguments parser.add_argument('-w', metavar='number worker', nargs='?', type=int, help='Number of concurent workers', default=10, dest='workers') args = parser.parse_args() static_inputs = {} Output.setup() actions = [] if args.bruteforce: actions.append(('bruteforce', args.bruteforce)) if args.axfr: actions.append(('axfr',)) dnsscan(args.targets, static_inputs, args.workers, args.dns, actions, args.timeout) Output.stop()
def __init__(self, arg_names): quiet = False args = [a.strip() for a in sys.argv[1 : ]] args = [a for a in args if len(a) > 0] if len(args) > 0 and args[0] == '-q': quiet = True args = args[1 : ] self.name = os.path.basename(sys.argv[0]) self.output = Output(quiet) self.arg_names = arg_names.split() self.arg_values = args self.arg_db = {} self.args_tail = self.arg_values[len(self.arg_names) :] required_num = 0 optional_num = 0 for name in self.arg_names: if name[0] == '[' and name[-1] == ']': optional_num += 1 else: required_num += 1 # Optional args are only allowed after all required args if optional_num > 0: self.usage() if len(self.arg_values) < required_num: self.usage() for name, value in zip(self.arg_names, self.arg_values): self.arg_db[name] = value current_dir = os.path.dirname(__file__) self.dir_a2x = os.path.abspath(os.path.join(current_dir, '..', '..')) self.dir_bin = os.path.join(self.dir_a2x, 'bin') self.dir_cfg = os.path.join(os.environ['HOME'], '.config', 'a2x') self.dir_make = os.path.join(self.dir_a2x, 'make') self.dir_src = os.path.join(self.dir_a2x, 'src') if not os.path.exists(self.dir_cfg): os.makedirs(self.dir_cfg) elif not os.path.isdir(self.dir_cfg): self.output.error('{} is not a dir'.format(self.dir_cfg))
def bruteforce_worker(target, timeout): for password in target['b_password_list']: domain = target['b_domain'] username = target['b_username'] mssqlscan = MSSQLScan(target['hostname'], target['port'], timeout) success = mssqlscan.connect() if not success: Output.write({ 'target': mssqlscan.url(), 'message': 'Unable to connect to MSSQL server' }) continue if not domain: user = username else: user = '******' % (domain, username) success = False stop = False try: success, is_admin = mssqlscan.auth(target['b_domain'], target['b_username'], password, None) Output.write({ 'target': mssqlscan.url(), 'message': 'Authentication success with credentials %s and password %s' % (user, password) }) if is_admin: Output.write({ 'target': mssqlscan.url(), 'message': 'Administrative privileges with account %s' % (user, ) }) stop = True except AuthFailure as e: pass try: mssqlscan.disconnect() except: pass if stop: break
def __init__(self, filepath, source='AXTX'): self.__root__ = TagNode.load(filepath) self.source = source self.output = Output() super(Oval_definition, self).__init__(self.__root__) for element in self.key_element: res = getattr(self, element+'s') for items in self.all(element+'s'): for item in items.get_childtag_list(): itemid = item.get_attr('id') res[itemid] = item if itemid not in self.records[element]: self.records[element][itemid] = None for key, value in self.variables.items(): if isinstance(value, list): continue self.variables[key] = Variable(value).result()
def axfr(self): if self.is_ip(self.hostname): return for ns_server in self.get_nameservers(): Output.write({"target": ns_server['target'], "message": "Checking AXFR against nameserver %s" % ns_server['resolved']}) # resolve nameserver IP resolver = dns.resolver.Resolver() resolver.timeout = self.timeout if self.dn_server != None: self.resolver.nameservers = [self.dn_server] answer = self.resolver.query(ns_server['resolved'], "A") for ns_ip in answer: axfr = dns.zone.from_xfr(dns.query.xfr(str(ns_ip), self.hostname, lifetime=self.timeout)) if axfr == None: continue for name, node in axfr.nodes.items(): name = str(name) if name == "@": name = self.hostname else: if not name.endswith('.'): name = "%s.%s" % (name, self.hostname) for rdataset in node.rdatasets: parts = str(rdataset).split() if len(parts) >= 4: query_type = parts[2] if not query_type in ["SOA", "NS"]: if query_type in ["MX"]: if not parts[4].endswith('.'): resolved = "%s.%s" % (parts[4], self.hostname) Output.write({"target": ns_server['target'], "message": "%s %s %s" % (name, query_type, resolved)}) else: resolved = parts[3] Output.write({"target": ns_server['target'], "message": "%s %s %s" % (name, query_type, resolved)}) else: Output.write({"target": ns_server['target'], "message": "%s %s %s" % (name, type(rdataset), rdataset)})
def winrmscan_worker(target, actions, creds, timeout): # Process creds if 'username' in creds and '\\' in creds['username']: creds['domain'] = creds['username'].split('\\')[0] creds['username'] = creds['username'].split('\\')[1] try: domain = creds['domain'] if 'domain' in creds else None username = creds['username'] if 'username' in creds else None password = creds['password'] if 'password' in creds else None hash = creds['hash'] if 'hash' in creds else None winrmscan = WinRMScan(target['hostname'], timeout) success = winrmscan.auth(domain, username, password, hash) if success: if domain: user = "******" % (domain, username) else: user = username if password: creds_str = "%s and password %s" % (user, password) else: creds_str = "%s and hash %s" % (user, hash) Output.write({ 'target': target['hostname'], 'message': 'Successful authentication with credentials %s' % creds_str }) if 'command' in actions: output = "Command '%s':\n" % actions['command']['command'] output += winrmscan.execute(actions['command']['command'], get_output=True) Output.write({'target': target['hostname'], 'message': output}) except Exception as e: Output.write({ 'target': target['hostname'], 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) }) finally: winrmscan.disconnect()
def readtext(self, name): Output.info('Reading text from {}'.format(name)) with open(name, 'rU') as f: return f.read()
def telnetscan_worker(target, actions, creds, timeout): try: telnet = Telnet(target['hostname'], target['port'], timeout) banner = telnet.connect() Output.write({ 'target': telnet.url(), 'message': 'Telnet: %s' % banner }) if 'username' in creds and 'password' in creds: success = telnet.auth(creds['username'], creds['password']) if success: Output.write({ 'target': telnet.url(), 'message': 'Successful authentication with username %s and password %s' % (creds['username'], creds['password']) }) if 'command' in actions: output = "Command '%s':\n" % actions['command']['command'] output += telnet.execute(actions['command']['command']) Output.write({ 'target': target['hostname'], 'message': output }) else: Output.write({ 'target': telnet.url(), 'message': 'Authentication failure with username %s and password %s' % (creds['username'], creds['password']) }) if 'bruteforce' in actions: if 'username_file' in actions['bruteforce'] != None: Output.write({ 'target': telnet.url(), 'message': 'Starting bruteforce:' }) username_file = actions['bruteforce']['username_file'] password_file = actions['bruteforce'][ 'password_file'] if 'password_file' in actions[ 'bruteforce'] else None bruteforce_workers = actions['bruteforce']['workers'] # The generator will provide a username:password_list couple gen = bruteforce_generator(target, username_file, password_file) gen_size = bruteforce_generator_count(target, username_file, password_file) args = (timeout, ) dispatch(gen, gen_size, bruteforce_worker, args, workers=bruteforce_workers, process=False, pg_name=target['hostname']) except ConnectionRefusedError: pass except Exception as e: Output.write({ 'target': telnet.url(), 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) }) finally: telnet.disconnect()
def dispatch(gen, gen_size, worker_func, func_args, workers=10, process=True, pg_name=None): try: worker_list = [] if process: n_process = int(workers / 100 + 1) n_threads = int(workers / n_process) else: n_threads = int(workers) # prepare progress bar thread pg_queue = Queue() pg_thread = Thread(target=progressbar_worker, args=(gen_size, pg_queue, pg_name)) pg_thread.daemon = True pg_thread.start() if process: n_all = n_threads * n_process else: n_all = n_threads # Start feeding worker feed_queue = Queue() feed_thread = Thread(target=feedqueue_worker, args=(gen, feed_queue, n_all)) feed_thread.daemon = True feed_thread.start() if process: # Start processes for _ in range(n_process): p = Process(target=process_worker, args=(feed_queue, worker_func, func_args, pg_queue, n_threads)) p.start() worker_list.append(p) else: for _ in range(n_threads): t = Thread(target=thread_worker, args=(feed_queue, worker_func, func_args, pg_queue)) t.start() worker_list.append(t) pg_thread.join() except KeyboardInterrupt: Output.write("Scan interrupted") finally: if process: num_terminated = 0 num_failed = 0 end_time = time.time() + STOP_WAIT_SECS for p in worker_list: join_secs = max(0.0, min(end_time - time.time(), STOP_WAIT_SECS)) p.join(join_secs) while worker_list: proc = worker_list.pop() if proc.is_alive(): proc.terminate() num_terminated += 1 else: exitcode = proc.exitcode if exitcode: num_failed += 1
def sshscan_worker(target, actions, creds, timeout): try: ssh = SSH(target['hostname'], target['port'], timeout) version = ssh.get_version() if not version: return Output.write({'target': ssh.url(), 'message': '%s' % version}) if 'username' in creds and 'password' in creds: success = ssh.auth(creds['username'], creds['password']) if success: Output.write({ 'target': ssh.url(), 'message': 'Successful authentication with username %s and password %s' % (creds['username'], creds['password']) }) if 'command' in actions: output = "Command '%s':\n" % actions['command']['command'] output += ssh.execute(actions['command']['command']) Output.write({ 'target': target['hostname'], 'message': output }) else: Output.write({ 'target': ssh.url(), 'message': 'Authentication failure with username %s and password %s' % (creds['username'], creds['password']) }) if 'bruteforce' in actions: if 'username_file' in actions['bruteforce'] != None: Output.write({ 'target': ssh.url(), 'message': 'Starting bruteforce:' }) username_file = actions['bruteforce']['username_file'] password_file = actions['bruteforce'][ 'password_file'] if 'password_file' in actions[ 'bruteforce'] else None bruteforce_workers = actions['bruteforce']['workers'] # The generator will provide a username:password_list couple gen = bruteforce_generator(target, username_file, password_file) gen_size = bruteforce_generator_count(target, username_file, password_file) args = (timeout, ) dispatch(gen, gen_size, bruteforce_worker, args, workers=bruteforce_workers, process=False, pg_name=target['hostname']) except paramiko.AuthenticationException as e: Output.write({ 'target': ssh.url(), 'message': 'Authentication failure with username %s and password %s' % (creds['username'], creds['password']) }) except ValueError as e: Output.write({ 'target': ssh.url(), 'message': "Authentication failure because of crypto failure: %s" % str(e) }) except paramiko.SSHException as e: pass except socket.error: pass except Exception as e: Output.write({ 'target': ssh.url(), 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) }) finally: ssh.disconnect()
def postgrescan_worker(target, actions, creds, timeout): try: postgresql = PostgreSQL(target['hostname'], target['port'], timeout) if not 'username' in creds: pass elif not 'password' in creds: pass else: username = creds['username'] password = creds['password'] success = False success, version = postgresql.auth(username, password) postgresql_info = {'version': version} postgresql_info['target'] = postgresql.url() postgresql_info['message_type'] = 'postgresql' Output.write(postgresql_info) if success: Output.write({ 'target': postgresql.url(), 'message': 'Successful authentication with credentials %s and password %s' % (username, password) }) if 'list_dbs' in actions: databases = postgresql.list_databases() output = "Databases:\n" for db in databases: output += " " * 60 + "- %s:\n" % db['name'] for table in db['tables']: output += " " * 60 + "\t- %s\n" % table Output.write({ 'target': postgresql.url(), 'message': output }) if 'cmd' in actions: output = "Command result:\n" output += postgresql.execute_cmd(actions['cmd']['command']) Output.write({ 'target': postgresql.url(), 'message': output }) else: Output.write({ 'target': postgresql.url(), 'message': 'Authentication failure with credentials %s and password %s' % (username, password) }) if 'bruteforce' in actions: if 'username_file' in actions['bruteforce'] != None: Output.write({ 'target': postgresql.url(), 'message': 'Starting bruteforce:' }) username_file = actions['bruteforce']['username_file'] password_file = actions['bruteforce'][ 'password_file'] if 'password_file' in actions[ 'bruteforce'] else None bruteforce_workers = actions['bruteforce']['workers'] # The generator will provide a username:password_list couple gen = bruteforce_generator(target, username_file, password_file) gen_size = bruteforce_generator_count(target, username_file, password_file) args = (timeout, ) dispatch(gen, gen_size, bruteforce_worker, args, workers=bruteforce_workers, process=False, pg_name=target['hostname']) except OSError: pass except ConnectionRefusedError: pass except Exception as e: Output.write({ 'target': postgresql.url(), 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) }) finally: postgresql.disconnect()
def readbytes(self, name): Output.info('Reading bytes from {}'.format(name)) with open(name, 'rb') as f: return f.read()
def ftpscan_worker(target, actions, creds, timeout): try: ftpscan = FTPScan(target['hostname'], target['port'], timeout) ftp_code, version = ftpscan.grab_banner() if ftp_code: Output.write({ 'target': ftpscan.url(), 'message': '%d %s' % (ftp_code, version) }) if 'username' in creds and 'password' in creds: success = ftpscan.auth(creds['username'], creds['password']) else: success = ftpscan.auth() if success: if 'username' in creds and 'password' in creds: Output.write({ 'target': ftpscan.url(), 'message': 'Successful connection with credentials %s:%s' % creds }) else: Output.write({ 'target': ftpscan.url(), 'message': 'Successful anonymous connection' }) if 'list' in actions: try: ftp_dir = '/' contents = "" for content in ftpscan.list_content( ftp_dir, recurse=actions['list']['recurse']): if 'size' in content: contents += " " * 60 + "- %s %s\n" % ( content['name'].ljust(30), sizeof_fmt(content['size'])) else: contents += " " * 60 + "- %s\n" % content[ 'name'] Output.write({ 'target': ftpscan.url(), 'message': 'Contents of %s\n%s' % (ftp_dir, contents) }) except socket.timeout as e: Output.write({ 'target': ftpscan.url(), 'message': 'Timeout while listing folder, do you have a firewall enabled ?' }) if 'bruteforce' in actions: if 'username_file' in actions['bruteforce'] != None: Output.write({ 'target': ftpscan.url(), 'message': 'Starting bruteforce:' }) username_file = actions['bruteforce']['username_file'] password_file = actions['bruteforce'][ 'password_file'] if 'password_file' in actions[ 'bruteforce'] else None bruteforce_workers = actions['bruteforce']['workers'] # The generator will provide a username:password_list couple gen = bruteforce_generator(target, username_file, password_file) gen_size = bruteforce_generator_count(target, username_file, password_file) args = (timeout, ) dispatch(gen, gen_size, bruteforce_worker, args, workers=bruteforce_workers, process=False, pg_name=target['hostname']) except Exception as e: Output.write({ 'target': ftpscan.url(), 'message': '%s: %s\n%s' % (type(e), e, traceback.format_exc()) }) finally: ftpscan.disconnect()
def run(self): self.title() self.validate() self.main() Output.coloredln('[ Done ]', Color.LightGreen)
def main(self): Output.error('{} does not implement main'.format(self.name))
def makedir(self, name): Output.info('Making dir {}'.format(name)) os.mkdir(name)
def writefile(self, name, contents): Output.info('Writing file {}'.format(name)) with open(name, 'w') as f: f.write(contents)
class Tool: def __init__(self, arg_names): quiet = False args = [a.strip() for a in sys.argv[1:]] args = [a for a in args if len(a) > 0] if len(args) > 0 and args[0] == '-q': quiet = True args = args[1:] self.name = os.path.basename(sys.argv[0]) self.output = Output(quiet) self.arg_names = arg_names.split() self.arg_values = args self.arg_db = {} self.args_tail = self.arg_values[len(self.arg_names):] required_num = 0 optional_num = 0 for name in self.arg_names: if name[0] == '[' and name[-1] == ']': optional_num += 1 else: required_num += 1 # Optional args are only allowed after all required args if optional_num > 0: self.usage() if len(self.arg_values) < required_num: self.usage() for name, value in zip(self.arg_names, self.arg_values): self.arg_db[name] = value current_dir = os.path.dirname(__file__) self.dir_a2x = os.path.abspath(os.path.join(current_dir, '..', '..')) self.dir_bin = os.path.join(self.dir_a2x, 'bin') self.dir_cfg = os.path.join(os.environ['HOME'], '.config', 'a2x') self.dir_make = os.path.join(self.dir_a2x, 'make') self.dir_src = os.path.join(self.dir_a2x, 'src') if not os.path.exists(self.dir_cfg): os.makedirs(self.dir_cfg) elif not os.path.isdir(self.dir_cfg): self.output.error('{} is not a dir'.format(self.dir_cfg)) def title(self): self.output.colored('a', Color.LightBlue) self.output.colored('2', Color.LightGreen) self.output.colored('x', Color.Yellow) self.output.colored('{} '.format(self.name[3:]), Color.White) self.output.coloredln(' '.join(self.arg_values), Color.LightGray) def done(self): self.output.coloredln('[ Done ]', Color.LightGreen) def usage(self): message = 'Usage: {}'.format(self.name) for arg in self.arg_names: message += ' {}'.format(arg) self.output.error(message) def get_arg(self, name): if name in self.arg_db: return self.arg_db[name] else: return '' def get_arg_tail(self): return self.args_tail def main(self): self.output.error('{} does not implement main'.format(self.name)) def run(self): self.title() self.main() self.done() def writefile(self, name, contents): self.output.info('Writing file {}'.format(name)) with open(name, 'w') as f: f.write(contents) def readbytes(self, name): with open(name, 'rb') as f: return f.read() def readtext(self, name): with open(name, 'rU') as f: return f.read() def readtextlines(self, name): with open(name, 'rU') as f: return f.readlines() def listdir(self, path): if not os.path.isdir(path): self.output.error('{} is not a dir'.format(path)) return sorted(os.listdir(path)) def shell(self, cmd): self.output.shell(cmd) status, output = subprocess.getstatusoutput(cmd) if not self.output.quiet: for line in output.splitlines(): print(' {}'.format(line)) if status != 0: sys.exit(status) def sanitizeFileNameForCVar(self, FileName): return FileName.replace('.', '_').replace('-', '_').replace('/', '_')
class Tool: def __init__(self, arg_names): quiet = False args = [a.strip() for a in sys.argv[1 : ]] args = [a for a in args if len(a) > 0] if len(args) > 0 and args[0] == '-q': quiet = True args = args[1 : ] self.name = os.path.basename(sys.argv[0]) self.output = Output(quiet) self.arg_names = arg_names.split() self.arg_values = args self.arg_db = {} self.args_tail = self.arg_values[len(self.arg_names) :] required_num = 0 optional_num = 0 for name in self.arg_names: if name[0] == '[' and name[-1] == ']': optional_num += 1 else: required_num += 1 # Optional args are only allowed after all required args if optional_num > 0: self.usage() if len(self.arg_values) < required_num: self.usage() for name, value in zip(self.arg_names, self.arg_values): self.arg_db[name] = value current_dir = os.path.dirname(__file__) self.dir_a2x = os.path.abspath(os.path.join(current_dir, '..', '..')) self.dir_bin = os.path.join(self.dir_a2x, 'bin') self.dir_cfg = os.path.join(os.environ['HOME'], '.config', 'a2x') self.dir_make = os.path.join(self.dir_a2x, 'make') self.dir_src = os.path.join(self.dir_a2x, 'src') if not os.path.exists(self.dir_cfg): os.makedirs(self.dir_cfg) elif not os.path.isdir(self.dir_cfg): self.output.error('{} is not a dir'.format(self.dir_cfg)) def title(self): self.output.colored('a', Color.LightBlue) self.output.colored('2', Color.LightGreen) self.output.colored('x', Color.Yellow) self.output.colored('{} '.format(self.name[3 : ]), Color.White) self.output.coloredln(' '.join(self.arg_values), Color.LightGray) def done(self): self.output.coloredln('[ Done ]', Color.LightGreen) def usage(self): message = 'Usage: {}'.format(self.name) for arg in self.arg_names: message += ' {}'.format(arg) self.output.error(message) def get_arg(self, name): if name in self.arg_db: return self.arg_db[name] else: return '' def get_arg_tail(self): return self.args_tail def main(self): self.output.error('{} does not implement main'.format(self.name)) def run(self): self.title() self.main() self.done() def writefile(self, name, contents): self.output.info('Writing file {}'.format(name)) with open(name, 'w') as f: f.write(contents) def readbytes(self, name): with open(name, 'rb') as f: return f.read() def readtext(self, name): with open(name, 'rU') as f: return f.read() def readtextlines(self, name): with open(name, 'rU') as f: return f.readlines() def listdir(self, path): if not os.path.isdir(path): self.output.error('{} is not a dir'.format(path)) return sorted(os.listdir(path)) def shell(self, cmd): self.output.shell(cmd) status, output = subprocess.getstatusoutput(cmd) if not self.output.quiet: for line in output.splitlines(): print(' {}'.format(line)) if status != 0: sys.exit(status) def sanitizeFileNameForCVar(self, FileName): return FileName.replace('.', '_').replace('-', '_').replace('/', '_')
def title(self): arguments = ' '.join(self.args) + ' ' if len(self.args) > 0 else '' whole_text = ' {} {}'.format(self.name, arguments) border = '-' * len(whole_text) Output.coloredln(border, Color.DarkGray) Output.colored(' a', Color.LightBlue) Output.colored('2', Color.LightGreen) Output.colored('x', Color.Yellow) Output.colored('{} '.format(self.name[3 : ]), Color.White) print(arguments) Output.coloredln(border, Color.DarkGray)