def connect_gvm(username, password): """connect via TLS and create a target for gvm this assumes you have connected to gvmd through local ssh forward, if not configure hostname to match hostname or ip address and change the port if needed, this will use the default port 9390""" transform = EtreeCheckCommandTransform() connection = TLSConnection() connection.hostname = '127.0.0.1' connection.port = '9390' gmp = Gmp(connection=connection, transform=transform) gmp.authenticate(username, password) return gmp
def test_connect_auth(self): with patch("ssl.SSLContext") as SSHContextMock: context_mock = SSHContextMock.return_value cert_file = Mock() ca_file = Mock() key_file = Mock() connection = TLSConnection(certfile=cert_file, cafile=ca_file, keyfile=key_file) connection.connect() context_mock.load_cert_chain.assert_called_once() context_mock.wrap_socket.assert_called_once() self.assertFalse(context_mock.check_hostname)
def create_connection( connection_type, socketpath=None, timeout=None, hostname=None, port=None, certfile=None, keyfile=None, cafile=None, ssh_username=None, ssh_password=None, **kwargs # pylint: disable=unused-argument ): if 'socket' in connection_type: return UnixSocketConnection(timeout=timeout, path=socketpath) if 'tls' in connection_type: return TLSConnection( timeout=timeout, hostname=hostname, port=port, certfile=certfile, keyfile=keyfile, cafile=cafile, ) return SSHConnection( timeout=timeout, hostname=hostname, port=port, username=ssh_username, password=ssh_password, )
def test_init_with_none(self): connection = TLSConnection( certfile=None, cafile=None, keyfile=None, hostname=None, port=None, password=None, timeout=None, ) self.check_default_values(connection)
def __post_init__(self): connection: TLSConnection = TLSConnection(hostname=self.hostname.ip, timeout=5) self.gmp: Gmp = Gmp(connection) try: response: str = self.gmp.authenticate(self.user, self.password) soup: BeautifulSoup = BeautifulSoup(response, 'xml') if int(soup.authenticate_response['status']) != 200: # print(soup.authenticate_response.attrs) self.print_and_exit(soup.authenticate_response['status_text']) except OSError: self.print_and_exit(f"Timeout connect Openvas {self.hostname.ip}") self.export = { 'PDF': 'c402cc3e-b531-11e1-9163-406186ea4fc5', 'XML': 'a994b278-1f62-11e1-96ac-406186ea4fc5', 'LATEX': 'a684c02c-b531-11e1-bdc2-406186ea4fc5', 'HTML': '6c248850-1f62-11e1-b082-406186ea4fc5' }
def __init__(self): connection = TLSConnection(hostname=config['HOST_NAME'], port=config['PORT'], certfile=None, cafile=None, keyfile=None, password=None, timeout=25) transform = EtreeTransform() self.gmp = Gmp(connection, transform=transform) self.storage_service = StorageService() # Login try: self.gmp.authenticate(config['OPENVAS_USERNAME'], config['OPENVAS_PASSWORD']) except: print(f'[{self.name}] Not able to connect to the {self.name}: ', sys.exc_info()) return
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"]) this.gmp = Gmp(connection) 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()
options, args = parser.parse_args() logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='[%Y-%m-%d %H:%M:%S]', level=options.loglevel.upper()) if len(args) != 2: parser.print_help() sys.exit() hosts = args[0] outputfile = args[1] logging.info('Hosts: {}'.format(hosts)) logging.info('Outputfile: {}'.format(outputfile)) connection = TLSConnection() transform = EtreeTransform() logging.info('Connecting to GMP') with Gmp(connection, transform=transform) as gmp: gmp.authenticate('admin', 'admin') logging.info('Authenticated') # Get the base config based on the provided name config = gmp.get_configs(filter="name=\"{}\"".format(options.scan_config), details=True) config_exists = len(config.xpath("//config")) == 1 if not config_exists: logging.error('Selected config "%s" does not exist' % options.scan_config)
def test_init_no_args(self): connection = TLSConnection() self.check_default_values(connection)
from gvm.transforms import EtreeTransform from gvm.xml import pretty_print import xml.etree.ElementTree as ET import untangle import base64 import csv, json import os.path from os import path import configparser # Read the configfile config = configparser.ConfigParser() config.sections() config.read('config/config.ini') connection = TLSConnection(hostname=config['DEFAULT']['host']) 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()
from gvm.connections import TLSConnection from gvm.protocols.gmp import Gmp from gvm.transforms import EtreeTransform from gvm.xml import pretty_print connection = TLSConnection(hostname='127.0.0.1', port=9390) transform = EtreeTransform() with Gmp(connection, transform=transform) as gmp: # Retrieve GMP version supported by the remote daemon version = gmp.get_version() # Prints the XML in beautiful form pretty_print(version) # Login gmp.authenticate('admin', 'admin') # Retrieve all tasks tasks = gmp.get_tasks() # Get names of tasks task_names = tasks.xpath('task/name/text()') pretty_print(task_names)
def _connect(self): conn = TLSConnection(hostname=self._config.host, port=self._config.port) with Gmp(connection=conn, transform=EtreeTransform()) as gmp: gmp.authenticate(self._config.username, self._config.password) yield gmp
def _loadconfig(): conf_file = APP_BASE_DIR+"/openvas.json" if not exists(conf_file): app.logger.error("Error: config file '{}' not found".format(conf_file)) return False 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" app.logger.error("Error: authentication failure Openvas instance") return False # Check port lists try: portlists = ET.fromstring(this.gmp.get_port_lists()) except Exception: return None for pl in portlists.findall('port_list'): pl_name = pl.find('name').text pl_uuid = pl.get('id') this.openvas_portlists.update({pl_name: pl_uuid}) # Create custom port lists if "patrowl-all_tcp" not in this.openvas_portlists.keys(): try: new_pl_xml = this.gmp.create_port_list( name="patrowl-all_tcp", port_range="T:1-65535" ) new_pl = ET.fromstring(new_pl_xml) this.openvas_portlists.update({"patrowl-all_tcp": new_pl.get('id')}) except Exception: return None if "patrowl-quick_tcp" not in this.openvas_portlists.keys(): try: new_pl_xml = this.gmp.create_port_list( name="patrowl-quick_tcp", port_range="T:21-80,T:443,U:53" ) new_pl = ET.fromstring(new_pl_xml) this.openvas_portlists.update({"patrowl-quick_tcp": new_pl.get('id')}) except Exception: return None if "patrowl-tcp_80" not in this.openvas_portlists.keys(): try: new_pl_xml = this.gmp.create_port_list( name="patrowl-tcp_80", port_range="T:80" ) new_pl = ET.fromstring(new_pl_xml) this.openvas_portlists.update({"patrowl-tcp_80": new_pl.get('id')}) except Exception: return None if "patrowl-tcp_443" not in this.openvas_portlists.keys(): try: new_pl_xml = this.gmp.create_port_list( name="patrowl-tcp_443", port_range="T:443" ) new_pl = ET.fromstring(new_pl_xml) this.openvas_portlists.update({"patrowl-tcp_443": new_pl.get('id')}) except Exception: return None if "patrowl-tcp_22" not in this.openvas_portlists.keys(): try: new_pl_xml = this.gmp.create_port_list( name="patrowl-tcp_22", port_range="T:22" ) new_pl = ET.fromstring(new_pl_xml) this.openvas_portlists.update({"patrowl-tcp_22": new_pl.get('id')}) except Exception: return None engine.scanner["status"] = "READY" engine.scanner["credentials"] = ()
dbCursor.execute('''INSERT INTO `reports`(resultId) VALUES(?)''', (resultId, )) dbConn.commit() def isReportFresh(resultId): """"Check if the report with id resultId is new. Return true if the resultId does not exist in the sqlite3 database `DB_PATH` else false.""" dbCursor.execute("SELECT COUNT(*) FROM `reports` WHERE resultId=?", (resultId, )) count = dbCursor.fetchone()[0] return count == 0 # Prepare TLS Connection to OpenVAS XML API. # Timeout=None is necessary because OpenVAS API can take a long time to generate the XML reports. connection = TLSConnection(hostname="openvas", port=9390, timeout=None) # Connect to local sqlite3 db dbConn = sqlite3.connect(DB_PATH) dbCursor = dbConn.cursor() # Create the needed table if it does not exist: dbCursor.execute('''CREATE TABLE IF NOT EXISTS `reports` ([id] INTEGER PRIMARY KEY AUTOINCREMENT,[resultId] text)''') dbConn.commit() # Create the needed index on the table if it does not exist. Useful for speeding up lookups on `resultId` in isReportFresh. dbCursor.execute('''CREATE INDEX IF NOT EXISTS `reports_by_ids` on `reports`([resultId])''') dbConn.commit() # Open the OpenVAS GMP connection and authenticate. with Gmp(connection) as gmp: gmp.authenticate(config['config']['OPENVAS_USER'], config['config']['OPENVAS_PASS']) reportFormatId = getReportFormat() # Get the identifier for the CSV report format. reportIds = getReportIds() # Get all report ids.
from gvm.connections import TLSConnection from gvm.protocols.gmp import Gmp from gvm.transforms import EtreeTransform from gvm.xml import pretty_print import xml.etree.ElementTree as ET connection = TLSConnection(hostname="gvmd") 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':
def test_connect(self): with patch("ssl.SSLContext") as SSHContextMock: context_mock = SSHContextMock.return_value connection = TLSConnection() connection.connect() context_mock.wrap_socket.assert_called_once()