def active_login(self): #Active scanner on login page zap = ZAPv2(apikey=apiKey) print('Running Active Scan {}'.format(target)) scanid = zap.ascan.scan(target) while(int(zap.ascan.status(scanid)) < 100): # Loop until the scanner has finished print('Scan progress %: {}'.format(zap.ascan.status(scanid))) time.sleep(5) print('Active Scan completed') zap = ZAPv2(apikey=apiKey) # Reports the results print('Hosts: {}'.format(', '.join(zap.core.hosts))) print('Alerts: ') pprint(zap.core.alerts())
def step_impl(context): subprocess.Popen('./owasp.sh') time.sleep(5) target = context.browser.current_url apikey = '6ojksn3a4nnepjm4ju03hh7rio' zap = ZAPv2(apikey=apikey, proxies={'http': 'http://127.0.0.1:8089', 'https': 'https://127.0.0.1:8089'}) print('zap has started') time.sleep(2) scanid = zap.spider.scan(target) time.sleep(2) while int(zap.spider.status(scanid)) < 100: time.sleep(2) while int(zap.pscan.records_to_scan) > 0: time.sleep(2) scanid = zap.ascan.scan(target) while int(zap.ascan.status(scanid)) < 100: time.sleep(5) allure.attach(zap.core.htmlreport(apikey=apikey), name="Security report", attachment_type=allure.attachment_type.HTML, extension='html') assert len(zap.core.alerts()) == 0, 'Security bugs has been found' zap.core.shutdown() time.sleep(2)
def main(): # If the script is run outside the dispatcher the environment variables # are checked. # ['EXECUTOR_CONFIG_API_KEY', 'EXECUTOR_CONFIG_TARGET_URL'] try: target = os.environ["EXECUTOR_CONFIG_TARGET_URL"] api_key = os.environ["EXECUTOR_CONFIG_API_KEY"] except KeyError: print("environment variable not found", file=sys.stderr) sys.exit() # zap is required to be started zap_run = subprocess.check_output("pgrep -f zap", shell=True) if len(zap_run.decode("utf-8").split("\n")) > 3: # the apikey from ZAP->Tools->Options-API zap = ZAPv2(apikey=api_key) # it passes the url to scan and starts scanID = zap.spider.scan(target) # Wait for the scan to finish while int(zap.spider.status(scanID)) < 100: time.sleep(1) # If finish the scan and the xml is generated zap_result = zap.core.xmlreport() plugin = PluginsManager().get_plugin("zap") plugin.parseOutputString(zap_result) print(plugin.get_json()) else: print("ZAP not running", file=sys.stderr) sys.exit()
def main(argv): # ------------------------------------------------------------------------- # Default Configurations - use -z/-zap and -w/-wavsep for different IP addrs # ------------------------------------------------------------------------- zapHostPort = 'http://localhost:8090' try: opts, args = getopt.getopt(argv,"z:",["zap="]) except getopt.GetoptError: # TODO print 'zap-backup-test.py -z <ZAPhostPort>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'zap-backup-test.py -z <ZAPhostPort>' sys.exit() elif opt in ("-z", "--zap"): zapHostPort = arg zap = ZAPv2(proxies={'http': zapHostPort, 'https': zapHostPort}) # Count number of messages old_mcount = zap.core.number_of_messages() old_acount = zap.core.number_of_alerts() print 'Initial msg count: %s' % old_mcount print 'Initial alert count: %s' % old_acount # Time backup start_time = time.time() zap.core.save_session(name='backup-test', overwrite='true') backup_time = (time.time() - start_time) print 'Backed up: %s' % str(time.strftime('%H:%M:%S', time.gmtime(int(backup_time)))) # Time new session start_time = time.time() zap.core.new_session(name='backup-empty', overwrite='true') new_time = (time.time() - start_time) print 'New session: %s' % str(time.strftime('%H:%M:%S', time.gmtime(int(new_time)))) # Sanity check new session new_count = zap.core.number_of_messages() if (new_count != '0'): print 'Unexpected empty count: %s' % new_count # Time restore start_time = time.time() zap.core.load_session(name='backup-test') rec_time = (time.time() - start_time) print 'Loaded: %s' % str(time.strftime('%H:%M:%S', time.gmtime(int(rec_time)))) rec_mcount = zap.core.number_of_messages() rec_acount = zap.core.number_of_alerts() if (old_mcount == rec_mcount): print 'PASS: msg counts match' else: print 'FAIL: msg counts differ - original: %s recovered: %s' % old_mcount, new_mcount if (old_acount == rec_acount): print 'PASS: alert counts match' else: print 'FAIL: alert counts differ - original: %s recovered: %s' % old_acount, new_acount
def run_scan(config): print("Getting free port") port = z.get_free_port() print("Starting zap") z.start_zap(port, ['-config', 'spider.maxDuration=2']) start = datetime.today().strftime('%Y%m%d%H%I%s') zap = ZAPv2( proxies={ 'http': 'http://localhost:' + str(port), 'https': 'http://localhost:' + str(port) }) z.wait_for_zap_start(zap, config.timeout * 60) access = z.zap_access_target(zap, config.target) z.zap_spider(zap, config.target) z.zap_wait_for_passive_scan(zap, config.timeout * 60) alerts = z.zap_get_alerts(zap, config.target, config.blacklist, {}) urls = zap.core.urls() # Cleanup alerts and remove nodes zap.core.delete_all_alerts() for site in zap.core.sites: zap.core.delete_site_node(site) zap.core.run_garbage_collection() zap.core.shutdown() return { "start": start, "config": config.as_dict(), "urls": urls, "alerts": alerts, }, zap
def run_zap_spider(target, proxy, loop, apikey="avi123"): # By default ZAP API client will connect to port 8080 zap = ZAPv2(apikey=apikey, proxies={'http': proxy}) #zap.core.set_option_use_proxy_chain(boolean=True) #zap.core.set_option_proxy_chain_name(string="10.79.111.22") #zap.core.set_option_proxy_chain_skip_name(string='127.0.0.1;') #zap.core.set_option_proxy_chain_port(integer=6666) #zap.core.set_option_use_proxy_chain_auth(boolean=True) #zap.core.set_option_proxy_chain_user_name(string="aviuser") #zap.core.set_option_proxy_chain_password(string="avi123") # Use the line below if ZAP is not listening on port 8080, for example, if listening on port 8090 # zap = ZAPv2(apikey=apikey, proxies={'http': 'http://127.0.0.1:8090', 'https': 'http://127.0.0.1:8090'}) # Proxy a request to the target so that ZAP has something to deal with print('Accessing target {}'.format(target)) zap.urlopen(target) # Give the sites tree a chance to get updated time.sleep(2) for loop in range(int(loop)): print('Spidering target {}'.format(target)) scanid = zap.spider.scan(target) # Give the Spider a chance to start time.sleep(2) while (int(zap.spider.status(scanid)) < 100): # Loop until the spider has finished print('Spider progress %: {}'.format(zap.spider.status(scanid)), end='\r') time.sleep(2) print("") print('Spider completed') print('All Spider runs completed')
def __enter__(self): logger.info("Opening OWASP ZAP") # The '-daemon' switch makes it start in headless mode (without a graphical interface) # 'stdout=open(os.devnull,'w')' ensures there is no output in most operating systems self.pid = subprocess.Popen([owasp_location,"-daemon"], stdout=open(os.devnull,"w")) self.zap = ZAPv2(apikey=api_key) # Start the ZAP API client (with default port 8080) return self
def set_target(self): seed = None host = None url_comp = None seed = raw_input( "\nEnter the URL of the web application you would like to begin testing:\n>" ) try: url_comp = urlparse(seed) if url_comp[0] == "": seed = "http://" + seed else: seed = seed url_comp = urlparse(seed) status = requests.get(seed).status_code socket.gethostbyname(url_comp[1]) except: status = 404 if (status >= 400): print "Error. Couldn't connect to " + seed + "\nStatus code: " + str( status) + "" return False try: self.zap.core.new_session() except: pass self.nm = None self.dir_tree = None self.host = url_comp[1] self.seed = seed self.zap = ZAPv2() self.alerts = {} print "Target set successfully!" raw_input("[Press Enter to continue]") return True
def _start_zap(self): """ Start ZAP daemon, create API client """ log.info("Starting ZAP daemon") bind_host = "127.0.0.1" if self.config.get("bind_all_interfaces", True): bind_host = "0.0.0.0" daemon_out = subprocess.DEVNULL if self.config.get("daemon_debug", False): daemon_out = sys.stdout zap_home_dir = tempfile.mkdtemp() log.debug("ZAP home directory: %s", zap_home_dir) self._zap_daemon = subprocess.Popen([ "/usr/bin/java", self.config.get("java_options", "-Xmx499m"), "-jar", constants.ZAP_PATH, "-dir", zap_home_dir, "-daemon", "-port", "8091", "-host", bind_host, "-config", "api.key=dusty", "-config", "api.addrs.addr.regex=true", "-config", "api.addrs.addr.name=.*", "-config", "ajaxSpider.browserId=htmlunit" ], stdout=daemon_out, stderr=daemon_out) self._zap_api = ZAPv2( apikey="dusty", proxies={ "http": "http://127.0.0.1:8091", "https": "http://127.0.0.1:8091" } )
def zap_connect(): all_zap = zap_settings_db.objects.all() zap_api_key = 'dwed23wdwedwwefw4rwrfw' zap_hosts = '127.0.0.1' zap_ports = '8090' zap_enabled = False for zap in all_zap: zap_enabled = zap.enabled if zap_enabled is False: zap_api_key = 'dwed23wdwedwwefw4rwrfw' zap_hosts = '127.0.0.1' zap_ports = '8090' elif zap_enabled is True: for zap in all_zap: zap_api_key = zap.zap_api zap_hosts = zap.zap_url zap_ports = zap.zap_port zap = ZAPv2(apikey=zap_api_key, proxies={ 'http': zap_hosts + ':' + zap_ports, 'https': zap_hosts + ':' + zap_ports }) return zap
def zap_scan_stop(request): if request.method == "GET": ip = request.GET.get("ip", None) port = request.GET.get("port", None) scanId = request.GET.get("scanid", None) if ip and port and scanId: try: instance = ZAPInstance.objects.get(server__ip=ip, port=port, enabled=True) apikey = instance.api_key zap = ZAPv2( proxies={ 'http': 'http://%s:%s' % (ip, port), 'https': 'http://%s:%s' % (ip, port) }) response = zap.ascan.stop(scanId, apikey=apikey) if response == "OK": return JsonResponse({"status": True}) else: return JsonResponse({"status": False}, 404) except: return JsonResponse( {"message": "No such instance found. Please check."}, 400) else: return JsonResponse({"message": "Invalid parameters recieved."}, 400)
def main(): attempt_banner_display() read_config() #prompt_inputs() get_module() # Pulling this chunk out of prompt_inputs(), may need more permanent solution # Set authmethodconfigparams using new data. # The below looks a bit confusing. That's because this string is a set of # queries containing queries. The outer set uses &, =, etc, while the inner # set uses the respective encodings of those special characters. This is how # ZAP is able to distinguish the inner from the outer. global authmethodconfigparams, zap authmethodconfigparams = 'loginUrl=' + target_url + '/user/login/' + \ '&loginRequestData=name%3D{%25username%25}' + \ '%26pass%3D{%25password%25}' + \ '%26form_id%3Duser_login_form%26op%3DLog%2Bin' # Set zap using new data. try: zap = ZAPv2(apikey=zap_apikey) except e: exit_program("Could not start ZAP. Is ZAP open? Is the API valid?") # Open logfile for writing flog = open(logfile, 'w') get_routing_paths(flog) setup_zap() #if not options.nospider: #spider_target() active_scan_target(flog) export_results() print Fore.GREEN + Style.BRIGHT + 'Done.' flog.close()
def test_security_scan(self): zap = ZAPv2(apikey=ZAP_API_KEY, proxies={'http': ZAP_API_URL, 'https': ZAP_API_URL}) print("Empezando exploración") explore_id = zap.ajaxSpider.scan(TARGET_URL) print(f"ID exploración: {explore_id}") timeout = time.time() + DEFAULT_TIMEOUT while zap.ajaxSpider.status == 'running': if time.time() > timeout: break time.sleep(DEFAULT_WAIT) assert zap.ajaxSpider.status == 'stopped', 'La exploración con ZAP excedió el timeout' explore_results = zap.ajaxSpider.results(start=0, count=10) print("Resultado de la exploración: {}".format(explore_results)) print("Empezando escaneo") scan_id = zap.ascan.scan(TARGET_URL) timeout = time.time() + DEFAULT_TIMEOUT while int(zap.ascan.status(scan_id)) < 100: if time.time() > timeout: break time.sleep(DEFAULT_WAIT) assert int(zap.ascan.status(scan_id)) == 100, 'El escaneo con ZAP excedió el timeout' alerts = zap.core.alerts(baseurl=TARGET_URL) with open('results/sec_report.html', 'w') as f: f.write(build_html(zap.core.hosts, alerts)) assert len(alerts) == 0, "Se encontraron vulnerabilidades en el escaneo con ZAP"
def zap_connect(random_port): all_zap = ZapSettingsDb.objects.filter() zap_api_key = "dwed23wdwedwwefw4rwrfw" zap_hosts = "127.0.0.1" zap_ports = "8090" zap_enabled = False for zap in all_zap: zap_enabled = zap.enabled if zap_enabled is False: zap_api_key = "dwed23wdwedwwefw4rwrfw" zap_hosts = "127.0.0.1" zap_ports = random_port if zap_enabled is True: for zap in all_zap: zap_api_key = zap.zap_api zap_hosts = zap.zap_url zap_ports = zap.zap_port zap = ZAPv2( apikey=zap_api_key, proxies={ "http": "http://" + zap_hosts + ":" + str(zap_ports), "https": "https://" + zap_hosts + ":" + str(zap_ports), }, ) return zap
def active(url, key): zap = ZAPv2(apikey=key) if not args.output: print('Active Scanning target {}'.format(url)) scan_id = zap.ascan.scan(url) while int(zap.ascan.status(scan_id)) < 100: print('Scan progress %: {}'.format(zap.ascan.status(scan_id))) time.sleep(5) # Print vulnerabilities found by the scanning print('Hosts: {}'.format(', '.join(zap.core.hosts))) print('Alerts: ') print(zap.core.alerts(baseurl=url)) print('Active Scan completed') elif args.output: print('Active Scanning target {}'.format(url)) scan_id = zap.ascan.scan(url) while int(zap.ascan.status(scan_id)) < 100: print('Scan progress %: {}'.format(zap.ascan.status(scan_id))) time.sleep(5) alerts = zap.core.alerts(baseurl=url) print(output(alerts)) else: print( 'Oops, Houston we have a problem here, please see Help options and retry this again' ) sys.exit() return
def zap_setup_context(target: Host, port: str, user: str, passwd: str) -> tuple: """ Creates a context for this scan, adding a new user to that context and sets up the authentication mechanism. """ zap = ZAPv2() if port == '443': url = "https://{}".format(str(target)) else: url = "http://{}".format(str(target)) low("Creating new context for zap scan.") context_id = zap.context.new_context("ZapScan") zap.context.include_in_context("ZapScan", "{}.*".format(str(target))) zap.context.include_in_context("ZapScan", "{}.*".format(url)) zap.authentication.set_authentication_method( context_id, 'httpAuthentication', 'hostname={}&realm='.format(str(target))) low("Creating user for context.") user_id = zap.users.new_user(context_id, "zapuser") zap.users.set_authentication_credentials( context_id, user_id, "username={}&password={}".format(user, passwd)) zap.users.set_user_enabled(context_id, user_id, True) zap.forcedUser.set_forced_user(context_id, user_id) zap.forcedUser.set_forced_user_mode_enabled(True) return context_id, user_id
def zap_connect(random_port, username): all_zap = zap_settings_db.objects.filter(username=username) zap_api_key = '' zap_hosts = '127.0.0.1' zap_ports = '8090' zap_enabled = False for zap in all_zap: zap_enabled = zap.enabled if zap_enabled is False: zap_api_key = 'dwed23wdwedwwefw4rwrfw' zap_hosts = '127.0.0.1' zap_ports = random_port if zap_enabled is True: for zap in all_zap: zap_api_key = zap.zap_api zap_hosts = zap.zap_url zap_ports = zap.zap_port zap = ZAPv2(apikey=zap_api_key, proxies={ 'http': 'http://' + zap_hosts + ':' + str(zap_ports), 'https': 'https://' + zap_hosts + ':' + str(zap_ports)}) return zap
def isZapReady(): zap=ZAPv2() try: urls=zap.core.urls() return "Ready" except ProxyError: return "NotReady"
def __init__(self, target): self._target = target self._httpProxy = 'http://127.0.0.1:1337' self._httpsProxy = 'http://127.0.0.1:1337' self._zap = ZAPv2(proxies = {'http':self._httpProxy, 'https':self._httpsProxy}) self._apiKey = '5a8au7kjk7itl2flqkt4ufi19q'
def openZapProxy(args): args.zap_host = re.sub(r'^((?!http://).*)', r'http://\1', args.zap_host) args.zap_host_ssh = re.sub(r'^((?!http?s://).*)', r'https://\1', args.zap_host_ssh) return ZAPv2(proxies={'http': args.zap_host, 'https': args.zap_host_ssh})
def __init__(self): self.register_in_service_locator() self.config = self.get_component("config") self.transaction = self.get_component("transaction") zap_proxy_address = "http://" + self.config.FrameworkConfigGet( "ZAP_PROXY_ADDR") + ":" + self.config.FrameworkConfigGet("ZAP_PROXY_PORT") self.zap = ZAPv2(proxies={'http': zap_proxy_address, 'https': zap_proxy_address}) # the values are hard-coded just for the test purpose, will be taken from config later
def url_auth(self): zap = ZAPv2(apikey=apiKey) ctx_name = " " Place a context for the url here ctx_id = zap.context.new_context(ctx_name) print('zap initizalized') login_url = " " # Place URL path you would like to scan here after authenticating with ZAP print("Now Authenticating..") zap.authentication.set_authentication_method(ctx_id, "formBasedAuthentication", "loginUrl=" + login_url)
def wait_for_zap(): """ Wait until the python api is able to interact with the zaproxy application. If after retries it doesnt work, raise zap error. """ zap = ZAPv2() zap.urlopen('http://127.0.0.1') sleep(3)
def passive(url, key): zap = ZAPv2(apikey=key) if not args.output: print('Passive Scanning target {}'.format(url)) st = 0 pg = 5000 alert_count = 0 alerts = zap.alert.alerts(baseurl=url, start=st, count=pg) blacklist = [1, 2] while len(alerts) > 0: print('Reading ' + str(pg) + ' alerts from ' + str(st)) alert_count += len(alerts) for alert in alerts: plugin_id = alert.get('pluginId') if plugin_id in blacklist: continue if alert.get('risk') == 'High': continue if alert.get('risk') == 'Informational': continue st += pg alerts = zap.alert.alerts(start=st, count=pg) print('Hosts: {}'.format(', '.join(zap.core.hosts))) print('Alerts: ') print(zap.core.alerts()) print('\n Passive Scan completed \n') print('Total number of alerts: ' + str(alert_count)) elif args.output: print('Passive Scanning target {}'.format(url)) st = 0 pg = 5000 alert_count = 0 alerts = zap.alert.alerts(baseurl=url, start=st, count=pg) blacklist = [1, 2] while len(alerts) > 0: print('Reading ' + str(pg) + ' alerts from ' + str(st)) alert_count += len(alerts) for alert in alerts: plugin_id = alert.get('pluginId') if plugin_id in blacklist: continue if alert.get('risk') == 'High': continue if alert.get('risk') == 'Informational': continue st += pg alerts = zap.alert.alerts(start=st, count=pg) print('Total number of alerts: ' + str(alert_count)) alerts = zap.core.alerts(baseurl=url) print(output(alerts)) else: print( 'Oops, Houston we have a problem here, please see Help options and retry this again' ) sys.exit() return
def zap_test(): zap = ZAPv2(apikey=apikey, proxies={'http': proxy}) zap.core.new_session(name="abc", overwrite=True) # Proxy a request to the target so that ZAP has something to deal with print('Accessing target {}'.format(target), file=sys.stderr) # zap.urlopen(target) zap.core.access_url(url=target) # Give the sites tree a chance to get updated time.sleep(2) print('Spidering target {}'.format(target), file=sys.stderr) # scanid = zap.spider.scan(target, maxchildren="10", recurse="false", subtreeonly="true") scanid = zap.spider.scan(target, maxchildren="20") # Give the Spider a chance to start time.sleep(2) while (int(zap.spider.status(scanid)) < 100): # Loop until the spider has finished print('Spider progress %: {}'.format(int(zap.spider.status(scanid))), file=sys.stderr) time.sleep(2) print('Spider completed', file=sys.stderr) zap.spider.stop_all_scans() # print('Enable all passive scanners -> ' + zap.pscan.enable_all_scanners(), file=sys.stderr) # while (int(zap.pscan.records_to_scan) > 0): # print('Records to passive scan : {}'.format(int(zap.pscan.records_to_scan)), file=sys.stderr) # time.sleep(2) # print('Passive Scan completed', file=sys.stderr) print('Active Scanning target {}'.format(target), file=sys.stderr) print('Enable all scanners -> ' + zap.ascan.enable_all_scanners(), file=sys.stderr) scanid = zap.ascan.scan(target) while (int(zap.ascan.status(scanid)) < 100): # Loop until the scanner has finished print('Scan progress %: {}'.format(zap.ascan.status(scanid)), file=sys.stderr) time.sleep(5) print('Active Scan completed', file=sys.stderr) # Report the results (for debug purposes) # print('Hosts: {}'.format(', '.join(zap.core.hosts))) # print('Alerts: ') # pprint(zap.core.alerts()) print("Total: %s" % len(zap.core.alerts()), file=sys.stderr) print("Stopping all scans...", file=sys.stderr) alerts = len(zap.core.alerts()) zap.ascan.stop_all_scans() return alerts
def zapSpiderInfo(host): # The URL of the application to be tested # Change to match the API key set in ZAP, or use None if the API key is disabled config = configparser.ConfigParser() config.read('config.ini') target = "https://" + host apiKey = None http_proxy = '' https_proxy = '' if 'ZAP' in config: vm_def = config['ZAP'] if config.has_option('ZAP', 'apiKey'): apiKey = vm_def['apiKey'] else: return "ZAP API Key not configured" if config.has_option('ZAP', 'http_proxy') and config.has_option( 'ZAP', 'https_proxy'): http_proxy = vm_def['http_proxy'] https_proxy = vm_def['https_proxy'] else: http_proxy = "" https_proxy = "" # By default ZAP API client will connect to port 8080 if not http_proxy and not https_proxy: zap = ZAPv2(apikey=apiKey) else: zap = ZAPv2(apikey=apiKey, proxies={ 'http': http_proxy, 'https': https_proxy }) print('Spidering target {}'.format(target)) # The scan returns a scan id to support concurrent scanning scanID = zap.spider.scan(target) while int(zap.spider.status(scanID)) < 100: # Poll the status until it completes print('Spider progress %: {}'.format(zap.spider.status(scanID))) time.sleep(1) print('Spider has completed!') # The URLs the spider has crawled print('\n'.join(map(str, zap.spider.results(scanID)))) return (zap.spider.results(scanID))
def start_zap_server(): subprocess.Popen( ['bin/zap_2.4.2/zap.sh', '-daemon', '-config api.disablekey=true'], stdout=open(os.devnull, 'w')) world.zap = ZAPv2(proxies={ 'http': 'http://127.0.0.1:8090', 'https': 'https://127.0.0.1:8090' }) sleep(5)
def __init__(self): self.host = None self.seed = None self.zap = ZAPv2() self.nm = None self.alerts = {} self.dir_tree = None self.subproc = None self.startup()
def __init__(self, zap_path='', port=8090, url='http://127.0.0.1', api_key='', logger=None): if os.path.isfile(zap_path): zap_path = os.path.dirname(zap_path) self.zap_path = zap_path self.port = port self.proxy_url = '{0}:{1}'.format(url, self.port) self.zap = ZAPv2(proxies={'http': self.proxy_url, 'https': self.proxy_url}, apikey=api_key) self.api_key = api_key self.logger = logger or console
def run(self): zap = ZAPv2(proxies={'http': self.ZAP_URL_HTTP}, apikey=self.API_KEY) zap.urlopen(self.__target) status = "Starting Analysys: target -> {}".format(self.__target) self.__update_database_status(status) if self.__debug: print(status) self.__spider(zap) self.__scanning(zap) self.__generate_report(zap)