def my_launch_scanner():
	sem = Semaphore(0)

	# Configure
	manager = VulnscanManager("localhost", "admin", "openvas")

	# Launch
	manager.launch_scan("127.0.0.1",
	                    profile="empty",
	                    callback_end=partial(lambda x: x.release(), sem),
	                    callback_progress=my_print_status)

	# Wait
	sem.acquire()

	# Finished scan
	print("finished")
Example #2
0
    def launch(self):

        sem = Semaphore(0)

        try:
            scanner = VulnscanManager(config.omp_ip, config.omp_user, config.omp_password)
            task_id, target_id = scanner.launch_scan(target='https://log.cmbchina.com',
                                                     profile="Full and fast",
                                                     callback_end=partial(lambda x: x.release(), sem)
                                                     )
            print task_id, target_id
            sem.acquire()
            print("finished")

            report_id = scanner.get_report_id(task_id)
            self.result_name = task_id + '.csv'

            cmd = 'omp --get-report ' + report_id + ' --format ' + data.format_csv + ' > ' + self.result_name
            Utils.cmd_block(self.client, cmd)

            Utils.sftp_get(config.server_ip,
                           config.port,
                           config.server_user,
                           config.server_password,
                           self.result_name,
                           './temp/server/'+self.result_name)

        except VulnscanException as e:
            print("Error:")
            print(e)
Example #3
0
def openvas_download(request, id):
    scanner = VulnscanManager("localhost", openvas_username, openvas_password)
    task = openvas_requests.objects.get(id=id)
    if task.state == "Finished":
        result = openvas_results.objects.get(id=task.id)
        print(result.report)
        # Retornant pdf
        report = scanner.get_report_pdf(str(result.report))
        nomArxiu = "Report_" + task.name.replace(
            " ", "-") + "_" + datetime.strftime(result.finish_date,
                                                "%Y%m%d%H%M") + ".pdf"
        #print("Report:" + report)
        reportXML = ElementTree.tostring(report.find("report"),
                                         encoding='utf-8',
                                         method='xml')
        print("ReportXML:" + str(reportXML).split(">")[-2].split("<")[0])
        #fullReport = ElementTree.fromstring(reportXML)
        #response = HttpResponse(base64.b64decode(fullReport.find("in_use").tail), content_type='application/pdf')
        response = HttpResponse(base64.b64decode(
            str(reportXML).split(">")[-2].split("<")[0]),
                                content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + nomArxiu
        return response
    else:
        context = crearContextBase(request)
        context.update({'openvas_tasks': "active"})
        results = "fail"
        context.update({'task': task, 'results': results})
        return render(request, 'openvas_task.html', context)
Example #4
0
def launch_scanner(target):
    print("start scan " + target)
    sem = Semaphore(0)

    # Configure
    manager = VulnscanManager("localhost", "admin", "openvas")

    # Launch
    scan_id, target_id = manager.launch_scan(target = target,
                        profile = "Full and fast",
                        callback_end = partial(lambda x: x.release(), sem),
                        callback_progress = print_status)

    # Wait
    sem.acquire()

    # Finished scan
    print("finished")
    openvas_results = manager.get_results(scan_id)
    results = []
    for opr in openvas_results:
        results.append({
            "id": opr.id,
            "subnet": opr.subnet,
            "host": opr.host,
            "port": {
                "port_name": opr.port.port_name,
                "number": opr.port.number,
                "proto": opr.port.proto
            },
            "nvt": {
                "oid" : opr.nvt.oid,
                "name" : opr.nvt.name,
                "cvss_base" : opr.nvt.cvss_base,
                "cvss_base_vector" : opr.nvt.cvss_base_vector,
                "risk_factor" : opr.nvt.risk_factor,
                "category" : opr.nvt.category,
                "summary" : opr.nvt.summary,
                "description" : opr.nvt.description,
                "family" : opr.nvt.family,
                "cves" : opr.nvt.cve,
                "bids" : opr.nvt.bid,
                "bugtraqs" : opr.nvt.bugtraq,
                "xrefs" : opr.nvt.xrefs,
                "fingerprints" : opr.nvt.fingerprints,
                "tags" : opr.nvt.tags
            },
            "threat": opr.threat,
            "description": opr.raw_description,
            "notes": opr.notes,
            "overrides": opr.overrides,
            "impact": opr.impact,
            "summary": opr.summary,
            "vulnerability_insight": opr.vulnerability_insight,
            "affected_software": opr.affected_software,
            "solution": opr.solution
        })
    return results
Example #5
0
def scan_entity(ip,openvas_conf):
    
    Sem = Semaphore(0)
    # Configure
    print "ip is",ip
    #print "openvas addr is",openvas_conf['addr']
    #print "openvas pass is",openvas_conf['pass']
    
    manager = VulnscanManager(openvas_conf['addr'].encode("utf-8"),\
                             openvas_conf['user'].encode("utf-8"),\
                             openvas_conf['pass'].encode("utf-8"))
    # Launch
    scan_id,target_id = manager.launch_scan(ip,
				profile = "Full and fast",
				callback_end = partial(lambda x: x.release(), Sem),
				callback_progress = my_print_status)
    # Wait
    Sem.acquire()
    # Finished scan
    print "finished"
    #scan_id=""
    #pdb.set_trace()
    #if get all results set False or set True 
    res_list= manager.get_results(scan_id,True)
    
    svc_name=''

    # initial requests
    requests.packages.urllib3.disable_warnings()
    #host_vuln = host_sample()

    for res in res_list:
        if not res.description:
            desc = ''
        else:
            desc = res.description
        create_time = str(int(time.mktime(datetime.datetime.now().timetuple())) * 1000)
        resentity['VulnerID'] = str(uuid.uuid1())
        resentity['Name'] = res.name
        resentity['HostIP'] = res.host
        resentity['Severity'] = res.severity
        resentity["Family"]=res.nvt.family
        resentity["Port"]=res.port.number
        resentity["Protocol"]=res.port.proto
        resentity["SvcName"]=str(res.port.number) + res.port.proto
        resentity["QOD"]=res.qod
        resentity["CVE"]=res.nvt.raw_cves
        resentity["BID"]=res.nvt.raw_bids
        resentity["CvssBase"]=res.nvt.cvss_base_vector
        resentity["CERT"]=res.nvt.cert
        resentity["Impact"]=res.nvt.impact
        resentity["Desc"]=desc
        resentity["Solution"]=res.nvt.solution
        resentity["Refer"]=res.nvt.raw_xrefs
        resentity["source"]="0"
        resentity["Time"]=create_time
		print "size of result list is ============", resentity
Example #6
0
def analyse(request):

    try:
        scanner = VulnscanManager(HOST, USER, PASSWORD, PORT, TIMEOUT)
        scan_id, target_id = scanner.launch_scan(target="192.168.144.135",  # Target to scan
                                                 profile="Full and fast")
    except VulnscanException as e:
        print("Error:")
        print(e)
    analyse = "liste des vulnerabilites ici"
    return render(request, "pentestapp/analyse_result.html", {"analyse": analyse})
Example #7
0
def openvas_integrator(hosts):

    try:
        scanner = VulnscanManager("192.168.25.125", "admin", "admin", 4000,
                                  300)
    except VulnscanException as e:
        print("Error:")
        print(e)

    for h in range(len(hosts)):
        scan_id, target_id = scanner.launch_scan(target="127.0.0.1",
                                                 profile="Full and fast")
Example #8
0
    def connect(self, params):
        self.logger.info("Attempting to connect to OpenVAS Server...")
        self.username = str(params.get("credentials").get("username"))
        self.password = str(params.get("credentials").get("password"))
        self.server = params.get("server", "127.0.0.1:9393")
        self.timeout = params.get("timeout", "10")
        self.ssl_verify = params.get("ssl_verify")
        try:
            self.server_host = str(self.server.split(":")[0])
            self.server_port = int(self.server.split(":")[1])
        except IndexError as e:
            self.logger.error(
                "Error connecting to OpenVAS Server: Invalid format of server string - requires IPAddress:Port - for example, 127.0.0.1:9390"
            )
        try:
            self.scanner = VulnscanManager(
                self.server_host,
                self.username,
                self.password,
                self.server_port,
                self.timeout,
                self.ssl_verify,
            )
        except Exception as err:
            self.logger.error("Error connecting to OpenVAS Server: " +
                              str(err))
            raise Exception("Connection to OpenVAS server failed, " + str(err))

        self.logger.info("Connected to server " + self.server)
Example #9
0
def main(ip, user, password, target, profile):
    try:
        manager = VulnscanManager(ip, user, password)
    except VulnscanException as e:
        print(str(e))
    else:
        run(manager, target, profile)
Example #10
0
    def connect(self):
        """
        Connecting with OpenVAS
        :return:
        """

        all_openvas = openvas_setting_db.objects.all()

        for openvas in all_openvas:
            ov_user = openvas.user
            ov_pass = openvas.password
            ov_host = openvas.host
            ov_port = openvas.port

        # ov_user = openvas_setting.openvas_username()
        # ov_pass = openvas_setting.openvas_pass()
        # ov_host = openvas_setting.openvas_host()

        lod_ov_user = ov_user
        lod_ov_pass = ov_pass
        lod_ov_host = ov_host
        lod_ov_port = ov_port

        scanner = VulnscanManager(str(lod_ov_host), str(lod_ov_user),
                                  str(lod_ov_pass), int(lod_ov_port))
        time.sleep(5)

        return scanner
Example #11
0
	def start_scan(self):
		print_info("connecting to openvas..")
		try:
                        self.scanner = VulnscanManager('127.0.0.1', 'admin', 'dinimere')
                except VulnscanException, e:
                        print "Error:"
                        print e
Example #12
0
 def _connect(self):
     try:
         app.logger.info("Trying to connect to scanner {}:{} ...".format(
             self.ov_host, self.ov_port))
         return VulnscanManager(self.ov_host, self.user, self.password,
                                self.ov_port, self.DEFAULT_TIMEOUT)
     except VulnscanServerError:
         raise ScanServerException("Scan server connection error.")
Example #13
0
def start_scan(ip="104.25.81.107", config=database.config):
    try:
        scanner = VulnscanManager("localhost", "admin", "admin")
        report_id = run(scanner, ip, config)
    except Exception as e:
        print("Error:" + "\n" + str(e))
        return
    return report_id
def _loadconfig():
    conf_file = APP_BASE_DIR + '/openvas.json'
    if os.path.exists(conf_file):
        json_data = open(conf_file)
        engine.scanner = json.load(json_data)
        engine.scanner['status'] = "INIT"

        # Check omp connectivity
        if set(["omp_host", "omp_port", "omp_username",
                "omp_password"]).issubset(engine.scanner['options'].keys()):
            try:
                this.openvas_cli = VulnscanManager(
                    str(engine.scanner['options']['omp_host']['value']),
                    str(engine.scanner['options']['omp_username']['value']),
                    str(engine.scanner['options']['omp_password']['value']),
                    int(engine.scanner['options']['omp_port']['value']))
            except VulnscanException as e:
                print("Error: {}".format(e))
        else:
            print("Error: missing required options in config file".format(
                conf_file))
            engine.scanner['status'] = "ERROR"
            return {"status": "error", "reason": "missing required options"}

        for pl_name, pl_data in this.openvas_cli.get_port_lists().items():
            this.openvas_portlists.update({pl_name: pl_data['id']})

        # Create custom port lists
        if "patrowl-all_tcp" not in this.openvas_portlists.keys():
            new_pl_id = this.openvas_cli.create_port_list(
                name="patrowl-all_tcp", port_range="T:1-65535")
            this.openvas_portlists.update({"patrowl-all_tcp": new_pl_id})

        if "patrowl-quick_tcp" not in this.openvas_portlists.keys():
            new_pl_id = this.openvas_cli.create_port_list(
                name="patrowl-quick_tcp", port_range="T:21-80,T:443,U:53")
            this.openvas_portlists.update({"patrowl-quick_tcp": new_pl_id})

        if "patrowl-tcp_80" not in this.openvas_portlists.keys():
            new_pl_id = this.openvas_cli.create_port_list(
                name="patrowl-tcp_80", port_range="T:80")
            this.openvas_portlists.update({"patrowl-tcp_80": new_pl_id})

        if "patrowl-tcp_443" not in this.openvas_portlists.keys():
            new_pl_id = this.openvas_cli.create_port_list(
                name="patrowl-tcp_443", port_range="T:443")
            this.openvas_portlists.update({"patrowl-tcp_443": new_pl_id})

        if "patrowl-tcp_22" not in this.openvas_portlists.keys():
            new_pl_id = this.openvas_cli.create_port_list(
                name="patrowl-tcp_22", port_range="T:22")
            this.openvas_portlists.update({"patrowl-tcp_22": new_pl_id})

        engine.scanner['status'] = "READY"
    else:
        print("Error: config file '{}' not found".format(conf_file))
        engine.scanner['status'] = "ERROR"
        return {"status": "error", "reason": "config file not found"}
Example #15
0
def openvas():
    # Setup openvas connection
    try:
        scanner = VulnscanManager(args.host, args.user, args.password)
        print(scanner)
    except VulnscanException as e:
        print("Error:")
        print(e)

    return scanner
Example #16
0
def my_launch_scanner():
    sem = Semaphore(0)
    #
    # # Configure
    manager = VulnscanManager("localhost", "admin", "123456")

    # Launch
    scan_id, target_id = manager.launch_scan('192.168.86.12',
                                             profile="Full and fast",
                                             callback_end=partial(
                                                 lambda x: x.release(), sem),
                                             callback_progress=my_print_status)
    print(scan_id)
    sem.acquire()
    res = manager.get_results(scan_id)
    for flag in res:
        print(
            '------------------------------------------------------------------------------------------------------------'
        )
        # print('impact:' + flag.impact + '  summary:' + flag.summary + '  vulnerability:' + flag.vulnerability_insight)
        print('vulnerability:' + str(flag.vulnerability_insight) +
              '  affected_software:' + str(flag.affected_software) +
              '  notes:' + str(flag.notes))
        print('raw_description:' + str(flag.raw_description) + '  overrides:' +
              str(flag.overrides))
        print('port:' + str(flag.port) + '  threat:' + str(flag.threat) +
              '  severity:' + str(flag.severity))
        print('nvt_name:' + str(flag.nvt.name) + '  cvss_base_vector:' +
              str(flag.nvt.cvss_base_vector) + '  cvss_base:' +
              str(flag.nvt.cvss_base))
        print('risk_factor' + str(flag.nvt.risk_factor) + '  summary:' +
              str(flag.nvt.summary) + '  description:' +
              str(flag.nvt.description))
        print('family:' + str(flag.nvt.family) + '  category:' +
              str(flag.nvt.category) + '  cve:' + str(flag.nvt.cve))
        print('bugtrap: ' + str(flag.nvt.bugtraq) + '  xrefs:' +
              str(flag.nvt.xrefs) + 'fingerprints:' +
              str(flag.nvt.fingerprints))
        print(
            '---------------------------------------------------------------------------------------------------------'
        )
    # Finished scan
    print("finished")
Example #17
0
def my_launch_scanner():
    sem = Semaphore(0)

    # Configure
    manager = VulnscanManager("localhost", "admin", "admin")

    # Launch
    task, target = manager.launch_scan('10.10.10.130',
                        profile="empty",
                        callback_end=partial(lambda x: x.release(), sem),
                        callback_progress=my_print_status)

    # Wait
    sem.acquire()

    # Finished scan
    print("finished")
    print(task)
    print(target)
    manager.get_results(task_id=task)
Example #18
0
 def import_results(self, input_file):
     try:
         xml_results = etree.parse(input_file)
         openvas_results = VulnscanManager.transform(xml_results.getroot())
         golismero_results = OpenVASPlugin.parse_results(openvas_results)
         if golismero_results:
             Database.async_add_many(golismero_results)
     except Exception, e:
         Logger.log_error("Could not load OpenVAS results from file: %s" %
                          input_file)
         Logger.log_error_verbose(str(e))
         Logger.log_error_more_verbose(format_exc())
Example #19
0
 def import_results(self, input_file):
     try:
         xml_results       = etree.parse(input_file)
         openvas_results   = VulnscanManager.transform(xml_results.getroot())
         golismero_results = OpenVASPlugin.parse_results(openvas_results)
         if golismero_results:
             Database.async_add_many(golismero_results)
     except Exception, e:
         Logger.log_error(
             "Could not load OpenVAS results from file: %s" % input_file)
         Logger.log_error_verbose(str(e))
         Logger.log_error_more_verbose(format_exc())
Example #20
0
    def scan(self, input_targets):
        # Merge targets into one string separated by comma
        targets = ""
        for i in range(0, len(input_targets) - 1):
            targets += input_targets[i] + ", "
        targets += input_targets[len(input_targets) - 1]
        print("SCANNING TARGET NETWORK: %s" % targets)

        sem = Semaphore(0)
        manager = VulnscanManager("localhost", "david", "password")

        scan_id, target_id = manager.launch_scan(targets,
                                                 profile="Full and fast",
                                                 callback_end=partial(
                                                     lambda x: x.release(),
                                                     sem),
                                                 callback_progress=self.status)
        # Wait
        sem.acquire()

        return (scan_id)
Example #21
0
def vuln_an_id(scan_id, project_id):
    """
    The function is filtering all data from OpenVAS and dumping to Archery database.
    :param scan_id:
    :return:
    """
    ov_ip = ""
    ov_user = ""
    ov_pass = ""
    all_openvas = OpenvasSettingDb.objects.filter()

    scan_status = "100"
    date_time = datetime.datetime.now()

    for openvas in all_openvas:
        ov_user = openvas.user
        ov_pass = openvas.password
        ov_ip = openvas.host

    scanner = VulnscanManager(str(ov_ip), str(ov_user), str(ov_pass))
    openvas_results = scanner.get_raw_xml(str(scan_id))

    hosts = OpenVas_Parser.get_hosts(openvas_results)

    del_old = NetworkScanDb.objects.filter(scan_id=scan_id)
    del_old.delete()

    for host in hosts:
        scan_dump = NetworkScanDb(
            ip=host,
            scanner="Openvas",
            scan_id=scan_id,
            date_time=date_time,
            project_id=project_id,
            scan_status=scan_status,
        )
        scan_dump.save()
    OpenVas_Parser.updated_xml_parser(project_id=project_id,
                                      scan_id=scan_id,
                                      root=openvas_results)
Example #22
0
def my_launch_scanner():

    sem = Semaphore(0)

    # Configure
    try:
        manager = VulnscanManager("127.0.0.1", "nishan",
                                  "e6cded22-43a3-4ca5-967f-5b3bf7eff4ce", 9390,
                                  5)
        print "Connection successful"
    except:
        print "Connection failed"
        sys.exit(-1)
    # Launch
    try:
        scan_id, task_id = manager.launch_scan(
            target="127.0.0.1",
            profile="Full and fast",
            callback_end=partial(lambda x: x.release(), sem),
            callback_progress=my_print_status)
        print "Scan ID is : {}\n".format(t)
        print "Task Created Successfull"
    except:
        print "Task Creation Unsuccessfull"
    # Wait
    sem.acquire()

    # Finished scan
    print("finished")
    id = manager.get_report_id(scan_id)
    command = "omp -u nishan -w e6cded22-43a3-4ca5-967f-5b3bf7eff4ce -R {} > /home/nishan/logs/log.xml".format(
        id)
    system(command)
    sleep(2)
    now = datetime.now()
    index = "openvas-{}.{}.{}".format(now.year, now.month, now.day)

    np = OpenVasES('/home/nishan/logs/log.xml', '10.10.66.66', '9200', index)
    np.toES()
Example #23
0
def vuln_an_id(scan_id, project_id, username):
    """
    The function is filtering all data from OpenVAS and dumping to Archery database.
    :param scan_id:
    :return:
    """
    global name, host, severity, port, creation_time, modification_time, threat, severity, description, family, cvss_base, cve, bid, xref, tags, banner, date_time, false_positive, duplicate_hash, duplicate_vuln, ov_ip, ov_user, ov_pass

    all_openvas = openvas_setting_db.objects.filter(username=username)

    scan_status = "100"
    date_time = datetime.now()

    for openvas in all_openvas:
        ov_user = openvas.user
        ov_pass = openvas.password
        ov_ip = openvas.host

    scanner = VulnscanManager(str(ov_ip), str(ov_user), str(ov_pass))
    openvas_results = scanner.get_raw_xml(str(scan_id))

    hosts = OpenVas_Parser.get_hosts(openvas_results)

    del_old = openvas_scan_db.objects.filter(scan_id=scan_id)
    del_old.delete()

    for host in hosts:
        scan_dump = openvas_scan_db(scan_ip=host,
                                    scan_id=host,
                                    date_time=date_time,
                                    project_id=project_id,
                                    scan_status=scan_status,
                                    username=username)
        scan_dump.save()
    OpenVas_Parser.updated_xml_parser(project_id=project_id,
                                      scan_id=scan_id,
                                      root=openvas_results,
                                      username=username)
Example #24
0
    def connect(self):
        """
        Connecting with OpenVAS
        :return:
        """
        ov_user = openvas_setting.openvas_username()
        ov_pass = openvas_setting.openvas_pass()
        ov_ip = openvas_setting.openvas_host()

        lod_ov_user = signing.loads(ov_user)
        lod_ov_pass = signing.loads(ov_pass)
        lod_ov_ip = signing.loads(ov_ip)

        scanner = VulnscanManager(str(lod_ov_ip), str(lod_ov_user),
                                  str(lod_ov_pass))
        time.sleep(5)

        return scanner
Example #25
0
    def connect(self):
        """
        Connecting with OpenVAS
        :return:
        """

        global ov_host, ov_user, ov_pass, ov_port
        all_openvas = openvas_setting_db.objects.filter(username=self.username)

        for openvas in all_openvas:
            ov_user = openvas.user
            ov_pass = openvas.password
            ov_host = openvas.host
            ov_port = openvas.port

        scanner = VulnscanManager(str(ov_host), str(ov_user), str(ov_pass),
                                  int(ov_port))
        time.sleep(5)

        return scanner
Example #26
0
def main():
    try:
        TARGET_IP = "127.0.0.1"
        OPENVAS_HOST = "127.0.0.1"
        USER = "******"
        PASSWORD = "******"
        PORT = 9390
        TIMEOUT = None
        #profile = "empty"
        profile = "Full and fast"
        manager = VulnscanManager(OPENVAS_HOST, USER, PASSWORD)

        sem = Semaphore(0)

        # Launch
        scan_id, target_id = manager.launch_scan(
            target=TARGET_IP,
            profile=profile,
            callback_end=partial(lambda x: x.release(), sem),
            callback_progress=my_print_status)

        print "scan_id=%s , target_id=%s " % (scan_id, target_id)

        # Wait
        sem.acquire()

        # Finished scan
        print("finished")

        report_id = manager.get_report_id(scan_id)
        write_report(manager, report_id, TARGET_IP)
        manager.delete_scan(scan_id)
        manager.delete_target(target_id)

    except VulnscanException, e:
        print "Error:"
        print e
Example #27
0
class OpenVASPlugin(TestingPlugin):


    #--------------------------------------------------------------------------
    def check_params(self):

        # Check the parameters.
        try:
            m_user = Config.plugin_args["user"]
            m_password = Config.plugin_args["password"]
            m_host = Config.plugin_args["host"]
            m_port = int(Config.plugin_args["port"])
            m_timeout = Config.plugin_args["timeout"]
            m_profile = Config.plugin_args["profile"]

            assert m_user,     "Missing username"
            assert m_password, "Missing password"
            assert m_host,     "Missing hostname"
            assert m_profile,  "Missing scan profile"
            assert 0 < m_port < 65536, "Missing or wrong port number"
            if m_timeout.lower().strip() in ("inf", "infinite", "none"):
                m_timeout = None
            else:
                m_timeout = int(m_timeout)
                assert m_timeout > 0, "Wrong timeout value"

        except Exception, e:
            raise ValueError(str(e))

        # Connect to the scanner.
        try:
            VulnscanManager(m_host, m_user, m_password, m_port, m_timeout)
        except VulnscanVersionError:
            raise RuntimeError(
                "Remote host is running an unsupported version of OpenVAS."
                " Only OpenVAS 6 is currently supported.")
        except VulnscanException, e:
            raise RuntimeError(str(e))
Example #28
0
    def recv_info(self, info):

        # Synchronization object to wait for completion.
        m_event = Event()

        # Get the config.
        m_user = Config.plugin_args["user"]
        m_password = Config.plugin_args["password"]
        m_host = Config.plugin_args["host"]
        m_port = Config.plugin_args["port"]
        m_timeout = Config.plugin_args["timeout"]
        m_profile = Config.plugin_args["profile"]

        # Sanitize the port and timeout.
        try:
            m_port = int(m_port)
        except Exception:
            m_port = 9390
        if m_timeout.lower().strip() in ("inf", "infinite", "none"):
            m_timeout = None
        else:
            try:
                m_timeout = int(m_timeout)
            except Exception:
                m_timeout = None

        # Connect to the scanner.
        try:
            m_scanner = VulnscanManager(m_host, m_user, m_password, m_port,
                                        m_timeout)
        except VulnscanException, e:
            t = format_exc()
            Logger.log_error("Error connecting to OpenVAS, aborting scan!")
            #Logger.log_error_verbose(str(e))
            Logger.log_error_more_verbose(t)
            return
Example #29
0
    def connect(self, params):
        self.logger.info('Attempting to connect to OpenVAS Server...')
        self.username = str(params.get('credentials').get('username'))
        self.password = str(params.get('credentials').get('password'))
        self.server = params.get('server', '127.0.0.1:9393')
        self.timeout = params.get('timeout', '10')
        self.ssl_verify = params.get('ssl_verify')
        try:
            self.server_host = str(self.server.split(':')[0])
            self.server_port = int(self.server.split(':')[1])
        except IndexError as e:
            self.logger.error(
                'Error connecting to OpenVAS Server: Invalid format of server string - requires IPAddress:Port - for example, 127.0.0.1:9390'
            )
        try:
            self.scanner = VulnscanManager(self.server_host, self.username,
                                           self.password, self.server_port,
                                           self.timeout, self.ssl_verify)
        except Exception as err:
            self.logger.error('Error connecting to OpenVAS Server: ' +
                              str(err))
            raise Exception('Connection to OpenVAS server failed, ' + str(err))

        self.logger.info('Connected to server ' + self.server)
Example #30
0
def vuln_an_id(scan_id):
    """
    The function is filtering all data from OpenVAS and dumping to Archery database.
    :param scan_id:
    :return:
    """
    # ov_user = openvas_setting.openvas_username()
    # ov_pass = openvas_setting.openvas_pass()
    # ov_ip = openvas_setting.openvas_host()
    #
    # lod_ov_user = signing.loads(ov_user)
    # lod_ov_pass = signing.loads(ov_pass)
    # lod_ov_ip = signing.loads(ov_ip)

    all_openvas = openvas_setting_db.objects.all()

    for openvas in all_openvas:
        ov_user = openvas.user
        ov_pass = openvas.password
        ov_ip = openvas.host

    lod_ov_user = ov_user
    lod_ov_pass = ov_pass
    lod_ov_ip = ov_ip

    scanner = VulnscanManager(str(lod_ov_ip), str(lod_ov_user),
                              str(lod_ov_pass))
    openvas_results = scanner.get_raw_xml(str(scan_id))

    for openvas in openvas_results.findall(".//result"):
        for r in openvas:
            if r.tag == "name":
                global name
                if r.text is None:
                    name = "NA"
                else:
                    name = r.text

            if r.tag == "creation_time":
                global creation_time
                if r.text is None:
                    creation_time = "NA"
                else:
                    creation_time = r.text

            if r.tag == "modification_time":
                global modification_time
                if r.text is None:
                    modification_time = "NA"
                else:
                    modification_time = r.text
            if r.tag == "host":
                global host
                if r.text is None:
                    host = "NA"
                else:
                    host = r.text

            if r.tag == "port":
                global port
                if r.text is None:
                    port = "NA"
                else:
                    port = r.text
            if r.tag == "threat":
                global threat
                if r.text is None:
                    threat = "NA"
                else:
                    threat = r.text
            if r.tag == "severity":
                global severity
                if r.text is None:
                    severity = "NA"
                else:
                    severity = r.text
            if r.tag == "description":
                global description
                if r.text is None:
                    description = "NA"
                else:
                    description = r.text

            for rr in r.getchildren():
                if rr.tag == "family":
                    global family
                    if rr.text is None:
                        family = "NA"
                    else:
                        family = rr.text
                if rr.tag == "cvss_base":
                    global cvss_base
                    if rr.text is None:
                        cvss_base = "NA"
                    else:
                        cvss_base = rr.text
                if rr.tag == "cve":
                    global cve
                    if rr.text is None:
                        cve = "NA"
                    else:
                        cve = rr.text
                if rr.tag == "bid":
                    global bid
                    if rr.text is None:
                        bid = "NA"
                    else:
                        bid = rr.text

                if rr.tag == "xref":
                    global xref
                    if rr.text is None:
                        xref = "NA"
                    else:
                        xref = rr.text

                if rr.tag == "tags":
                    global tags
                    if rr.text is None:
                        tags = "NA"
                    else:
                        tags = rr.text
                if rr.tag == "type":
                    global banner
                    if rr.text is None:
                        banner = "NA"
                    else:
                        banner = rr.text

        date_time = timezone.now()
        vul_id = uuid.uuid4()

        s_data = scan_save_db.objects.filter(scan_id=scan_id)

        for data in s_data:
            if data.scan_ip == host:

                dup_data = name + host + severity
                duplicate_hash = hashlib.sha256(dup_data).hexdigest()

                save_all = ov_scan_result_db(
                    scan_id=scan_id,
                    vul_id=vul_id,
                    name=name,
                    creation_time=creation_time,
                    modification_time=modification_time,
                    host=host,
                    port=port,
                    threat=threat,
                    severity=severity,
                    description=description,
                    family=family,
                    cvss_base=cvss_base,
                    cve=cve,
                    bid=bid,
                    xref=xref,
                    tags=tags,
                    banner=banner,
                    date_time=date_time,
                    false_positive='No',
                    vuln_status='Open',
                    dup_hash=duplicate_hash)
                save_all.save()

                openvas_vul = ov_scan_result_db.objects.filter(scan_id=scan_id) \
                    .values('name',
                            'threat').distinct()
                total_vul = len(openvas_vul)
                total_high = len(openvas_vul.filter(threat="High"))
                total_medium = len(openvas_vul.filter(threat="Medium"))
                total_low = len(openvas_vul.filter(threat="Low"))
                total_log = len(openvas_vul.filter(threat="Log"))
                scan_status = str(scanner.get_progress(str(scan_id)))

                scan_save_db.objects.filter(scan_id=scan_id) \
                    .update(total_vul=total_vul,
                            high_total=total_high,
                            medium_total=total_medium,
                            low_total=total_low,
                            log_total=total_log,
                            scan_status=scan_status)
Example #31
0
    def run(self, info):

        # Checks if connection was not set as down
        if not self.state.check("connection_down"):

            # Synchronization object to wait for completion.
            m_event = Event()

            # Get the config.
            m_user = Config.plugin_args["user"]
            m_password = Config.plugin_args["password"]
            m_host = Config.plugin_args["host"]
            m_port = Config.plugin_args["port"]
            m_timeout = Config.plugin_args["timeout"]
            m_profile = Config.plugin_args["profile"]

            # Sanitize the port and timeout.
            try:
                m_port = int(m_port)
            except Exception:
                m_port = 9390
            if m_timeout.lower().strip() in ("inf", "infinite", "none"):
                m_timeout = None
            else:
                try:
                    m_timeout = int(m_timeout)
                except Exception:
                    m_timeout = None

            # Connect to the scanner.
            try:
                Logger.log_more_verbose(
                    "Connecting to OpenVAS server at %s:%d" % (m_host, m_port))
                m_scanner = VulnscanManager(
                    m_host, m_user, m_password, m_port, m_timeout)

            except VulnscanVersionError:
                Logger.log_error(
                    "Remote host is running an unsupported version of OpenVAS."
                    " Only OpenVAS 6 is currently supported.")

                # Set the openvas connection as down and remember it.
                self.state.put("connection_down", True)
                return

            except VulnscanException, e:
                t = format_exc()
                Logger.log_error("Error connecting to OpenVAS, aborting scan!")
                Logger.log_error_more_verbose(t)

                # Set the openvas connection as down and remember it.
                self.state.put("connection_down", True)
                return

            m_scan_id = None
            m_target_id = None
            try:
                # Launch the scanner.
                m_scan_id, m_target_id = m_scanner.launch_scan(
                    target=info.address,
                    profile=m_profile,
                    callback_end=partial(lambda x: x.set(), m_event),
                    callback_progress=OpenVASProgress(self.update_status)
                )
                Logger.log_more_verbose("OpenVAS task ID: %s" % m_scan_id)

                # Wait for completion.
                m_event.wait()

                # Get the scan results.
                m_openvas_results = m_scanner.get_results(m_scan_id)

            except Exception, e:
                t = format_exc()
                Logger.log_error_verbose(
                    "Error parsing OpenVAS results: %s" % str(e))
                Logger.log_error_more_verbose(t)
                return
Example #32
0
def Scan_Launch(scan_ip, project_id, sel_profile):

    with open(openvas_data, 'r+') as f:
        data = json.load(f)
        ov_user = data['open_vas_user']
        ov_pass = data['open_vas_pass']
        ov_ip = data['open_vas_ip']

        lod_ov_user = signing.loads(ov_user)
        lod_ov_pass = signing.loads(ov_pass)
        lod_ov_ip = signing.loads(ov_ip)

    scanner = VulnscanManager(str(lod_ov_ip), str(lod_ov_user), str(lod_ov_pass))
    time.sleep(5)
    profile = None
    if profile is None:
        profile = "Full and fast"
    else:
        profile = sel_profile
    scan_id, target_id = scanner.launch_scan(target=str(scan_ip), profile=str(profile))
    save_all = scan_save_db(scan_id=str(scan_id), project_id=str(project_id), scan_ip=str(scan_ip),
                            target_id=str(target_id))
    save_all.save()

    while int(scanner.get_progress(str(scan_id))) < 100.0:
        print 'Scan progress %: ' + str(scanner.get_progress(str(scan_id)))
        status = str(scanner.get_progress(str(scan_id)))
        scan_save_db.objects.filter(scan_id=scan_id).update(scan_status=status)
        time.sleep(5)

    global status
    status = "100"
    scan_save_db.objects.filter(scan_id=scan_id).update(scan_status=status)

    if profile == "Discovery":
        print "returning....."

    else:
        time.sleep(10)
        try:
            openvas_results = scanner.get_raw_xml(str(scan_id))
            vul_an_id(scan_id, openvas_results)
        except Exception as e:
            print e

        try:
            openvas_vul = ov_scan_result_db.objects.filter(scan_id=scan_id).order_by('scan_id')
            total_vul = len(openvas_vul)
            total_high = len(openvas_vul.filter(threat="High"))
            total_medium = len(openvas_vul.filter(threat="Medium"))
            total_low = len(openvas_vul.filter(threat="Low"))

            scan_save_db.objects.filter(scan_id=scan_id).update(total_vul=total_vul, high_total=total_high,
                                                                medium_total=total_medium, low_total=total_low)
        except Exception as e:
            print e

        try:
            for vul_id in ov_scan_result_db.objects.values_list('vul_id', flat=True).distinct():
                ov_scan_result_db.objects.filter(
                    pk=ov_scan_result_db.objects.filter(vul_id=vul_id).values_list('id', flat=True)[1:]).delete()
        except Exception as e:
            print e
Example #33
0
    def run(self, info):

        # Checks if connection was not set as down
        if not self.state.check("connection_down"):

            # Synchronization object to wait for completion.
            m_event = Event()

            # Get the config.
            m_user = Config.plugin_args["user"]
            m_password = Config.plugin_args["password"]
            m_host = Config.plugin_args["host"]
            m_port = Config.plugin_args["port"]
            m_timeout = Config.plugin_args["timeout"]
            m_profile = Config.plugin_args["profile"]

            # Sanitize the port and timeout.
            try:
                m_port = int(m_port)
            except Exception:
                m_port = 9390
            if m_timeout.lower().strip() in ("inf", "infinite", "none"):
                m_timeout = None
            else:
                try:
                    m_timeout = int(m_timeout)
                except Exception:
                    m_timeout = None

            # Connect to the scanner.
            try:
                Logger.log_more_verbose(
                    "Connecting to OpenVAS server at %s:%d" % (m_host, m_port))
                m_scanner = VulnscanManager(m_host, m_user, m_password, m_port,
                                            m_timeout)

            except VulnscanVersionError:
                Logger.log_error(
                    "Remote host is running an unsupported version of OpenVAS."
                    " Only OpenVAS 6 is currently supported.")

                # Set the openvas connection as down and remember it.
                self.state.put("connection_down", True)
                return

            except VulnscanException, e:
                t = format_exc()
                Logger.log_error("Error connecting to OpenVAS, aborting scan!")
                Logger.log_error_more_verbose(t)

                # Set the openvas connection as down and remember it.
                self.state.put("connection_down", True)
                return

            m_scan_id = None
            m_target_id = None
            try:
                # Launch the scanner.
                m_scan_id, m_target_id = m_scanner.launch_scan(
                    target=info.address,
                    profile=m_profile,
                    callback_end=partial(lambda x: x.set(), m_event),
                    callback_progress=OpenVASProgress(self.update_status))
                Logger.log_more_verbose("OpenVAS task ID: %s" % m_scan_id)

                # Wait for completion.
                m_event.wait()

                # Get the scan results.
                m_openvas_results = m_scanner.get_results(m_scan_id)

            except Exception, e:
                t = format_exc()
                Logger.log_error_verbose("Error parsing OpenVAS results: %s" %
                                         str(e))
                Logger.log_error_more_verbose(t)
                return
Example #34
0
def Scan_Launch(scan_ip, project_id, sel_profile):

    with open(openvas_data, 'r+') as f:
        data = json.load(f)
        ov_user = data['open_vas_user']
        ov_pass = data['open_vas_pass']
        ov_ip = data['open_vas_ip']

        lod_ov_user = signing.loads(ov_user)
        lod_ov_pass = signing.loads(ov_pass)
        lod_ov_ip = signing.loads(ov_ip)

    scanner = VulnscanManager(str(lod_ov_ip), str(lod_ov_user), str(lod_ov_pass))
    time.sleep(5)
    profile = None
    if profile is None:
        profile = "Full and fast"
    else:
        profile = sel_profile
    scan_id, target_id = scanner.launch_scan(target=str(scan_ip), profile=str(profile))
    date_time = datetime.datetime.now()
    save_all = scan_save_db(scan_id=str(scan_id), project_id=str(project_id), scan_ip=str(scan_ip),
                            target_id=str(target_id), date_time=date_time)
    save_all.save()

    while int(scanner.get_progress(str(scan_id))) < 100.0:
        print 'Scan progress %: ' + str(scanner.get_progress(str(scan_id)))
        status = str(scanner.get_progress(str(scan_id)))
        scan_save_db.objects.filter(scan_id=scan_id).update(scan_status=status)
        time.sleep(5)

    global status
    status = "100"
    scan_save_db.objects.filter(scan_id=scan_id).update(scan_status=status)

    if profile == "Discovery":
        print "returning....."

    else:
        time.sleep(10)
        try:
            openvas_results = scanner.get_raw_xml(str(scan_id))
            vul_an_id(scan_id, openvas_results)
        except Exception as e:
            print e

        try:
            openvas_vul = ov_scan_result_db.objects.filter(scan_id=scan_id).values('name', 'severity', 'vuln_color', 'threat', 'host', 'port').distinct()
            total_vul = len(openvas_vul)
            total_high = len(openvas_vul.filter(threat="High"))
            total_medium = len(openvas_vul.filter(threat="Medium"))
            total_low = len(openvas_vul.filter(threat="Low"))

            scan_save_db.objects.filter(scan_id=scan_id).update(total_vul=total_vul, high_total=total_high,
                                                                medium_total=total_medium, low_total=total_low)
        except Exception as e:
            print e

        try:
            for vul_id in ov_scan_result_db.objects.values_list('vul_id', flat=True).distinct():
                ov_scan_result_db.objects.filter(
                    pk=ov_scan_result_db.objects.filter(vul_id=vul_id).values_list('id', flat=True)[1:]).delete()
        except Exception as e:
            print e