scannotebook.py

来自「Ubuntu packages of security software。 相」· Python 代码 · 共 1,296 行 · 第 1/4 页

PY
1,296
字号
        log.debug(">>> XML output file that is going to be parsed: %s" % file_to_parse)                self.host_view_selection = self.scan_result.get_host_selection()        self.service_view_selection = self.scan_result.get_service_selection()                # All hosts details pages        self.host_pages = []        self.changes = True                self.host_view_selection.connect('changed', self.update_host_info)        self.service_view_selection.connect('changed', self.update_service_info)        self.scan_result.scan_host_view.clear_host_list()        self.hosts = {}        self.services = {}        # Removed and created again to avoid host duplication problems when making        # multiple scans inside the same scan tab        try: del(self.parsed)        except: pass        if file_to_parse:            self.parsed = NmapParser()            self.parsed.set_xml_file(file_to_parse)            try:                log.debug(">>> Start parsing...")                self.parsed.parse()                log.debug(">>> Successfully parsed!")            except:                log.debug(">>> An exception occourried during xml ouput parsing")                try:                    error = self.command_execution.get_error()                except:                    error = _('Unknown error!')                log.debug(">>> Error: '%s'" % error)                # Treat root exceptions more carefully!                if re.findall('[rR][oO0]{2}[tT]', error):                    need_root = HIGAlertDialog(\                            message_format=_('Root privileges are needed!'),\                            secondary_text=error)                    need_root.run()                    need_root.destroy()                else:                    unknown_problem = HIGAlertDialog(\                        message_format=_('An unexpected error occourried!'),\                        secondary_text=error)                    unknown_problem.run()                    unknown_problem.destroy()                return        elif parsed_result:            self.parsed = parsed_result        if int(self.parsed.get_hosts_up()):            for host in self.parsed.get_hosts():                hostname = host.get_hostname()                host_page = self.set_host_details(host)                list_states = ["open", "filtered", "open|filtered"]                for service in host.services:                    name = service["service_name"]                    state = service["port_state"]                    if state not in list_states:                        continue                                        if name not in self.services.keys():                        self.services[name] = {"hosts":[]}                    hs = {"host":host, "page":host_page, "hostname":hostname}                    hs.update(service)                                            self.services[name]["hosts"].append(hs)                                    self.hosts[hostname] = {'host':host, 'page':host_page}                                    host_details = self.hosts[hostname]['page'].host_details                host_info = self.hosts[hostname]['host']                                    try:                    host_details.set_os_image(get_os_logo(host.get_osmatch()['name']))                except:                    host_details.set_os_image(get_os_logo(''))                                    host_details.set_vulnerability_image(get_vulnerability_logo\                                                     (host_info.get_open_ports()))                                    icon = None                try:icon = get_os_icon(host.get_osmatch()['name'])                except:icon = get_os_icon('')                                    self.scan_result.scan_host_view.add_host({hostname:{'stock':icon,                                                                    'action':None}})                            # Select the first host found            self.host_view_selection.select_iter(self.scan_result.scan_host_view.\                                                 host_list.get_iter_root())        self.scan_result.scan_host_view.set_services(self.services.keys())                    try:            # And them, we update the nmap output! ;)            self.scan_result.scan_result_notebook.nmap_output.nmap_output.refresh_output()        except:            # Put saved nmap output            self.scan_result.scan_result_notebook.nmap_output.\                        nmap_output.text_buffer.\                        set_text('\n'.join(self.parsed.get_nmap_output().split('\\n')))                    target = self.parsed.get_target()                    if target != '':            self.toolbar.target_entry.child.set_text(target)                    profile_name = self.parsed.profile_name                    if profile_name != '':            profile = CommandProfile()            profile.add_profile(self.parsed.profile_name,                                command=self.parsed.profile,                                hint=self.parsed.profile_hint,                                options=self.parsed.profile_options,                                description=self.parsed.profile_description,                                annotation=self.parsed.profile_annotation)            del(profile)                            self.toolbar.profile_entry.update()                            self.toolbar.selected_profile = profile_name        else:            pass            # The line bellow seens to be useless            #self.command_toolbar.command = self.parsed.get_nmap_command()        self.collect_umit_info()        self.switch_scan_details(self.__set_scan_info())        self.check_fingerprints()    def check_fingerprints(self):        re_host = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")        re_os_fp = re.compile(r"(SInfo.*\);)")        re_service_fp = re.compile(r"(SF-Port.*\);)")        re_service_number = re.compile(r"SF-Port(\d+)")                nmap_output = self.parsed.nmap_output.split("\\n\\n")        fingerprints = {}        current_ip = None        for line in nmap_output:            match_host = re_host.search(line)            match_os = re_os_fp.search(line)            match_service = re_service_fp.search(line)                        if match_host:                current_ip = match_host.groups()[0]            if match_os:                if current_ip not in fingerprints.keys():                    fingerprints[current_ip] = {}                                fingerprints[current_ip]["os"] = match_os.groups()[0]            if match_service:                if current_ip not in fingerprints.keys():                    fingerprints[current_ip] = {}                fp = match_service.groups()[0]                                fingerprints[current_ip]["service"] = fp                #port = re_service_port.search(fp).groups()[0]                #fingerprints[current_ip]["service_port"] = port                #fingerprints[current_ip]["service_name"]                        """        for fp in fingerprints:            # We've found a new fp! Please contribute dialog            # If ok, show the form, sending the ip and fingerprint.        """        key_num = len(fingerprints.keys())        dialog_text = "%s. The submission and registration of \fingerprints are very important for you and the Nmap project! If you would like to contribute \to see your favorite network mapper recognizing those fingerprints in the future, choose the \Ok button, and a submission page will be open in your default web browser with instructions \about how to proceed on this registration."                if key_num == 1:            msg = _("Your network scan discovered an unknown fingerprint sent by the \host %s") % fingerprints.keys()[0]                        self.show_contribute_dialog(dialog_text % msg)        elif key_num > 1:            msg = _("Your network scan discovered several unknown fingerprints sent by the \follwoing hosts: ")            for i in fingerprints:                msg += "%s, " % i            msg = msg[:-2]            self.show_contribute_dialog(dialog_text % msg)    def show_contribute_dialog(self, dialog_text):        contribute_dialog = HIGAlertDialog(message_format=_("Unrecognized Services/OS \Fingerprints Found!"),                                           secondary_text=dialog_text,                                           type=gtk.MESSAGE_QUESTION,                                           buttons=gtk.BUTTONS_OK_CANCEL)        response = contribute_dialog.run()        contribute_dialog.destroy()        if response == gtk.RESPONSE_OK:            import webbrowser            webbrowser.open("http://www.insecure.org/nmap/submit/")            def __verify_comments_changes(self):        try:            for hostname in self.hosts:                if self.hosts[hostname]['page'].host_details.\                       get_comment() != self.comments[hostname]:                                        log.debug("Changes on comments")                    self.changes = True                    return True        except:            return False        def __set_scan_info(self):        self.clean_scan_details()        run_details = ScanRunDetailsPage()                run_details.set_command_info(\            {'command':self.parsed.get_nmap_command(),\             'version':self.parsed.get_scanner_version(),\             'verbose':self.parsed.get_verbose_level(),             'debug':self.parsed.get_debugging_level()})                run_details.set_general_info(\            {'start':self.parsed.get_formated_date(),\             'finish':self.parsed.get_formated_finish_date(),\             'hosts_up':str(self.parsed.get_hosts_up()),\             'hosts_down':str(self.parsed.get_hosts_down()),\             'hosts_scanned':str(self.parsed.get_hosts_scanned()),\             'open_ports':str(self.parsed.get_open_ports()),\             'filtered_ports':str(self.parsed.get_filtered_ports()),\             'closed_ports':str(self.parsed.get_closed_ports())})                     run_details.set_scan_infos(self.parsed.get_scaninfo())                return run_details        def update_host_info(self, widget):        self.scan_result.scan_result_notebook.port_mode()        model_host_list, selection = widget.get_selected_rows()        #host_objs = [self.hosts[model_host_list[i[0]][1]] for i in selection]        host_objs = []        for i in selection:            key = model_host_list[i[0]][1]            if self.hosts.has_key(key):                host_objs.append(self.hosts[key])        self.clean_host_details()                if len(host_objs) == 1:            self.set_single_host_port(host_objs[0]['host'])            self.switch_host_details(host_objs[0]['page'])        else:            self.set_multiple_host_port(host_objs)            self.switch_host_details(self.set_multiple_host_details(host_objs))        # Switch nmap output to show first host occourrence        try:            self.go_to_host(host_objs[0]['host'].get_hostname())        except IndexError:            pass    def update_service_info(self, widget):        self.scan_result.scan_result_notebook.host_mode()                model_service_list, selection = widget.get_selected_rows()        #serv_objs = [self.services[model_service_list[i[0]][0]] for i in selection]        serv_objs = []        for i in selection:            key = model_service_list[i[0]][0]            if self.services.has_key(key):                serv_objs.append(self.services[key])        # Removing current widgets from the host details page        self.clean_host_details()        if len(serv_objs) == 1:            self.set_single_service_host(serv_objs[0]['hosts'])            self.switch_host_details([page["page"] for page in serv_objs[0]['hosts']])        else:            servs = []            for s in serv_objs:                servs.append({"service_name":s["hosts"][0]["service_name"],                     "hosts":s["hosts"]})            self.set_multiple_service_host(servs)                        pages = []            for serv in [serv["hosts"] for serv in serv_objs]:                for h in serv:                    # Prevent from adding a host more then once                    if h["page"] not in pages:                        pages.append(h["page"])                        self.switch_host_details(pages)        # Change scan tab to "Ports/Hosts"        self.scan_result.scan_result_notebook.set_current_page(0)        def clean_host_details(self):        parent = self.scan_result.scan_result_notebook.host_details_vbox        children = parent.get_children()                for child in children:            parent.remove(child)                def clean_scan_details(self):        parent = self.scan_result.scan_result_notebook.scan_details_vbox

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?