def test_unix_socket_connection_connect_send_str_read(self):
     self.connection = UnixSocketConnection(path=self.socketname,
                                            timeout=DEFAULT_TIMEOUT)
     self.connection.connect()
     self.connection.send("<gmp/>")
     self.connection.read()
     self.connection.disconnect()
示例#2
0
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_unix_socket_connection_connect_send_str_read(self):
     connection = UnixSocketConnection(
         path=self.socketname, timeout=DEFAULT_TIMEOUT
     )
     connection.connect()
     req = connection.send("<gmp/>")
     self.assertIsNone(req)
     resp = connection.read()
     self.assertEqual(resp, '<gmp_response status="200" status_text="OK"/>')
     connection.disconnect()
示例#4
0
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
示例#5
0
 def __init__(self, password, socket_path='/var/run/gvmd.sock', user='******', timeout=10, loglevel=logging.ERROR):
   logging.basicConfig(level=loglevel)
   self.connection_errors = 0
   self.container_tasks = {}
   self.password = password
   self.user = user
   self.socketconnection = UnixSocketConnection(path=socket_path, timeout=timeout)
   self.connection = DebugConnection(self.socketconnection)
   self.transform = EtreeCheckCommandTransform()
   self.gmp = Gmp(connection=self.connection, transform=self.transform)
   self.connect()
示例#6
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))
示例#7
0
    def __init__(self):
        connection = UnixSocketConnection(path=config['OPENVAS_SOCKET'])
        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
示例#8
0
def main():
    logging.basicConfig(filename='openvas-error.log', level=logging.ERROR)
    logging.basicConfig(filename='openvas-debug.log', level=logging.DEBUG)
    path = '/usr/local/var/run/gvmd.sock'
    connection = UnixSocketConnection(path=path)
    transform = EtreeTransform()
    openvas_remote = OpenvasRemote(path, connection, transform)
    username = str(sys.arg[1])
    password = str(sys.arg[2])
    #==================Please comment out the next 4 lines after running this python script once===================================
    id = openvas_remote.create_target('TestTarget',['192.168.112.137'], username, password)
    task_id = openvas_remote.create_task('OpenVasTestTask',  openvas_remote.get_full_and_fast_config_id(), id,  openvas_remote.get_default_openvas_scanner_id(), username , password)
    report_id = openvas_remote.start_task(task_id, username, password)
    print('replace this id: ' + report_id + ' in report id in this code file to get the report in a json format')
 def test_unix_socket_connect_could_not_connect(self):
     connection = UnixSocketConnection(
         path=self.socketname, timeout=DEFAULT_TIMEOUT
     )
     with patch("socket.socket.connect") as ConnectMock:
         connect_mock = ConnectMock
         connect_mock.side_effect = ConnectionError
         with self.assertRaises(
             GvmError, msg=f"Could not connect to socket {self.socketname}"
         ):
             connection.connect()
         connection.disconnect()
示例#10
0
def create_connection():
    """
           **Creates the connection*
           This function allows user to create a connection with openvas manager using gvm. The UnixSocketConnection function
           takes as a parameter a path that leads to openvasmd socket file (/var/run/openvasmd.sock) that exists in the VM that runs OpenVAS manager.
           Read rights must be granted (sudo chmod a+rwx openvasmd.sock)

           :return: The connection that gives access to the OpenVAS interface.
       """

    subprocess.call(["sudo", "./config.sh"])
    connection = UnixSocketConnection(path='/var/run/gvmd.sock')
    # transform = EtreeTransform()
    gmp = Gmp(connection)

    # version = gmp.get_version()
    gmp.authenticate('admin', 'admin')

    return gmp
示例#11
0
    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
示例#12
0
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!")
示例#13
0
 def test_init_with_none(self):
     connection = UnixSocketConnection(path=None, timeout=None)
     self.check_default_values(connection)
 def test_unix_socket_send_unconnected_socket(self):
     self.connection = UnixSocketConnection(path=self.socketname,
                                            timeout=DEFAULT_TIMEOUT)
     with self.assertRaises(GvmError):
         self.connection.send("<gmp>/")
示例#15
0
from gvm.connections import UnixSocketConnection
from gvm.protocols.gmp import Gmp
from gvm.transforms import EtreeTransform
from gvm.xml import pretty_print

connection = UnixSocketConnection()
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', '24dd0dc1-0d00-4182-b21e-48ce4f142006')

    # Retrieve all tasks
    tasks = gmp.get_tasks()

    # Get names of tasks
    task_names = tasks.xpath('task/name/text()')

    # get targets
    target_id = tasks.xpath('task/target/@id')[0]
    target = gmp.get_target(target_id)
    pretty_print(target)
class UnixSocketConnectionTestCase(unittest.TestCase):
    def setUp(self):
        self.socketname = "%s/%s.sock" % (
            tempfile.gettempdir(),
            str(uuid.uuid4()),
        )
        self.sockserv = ThreadedUnixStreamServer(self.socketname,
                                                 DummyRequestHandler)
        self.server_thread = threading.Thread(
            target=self.sockserv.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def tearDown(self):
        self.sockserv.shutdown()
        self.sockserv.server_close()
        os.unlink(self.socketname)

    def test_unix_socket_connection_connect_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_connection_connect_send_bytes_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.send(bytes("<gmp/>", 'utf-8'))
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_connection_connect_send_str_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.send("<gmp/>")
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_send_unconnected_socket(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        with self.assertRaises(GvmError):
            self.connection.send("<gmp>/")
示例#17
0
 def test_unix_socket_connection_connect_read(self):
     self.connection = UnixSocketConnection(self.socketname, DEFAULT_TIMEOUT)
     self.connection.connect()
     self.connection.read()
     self.connection.disconnect()
 def test_unix_socket_connect_file_not_found(self):
     connection = UnixSocketConnection(path="foo", timeout=DEFAULT_TIMEOUT)
     with self.assertRaises(GvmError, msg="Socket foo does not exist"):
         connection.connect()
     connection.disconnect()
示例#19
0
 def test_unix_socket_connection_connect_send_bytes_read(self):
     self.connection = UnixSocketConnection(self.socketname, DEFAULT_TIMEOUT)
     self.connection.connect()
     self.connection.send(bytes("<gmp/>", 'utf-8'))
     self.connection.read()
     self.connection.disconnect()
示例#20
0
            continue
        nvt = vuln.get('nvt', {})
        scan_result = {}
        scan_result['name'] = name
        scan_result['severity'] = float(nvt.get('cvss_base', 0))
        scan_result['risk'] = vuln.get('threat')
        scan_result['cve_id'] = nvt.get(
            'cve', 'N/A') if nvt.get('cve') != 'NOCVE' else 'N/A'
        scan_result['description'] = ''  # vuln.get('description')
        scan_result['solution'] = 'N/A'
        scan_result['reported_by'] = 'OpenVAS'
        scan_results[name] = scan_result
    return scan_results


connection = UnixSocketConnection(path='/var/run/openvasmd.sock')
transform = EtreeTransform()
gmp = Gmp(connection, transform=transform)

# 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')

name = 'name-5'
ip_address = 'scanme.nmap.org'
# ip_address = 'webscantest.com'
示例#21
0
 def __init__(self, socket_path='/var/run/openvasmd.sock', username='******', password='******'):
     self.username = username
     self.password = password
     connection = UnixSocketConnection(path=socket_path)
     transform = EtreeCheckCommandTransform()
     self.gmp = Gmp(connection=connection, transform=transform)
示例#22
0
class UnixSocketConnectionTestCase(unittest.TestCase):
    # pylint: disable=protected-access
    def setUp(self):
        self.socketname = "%s/%s.sock" % (
            tempfile.gettempdir(),
            str(uuid.uuid4()),
        )
        self.sockserv = ThreadedUnixStreamServer(self.socketname,
                                                 DummyRequestHandler)
        self.server_thread = threading.Thread(
            target=self.sockserv.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def tearDown(self):
        self.sockserv.shutdown()
        self.sockserv.server_close()
        os.unlink(self.socketname)

    def test_unix_socket_connection_connect_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_connection_connect_send_bytes_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.send(bytes("<gmp/>", 'utf-8'))
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_connection_connect_send_str_read(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        self.connection.connect()
        self.connection.send("<gmp/>")
        self.connection.read()
        self.connection.disconnect()

    def test_unix_socket_send_unconnected_socket(self):
        self.connection = UnixSocketConnection(path=self.socketname,
                                               timeout=DEFAULT_TIMEOUT)
        with self.assertRaises(GvmError):
            self.connection.send("<gmp>/")

    def test_init_no_args(self):
        connection = UnixSocketConnection()
        self.check_default_values(connection)

    def test_init_with_none(self):
        connection = UnixSocketConnection(path=None, timeout=None)
        self.check_default_values(connection)

    def check_default_values(self, connection: UnixSocketConnection):
        self.assertEqual(connection._timeout, DEFAULT_TIMEOUT)
        self.assertEqual(connection.path, DEFAULT_UNIX_SOCKET_PATH)
from gvm.errors import GvmError

import xmltodict
import json

import logging
from datetime import datetime

DEBUG = True

logging.basicConfig(level=logging.DEBUG, filename="test-gvm" + str(datetime.now().date()) + ".log")

# path = "/var/run/openvasmd.sock"
path = '/var/run/gvmd.sock'

OPENVAS_CONN=DebugConnection(UnixSocketConnection(path=path)) if DEBUG else UnixSocketConnection(path=path)


class OpenVASTool():
    def __init__(self, connection=OPENVAS_CONN, username="******", password="******"):
        self.gmp = Gmp(connection=connection)
        self.username=username
        self.password=password
        try:
            self.gmp.authenticate(self.username, self.password)
        except GvmError as e:
            print('An error occurred', e, file=sys.stderr)

    def push_command(self, command, params):
        """
示例#24
0
 def test_init_no_args(self):
     connection = UnixSocketConnection()
     self.check_default_values(connection)