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")
예제 #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)
예제 #3
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
예제 #4
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
예제 #5
0
파일: views.py 프로젝트: xarala221/scanapp
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})
예제 #6
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")
예제 #7
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")
예제 #8
0
파일: test.py 프로젝트: somecat1996/PRP
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)
예제 #9
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)
예제 #10
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()
예제 #11
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
예제 #12
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
예제 #13
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
예제 #14
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
예제 #15
0
def launch_scanner(server, username, password, target, profile, args):

    global pbar

    try:

        sem = Semaphore(0)

        # configure the scan
        print_loading("Connecting to openVAS\r")
        manager = VulnscanManager(server, username, password)
        stdout.write("\033[K")
        print_ok("Connected to openVAS\n")
        # print_loading("Launching Scan\r")
        stdout.flush()

        pbar = ChargingBar("Scanning", max=100, suffix='%(percent)d%%')
        pbar.next(n=0)
        # pbar.next()
        scan_id, target_id = manager.launch_scan(
            target,
            profile=profile,
            callback_end=partial(lambda x: x.release(), sem),
            callback_progress=print_status)

        # wait
        sem.acquire()
        sleep(2)
        pbar.finish()
        stdout.write("\033[A")
        stdout.write("\033[K")
        stdout.flush()
        # print()
        # stdout.write("\033[K")
        # stdout.flush()
        print_ok("Finished Scan\n")
        # print_loading("Getting Report ID")
        report_id = manager.get_report_id(scan_id)

        # check if it has been specified to save the file as an xml
        if args.save_xml or args.save_all:

            print_loading("Getting XML Report ")
            report = manager.get_report_xml(report_id)
            # print(report)

            stdout.write("\r\033[K")
            stdout.flush()
            print_ok("Loaded XML Report\n")

            name = args.save_xml
            if not name.lower().endswith(".xml"):
                name += ".xml"

            print_loading("Attempting to save XML Report ")
            with open(name, "wb") as f:
                f.write(
                    ElementTree.tostring(report,
                                         encoding="utf-8",
                                         method="xml"))

            stdout.write("\r\033[K")
            stdout.flush()
            print_ok("Saved XML Report as : {}\n".format(name))

        # check if it has been specified to save the file as an html
        if args.save_html or args.save_all:

            print_loading("Getting HTML Report ")
            report = manager.get_report_html(report_id)

            html_text = report.find("report").text
            if not html_text:
                html_text = report.find("report").find("report_format").tail

            stdout.write("\r\033[K")
            stdout.flush()
            print_ok("Loaded HTML Report\n")

            name = args.save_html
            if not name.lower().endswith(".html"):
                name += ".html"

            print_loading("Attempting to save HTML Report ")
            with open(name, "wb") as f:
                f.write(base64.b64decode(html_text))

            stdout.write("\r\033[K")
            stdout.flush()
            print_ok("Saved HTML Report as : {}\n".format(name))

        print_ok("Scan ID : {}\n".format(scan_id))
        print_ok("Target ID : {}\n".format(target_id))
        print_ok("Report ID : {}\n".format(report_id))

        # finished scan
        print_ok("Finished\n")

    except Exception as e:
        print_error(e)
        os._exit(-1)
예제 #16
0
파일: __init__.py 프로젝트: somecat1996/PRP
class ScannerManager:
    def __init__(self, host, user, password, port0=9390, timeout0=None):
        self.scanner_manager = VulnscanManager(host, user, password, port0,
                                               timeout0)
        self.scanner_list = {}
        self.user = user
        self.password = password

    def launch_scan(self, target, **kwargs):
        task_id, target_id = self.scanner_manager.launch_scan(target, **kwargs)
        name = kwargs.get("name", 'nunamed')
        self.scanner_list[task_id] = Scanner(target, target_id, name)
        return task_id

    def delete_scan(self, task_id):
        self.scanner_manager.delete_scan(task_id)
        del self.scanner_list[task_id]

    def get_results(self, task_id):
        if task_id in self.scanner_list:
            tmp = commands.getoutput("omp -u " + self.user + " -w " +
                                     self.password +
                                     " -iX '<get_results task_id=\"" +
                                     task_id + "\"/>'")
            results = re.findall("(<result.*?</result>)", tmp, re.S)
            for i in results:
                tmp = Result(i)
                if tmp.name == '':
                    continue
                else:
                    flag = True
                    for j in self.scanner_list[task_id].result:
                        if j.id == tmp.id:
                            flag = False
                    if flag:
                        self.scanner_list[task_id].result.append(tmp)
        else:
            return "Error: my_scanner doesn't exist."

    def display_result(self, task_id):
        results = self.scanner_list[task_id].result
        for i in results:
            print "id:%s" % i.id
            print "ownername:%s" % i.ownername
            print "comment:%s" % i.comment
            print "creation_time:%s" % i.creation_time
            print "modification_time:%s" % i.modification_time
            print "host:%s" % i.host
            print "port:%s" % i.port
            print "nvt_oid:%s" % i.nvt_oid
            print "name:%s" % i.name
            print "family:%s" % i.family
            print "summary:%s" % i.summary
            print "solution:%s" % i.solution
            print "scan_nvt_version:%s" % i.scan_nvt_version
            print "threat:%s" % i.threat
            print "severity:%s" % i.severity
            print "type:%s" % i.type
            print "qod:%s" % i.qod
            print "description:%s" % i.description
            print ''
예제 #17
0
파일: openvas.py 프로젝트: alexfrancow/iSOC
import sys
import argparse
from openvas_lib import VulnscanManager, VulnscanException

parser = argparse.ArgumentParser(
    description='Discover WordPress version with Machine Learning')
parser.add_argument('-i',
                    '--ip',
                    help='IP address to scan',
                    type=str,
                    action="store")
parser.add_argument('-m',
                    '--method',
                    help='Web scan or normal scan',
                    type=str,
                    action="store")
args = parser.parse_args()

if args.ip and args.method:
    try:
        scanner = VulnscanManager("192.168.1.13", "admin", "admin")
        scan_id, target_id = scanner.launch_scan(target=args.ip,
                                                 profile=args.method)

    except VulnscanException as e:
        print("Error:")
        print(e)

else:
    sys.exit()
예제 #18
0
파일: openvas.py 프로젝트: p4int3r/Tools
    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
예제 #19
0
def launch_scan(request):
    all_ip = scan_save_db.objects.all()

    scanner = VulnscanManager(scan_host, user, password)
    time.sleep(5)
    if request.method == 'POST':
        all_ip = scan_save_db.objects.all()
        scan_ip = request.POST.get('ip')
        profile = None
        if profile is None:
            profile = "Full and fast"
        else:
            profile = request.POST.get('scan_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),
                                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(
                    Q(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

    return render_to_response('vul_details.html', {'all_ip': all_ip})