|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +""" cli to connect to Stormshield Network Security appliances""" |
| 4 | + |
| 5 | +import sys |
| 6 | +import os |
| 7 | +import re |
| 8 | +import logging |
| 9 | +import readline |
| 10 | +import getpass |
| 11 | +import atexit |
| 12 | +import xml.dom.minidom |
| 13 | +import begin |
| 14 | +from pygments import highlight |
| 15 | +from pygments.lexers import XmlLexer |
| 16 | +from pygments.formatters import TerminalFormatter |
| 17 | +from colorlog import ColoredFormatter |
| 18 | + |
| 19 | +from stormshield.sns.sslclient import SSLClient, ServerError |
| 20 | + |
| 21 | +FORMATTER = ColoredFormatter( |
| 22 | + "%(log_color)s%(levelname)-8s%(reset)s %(message)s", |
| 23 | + datefmt=None, |
| 24 | + reset=True, |
| 25 | + log_colors={ |
| 26 | + 'DEBUG': 'green', |
| 27 | + 'INFO': 'cyan', |
| 28 | + 'WARNING': 'yellow', |
| 29 | + 'ERROR': 'red', |
| 30 | + 'CRITICAL': 'red,bg_white' |
| 31 | + }, |
| 32 | + secondary_log_colors={}, |
| 33 | + style='%' |
| 34 | +) |
| 35 | + |
| 36 | +EMPTY_RE = re.compile(r'^\s*$') |
| 37 | + |
| 38 | +def make_completer(): |
| 39 | + """ load completer for readline """ |
| 40 | + vocabulary = [] |
| 41 | + with open(SSLClient.get_completer(), "r") as completelist: |
| 42 | + for line in completelist: |
| 43 | + vocabulary.append(line.replace('.', ' ').strip('\n')) |
| 44 | + |
| 45 | + def custom_complete(text, state): |
| 46 | + results = [x for x in vocabulary if x.startswith(text)] + [None] |
| 47 | + return results[state] |
| 48 | + return custom_complete |
| 49 | + |
| 50 | +@begin.start(auto_convert=True, short_args=False, lexical_order=True) |
| 51 | +@begin.logging |
| 52 | +def main(host: 'Remote UTM' = None, |
| 53 | + ip: 'Remote UTM ip' = None, |
| 54 | + usercert: 'User certificate file' = None, |
| 55 | + cabundle: 'CA bundle file' = None, |
| 56 | + password: 'Password' = None, |
| 57 | + port: 'Remote port' = 443, |
| 58 | + user: 'User name' = 'admin', |
| 59 | + sslverifypeer: 'Strict SSL CA check' = True, |
| 60 | + sslverifyhost: 'Strict SSL host name check' = True, |
| 61 | + credentials: 'Privilege list' = None, |
| 62 | + script: 'Command script' = None, |
| 63 | + outputformat: 'Output format (ini|xml)' = 'ini'): |
| 64 | + |
| 65 | + for handler in logging.getLogger().handlers: |
| 66 | + if handler.__class__ == logging.StreamHandler: |
| 67 | + handler.setFormatter(FORMATTER) |
| 68 | + |
| 69 | + if script is not None: |
| 70 | + try: |
| 71 | + script = open(script, 'r') |
| 72 | + except Exception as exception: |
| 73 | + logging.error("Can't open script file - %s", str(exception)) |
| 74 | + sys.exit(1) |
| 75 | + |
| 76 | + if outputformat not in ['ini', 'xml']: |
| 77 | + logging.error("Unknown output format") |
| 78 | + sys.exit(1) |
| 79 | + |
| 80 | + if host is None: |
| 81 | + logging.error("No host provided") |
| 82 | + sys.exit(1) |
| 83 | + |
| 84 | + if password is None and usercert is None: |
| 85 | + password = getpass.getpass() |
| 86 | + |
| 87 | + try: |
| 88 | + client = SSLClient( |
| 89 | + host=host, ip=ip, port=port, user=user, password=password, |
| 90 | + sslverifypeer=sslverifypeer, sslverifyhost=sslverifyhost, |
| 91 | + credentials=credentials, |
| 92 | + usercert=usercert, cabundle=cabundle, autoconnect=False) |
| 93 | + except Exception as exception: |
| 94 | + logging.error(str(exception)) |
| 95 | + sys.exit(1) |
| 96 | + |
| 97 | + try: |
| 98 | + client.connect() |
| 99 | + except Exception as exception: |
| 100 | + search = re.search(r'doesn\'t match \'(.*)\'', str(exception)) |
| 101 | + if search: |
| 102 | + logging.error(("Appliance name can't be verified, to force connection " |
| 103 | + "use \"--host %s --ip %s\" or \"--no-sslverifyhost\" " |
| 104 | + "options"), search.group(1), host) |
| 105 | + else: |
| 106 | + logging.error(str(exception)) |
| 107 | + sys.exit(1) |
| 108 | + |
| 109 | + # disconnect gracefuly at exit |
| 110 | + atexit.register(client.disconnect) |
| 111 | + |
| 112 | + if script is not None: |
| 113 | + for cmd in script.readlines(): |
| 114 | + cmd = cmd.strip('\r\n') |
| 115 | + print(cmd) |
| 116 | + if cmd.startswith('#'): |
| 117 | + continue |
| 118 | + if EMPTY_RE.match(cmd): |
| 119 | + continue |
| 120 | + try: |
| 121 | + response = client.send_command(cmd) |
| 122 | + except Exception as exception: |
| 123 | + logging.error(str(exception)) |
| 124 | + sys.exit(1) |
| 125 | + if outputformat == 'xml': |
| 126 | + print(highlight(xml.dom.minidom.parseString(response.xml).toprettyxml(), |
| 127 | + XmlLexer(), TerminalFormatter())) |
| 128 | + else: |
| 129 | + print(response.output) |
| 130 | + sys.exit(0) |
| 131 | + |
| 132 | + # Start cli |
| 133 | + |
| 134 | + # load history |
| 135 | + histfile = os.path.join(os.path.expanduser("~"), ".sslclient_history") |
| 136 | + try: |
| 137 | + readline.read_history_file(histfile) |
| 138 | + readline.set_history_length(1000) |
| 139 | + except FileNotFoundError: |
| 140 | + pass |
| 141 | + |
| 142 | + def save_history(histfile): |
| 143 | + try: |
| 144 | + readline.write_history_file(histfile) |
| 145 | + except: |
| 146 | + logging.warning("Can't write history") |
| 147 | + |
| 148 | + atexit.register(save_history, histfile) |
| 149 | + |
| 150 | + # load auto-complete |
| 151 | + readline.parse_and_bind('tab: complete') |
| 152 | + readline.set_completer_delims('') |
| 153 | + readline.set_completer(make_completer()) |
| 154 | + |
| 155 | + while True: |
| 156 | + try: |
| 157 | + cmd = input("> ") |
| 158 | + except EOFError: |
| 159 | + break |
| 160 | + |
| 161 | + # skip comments |
| 162 | + if cmd.startswith('#'): |
| 163 | + continue |
| 164 | + |
| 165 | + try: |
| 166 | + response = client.send_command(cmd) |
| 167 | + except ServerError as exception: |
| 168 | + # do not log error on QUIT |
| 169 | + if "quit".startswith(cmd.lower()) \ |
| 170 | + and str(exception) == "Server disconnected": |
| 171 | + sys.exit(0) |
| 172 | + logging.error(str(exception)) |
| 173 | + sys.exit(1) |
| 174 | + except Exception as exception: |
| 175 | + logging.error(str(exception)) |
| 176 | + sys.exit(1) |
| 177 | + |
| 178 | + if response.ret == client.SRV_RET_DOWNLOAD: |
| 179 | + filename = input("File to save: ") |
| 180 | + try: |
| 181 | + client.download(filename) |
| 182 | + logging.info("File downloaded") |
| 183 | + except Exception as exception: |
| 184 | + logging.error(str(exception)) |
| 185 | + elif response.ret == client.SRV_RET_UPLOAD: |
| 186 | + filename = input("File to upload: ") |
| 187 | + try: |
| 188 | + client.upload(filename) |
| 189 | + logging.info("File uploaded") |
| 190 | + except Exception as exception: |
| 191 | + logging.error(str(exception)) |
| 192 | + else: |
| 193 | + if outputformat == 'xml': |
| 194 | + print(highlight(xml.dom.minidom.parseString(response.xml).toprettyxml(), |
| 195 | + XmlLexer(), TerminalFormatter())) |
| 196 | + else: |
| 197 | + print(response.output) |
0 commit comments