|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +from argparse import ArgumentError |
| 5 | +import json |
| 6 | +import os |
| 7 | +from getpass import getpass |
| 8 | +from sys import argv |
| 9 | +import textwrap |
| 10 | +import re |
| 11 | + |
| 12 | +def _split_args(argv: list[str], delimiters: list[str]) -> tuple[list, list]: |
| 13 | + parseable_args = [] |
| 14 | + remaining_args = [] |
| 15 | + for x, arg in enumerate(argv): |
| 16 | + if arg not in delimiters: |
| 17 | + parseable_args.append(arg) |
| 18 | + else: |
| 19 | + remaining_args = argv[x:] |
| 20 | + break |
| 21 | + return parseable_args, remaining_args |
| 22 | + |
| 23 | +def parse_args(argv: list[str]) -> dict: |
| 24 | + commands = { |
| 25 | + 'setpasswords': None, |
| 26 | + 'configureserver': None, |
| 27 | + 'setscanpolicy': None |
| 28 | + } |
| 29 | + |
| 30 | + args = {} |
| 31 | + parser = argparse.ArgumentParser( |
| 32 | + description="Update a NessusAPI JSON configuration's core settings.", |
| 33 | + usage="USAGE: ./nessus-policy-update.py [-vh] CONFIG {-o OUTFILE | --overwrite} COMMAND ...", |
| 34 | + epilog=textwrap.dedent('''\ |
| 35 | + Commands: |
| 36 | + setpasswords: Set credentials for a scan policy |
| 37 | + configureserver: Set server connection settings |
| 38 | + setscanpolicy: Set path to the Nessus scan policy XML |
| 39 | + ''') |
| 40 | + ) |
| 41 | + parser.add_argument("config", required=True, metavar="CONFIG", help="NessusAPI Policy JSON config") |
| 42 | + output_group = parser.add_mutually_exclusive_group(required=True) |
| 43 | + output_group.add_argument("--overwrite", action="store_true", help="Overwrite the existing config file.") |
| 44 | + output_group.add_argument("-o", "--outfile", metavar="OUTFILE", help="Path to write the new config to") |
| 45 | + |
| 46 | + setpasswords_parser = argparse.ArgumentParser(description="Replace all passwords in a NessusAPI JSON configuration with real system passwords") |
| 47 | + setpasswords_parser.add_argument("--password_placeholder", required=False, metavar="STRING", default='*', help="Scan config for a custom password placeholder string.") |
| 48 | + |
| 49 | + configureserver_parser = argparse.ArgumentParser(description="Configure Nessus connection in a NessusAPI JSON configuration with real system passwords") |
| 50 | + configureserver_parser.add_argument('-H', '--host', metavar="HOST", help='IP or hostname to connect to Nessus') |
| 51 | + configureserver_parser.add_argument('-P', '--port', metavar="PORT", default=8834, help='Port to connect to Nessus (default=8834)') |
| 52 | + auth_group = configureserver_parser.add_mutually_exclusive_group() |
| 53 | + auth_group.add_argument('-p', '--usepassword', required=True, action='store_true', help='Prompt for user/password to authenticate to Nessus') |
| 54 | + auth_group.add_argument('-k', '--usekeys', required=True, action='store_true', help='Prompt for authentication keys to authenticate to Nessus') |
| 55 | + |
| 56 | + setscanpolicy_parser = argparse.ArgumentParser(description="Update path to the scan policy to use") |
| 57 | + setscanpolicy_parser.add_argument('policy', metavar="POLICY", required=True, help='Path to the scan policy XML') |
| 58 | + |
| 59 | + # Parse global args |
| 60 | + remaining_args = argv |
| 61 | + while len(remaining_args) > 0: |
| 62 | + parseable_args, remaining_args = _split_args(argv, commands) |
| 63 | + if len(parseable_args) == 0: |
| 64 | + raise ArgumentError(f'Unknown argument: "{remaining_args[0]}"') |
| 65 | + if parseable_args[0] not in commands: |
| 66 | + args += vars(parser.parse_args(parseable_args)) |
| 67 | + else: |
| 68 | + command = parseable_args.pop(0) |
| 69 | + if args.get(command): |
| 70 | + raise ArgumentError(f'Duplicate command found: "{command}"') |
| 71 | + args[command] = vars(parser.parse_args(parseable_args)) |
| 72 | + |
| 73 | + return args |
| 74 | + |
| 75 | +def replace_passwords(dictionary: dict, path: list[str], placeholder_string: str = '*') -> None: |
| 76 | + current_path = path |
| 77 | + for key, value in dictionary.items(): |
| 78 | + current_path = path + [key] |
| 79 | + if 'password' in key.lower(): |
| 80 | + if isinstance(value, str) and (placeholder_string == '*' or value == placeholder_string): |
| 81 | + passwd, confirm_passwd = '', '' |
| 82 | + while not passwd or passwd != confirm_passwd: |
| 83 | + print("Update Password Configuration:") |
| 84 | + # print configuration using password (omit nested items) |
| 85 | + print('.'.join(current_path), '= {') |
| 86 | + for k,v in dictionary: |
| 87 | + if isinstance(k, str) and isinstance(v, str): |
| 88 | + print(f" {k}: {v}") |
| 89 | + print('}') |
| 90 | + # actually change the password |
| 91 | + if (user := dictionary.get('username')): |
| 92 | + passwd = getpass(f'New Password for "{user}": ') |
| 93 | + else: |
| 94 | + passwd = getpass(f'New Password": ') |
| 95 | + passwd = passwd.strip() |
| 96 | + confirm_passwd = getpass(f'Confirm Password": ') |
| 97 | + print('\n') # clear the screen a bit |
| 98 | + dictionary[key] = passwd |
| 99 | + elif isinstance(value, dict): |
| 100 | + replace_passwords(value, current_path, placeholder_string=placeholder_string) |
| 101 | + elif isinstance(value, list): |
| 102 | + for x, nested_list in enumerate(value): |
| 103 | + replace_passwords(value, current_path + [f'[{x}]'], placeholder_string=placeholder_string) |
| 104 | + |
| 105 | +def is_username_valid(username: str) -> bool: |
| 106 | + if (3 <= len(username) <= 20) and re.match(r'^[a-zA-Z][a-zA-Z0-9-_]*[a-zA-Z]'): |
| 107 | + return True |
| 108 | + return False |
| 109 | + |
| 110 | +if __name__ == '__main__': |
| 111 | + args = parse_args(argv) |
| 112 | + |
| 113 | + if not os.path.exists(args['config']): |
| 114 | + raise OSError("Config file does not exist") |
| 115 | + |
| 116 | + config = json.loads(open(args['config'], 'rb').read()) |
| 117 | + |
| 118 | + if command := args.get('setpasswords'): |
| 119 | + placeholder_string = command.get('password_placeholder', '*') |
| 120 | + replace_passwords(config['policies']['credentials'], [], placeholder_string='*') |
| 121 | + |
| 122 | + elif command := args.get('configureserver'): |
| 123 | + if command.get('usepassword'): |
| 124 | + username = '' |
| 125 | + while not is_username_valid(username): |
| 126 | + username = input('Server Username: ') |
| 127 | + passwd, _passwd = None, None |
| 128 | + while not passwd: |
| 129 | + passwd = getpass("Server Password: ") |
| 130 | + _passwd = getpass("Server Password [Confirm]: ") |
| 131 | + if passwd != _passwd: |
| 132 | + passwd = None |
| 133 | + print("Error: Passwords do not match!") |
| 134 | + |
| 135 | + config['server']['credentials'] = { |
| 136 | + "type": "password", |
| 137 | + "username": username, |
| 138 | + "password": passwd |
| 139 | + } |
| 140 | + elif command.get('usekeys'): |
| 141 | + raise NotImplementedError() |
| 142 | + |
| 143 | + elif command := args.get('setscanpolicy'): |
| 144 | + if not os.path.exists(command['policy']): |
| 145 | + print(f'Cannot find policy file: '{command['policy']}'') |
| 146 | + confirm = input("Update anyways? [Y/n]: ") |
| 147 | + if confirm.lower() in ['y', 'yes']: |
| 148 | + config['policies']['file']= command['policy'] |
| 149 | + else: |
| 150 | + print('Policy not updated.') |
| 151 | + |
| 152 | + outfile_name = args.config if args.get('overwrite') else args['outfile'] |
| 153 | + with open(outfile_name, 'w', encoding='ascii') as outfile: |
| 154 | + outfile.write(json.dumps(config, indent=4)) |
| 155 | + |
| 156 | + print('Config updated successfully.') |
0 commit comments