Exemplo n.º 1
0
    def run_nmscan(pid: int):
        """
        When run, queries the process information by the id provided from the database.
        Runs the test and returns the ouput of the test to the database
        :param pid: Id of process to run
        :return: None
        """
        process = Process.query.filter_by(id=pid).first()
        scan = Scan.query.filter_by(id=process.scan_id).first()
        target_obj = Target.query.filter_by(id=scan.target_id).first()
        target = target_obj.domain
        nm = NmapProcess(targets=target, options="-sV -Pn -f --mtu 64 -p '*' -O")
        rc = nm.run_background()
        process.status = nm.state
        process.progress = nm.progress
        process.date_started = datetime.now().isoformat()
        scan.date_started = datetime.now().isoformat()
        db.session.commit()

        if nm.has_failed():
            process.output = "nmap scan failed: {0}".format(nm.stderr)
            db.session.commit()
            return 1

        while nm.is_running():
            print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nm.etc,
                                                                  nm.progress))
            if int(scan.progress) < int(float(nm.progress)):
                process.progress = int(float(nm.progress))
                scan.progress = int(float(nm.progress))
                db.session.commit()
            sleep(5)

        process.date_completed = datetime.now().isoformat()
        scan.date_completed = datetime.now().isoformat()
        if nm.has_failed():
            process.status = nm.state
            scan.status = nm.state
            process.output = str(nm.stderr)
        elif nm.is_successful():
            process.status = 3
            scan.status = 3
            scan.progress = 100
            nmap_full_output = json.dumps(cb.data(fromstring(str(nm.stdout))))
            nmap_output = Nmap.parse_nmap_output(nmap_full_output)
            if nmap_output:
                process.output = json.dumps(nmap_output)
                scan.output = json.dumps(nmap_output)
            else:
                scan.output = None
        db.session.commit()
Exemplo n.º 2
0
class NmapAdapter(ToolAdapter):
    @log(logger)
    def __init__(self, ip, commandline=None):
        if self.is_valid_ip(ip):
            self.ip = ip
        else:
            raise ValueError

        if commandline:
            self.commandline = commandline
        else:
            self.commandline = '-sV'
        self.nmproc = NmapProcess(self.ip, self.commandline)

    @log(logger)
    def start(self):
        logger.info('nmap started on IP {}'.format(self.ip))
        rc = self.nmproc.run_background()
        if self.nmproc.stderr:
            logger.critical('nmap has failed: {0}'.format(self.nmproc.stderr))
            print('nmap scan has failed:', self.nmproc.stderr)

    def status(self):
        if self.nmproc.is_running():
            return 'running: {0}%'.format(self.nmproc.progress)
        else:
            if self.nmproc.has_failed():
                return 'failed'
            elif self.nmproc.is_successful():
                return 'finished (successfully)'
            else:
                return 'stopped'

    @log(logger)
    def stop(self):
        if self.nmproc.is_running():
            self.nmproc.stop()

    @log(logger)
    def get_result_json(self):
        report = None
        try:
            report = NmapParser.parse(self.nmproc.stdout)
        except NmapParserException as e:
            logger.critical("Exception raised while parsing scan: {0}".format(
                e.msg))
            print("Exception raised while parsing scan: {0}".format(e.msg))
            return None
        report_dict = {}
        report_dict['starttime'] = report.started
        report_dict['endtime'] = report.endtime
        report_dict['host'] = self.ip
        host = report.hosts[0]
        report_dict['hoststatus'] = host.status
        services = []
        for serv in host.services:
            service = {}
            service['port'] = serv.port
            service['protocol'] = serv.protocol
            service['state'] = serv.state
            service['service'] = serv.service
            if len(serv.banner):
                service['banner'] = serv.banner
            if len(serv.cpelist):
                cpe = {}
                cpe['part'] = serv.cpelist[0].get_part()
                cpe['vendor'] = serv.cpelist[0].get_vendor()
                cpe['product'] = serv.cpelist[0].get_product()
                cpe['version'] = serv.cpelist[0].get_version()
                cpe['update'] = serv.cpelist[0].get_update()
                cpe['edition'] = serv.cpelist[0].get_edition()
                cpe['language'] = serv.cpelist[0].get_language()
                service['cpe'] = cpe
            services.append(service)
        report_dict['services'] = services
        json_data = dumps(report_dict)
        return json_data