def get_alert( gmp: Gmp, sender_email: str, recipient_email: str, alert_name: str = None, debug: bool = False, ): # create alert if necessary alert_object = gmp.get_alerts(filter_string=f'name={alert_name}') alert = alert_object.xpath('alert') if len(alert) == 0: print(f"creating new alert {alert_name}") gmp.create_alert( name=alert_name, event=gmp.types.AlertEvent.TASK_RUN_STATUS_CHANGED, event_data={"status": "Done"}, condition=gmp.types.AlertCondition.ALWAYS, method=gmp.types.AlertMethod.EMAIL, method_data={ """Task '$n': $e After the event $e, the following condition was met: $c This email escalation is configured to attach report format '$r'. Full details and other report formats are available on the scan engine. $t Note: This email was sent to you as a configured security scan escalation. Please contact your local system administrator if you think you should not have received it. """: "message", "2": "notice", sender_email: "from_address", "[OpenVAS-Manager] Task": "subject", "c402cc3e-b531-11e1-9163-406186ea4fc5": "notice_attach_format", recipient_email: "to_address", }, ) alert_object = gmp.get_alerts(filter_string='name={recipient_email}') alert = alert_object.xpath('alert') alert_id = alert[0].get('id', 'no id found') if debug: print(f"alert_id: {str(alert_id)}") return alert_id
def create_target(gmp: Gmp, name: str) -> str: try: res = gmp.create_target(name, hosts=[name]) target_id = res.xpath('@id')[0] except GvmError: res = gmp.get_targets(filter_string=f'name={name} hosts={name}') target_id = res.xpath('target/@id')[0] return target_id
def combine_reports(gmp: Gmp, reports: List[str], filter_term: str, filter_id: str) -> e.Element: """Combining the filtered ports, results and hosts of the given report ids into one new report. gmp: the GMP object reports (List): List of report_ids filter_term (str): the result filter string """ new_uuid = generate_uuid() combined_report = e.Element( 'report', { 'id': new_uuid, 'format_id': 'd5da9f67-8551-4e51-807b-b6a873d70e34', 'extension': 'xml', 'content_type': 'text/xml', }, ) report_elem = e.Element('report', {'id': new_uuid}) ports_elem = e.Element('ports', {'start': '1', 'max': '-1'}) results_elem = e.Element('results', {'start': '1', 'max': '-1'}) combined_report.append(report_elem) report_elem.append(ports_elem) report_elem.append(results_elem) for report in reports: try: if filter_id: current_report = gmp.get_report( report, filter_id=filter_id, details=True, ignore_pagination=True, ).find('report') else: current_report = gmp.get_report( report, filter=filter_term, details=True, ignore_pagination=True, ).find('report') except GvmError: print("Could not find the report [{}]".format(report)) for port in current_report.xpath('report/ports/port'): ports_elem.append(port) for result in current_report.xpath('report/results/result'): results_elem.append(result) for host in current_report.xpath('report/host'): report_elem.append(host) return combined_report
def parse_send_xml_tree(gmp: Gmp, xml_tree: Element) -> None: for schedule in xml_tree.xpath('schedule'): name = schedule.find('name').text comment = schedule.find('comment').text if comment is None: comment = '' ical = schedule.find('icalendar').text timezone = schedule.find('timezone').text gmp.create_schedule( name=name, comment=comment, timezone=timezone, icalendar=ical )
def get_scan_config(gmp: Gmp, config: int, debug: bool = False): # get all configs of the openvas instance # filter for all rows! res = gmp.get_scan_configs(filter_string="rows=-1") if config < 0 or config > 4: raise ValueError("Wrong config identifier. Choose between [0,4].") # match the config abbreviation to accepted config names config_list = [ 'Full and fast', 'Full and fast ultimate', 'Full and very deep', 'Full and very deep ultimate', 'System Discovery', ] template_abbreviation_mapper = { 0: config_list[0], 1: config_list[1], 2: config_list[2], 3: config_list[3], 4: config_list[4], } for conf in res.xpath('config'): cid = conf.xpath('@id')[0] name = conf.xpath('name/text()')[0] # get the config id of the desired template if template_abbreviation_mapper.get(config) == name: config_id = cid if debug: print(name + ": " + config_id) break return config_id
def print_result_tables(gmp: Gmp, reports_xml: e.Element) -> None: report_list = reports_xml.xpath('report') for report in report_list: report_id = report.xpath('report/@id')[0] name = report.xpath('name/text()')[0] res = gmp.get_report(report_id) print('\nReport: {0}'.format(report_id)) table_data = [['Hostname', 'IP', 'Bericht', 'high', 'medium', 'low']] for host in res.xpath('report/report/host'): hostname = host.xpath('detail/name[text()="hostname"]/../' 'value/text()') if len(hostname) > 0: hostname = str(hostname[0]) else: hostname = "" ip = host.xpath('ip/text()')[0] high = host.xpath('result_count/hole/page/text()')[0] medium = host.xpath('result_count/warning/page/text()')[0] low = host.xpath('result_count/info/page/text()')[0] table_data.append([hostname, ip, name, high, medium, low]) table = AsciiTable(table_data) print(table.table + '\n')
def get_reports_xml(gmp: Gmp, from_date: date, to_date: date) -> e.Element: """Getting the Reports in the defined time period""" report_filter = "rows=-1 created>{0} and created<{1}".format( from_date.isoformat(), to_date.isoformat()) return gmp.get_reports(filter=report_filter)
def check_login(self): if (self.hostname_input.text() == "" or self.username_input.text() == "" or self.password_input.text() == ""): QMessageBox.about(QMainWindow(), "Error", "Please enter a all Information") else: try: connection = SSHConnection(hostname=self.hostname_input.text()) with Gmp(connection=connection, transform=ObjectTransform()) as gmp: try: response = gmp.authenticate( username=self.username_input.text(), password=self.password_input.text(), ) print(response) self.signal.login_event.emit(gmp, self.window) except GvmResponseError: QMessageBox.about(QMainWindow(), "Error", "Wrong username or password.") except (gaierror, NoValidConnectionsError, GvmError) as ex: QMessageBox.about(QMainWindow(), "Error", str(ex))
def combine_reports(gmp: Gmp, args: Namespace) -> e.Element: new_uuid = generate_uuid() combined_report = e.Element( 'report', { 'id': new_uuid, 'format_id': 'd5da9f67-8551-4e51-807b-b6a873d70e34', 'extension': 'xml', 'content_type': 'text/xml', }, ) report_elem = e.Element('report', {'id': new_uuid}) ports_elem = e.Element('ports', {'start': '1', 'max': '-1'}) results_elem = e.Element('results', {'start': '1', 'max': '-1'}) combined_report.append(report_elem) report_elem.append(results_elem) if 'first_task' in args.script: arg_len = args.script[1:-1] else: arg_len = args.script[1:] for argument in arg_len: current_report = gmp.get_report(argument, details=True, ignore_pagination=True)[0] for port in current_report.xpath('report/ports/port'): ports_elem.append(port) for result in current_report.xpath('report/results/result'): results_elem.append(result) for host in current_report.xpath('report/host'): report_elem.append(host) return combined_report
def print_reports(gmp: Gmp, from_date: date, to_date: date) -> None: host_filter = (f'rows=-1 and modified>{from_date.isoformat()} ' f'and modified<{to_date.isoformat()}') hosts_xml = gmp.get_hosts(filter_string=host_filter) sum_high = 0 sum_medium = 0 sum_low = 0 table_data = [['Hostname', 'IP', 'Bericht', 'high', 'medium', 'low']] for host in hosts_xml.xpath('asset'): ip = host.xpath('name/text()')[0] hostnames = host.xpath( 'identifiers/identifier/name[text()="hostname"]/../value/text()') if len(hostnames) == 0: continue hostname = hostnames[0] results = gmp.get_results(details=False, filter=f'host={ip} and severity>0.0') low = int(results.xpath('count(//result/threat[text()="Low"])')) sum_low += low medium = int(results.xpath('count(//result/threat[text()="Medium"])')) sum_medium += medium high = int(results.xpath('count(//result/threat[text()="High"])')) sum_high += high best_os_cpe_report_id = host.xpath( 'host/detail/name[text()="best_os_cpe"]/../source/@id')[0] table_data.append( [hostname, ip, best_os_cpe_report_id, high, medium, low]) table = AsciiTable(table_data) print(f'{table.table}\n') print(f'Summary of results from {from_date.isoformat()} ' f'to {to_date.isoformat()}') print(f'High: {int(sum_high)}') print(f'Medium: {int(sum_medium)}') print(f'Low: {int(sum_low)}\n\n')
def get_task(task_id): with Gmp(connection, transform=transform) as gmp: gmp.authenticate(user, password) task = gmp.get_task(task_id) task_name = get_name(task)[1] #get_target_name(task) report_id = get_id(task, "report")[0] return Task(task_id, report_id, task_name)
def create_and_start_task(gmp: Gmp, name: str, nvt_oid: str, config_id: str, target_id: str) -> None: # Standard Scanner OpenVAS Default scanner_id = '08b69003-5fc2-4037-a479-93b440211c73' date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Create task task_name = f'{name}_{nvt_oid}_{date_time}' res = gmp.create_task( name=task_name, config_id=config_id, target_id=target_id, scanner_id=scanner_id, ) task_id = res.xpath('@id')[0] # Start the task gmp.start_task(task_id=task_id) print(f'\nTask {task_id} started')
def get_target_name(inputxml): xmlstr = ElementTree.tostring(inputxml, encoding='utf8', method='xml') regexid = re.findall(r'\<target id="[0-9a-z-]*', xmlstr.decode('utf8')) target_id = regexid[0][:12] with Gmp(connection, transform=transform) as gmp: gmp.authenticate(user, password) result = gmp.get_target(target_id) pretty_print(result) return regexid[0][:12]
def get_reports_xml(gmp: Gmp, from_date: date, to_date: date) -> Element: """Getting the Reports in the defined time period""" report_filter = ( f'rows=-1 created>{from_date.isoformat()} and ' f'created<{to_date.isoformat()}' ) return gmp.get_reports(filter_string=report_filter)
def addTargetToSca(target, scantype, scanscanner): ''' This will add a target to the list and start the sca of the targets ''' with Gmp(connection) as gmp: # Login gmp.authenticate('admin', 'admin') theTargetName = str("target_{0}".format(target.replace('.', '-'))) #Create target gmp.create_target(theTargetName, hosts=[target], comment="Auto generated") #Get the targets ID targetID = "" targets = gmp.get_targets(filter=theTargetName) #pretty_print(targets) root = ET.fromstring(targets) for target in root: if target.tag == 'target': targetID = target.attrib.get('id') #GEt the configs to use configID = "" configs = gmp.get_configs(filter=scantype) #pretty_print(configs) rootConfig = ET.fromstring(configs) for configs in rootConfig: if configs.tag == 'config': for config in configs: if config.text == scantype: configID = configs.attrib.get('id') #Get the scanner id scannerID = "" scanners = gmp.get_scanners(filter=scanscanner) #pretty_print(configs) rootScanner = ET.fromstring(scanners) for scanner in rootScanner: if scanner.tag == 'scanner': for scan in scanner: if scan.text == scanscanner: scannerID = scanner.attrib.get('id') back = gmp.create_task(theTargetName, config_id=configID, target_id=targetID, scanner_id=scannerID) taskResponse = ET.fromstring(back) task_id = taskResponse.attrib.get('id') #Start the task gmp.start_task(task_id)
def get_report_formats(): with Gmp(connection, transform=transform) as gmp: gmp.authenticate(user, password) xml = gmp.get_report_formats() ids = get_id(xml, "report_format") names = get_report_name(xml) map = {} for i in (0, 4, 6): map[ids[i]] = names[i] return map
def is_running(taskid): connection = UnixSocketConnection() transform = EtreeTransform() with Gmp(connection, transform=transform) as gmp: # Login -> change to default admin password gmp.authenticate('scanner', 'scanner') taskxml = gmp.get_task(taskid) if get_status(taskxml) == 'Running': return True return False
def send_report(gmp: Gmp, args: Namespace, combined_report: e.Element) -> str: if 'first_task' in args.script: main_report = gmp.get_report(args.script[1])[0] task_id = main_report.xpath('//task/@id')[0] else: the_time = time.strftime("%Y/%m/%d-%H:%M:%S") task_id = '' task_name = f"Combined_Report_{the_time}" res = gmp.create_container_task(name=task_name, comment="Created with gvm-tools.") task_id = res.xpath('//@id')[0] combined_report = e.tostring(combined_report) res = gmp.import_report(combined_report, task_id=task_id, in_assets=True) return res.xpath('//@id')[0]
def exportReports(): ''' This will add a target to the list and start the sca of the targets ''' with Gmp(connection) as gmp: # Login gmp.authenticate(config['DEFAULT']['username'], config['DEFAULT']['password']) #Get the CSV report type reportFormatID = "" report_format = gmp.get_report_formats() report_root = ET.fromstring(report_format) for report in report_root: report.tag == "report_format" for report_format in report: if report_format.text == 'CSV result list.': reportFormatID = report.attrib.get('id') #reportFromatData = gmp.get_report_format(reportFormatID) #pretty_print(reportFromatData) getReports = [] allreports = gmp.get_reports() allreports_root = ET.fromstring(allreports) for report in allreports_root: if report.tag == 'report': for onereport in report: if onereport.tag == 'report': pretty_print(onereport) print(report.attrib) getReports.append(report.attrib.get('id')) #Get out the reports and get them as csv files to use for reportID in getReports: print("################{0}".format(reportID)) reportscv = gmp.get_report(reportID, report_format_id=reportFormatID, filter="apply_overrides=0 min_qod=70", ignore_pagination=True, details=True) #pretty_print(reportscv) obj = untangle.parse(reportscv) resultID = obj.get_reports_response.report['id'] base64CVSData = obj.get_reports_response.report.cdata data = str(base64.b64decode(base64CVSData), "utf-8") #print(data) #Write the result to file #Check if we have already process the result if the skip if haveThisBeanDone(resultID): writeResultToFile(resultID, data)
def create_default_user(): with Gmp(connection, transform=transform) as gmp: # Login -> change to default admin password gmp.authenticate('admin', '444c6ee8-f3f9-4bd8-873a-bbfdf37b8221') #check if scanner user already exists if any("<name>scanner</name>" in s for s in get_name(gmp.get_users())): print("no new user created") else: #user creation user = gmp.create_user( 'scanner', password='******', role_ids=['7a8cb5b4-b74d-11e2-8187-406186ea4fc5'])
def send_report(gmp: Gmp, combined_report: e.Element, period_start: date, period_end: date) -> str: """Creating a container task and sending the combined report to the GSM gmp: the GMP object combined_report: the combined report xml object period_start: the start date period_end: the end date """ task_name = f'Consolidated Report [{period_start} - {period_end}]' res = gmp.create_container_task(name=task_name, comment='Created with gvm-tools.') task_id = res.xpath('//@id')[0] combined_report = e.tostring(combined_report) res = gmp.import_report(combined_report, task_id=task_id, in_assets=True) return res.xpath('//@id')[0]
def get_newprogress(taskid): connection = UnixSocketConnection() transform = EtreeTransform() with Gmp(connection, transform=transform) as gmp: # Login -> change to default admin password gmp.authenticate('scanner', 'scanner') taskxml = gmp.get_task(taskid) if is_requested(taskid): return 0 if is_running(taskid): return int(get_progress(taskxml))
def download_report(report_id, report_format_id): formats = get_report_formats() try: os.system("mkdir reportdownload") except: print("directory exists") with Gmp(connection, transform=transform) as gmp: # Login -> change to default admin password gmp.authenticate(user, password) base64 = get_data( gmp.get_report(report_id=report_id, report_format_id=report_format_id, details=True, filter="apply_overrides=0 levels=hml")) f = open("reportdownload/" + report_id + '.csv', 'wb') f.write(b64decode(base64)) f.close()
def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=unused-argument response_xml = gmp.get_tasks() tasks_xml = response_xml.xpath('task') heading = ['ID', 'Name', 'Severity'] rows = [] for task in tasks_xml: name = ''.join(task.xpath('name/text()')) task_id = task.get('id') severity = ''.join(task.xpath('last_report/report/severity/text()')) rows.append([task_id, name, severity]) print(Table(heading=heading, rows=rows))
def get_last_reports_from_tasks(gmp: Gmp, task_filter: str) -> List[str]: """Get the last reports from the tasks in the given time period gmp: the GMP object task_filter: task filter string """ print('Filtering the task with the filter term [{}]'.format(task_filter)) tasks_xml = gmp.get_tasks(filter=task_filter) reports = [] for report in tasks_xml.xpath('task/last_report/report/@id'): reports.append(str(report)) # remove duplicates ... just in case reports = list(dict.fromkeys(reports)) return reports
def get_response(self, request, data, show_graphiql=False) -> Tuple[str, int]: try: connection = UnixSocketConnection( path=self.settings['GMP_SOCKET_PATH']) with Gmp(connection=connection, transform=self.transform) as gmp: request.gmp = gmp if request.session.get('username'): username = request.session['username'] password = request.session['password'] try: gmp.authenticate(username, password) except GvmResponseError as e: result = self.get_error_result(request, e, show_graphiql) return result, 403 return super().get_response(request, data, show_graphiql) except GvmClientError as e: # not sure if the session should get flushed request.session.flush() result = self.get_error_result(request, e, pretty=show_graphiql) return result, 400 except (ConnectionError, GvmError) as e: result = self.get_error_result(request, e, pretty=show_graphiql) return result, 500 except AuthenticationRequired as e: # remove session information request.session.flush() result = self.get_error_result(request, e, pretty=show_graphiql) return result, e.httpStatusCode except SeleneError as e: result = self.get_error_result(request, e, pretty=show_graphiql) return result, e.httpStatusCode
def main(gmp: Gmp, args: Namespace) -> None: # check if report id and PDF filename are provided to the script # argv[0] contains the script name check_args(args) report_id = args.argv[1] if len(args.argv) == 3: pdf_filename = args.argv[2] else: pdf_filename = args.argv[1] + ".pdf" pdf_report_format_id = "c402cc3e-b531-11e1-9163-406186ea4fc5" response = gmp.get_report(report_id=report_id, report_format_id=pdf_report_format_id) report_element = response.find("report") # get the full content of the report element content = report_element.find("report_format").tail if not content: print( 'Requested report is empty. Either the report does not contain any ' ' results or the necessary tools for creating the report are ' 'not installed.', file=sys.stderr, ) sys.exit(1) # convert content to 8-bit ASCII bytes binary_base64_encoded_pdf = content.encode('ascii') # decode base64 binary_pdf = b64decode(binary_base64_encoded_pdf) # write to file and support ~ in filename path pdf_path = Path(pdf_filename).expanduser() pdf_path.write_bytes(binary_pdf) print('Done. PDF created: ' + str(pdf_path))
def check_args(gmp: Gmp, args: Namespace) -> None: len_args = len(args.script) - 1 if len_args != 1: message = """ This script pulls schedule data from an xml document and feeds it to \ a desired GSM One parameter after the script name is required. 1. <xml_doc> -- .xml file containing schedules Example: $ gvm-script --gmp-username name --gmp-password pass \ ssh --hostname <gsm> scripts/send-schedules.gmp.py example_file.xml """ print(message) sys.exit() major, minor = gmp.get_protocol_version() if major < 21 and minor < 5: print(f"This script requires GMP version {major}.{minor}") sys.exit()
def scan(target_name, ipList, config_id): thread_list = [] connection = UnixSocketConnection() transform = EtreeTransform() with Gmp(connection, transform=transform) as gmp: gmp.authenticate('scanner', 'scanner') # #target creation custome_port_table(ipList) #target creation with custome port list with open("ports/ports.txt", "r") as f: inhoud2 = f.read() #Creating a new portlist portListName = target_name.replace( ' ', '-').lower() + "_" + datetime.now().strftime("%d/%m/%Y_%H:%M:%S") superCooleLijst = gmp.create_port_list(portListName, inhoud2) pretty_print(superCooleLijst) superCooleLijstID = get_id(superCooleLijst) target = gmp.create_target(target_name, hosts=ipList, port_list_id=superCooleLijstID) target_id = get_id(target) # task creation # arguments: target_name, config_id, target_id, scanner_id task = gmp.create_task(target_name, config_id, target_id, '08b69003-5fc2-4037-a479-93b440211c73') task_id = get_id(task) #task start gmp.start_task(task_id) return task_id #for cli version (old) print("task started succesfully!")
def _loadconfig(): conf_file = APP_BASE_DIR + "/openvas.json" if not exists(conf_file): print("Error: config file '{}' not found".format(conf_file)) json_data = open(conf_file) engine.scanner = load(json_data) try: connection = TLSConnection( hostname=engine.scanner["options"]["gmp_host"]["value"], port=engine.scanner["options"]["gmp_port"]["value"]) with Gmp(connection) as this.gmp: this.gmp.authenticate( engine.scanner["options"]["gmp_username"]["value"], engine.scanner["options"]["gmp_password"]["value"]) except Exception: engine.scanner["status"] = "ERROR" print("Error: authentication failure Openvas instance") return False engine.scanner["status"] = "READY" engine.scanner["credentials"] = () engine.scanner["scan_config"] = get_scan_config()