def __init__(self, device, snaplen, promisc, to_ms, monitor=None): self.errbuf = create_string_buffer(PCAP_ERRBUF_SIZE) self.iface = create_string_buffer(device.encode("utf8")) self.dtl = None if monitor: if WINDOWS and not conf.use_npcap: raise OSError("On Windows, this feature requires NPcap !") # Npcap-only functions from pocsuite3.thirdparty.scapy.winpcapy import pcap_create, \ pcap_set_snaplen, pcap_set_promisc, \ pcap_set_timeout, pcap_set_rfmon, pcap_activate self.pcap = pcap_create(self.iface, self.errbuf) pcap_set_snaplen(self.pcap, snaplen) pcap_set_promisc(self.pcap, promisc) pcap_set_timeout(self.pcap, to_ms) if pcap_set_rfmon(self.pcap, 1) != 0: logger.info("Could not set monitor mode") if pcap_activate(self.pcap) != 0: raise OSError("Could not activate the pcap handler") else: self.pcap = pcap_open_live(self.iface, snaplen, promisc, to_ms, self.errbuf) error = bytes(bytearray(self.errbuf)).strip(b"\x00") if error: raise OSError(error) if WINDOWS: # Winpcap/Npcap exclusive: make every packet to be instantly # returned, and not buffered within Winpcap/Npcap pcap_setmintocopy(self.pcap, 0) self.header = POINTER(pcap_pkthdr)() self.pkt_data = POINTER(c_ubyte)() self.bpf_program = bpf_program()
def start(self, daemon=True): # Http server can only allow start once in pocsuite3, avoid muti-threading start muti-times if self.server_locked: logger.info('Httpd serve has been started on {}://{}:{}, '.format( self.scheme, self.bind_ip, self.bind_port)) return if check_port(self.host_ip, self.bind_port): logger.error( 'Port {} has been occupied, start Httpd serve failed!'.format( self.bind_port)) return self.server_locked = True self.setDaemon(daemon) threading.Thread.start(self) # Detect http server is started or not logger.info('Detect {} server is runing or not...'.format(self.scheme)) detect_count = 10 while detect_count: try: if check_port(self.host_ip, self.bind_port): break except Exception as ex: logger.error(str(ex)) time.sleep(random.random()) detect_count -= 1
def check_requires(data): requires = get_poc_requires(data) requires = [ i.strip().strip('"').strip("'") for i in requires.split(',') ] if requires else [''] if requires[0]: poc_name = get_poc_name(data) info_msg = 'PoC script "{0}" requires "{1}" to be installed'.format( poc_name, ','.join(requires)) logger.info(info_msg) try: for r in requires: if ":" in r: rows = r.split(":") if len(rows) == 2: r, module = rows else: module = rows[-1] r = ''.join(rows[:-1]) __import__(module) else: __import__(r) except ImportError: err_msg = 'try install with "python -m pip install {0}"'.format( r) logger.error(err_msg) raise SystemExit
def init_options(input_options=AttribDict(), override_options=False): cmd_line_options.update(input_options) _set_conf_attributes() _set_poc_options(input_options) _set_kb_attributes() _merge_options(input_options, override_options) # export rules, dont run the poc in the default status if conf.rule or conf.rule_req: logger.info( "The rule export function is in use. The POC is not executed at this point" ) if conf.pocs_path: if check_path(conf.pocs_path): paths.USER_POCS_PATH = conf.pocs_path for root, dirs, files in os.walk(paths.USER_POCS_PATH): files = list( filter( lambda x: not x.startswith("__") and x.endswith( ".py"), files)) regex_rule(list(paths.USER_POCS_PATH + i for i in files)) if conf.poc: regex_rule(conf.poc) exit() # if check version if conf.show_version: exit()
def run(self): try: while self.__running.is_set(): time.sleep(1) self.__flag.wait() if not self.server_started: self.httpd = self.httpserver( (self.bind_ip, self.bind_port), self.requestHandler) logger.info("Starting httpd on {}://{}:{}".format( self.scheme, self.bind_ip, self.bind_port)) if self.https: if self.certfile: self.httpd.socket = ssl.wrap_socket( self.httpd.socket, certfile=self.certfile, server_side=True) else: logger.error( "You must provide certfile to use https") break thread = threading.Thread(target=self.httpd.serve_forever) thread.setDaemon(True) thread.start() self.server_started = True self.__flag.clear() self.httpd.shutdown() self.httpd.server_close() logger.info('Stop httpd server on {}://{}:{}'.format( self.scheme, self.bind_ip, self.bind_port)) except Exception as ex: self.httpd.shutdown() self.httpd.server_close() logger.error(str(ex))
def __init__(self, module_directory=paths.POCSUITE_POCS_PATH): super(PocsuiteInterpreter, self).__init__() self.current_module = None self.raw_prompt_template = None self.module_prompt_template = None self.prompt_hostname = "Pocsuite3" self.show_sub_commands = ("info", "options", "ip", "all") self.global_commands = sorted( ["use ", "help", "exit", "show ", "search ", "clear"]) self.module_commands = ["run", "back", "set ", "setg ", "check"] self.module_commands.extend(self.global_commands) self.module_commands.sort() self.modules = index_modules(module_directory) self.module_parent_directory = os.sep.join( module_directory.rstrip(os.sep).split(os.sep)[0:-1]) + os.sep self.modules_count = len(self.modules) # init conf.console_mode = True banner() logger.info("Load Pocs :{}".format(self.modules_count)) self.last_search = [] self.last_ip = [] self.main_modules_dirs = [] for module in self.modules: temp_module = module temp_module = ltrim(temp_module, self.module_parent_directory).lstrip(os.sep) self.main_modules_dirs.append(temp_module) self.__parse_prompt()
def check_requires(data): requires = get_poc_requires(data) requires = [ i.strip().strip('"').strip("'") for i in requires.split(',') ] if requires else [''] if requires[0]: poc_name = get_poc_name(data) info_msg = 'PoC script "{0}" requires "{1}" to be installed'.format( poc_name, ', '.join(requires)) logger.info(info_msg) try: for r in requires: r = r.replace(' ', '') install_name, import_name = (r.split(':') + [''])[0:2] t = re.split('>|<|=|~', install_name) if len(t) > 1: install_name = t[0] if not import_name: import_name = install_name m = __import__(import_name) ver = m.__version__ if hasattr(m, '__version__') else '' logger.info(f'{install_name} {ver} has been installed') except ImportError: err_msg = f'{install_name} not found, try install with "python -m pip install {install_name}"' logger.error(err_msg) raise SystemExit
def __init__(self, filter): super().__init__() self.filter = "host %s" % filter self.daemon = True self.socket = None self.use_pcap = True self.is_admin = False logger.info( 'Local network adapter information, choose a network you want to ' 'capture.') message = '----- Local IP Address -----\n' ifaces = [] if WINDOWS: import ctypes from scapy.all import IFACES if ctypes.windll.shell32.IsUserAnAdmin(): self.is_admin = True for i, iface in enumerate(sorted(IFACES)): dev = IFACES[iface] ifaces.append(dev.description) message += "{0} {1} {2}\n".format(i, dev.description, dev.ip) else: if os.getuid() == 0: self.is_admin = True ifaces = get_if_list() for i, iface in enumerate(ifaces): ip = get_if_addr(iface) message += "{0} {1} {2}\n".format(i, iface, ip) data_to_stdout(message) choose = input('Choose>: ').strip() self.interface = ifaces[int(choose)] self.use_pcap = True self.stop_sniffer = Event() self.pcap = None
def __init__(self): super(PocsuiteInterpreter, self).__init__() self.current_module = None self.raw_prompt_template = None self.module_prompt_template = None self.prompt_hostname = "Pocsuite3" self.show_sub_commands = ("info", "options", "ip", "all") self.global_commands = sorted( ["use ", "help", "exit", "show ", "search "]) self.module_commands = ["run", "back", "set ", "setg ", "check"] self.module_commands.extend(self.global_commands) self.module_commands.sort() self.modules = index_modules() self.modules_count = len(self.modules) # init conf.console_mode = True banner() logger.info("Load Pocs :{}".format(self.modules_count)) self.last_search = [] self.main_modules_dirs = [] for module in self.modules: temp_module = module if IS_WIN: temp_module = temp_module.replace("/", "\\") temp_module = temp_module.replace(paths.POCSUITE_ROOT_PATH, "").lstrip("\\") temp_module = temp_module.replace(paths.POCSUITE_ROOT_PATH, "").lstrip("/") self.main_modules_dirs.append(temp_module) self.__parse_prompt()
def command_setg(self, *args, **kwargs): key, _, value = args[0].partition(" ") if key in self.current_module.global_options: self.current_module.setg_option(key, value) logger.info("{} => {}".format(key, value)) else: logger.error("You can't set option '{}'.\n" "Available options: {}".format(key, self.current_module.options))
def test_only_start_server_once(self): logger.info("Test http server is only start once") PHTTPServer._instance = None httpd1 = PHTTPServer() httpd2 = PHTTPServer() httpd1.start() httpd2.start() httpd1.stop() httpd2.stop()
def token_is_available(self): if self.token: try: resp = requests.get( 'https://api.shodan.io/account/profile?key={0}'.format(self.token), headers=self.headers) logger.info(resp.text) if resp and resp.status_code == 200 and "member" in resp.json(): return True except Exception as ex: logger.error(str(ex)) return False
def token_is_available(self): if self.secret and self.uid: try: resp = requests.get("https://censys.io/api/v1/account", auth = (self.uid, self.secret)) if resp.status_code == 200 and "email" in resp.json(): logger.info("[PLUGIN] Censys login success email:{}".format(resp.json()["email"])) self.credits = resp.json()["quota"]["allowance"] - resp.json()["quota"]["used"] return True except Exception as ex: logger.error(ex) return False
def task_run(): while not kb.task_queue.empty() and kb.thread_continue: target, poc_module = kb.task_queue.get() if not conf.console_mode: poc_module = copy.deepcopy(kb.registered_pocs[poc_module]) poc_name = poc_module.name info_msg = "running poc:'{0}' target '{1}'".format(poc_name, target) logger.info(info_msg) # hand user define parameters if hasattr(poc_module, "_options"): for item in kb.cmd_line: value = cmd_line_options.get(item, "") if item in poc_module.options: poc_module.set_option(item, value) info_msg = "Parameter {0} => {1}".format(item, value) logger.info(info_msg) # check must be option for opt, v in poc_module.options.items(): # check conflict in whitelist if opt in CMD_PARSE_WHITELIST: info_msg = "Poc:'{0}' You can't customize this variable '{1}' because it is already taken up by the pocsuite.".format( poc_name, opt) logger.error(info_msg) raise SystemExit if v.require and v.value == "": info_msg = "Poc:'{poc}' Option '{key}' must be set,please add parameters '--{key}'".format( poc=poc_name, key=opt) logger.error(info_msg) raise SystemExit result = poc_module.execute(target, headers=conf.http_headers, mode=conf.mode, verbose=False) if not result: continue if not conf.quiet: result.show_result() result_status = "success" if result.is_success() else "failed" output = AttribDict(result.to_dict()) output.update({ 'target': target, 'poc_name': poc_name, 'created': time.strftime("%Y-%m-%d %X", time.localtime()), 'status': result_status }) kb.results.append(output)
def token_is_available(self): if self.token and self.user: try: resp = requests.get( f'{self.api_url}/info/my?email={self.user}&key={self.token}', headers=self.headers) logger.info(resp.text) if resp and resp.status_code == 200 and "username" in resp.json(): return True except Exception as ex: logger.error(str(ex)) return False
def test_ipv6(self): try: logger.info('Test http server in ipv6') PHTTPServer._instance = None httpd = PHTTPServer(bind_ip='::', bind_port=6666, requestHandler=BaseRequestHandler) httpd.start() url = '{}://{}:{}/'.format('http', '[{}]'.format(get_host_ipv6()), 6666) resp = requests.get(url) self.assertEqual(resp.status_code, 200) except Exception: pass finally: httpd.stop()
def token_is_available(self): if self.token: self.headers['Authorization'] = f'JWT {self.token}' try: resp = requests.get('https://api.zoomeye.org/resources-info', headers=self.headers) if resp and resp.status_code == 200 and "plan" in resp.text: return True else: logger.info(resp.text) except Exception as ex: logger.error(str(ex)) return False
def update(): if not conf.update_all: return success = False if not os.path.exists(os.path.join(paths.POCSUITE_ROOT_PATH, "../", ".git")): warn_msg = "not a git repository. It is recommended to clone the 'knownsec/pocsuite3' repository " warn_msg += "from GitHub (e.g. 'git clone --depth 1 {} pocsuite3')".format( GIT_REPOSITORY) logger.warn(warn_msg) if VERSION == get_latest_revision(): logger.info("already at the latest revision '{}'".format( get_revision_number())) return else: info_msg = "updating pocsuite3 to the latest development revision from the " info_msg += "GitHub repository" logger.info(info_msg) debug_msg = "pocsuite3 will try to update itself using 'git' command" logger.debug(debug_msg) data_to_stdout("\r[{0}] [INFO] update in progress ".format( time.strftime("%X"))) cwd_path = os.path.join(paths.POCSUITE_ROOT_PATH, "../") try: process = subprocess.Popen( "git checkout . && git pull %s HEAD" % GIT_REPOSITORY, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd_path.encode(sys.getfilesystemencoding() or UNICODE_ENCODING)) poll_process(process, True) stdout, stderr = process.communicate() success = not process.returncode except (IOError, OSError) as ex: success = False stderr = str(ex) if success: logger.info("{0} the latest revision '{1}'".format( "already at" if b"Already" in stdout else "updated to", get_revision_number())) else: if "Not a git repository" in stderr: err_msg = "not a valid git repository. Please checkout the 'knownsec/pocsuite3' repository " err_msg += "from GitHub (e.g. 'git clone --depth 1 %s pocsuite3')" % GIT_REPOSITORY logger.error(err_msg) else: logger.error("update could not be completed ('%s')" % re.sub(r"\W+", " ", stderr).strip()) if not success: if IS_WIN: info_msg = "for Windows platform it's recommended " info_msg += "to use a GitHub for Windows client for updating " info_msg += "purposes (http://windows.github.com/) or just " info_msg += "download the latest snapshot from " info_msg += "https://github.com/knownsec/pocsuite3/downloads" else: info_msg = "for Linux platform it's recommended " info_msg += "to install a standard 'git' package (e.g.: 'sudo apt-get install git')" logger.info(info_msg)
def token_is_available(self): if self.token: # distinguish Jwt Token & API Token self.headers['Authorization'] = self.token if len( self.token) < 48 else f'JWT {self.token}' try: resp = requests.get('http://api.ceye.io/v1/identify', headers=self.headers) if resp and resp.status_code == 200 and "identify" in resp.text: return True else: logger.info(resp.text) except Exception as ex: logger.error(str(ex)) return False
def _set_pocs_modules(): # TODO # load poc scripts .pyc file support if conf.poc: # step1. load system packed poc from pocsuite3/pocs folder exists_poc_with_ext = list( filter(lambda x: x not in ['__init__.py', '__init__.pyc'], os.listdir(paths.POCSUITE_POCS_PATH))) exists_pocs = dict([os.path.splitext(x) for x in exists_poc_with_ext]) for poc in conf.poc: load_poc_sucess = False if any([poc in exists_poc_with_ext, poc in exists_pocs]): poc_name, poc_ext = os.path.splitext(poc) if poc_ext in ['.py', '.pyc']: file_path = os.path.join(paths.POCSUITE_POCS_PATH, poc) else: file_path = os.path.join(paths.POCSUITE_POCS_PATH, poc + exists_pocs.get(poc)) if file_path: info_msg = "loading PoC script '{0}'".format(file_path) logger.info(info_msg) load_poc_sucess = load_file_to_module(file_path) # step2. load poc from given file path try: if not load_poc_sucess: if not poc.startswith('ssvid-') and check_file(poc): info_msg = "loading PoC script '{0}'".format(poc) logger.info(info_msg) load_poc_sucess = load_file_to_module(poc) except PocsuiteSystemException: logger.error('PoC file "{0}" not found'.format(repr(poc))) continue # step3. load poc from seebug website using plugin 'poc_from_seebug' if not load_poc_sucess: if poc.startswith('ssvid-'): info_msg = "loading Poc script 'https://www.seebug.org/vuldb/{0}'".format( poc) logger.info(info_msg) if "poc_from_seebug" not in conf.plugins: conf.plugins.append('poc_from_seebug') load_poc_sucess = True load_keyword_poc_sucess = False if conf.vul_keyword: # step4. load poc with vul_keyword search seebug website info_msg = "loading PoC script from seebug website using search keyword '{0}' ".format( conf.vul_keyword) logger.info(info_msg) conf.plugins.append('poc_from_seebug') load_keyword_poc_sucess = True if all([not kb.registered_pocs, not load_keyword_poc_sucess]): error_msg = "no PoC loaded, please check your PoC file" logger.error(error_msg) raise PocsuiteSystemException(error_msg)
def new_token(self): data = '{{"username": "******", "password": "******"}}'.format( self.username, self.password) try: resp = requests.post('https://api.zoomeye.org/user/login', data=data) if resp.status_code != 401 and "access_token" in resp.text: content = resp.json() self.token = content['access_token'] self.headers['Authorization'] = f'JWT {self.token}' return True else: logger.info(resp.text) except Exception as ex: logger.error(str(ex)) return False
def token_is_available(self): if self.token: try: self.headers['X-QuakeToken'] = self.token resp = requests.get('https://quake.360.cn/api/v3/user/info', headers=self.headers) if 'month_remaining_credit' not in resp.text: logger.info(resp.text) if resp and resp.status_code == 200 and resp.json( )['code'] == 0: return True except Exception as ex: logger.error(str(ex)) return False
def search(self, dork): search_result = set() # create a browser instance browser = pychrome.Browser(url="http://127.0.0.1:9222") # create a tab tab = browser.new_tab() # start the tab tab.start() tab.Page.enable() # call method tab.Network.enable() tab.Runtime.enable() start = 1000 for step in range(0, start + 10, 10): url = "https://www.google.com/search?q={}".format(dork) url = url + "&start={}".format(step) # stepinfo="step:"+str(step) # logger.info(stepinfo) try: # call method with timeout tab.Page.navigate(url=url, _timeout=5) tab.wait(5) exp = 'document.getElementsByClassName("r").length' length = tab.Runtime.evaluate(expression=exp) # google就看报不报错,报错了的话document.getElementsByClassName("r").length是为0的 if length['result']['value'] == 0: logger.warn("[PLUGIN] Google Dork get 0, Exit") break # 从每一页上抓取url for l in range(0, length['result']['value']): # tab.wait(1) exp1 = 'document.getElementsByClassName("r")[{}].getElementsByTagName("a")[0].href'.format( l) res1 = tab.Runtime.evaluate(expression=exp1) logger.info(res1['result']['value']) search_result.add(res1['result']['value']) except Exception as ex: logger.error(str(ex)) tab.stop() browser.close_tab(tab) return search_result
def test_ipv4_https(self): try: logger.info('Test https server in ipv4') PHTTPServer._instance = None httpd = PHTTPServer(bind_ip='0.0.0.0', bind_port=6666, use_https=True, requestHandler=BaseRequestHandler) httpd.start() url = '{}://{}:{}/'.format('https', get_host_ip(), 6666) requests.get(url) except requests.exceptions.SSLError: url = '{}://{}:{}/'.format('https', get_host_ip(), 6666) resp = requests.get(url, verify=False) self.assertEqual(resp.status_code, 200) except Exception: assert False finally: httpd.stop()
def _set_pocs_modules(): # TODO # load poc scripts .pyc file support if conf.poc: load_poc_sucess = False # step1. load system packed poc from pocsuite3/pocs folder for found in glob.glob(os.path.join(paths.POCSUITE_POCS_PATH, "*.py*")): dirname, filename = os.path.split(found) poc_name = os.path.splitext(filename)[0] for poc in conf.poc: if found.endswith(('__init__.py', '__init__.pyc')): continue if poc in (filename, poc_name): info_msg = "loading PoC script '{0}'".format(found) logger.info(info_msg) load_poc_sucess = load_file_to_module(found) # step2. load poc from given file path try: if not load_poc_sucess: for poc in conf.poc: if not poc.startswith('ssvid-') and check_file(poc): info_msg = "loading PoC script '{0}'".format(poc) logger.info(info_msg) load_poc_sucess = load_file_to_module(poc) except PocsuiteSystemException: logger.error('PoC file "{0}" not found'.format(repr(conf.poc))) raise SystemExit # step3. load poc from seebug website using plugin 'poc_from_seebug' if not load_poc_sucess: for poc in conf.poc: if poc.startswith('ssvid-'): info_msg = "loading Poc script 'https://www.seebug.org/vuldb/{0}'".format( poc) logger.info(info_msg) if "poc_from_seebug" not in conf.plugins: conf.plugins.append('poc_from_seebug') load_poc_sucess = True if conf.vul_keyword: # step4. load poc with vul_keyword search seebug website info_msg = "loading PoC script from seebug website using search keyword '{0}' ".format( conf.vul_keyword) logger.info(info_msg) conf.plugins.append('poc_from_seebug') load_poc_sucess = True if (conf.poc or conf.vul_keyword) and not load_poc_sucess: error_msg = "" logger.error(error_msg) raise PocsuiteSyntaxException(error_msg)
def start(self): """ Routersploit main entry point. Starting interpreter loop. """ while True: try: command, args = self.parse_line(input(self.prompt)) command = command.lower() if not command: continue command_handler = self.get_command_handler(command) command_handler(args) except PocsuiteBaseException as err: logger.error(err) except EOFError: logger.info("Pocsuite stopped") break except KeyboardInterrupt: logger.info("User Quit") break
def __init__(self, filter): super().__init__() self.filter = "host %s" % filter self.daemon = True self.socket = None self.use_pcap = True self.is_admin = False logger.info( "Local network adapter information, choose a network you want to capture" ) if WINDOWS: iface = [] import ctypes if ctypes.windll.shell32.IsUserAnAdmin(): self.is_admin = True ips = get_local_ip(all=True) message = '----- Local IP Address -----\n' name = [] interface_ips = [] for iface_name in sorted(IFACES): if list(set(IFACES[iface_name].data['ips'])): if list(set(IFACES[iface_name].data['ips']))[0] in ips: name.append(IFACES[iface_name].data['name']) interface_ips.append( list(set(IFACES[iface_name].data['ips']))[0]) iface.append(IFACES[iface_name].data['description']) for i, ip in enumerate(interface_ips): message += "{0} {1} {2}\n".format(i, name[i], ip) else: if os.getuid() == 0: self.is_admin = True from pocsuite3.thirdparty.scapy.core import get_if_list, get_if_lists iface, ips = get_if_lists() message = '----- Local IP Address -----\n' for i, ip in enumerate(ips): message += "{0} {1} {2}\n".format(i, iface[i], ip) data_to_stdout(message) choose = input('Choose>: ').strip() self.interface = iface[int(choose)] self.use_pcap = conf.use_pcap self.stop_sniffer = Event() self.pcap = None
def command_set(self, *args, **kwargs): key, _, value = args[0].partition(" ") if key in self.current_module.options: self.current_module.set_option(key, value) logger.info("{} => {}".format(key, value)) elif key in self.current_module.global_options: self.current_module.setg_option(key, value) logger.info("{} => {}".format(key, value)) elif key in self.current_module.payload_options: self.current_module.setp_option(key, value) logger.info("{} => {}".format(key, value)) else: logger.error("You can't set option '{}'.".format(key))
def start(): runtime_check() tasks_count = kb.task_queue.qsize() info_msg = "pocsusite got a total of {0} tasks".format(tasks_count) logger.info(info_msg) logger.debug("pocsuite will open {} threads".format(conf.threads)) try: run_threads(conf.threads, task_run) logger.info("Scan completed,ready to print") finally: task_done() if conf.mode == "shell" and not conf.api: info_msg = "connect back ip: {0} port: {1}".format( conf.connect_back_host, conf.connect_back_port) logger.info(info_msg) info_msg = "watting for shell connect to pocsuite" logger.info(info_msg) if conf.console_mode: handle_listener_connection_for_console() else: handle_listener_connection()
def start(): tasks_count = kb.task_queue.qsize() info_msg = "pocsusite got a total of {0} tasks".format(tasks_count) logger.info(info_msg) run_threads(conf.threads, task_run) task_done() if conf.mode == "shell": info_msg = "connect back ip: {0} port: {1}".format( conf.connect_back_host, conf.connect_back_port) logger.info(info_msg) info_msg = "watting for shell connect to pocsuite" logger.info(info_msg) if conf.console_mode: handle_listener_connection_for_console() else: handle_listener_connection()