def parse_period(period: List[str]) -> Tuple[date, date]: """Parsing and validating the given time period period (List): A list with two entries containing dates in the format yyyy/mm/dd Returns two date-objects containing the passed dates """ try: s_year, s_month, s_day = map(int, period[0].split('/')) except ValueError as e: error_and_exit( 'Start date [{}] is not a correct date format:\n{}'.format( period[0], e.args[0])) try: e_year, e_month, e_day = map(int, period[1].split('/')) except ValueError as e: error_and_exit( 'End date [{}] is not a correct date format:\n{}'.format( period[1], e.args[0])) try: period_start = date(s_year, s_month, s_day) except ValueError as e: error_and_exit('Start date: {}'.format(e.args[0])) try: period_end = date(e_year, e_month, e_day) except ValueError as e: error_and_exit('End date: {}'.format(e.args[0])) if period_end < period_start: error_and_exit('The start date seems to after the end date.') return period_start, period_end
def parse(self) -> Report: """Loads an JSON file and extracts host information: Args: host_dump: the dumped json results, containing a hostname, host_ip, host_ip_range, host_operating_system, host_os_cpe, arrays of found_app, app_version, app_cpe """ report = Report(gmp=gmp) date_time = datetime.datetime.now() count = len(self.json_dump) progressed = 0 print(f'Found {str(count)} hosts:') progressbar = ProgressBar(length=100, count=count, pl_name="Hosts") for entry in self.json_dump: if entry[3] is None: error_and_exit("The JSON format is not correct.") name = entry[0] # print(f"Creating Results for the host {name}") ips = entry[1] if isinstance(ips, str): ips = [ips] os = entry[3] os_cpe = convert_cpe23_to_cpe22(entry[4])[0] cpes = [] # entry[7] should be the CPEs ... if entry[7] is not None: if isinstance(entry[7], str): cpes.extend(self._get_cpes(entry[7])) else: for cpe in entry[7]: if cpe: cpes.extend(self._get_cpes(cpe)) vulns = self._get_cves(cpes) if vulns: for ip in ips: report.add_results( ip=ip, hostname=name, cpes=vulns, cpeo=os_cpe, os=os, date_time=date_time, ) progressed += 1 progressbar.update(progressed=progressed) progressbar.done() return report
def __init__(self, gmp: Gmp, filename: Path, recreate: bool): self.gmp = gmp if filename.exists(): if recreate: filename.unlink() else: error_and_exit(f'The file "{filename}" already exists. ' 'If you want to delete the old list and ' 'recreate the list run with "++create-list ' f'recreate +f {filename}"') self.file = open(filename, 'w')
def load_host_list(host_file): try: with open(host_file) as f: content = f.readlines() host_list = [x.strip() for x in content] host_list = list(filter(None, host_list)) except IOError as e: error_and_exit("Failed to read host_file: {} (exit)".format(str(e))) if len(host_list) == 0: error_and_exit("Host file is empty (exit)") return host_list
def interactive_options(gmp, task, keywords): options_dict = {} options_dict['config'] = gmp.get_configs() options_dict['scanner'] = gmp.get_scanners() options_dict['target'] = gmp.get_targets() for option in options_dict: object_dict, object_list = {}, [] object_id = task.xpath('{}/@id'.format(option))[0] object_xml = options_dict[option] for i in object_xml.xpath('{}'.format(option)): object_dict[i.find('name').text] = i.xpath('@id')[0] object_list.append(i.find('name').text) if object_id in object_dict.values(): keywords['{}_id'.format(option)] = object_id elif object_id not in object_dict.values() and len(object_dict) != 0: response = yes_or_no( "\nRequired Field: failed to detect {}_id: {}... " "\nWould you like to select from available options, or exit " "the script?".format( option, task.xpath('{}/@id'.format(option))[0] ) ) if response is True: counter = 1 print("{} options:".format(option.capitalize())) for j in object_list: print(" {} - {}".format(counter, j)) counter += 1 answer = numerical_option( "\nPlease enter the number of your choice.", len(object_list), ) keywords['{}_id'.format(option)] = object_dict[ object_list[answer - 1] ] else: print("\nTerminating...") quit() else: error_and_exit( "Failed to detect {}_id" "\nThis field is required therefore the script is unable to " "continue.\n".format(option) )
def interactive_options(gmp, task, keywords): options_dict = {} options_dict['config'] = gmp.get_scan_configs() options_dict['scanner'] = gmp.get_scanners() options_dict['target'] = gmp.get_targets() for option_key, option_value in options_dict.items(): object_dict, object_list = {}, [] object_id = task.find(option_key).get('id') object_xml = option_value for i in object_xml.findall(option_key): object_dict[i.find('name').text] = i.xpath('@id')[0] object_list.append(i.find('name').text) if object_id in object_dict.values(): keywords[f'{option_key}_id'] = object_id elif object_id not in object_dict.values() and len(object_dict) != 0: response = yes_or_no( f"\nRequired Field: failed to detect {option_key}_id: " f"{task.xpath(f'{option_key}/@id')[0]}... " "\nWould you like to select from available options, or exit " "the script?") if response is True: counter = 1 print(f"{option_key.capitalize()} options:") for j in object_list: print(f" {counter} - {j}") counter += 1 answer = numerical_option( "\nPlease enter the number of your choice.", len(object_list), ) keywords[f'{option_key}_id'] = object_dict[object_list[answer - 1]] else: print("\nTerminating...") sys.exit() else: error_and_exit( f"Failed to detect {option_key}_id\nThis field is required " "therefore the script is unable to continue.\n")
def parse_send_xml_tree(gmp, xml_tree): task_xml_elements = xml_tree.xpath('task') print(task_xml_elements) if not task_xml_elements: error_and_exit("No tasks found.") tasks = [] for task in task_xml_elements: keywords = {'name': task.find('name').text} if task.find('comment').text is not None: keywords['comment'] = task.find('comment').text interactive_options(gmp, task, keywords) if task.find('schedule_periods') is not None: keywords['schedule_periods'] = int( task.find('schedule_periods').text) if task.find('observers').text: keywords['observers'] = task.find('observers').text if task.xpath('schedule/@id')[0]: keywords['schedule_id'] = task.xpath('schedule/@id')[0] if task.xpath('preferences/preference'): preferences, scanner_name_list, value_list = {}, [], [] for preference in task.xpath('preferences/preference'): scanner_name_list.append(preference.find('scanner_name').text) if preference.find('value').text is not None: value_list.append(preference.find('value').text) else: value_list.append('') preferences['scanner_name'] = scanner_name_list preferences['value'] = value_list keywords['preferences'] = preferences new_task = gmp.create_task(**keywords) tasks.append(new_task.xpath('//@id')[0]) return tasks
def load_host_file(filename): host_list = list() try: f = open(filename) for line in f: host = line.split(",")[0] host = host.strip() if len(host) == 0: continue host_list.append(host) except IOError as e: error_and_exit("Failed to read host_file: {} (exit)".format(str(e))) if len(host_list) == 0: error_and_exit("Host file is empty (exit)") hosts_string = ', '.join(map(str, host_list)) return hosts_string
def __init__(self, gmp: Gmp, json_file: Path, cpe_list: Path) -> None: try: self.cpe_list = open(cpe_list, 'r') self.reader = csv.reader(self.cpe_list) except FileNotFoundError: error_and_exit( f'There is no file "{cpe_list}". ' 'Maybe you need to create a list first. Run with ' f'argument "++create-list +f {cpe_list}", to create ' 'a new list, or pass the correct location of an existing list.' ) self.gmp = gmp try: self.json_fp = open(json_file) self.json_dump = json.load(self.json_fp)[0]['results'] except FileNotFoundError: error_and_exit(f'There is no file "{json_file}".') except json.JSONDecodeError as e: error_and_exit(f'The JSON seems to be invalid: {e.args[0]}')
def test_error_and_exit(self): with self.assertRaises(SystemExit): error_and_exit('foo')