Changeset 3927
- Timestamp:
- 01/07/09 14:33:07 (4 years ago)
- Location:
- trunk
- Files:
-
- 9 modified
-
. (modified) (1 prop)
-
umitCore/NmapParser.py (modified) (33 diffs)
-
umitCore/SearchResult.py (modified) (5 diffs)
-
umitGUI/DiffCompare.py (modified) (4 diffs)
-
umitGUI/ScanHostDetailsPage.py (modified) (4 diffs)
-
umitGUI/ScanNotebook.py (modified) (5 diffs)
-
umitGUI/SearchGUI.py (modified) (4 diffs)
-
umitGUI/radialnet/GraphBuilder.py (modified) (13 diffs)
-
umitGUI/radialnet/NodeNotebook.py (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk
- Property svnmerge-integrated changed from /branch/NetworkInventory:1-3848 to /branch/NetworkInventory:1-3848,3913-3919,3921-3926
-
trunk/umitCore/NmapParser.py
r3789 r3927 24 24 25 25 import re 26 import os27 import os.path28 26 import time 29 30 from types import StringTypes 27 import calendar 28 31 29 from xml.sax import make_parser 32 30 from xml.sax.handler import ContentHandler 33 31 from xml.sax.saxutils import XMLGenerator 34 from xml.sax.xmlreader import AttributesImpl as Attributes 35 36 from umitCore.I18N import _ 37 from umitCore.UmitLogging import log 38 39 import string 40 41 months = ('',_('January'), 42 _('February'), 43 _('March'), 44 _('April'), 45 _('May'), 46 _('June'), 47 _('July'), 48 _('August'), 49 _('September'), 50 _('October'), 51 _('November'), 52 _('December'),) 32 from xml.sax.xmlreader import AttributesImpl 33 34 UNKNOWN = "Unknown" 35 36 class AttributesImplDict(dict, AttributesImpl): 37 pass 53 38 54 39 class HostInfo(object): 55 def __init__(self, id): 56 self.id = id 57 40 def __init__(self, host_id): 41 self.osclass = [] 42 self.osmatch = [] 43 self.osfingerprint = [] 44 self.portused = [] 45 self.ports = [] 46 self.extraports = [] 47 self.tcpsequence = {} 48 self.hostnames = [] 49 self.tcptssequence = {} 50 self.ipidsequence = {} 51 self.trace = {'port': '', 'proto': '', 'hop': []} 52 self.status = {} 53 self.address = [] 54 self.hostscript = [] 55 56 # Umit extension 57 self.id = host_id 58 self.comment = '' 59 60 self.nmap_host = { 61 'status': {'state': '', 'reason': ''}, 62 'smurf': {'responses': ''}, 63 'times': {'to': '', 'srtt': '', 'rttvar': ''}, 64 'hostscript': [], 65 'distance': {'value': ''}, 66 'trace': {'port': '', 'proto': '', 'hop': []}, 67 'address': [], 68 'hostnames': [], 69 'ports': [], 70 'uptime': {'seconds': '', 'lastboot': ''}, 71 'tcpsequence': {'index': '', 'values': '', 'class': ''}, 72 'tcptssequence': {'values': '', 'class': ''}, 73 'ipidsequence': {'values': '', 'class': ''}, 74 'os': {} 75 } 76 58 77 # Host ID 59 78 def get_id(self): 60 if self._id != 0:79 try: 61 80 return self._id 62 raise Exception("Id was not set yet.") 63 64 def set_id(self, id): 65 if type(id) == type(0): 66 self._id = id 67 elif type(id) in StringTypes: 68 try: 69 self._id = int(id) 70 except: 71 raise Exception("Id invalid! Id must be an integer, \ 72 but received this instead: '%s'" % str(id)) 73 else: 74 raise Exception("Id invalid! Id must be an integer, but received \ 75 this instead: '%s'" % str(id)) 76 77 # TCP SEQUENCE 78 def set_tcpsequence(self, sequence): 79 if type(sequence) == type([]): 80 self._tcpsequence = sequence[0] 81 else: 82 self._tcpsequence = sequence 83 84 def get_tcpsequence(self): 85 if self._tcpsequence: 86 return self._tcpsequence 87 return {} 88 89 # TCPTS SEQUENCE 90 def set_tcptssequence(self, sequence): 91 if type(sequence) == type([]): 92 self._tcptssequence = sequence[0] 93 else: 94 self._tcptssequence = sequence 95 96 def get_tcptssequence(self): 97 if self._tcptssequence: 98 return self._tcptssequence 99 return {} 81 except AttributeError: 82 raise Exception("Id was not set yet.") 83 84 def set_id(self, host_id): 85 try: 86 self._id = int(host_id) 87 except (TypeError, ValueError): 88 raise Exception("Invalid id! It must represent an integer, " 89 "received %r" % host_id) 100 90 101 91 # VENDOR 102 92 def get_vendor(self): 103 try:return self._mac['vendor'] 104 except:return _('Unknown') 105 106 # IP ID SEQUENCE 107 def set_ipidsequence(self, sequence): 108 if type(sequence) == type([]): 109 self._ipidsequence = sequence[0] 110 else: 111 self._ipidsequence = sequence 112 113 def get_ipidsequence(self): 114 if self._ipidsequence: 115 return self._ipidsequence 116 return {} 117 118 # OS CLASSES 119 def set_osclasses(self, classes): 120 self._osclasses = classes 121 122 def get_osclasses(self): 123 return self._osclasses 124 125 # OS MATCHES 126 def set_osmatches(self, matches): 127 if type(matches) == type([]): 128 self._osmatches = matches 129 130 def get_osmatches(self): 131 if self._osmatches: 132 return self._osmatches 133 return [] 134 135 # OS MATCH 136 def set_osmatch(self, match): 137 if type(match) == type([]): 138 self._osmatch = match[0] 139 else: 140 self._osmatch = match 141 142 def get_osmatch(self): 143 if self._osmatch: 144 return self._osmatch 145 return {} 146 147 # OS FINGERPRINT 148 def set_osfingerprint(self, fingerprint): 149 if type(fingerprint) == type([]): 150 self._osfingerprint = fingerprint[0] 151 else: 152 self._osfingerprint = fingerprint 153 154 def get_osfingerprint(self): 155 if self._osfingerprint: 156 return self._osfingerprint 157 return {} 158 159 # PORTS USED 160 def set_ports_used(self, ports): 161 self._ports_used = ports 162 163 def get_ports_used(self): 164 return self._ports_used 165 93 vendor = UNKNOWN 94 for address in self.address: 95 if address['addrtype'] != 'mac': 96 continue 97 try: 98 vendor = address['vendor'] 99 break 100 except KeyError: 101 pass 102 103 return vendor 104 166 105 # TRACEROUTE 167 def set_trace(self, trace):168 self._trace = trace169 170 def get_trace(self):171 return self._trace172 173 def set_hops(self, hops):174 self._hops = hops175 176 def get_hops(self):177 return self._hops178 179 106 def get_hop_by_ttl(self, ttl): 180 for hop in self. _hops:181 if ttl == string.atoi(hop['ttl']):107 for hop in self.trace['hop']: 108 if ttl == int(hop['ttl']): 182 109 return hop 183 110 return None 111 184 112 def get_number_of_hops(self): 185 113 count = 0 186 for hop in self. _hops:187 if string.atoi(hop['ttl']) > count:188 count = string.atoi(hop['ttl'])114 for hop in self.trace['hop']: 115 if int(hop['ttl']) > count: 116 count = int(hop['ttl']) 189 117 return count 190 118 191 119 # UPTIME 192 120 # FORMAT: {"seconds":"", "lastboot":""} 193 121 def set_uptime(self, uptime): 194 122 self._uptime = uptime 195 123 196 124 def get_uptime(self): 197 125 if self._uptime: 198 126 return self._uptime 199 127 200 128 # Avoid empty dict return 201 return {"seconds":"", "lastboot":""} 202 203 # PORTS 204 def set_ports(self, port_list): 205 self._ports = port_list 206 207 def get_ports(self): 208 return self._ports 209 210 def set_extraports(self, port_list): 211 self._extraports = port_list 212 213 def get_extraports(self): 214 return self._extraports 215 216 # HOSTNAMES 217 def set_hostnames(self, hostname_list): 218 self._hostnames = hostname_list 219 220 def get_hostnames(self): 221 return self._hostnames 222 223 # IP 224 def set_ip_address(self, addr): 225 log.warning(_("umitCore.NmapParser.set_ip_address deprecated! Use \ 226 umitCore.NmapParser.set_ip instead.")) 227 self.set_ip(addr) 228 229 def get_ip_address(self): 230 log.warning(_("umitCore.NmapParser.get_ip_address deprecated! Use \ 231 umitCore.NmapParser.get_ip instead.")) 232 return self.get_ip() 233 234 def set_ip(self, addr): 235 self._ip = addr 236 237 def get_ip(self): 238 return self._ip 239 240 # COMMENT 241 def get_comment(self): 242 return self._comment 243 244 def set_comment(self, comment): 245 self._comment = comment 246 247 # MAC 248 def set_mac_address(self, addr): 249 log.warning(_("umitCore.NmapParser.set_mac_address deprecated! Use \ 250 umitCore.NmapParser.set_mac instead.")) 251 self.set_mac(addr) 252 253 def get_mac_address(self): 254 log.warning(_("umitCore.NmapParser.get_mac_address deprecated! Use \ 255 umitCore.NmapParser.get_mac instead.")) 256 return self.get_mac() 257 258 def set_mac(self, addr): 259 self._mac = addr 260 261 def get_mac(self): 262 return self._mac 263 264 # IPv6 265 def set_ipv6_address(self, addr): 266 log.warning(_("umitCore.NmapParser.set_ipv6_address deprecated! Use \ 267 umitCore.NmapParser.set_ipv6 instead.")) 268 self.set_ipv6(addr) 269 270 def get_ipv6_address(self): 271 log.warning(_("umitCore.NmapParser.get_ipv6_address deprecated! Use \ 272 umitCore.NmapParser.get_ipv6 instead.")) 273 return self.get_ipv6() 274 275 def set_ipv6(self, addr): 276 self._ipv6 = addr 277 278 def get_ipv6(self): 279 return self._ipv6 280 281 # STATE 282 def set_state(self, status): 283 self._state = status 284 285 def get_state(self): 286 return self._state 129 return {'seconds': '', 'lastboot': ''} 287 130 288 131 # HOSTNAME 289 132 def get_hostname(self): 290 hostname = '' 291 try: 292 hostname = self._hostnames[0]['hostname'] + ' ' 293 except: 294 pass 295 296 # FIXME: Check if i can return the 'addr' key directly from get_ip, 297 # get_ipv6 and get_mac 298 if self.ip: 299 hostname += self._ip['addr'] 300 elif self.ipv6: 301 hostname += self._ipv6['addr'] 302 elif self.mac: 303 hostname += self._mac['addr'] 304 else: 305 hostname = _('Unknown Host') 306 307 return hostname 133 hostname = [] 134 135 if self.hostnames: 136 try: 137 hostname.append(self.hostnames[0]['name']) 138 except KeyError: 139 pass 140 141 for addr in self.address: 142 if addr['addrtype'] == 'mac': 143 format = '(%s)' 144 else: 145 format = '%s' 146 hostname.append(format % addr['addr']) 147 148 return ' '.join(hostname) or UNKNOWN 308 149 309 150 def get_open_ports(self): 310 ports = self.get_ports() 311 open = 0 312 313 for i in ports: 314 port = i['port'] 315 for p in port: 316 if re.findall('open', p['port_state']): 317 open+=1 318 319 return open 320 151 open_count = 0 152 for port in self.ports: 153 if port['state'] == 'open': 154 open_count += 1 155 156 return open_count 157 321 158 def get_filtered_ports(self): 322 ports = self.get_ports() 323 extraports = self.get_extraports() 324 filtered = 0 325 326 for i in ports: 327 port = i['port'] 328 for p in port: 329 if re.findall('filtered', p['port_state']): 330 filtered+=1 331 for extra in extraports: 332 if extra["state"] == "filtered": 333 filtered += int(extra["count"]) 334 return filtered 335 159 filtered_count = 0 160 for port in self.ports: 161 if port['state'] == 'filtered': 162 filtered_count += 1 163 for extra in self.extraports: 164 if extra['state'] == 'filtered': 165 filtered_count += int(extra['count']) 166 167 return filtered_count 168 336 169 def get_closed_ports(self): 337 ports = self.get_ports() 338 extraports = self.get_extraports() 339 closed = 0 340 341 for i in ports: 342 port = i['port'] 343 for p in port: 344 if re.findall('closed', p['port_state']): 345 closed+=1 346 for extra in extraports: 347 if extra["state"] == "closed": 348 closed += int(extra["count"]) 349 return closed 350 170 closed_count = 0 171 for port in self.ports: 172 if port['state'] == 'closed': 173 closed_count += 1 174 for extra in self.extraports: 175 if extra['state'] == 'closed': 176 closed_count += int(extra['count']) 177 178 return closed_count 179 351 180 def get_scanned_ports(self): 352 ports = self.get_ports() 353 extraports = self.get_extraports() 354 scanned = 0 355 356 for i in ports: 357 port = i['port'] 358 for p in port: 359 scanned+=1 360 for extra in extraports: 361 scanned += int(extra["count"]) 181 scanned = len(self.ports) 182 for extra in self.extraports: 183 scanned += int(extra['count']) 184 362 185 return scanned 363 186 … … 365 188 services = [] 366 189 for port in self.ports: 367 for p in port.get("port", []): 368 services.append({"service_name":p.get("service_name", 369 _("unknown")), 370 "portid":p.get("portid", ""), 371 "service_version":p.get("service_version", 372 _("Unknown version")), 373 "service_product":p.get("service_product", ""), 374 "port_state":p.get("port_state", _("Unknown")), 375 "protocol":p.get("protocol", "")}) 190 services.append({ 191 'service_name': port.get('name', UNKNOWN), 192 'portid': port.get('portid', ''), 193 'service_version': port.get('version', UNKNOWN), 194 'service_product': port.get('product', ''), 195 'port_state': port.get('state', UNKNOWN), 196 'protocol': port.get('protocol', '')}) 376 197 return services 198 199 def _get_status_state(self): 200 return self.status.get('state', '') 201 202 def _get_type_address(self, addrtype): 203 for addr in self.address: 204 if addr['addrtype'] == addrtype: 205 return addr 206 207 def _get_ipv4(self): 208 return self._get_type_address('ipv4') 209 210 def _get_ipv6(self): 211 return self._get_type_address('ipv6') 212 213 def _get_mac(self): 214 return self._get_type_address('mac') 377 215 378 216 # Properties 379 217 id = property(get_id, set_id) 380 tcpsequence = property(get_tcpsequence, set_tcpsequence)381 osclasses = property(get_osclasses, set_osclasses)382 osmatch = property(get_osmatch, set_osmatch)383 osmatches = property(get_osmatches, set_osclasses)384 osfingerprint = property(get_osfingerprint, set_osfingerprint)385 ports = property(get_ports, set_ports)386 ports_used = property(get_ports_used, set_ports_used)387 extraports = property(get_extraports, set_extraports)388 218 uptime = property(get_uptime, set_uptime) 389 hostnames = property(get_hostnames, set_hostnames)390 tcptssequence = property(get_tcptssequence, set_tcptssequence)391 ipidsequence = property(get_ipidsequence, set_ipidsequence)392 ip = property(get_ip, set_ip)393 ipv6 = property(get_ipv6, set_ipv6)394 mac = property(get_mac, set_mac)395 state = property(get_state, set_state)396 comment = property(get_comment, set_comment)397 219 services = property(get_services) 398 trace = property(get_trace, set_trace) 399 hops = property(get_hops, set_hops) 400 401 402 _id = 0 403 _tcpsequence = {} 404 _osclasses = [] 405 _osmatch = [] 406 _osmatches = [] 407 _osfingerprint = {} 408 _ports = [] 409 _ports_used = [] 410 _extraports = [] 220 state = property(_get_status_state, doc="Get the host status state") 221 ip = property(_get_ipv4, doc="Return the first ipv4 address found") 222 ipv6 = property(_get_ipv6, doc="Return the first ipv6 address found") 223 mac = property(_get_mac, doc="Return the first mac address found") 224 411 225 _uptime = {} 412 _hostnames = []413 _tcptssequence = {}414 _ipidsequence = {}415 _ip = {}416 _ipv6 = {}417 _mac = {}418 _state = ''419 _comment = ''420 _trace = []421 _hops = []422 226 423 227 424 228 class ParserBasics(object): 425 229 def __init__ (self): 426 self.nmap = {'nmaprun':{},\ 427 'scaninfo':[],\ 428 'verbose':'',\ 429 'debugging':'',\ 430 'hosts':[],\ 431 'runstats':{}} 230 self.nmap = { 231 'nmaprun': {}, 232 'runstats': { 233 'finished': {}, 234 'hosts': {'up': '', 'down': '', 'total': ''} 235 }, 236 'verbose': {'level': ''}, 237 'debugging': {'level': ''}, 238 'scaninfo': [], 239 'taskbegin': [], 240 'taskprogress': [], 241 'taskend': [], 242 #'host': [], 243 'hosts': [] 244 } 432 245 433 246 def set_host_comment(self, host_id, comment): … … 437 250 break 438 251 else: 439 raise Exception("Comment could not be saved! Host not \440 found at NmapParser!")252 raise Exception("Comment could not be saved! Host not " 253 "found at NmapParser!") 441 254 442 255 def get_host_comment(self, host_id): … … 445 258 return host.comment 446 259 else: 447 raise Exception("Comment could not be saved! Host not \448 found at NmapParser!")260 raise Exception("Comment could not be saved! Host not " 261 "found at NmapParser!") 449 262 450 263 def get_profile(self): … … 453 266 def set_profile(self, profile): 454 267 self.nmap['nmaprun']['profile'] = profile 455 268 456 269 def get_profile_name(self): 457 270 return self.nmap['nmaprun'].get('profile_name', '') … … 459 272 def set_profile_name(self, name): 460 273 self.nmap['nmaprun']['profile_name'] = name 461 274 462 275 def get_profile_description(self): 463 276 return self.nmap['nmaprun'].get('description', '') … … 465 278 def set_profile_description(self, description): 466 279 self.nmap['nmaprun']['description'] = description 467 280 468 281 def get_profile_hint(self): 469 282 return self.nmap['nmaprun'].get('hint', '') … … 471 284 def set_profile_hint(self, hint): 472 285 self.nmap['nmaprun']['hint'] = hint 473 286 474 287 def get_profile_annotation(self): 475 288 return self.nmap['nmaprun'].get('annotation', '') … … 477 290 def set_profile_annotation(self, annotation): 478 291 self.nmap['nmaprun']['annotation'] = annotation 479 292 480 293 def get_profile_options(self): 481 294 options = self.nmap['nmaprun'].get('options', '') 482 if type(options) == type([]):295 if isinstance(options, list): 483 296 return ','.join(options) 484 elif type(options) in StringTypes:297 elif isinstance(options, basestring): 485 298 return options 486 299 487 300 def set_profile_options(self, options): 488 if (type(options) == type([])) or (type(options) in StringTypes):301 if isinstance(options, (list, basestring)): 489 302 self.nmap['nmaprun']['options'] = options 490 elif type(options) == type({}):303 elif isinstance(options, dict): 491 304 self.nmap['nmaprun']['options'] = options.keys() 492 305 else: 493 raise Exception("Profile option error: wrong argument format! \494 Need a string or list.")495 306 raise Exception("Profile option error: wrong argument format! " 307 "Need a string, list or dict.") 308 496 309 def get_target(self): 497 310 return self.nmap['nmaprun'].get('target', '') … … 505 318 def set_nmap_output(self, nmap_output): 506 319 self.nmap['nmaprun']['nmap_output'] = nmap_output 507 320 508 321 def get_debugging_level (self): 509 return self.nmap .get('debugging', '')322 return self.nmap['debugging'].get('level', '') 510 323 511 324 def set_debugging_level(self, level): 512 self.nmap['debugging'] = level 513 325 self.nmap['debugging']['level'] = level 326 327 def set_debugging(self, debug): 328 self.nmap['debugging'] = debug 329 514 330 def get_verbose_level (self): 515 return self.nmap .get('verbose', '')331 return self.nmap['verbose'].get('level', '') 516 332 517 333 def set_verbose_level(self, level): 518 self.nmap['verbose'] = level 519 334 self.nmap['verbose']['level'] = level 335 336 def set_verbose(self, verbose): 337 self.nmap['verbose'] = verbose 338 520 339 def get_scaninfo(self): 521 return self.nmap.get('scaninfo', '')340 return self.nmap.get('scaninfo', []) 522 341 523 342 def set_scaninfo(self, info): 524 343 self.nmap['scaninfo'] = info 525 526 def get_services_scanned (self): 527 if self._services_scanned == None: 528 return self._services_scanned 529 530 services = [] 531 for scan in self.nmap.get('scaninfo', []): 532 services.append(scan['services']) 533 534 self._services_scanned = ','.join(services) 535 return self._services_scanned 536 537 def set_services_scanned (self, services_scanned): 538 self._services_scanned = services_scanned 539 540 def get_nmap_command (self): 344 345 def append_scaninfo(self, info): 346 self.nmap['scaninfo'].append(info) 347 348 def get_services_scanned(self): 349 services = [scan['services'] for scan in self.nmap.get('scaninfo', [])] 350 return ','.join(services) 351 352 def get_nmap_command(self): 541 353 return self._verify_output_options(self.nmap['nmaprun'].get('args', '')) 542 354 … … 544 356 self.nmap['nmaprun']['args'] = self._verify_output_options(command) 545 357 546 def get_scan_type (self): 547 types = [] 548 for t in self.nmap.get('scaninfo', []): 549 types.append(t['type']) 550 return types 358 def get_scan_type(self): 359 return [stype['type'] for stype in self.nmap.get('scaninfo', [])] 551 360 552 361 def get_protocol (self): 553 protocols = [] 554 for proto in self.nmap.get('scaninfo', []): 555 protocols.append(proto['protocol']) 556 return protocols 557 558 def get_num_services (self): 559 if self._num_services == None: 560 return self._num_services 561 362 return [proto['protocol'] for proto in self.nmap.get('scaninfo', [])] 363 364 def get_num_services(self): 562 365 num = 0 563 for n in self.nmap.get('scaninfo', []): 564 num += int(n['numservices']) 565 566 self._num_services = num 567 return self._num_services 568 569 def set_num_services (self, num_services): 570 self._num_services = num_services 571 572 def get_date (self): 366 for sinfo in self.nmap.get('scaninfo', []): 367 num += int(sinfo['numservices']) 368 369 return num 370 371 def get_date(self): 573 372 epoch = int(self.nmap['nmaprun'].get('start', '0')) 574 return time.localtime (epoch)373 return time.localtime(epoch) 575 374 576 375 def get_start(self): … … 584 383 self.nmap['nmaprun']['start'] = date 585 384 else: 586 raise Exception("Wrong date format. Date should be saved \587 in epoch format!")588 385 raise Exception("Wrong date format. Date should be saved " 386 "in epoch format!") 387 589 388 def get_open_ports(self): 590 ports = 0 591 592 for h in self.nmap.get('hosts', []): 593 ports += h.get_open_ports() 594 595 return ports 389 open_count = 0 390 for host in self.nmap.get('hosts', []): 391 open_count += host.get_open_ports() 392 393 return open_count 596 394 597 395 def get_filtered_ports(self): 598 ports = 0 599 600 for h in self.nmap.get('hosts', []): 601 ports += h.get_filtered_ports() 602 603 604 log.debug(">>> EXTRAPORTS: %s" % str(self.list_extraports)) 605 606 return ports 396 filtered_count = 0 397 for host in self.nmap.get('hosts', []): 398 filtered_count += host.get_filtered_ports() 399 400 return filtered_count 607 401 608 402 def get_closed_ports(self): 609 ports = 0 610 611 for h in self.nmap['hosts']: 612 ports += h.get_closed_ports() 613 614 return ports 403 closed_count = 0 404 for host in self.nmap['hosts']: 405 closed_count += host.get_closed_ports() 406 407 return closed_count 615 408 616 409 def get_formated_date(self): 617 410 date = self.get_date() 618 return "%s %s, %s - %s:%s" % (months[date[1]],619 str(date[2]), 411 return '%s %s, %s - %s:%s' % (calendar.month_name[date[1]], 412 str(date[2]), 620 413 str(date[0]), 621 str(date[3]).zfill(2), 414 str(date[3]).zfill(2), 622 415 str(date[4]).zfill(2)) 623 416 624 def get_scanner (self):417 def get_scanner(self): 625 418 return self.nmap['nmaprun'].get('scanner', '') 626 419 627 420 def set_scanner(self, scanner): 628 421 self.nmap['nmaprun']['scanner'] = scanner 629 422 630 423 def get_scanner_version (self): 631 424 return self.nmap['nmaprun'].get('version', '') … … 634 427 self.nmap['nmaprun']['version'] = version 635 428 636 # IPv4 637 def get_ipv4_addresses (self): 638 log.warning(_("umitCore.NmapParser.get_ipv4_address deprecated! Use \ 639 umitCore.NmapParser.get_ipv4 instead.")) 640 return self.get_ipv4() 641 642 def get_ipv4(self): 429 ## Addresses 430 def get_type_addresses(self, addrtype): 643 431 addresses = [] 644 432 for host in self.nmap.get('hosts', []): 645 try: 646 addresses.append(host.get_ip().get('addr', '')) 647 except: 648 pass 649 433 for addr in host.address: 434 if addr['addrtype'] == addrtype: 435 addresses.append(addr['addr']) 650 436 return addresses 651 437 438 # IPv4 439 def get_ipv4_addresses(self): 440 return self.get_type_addresses('ipv4') 441 652 442 # MAC 653 def get_mac_addresses (self): 654 log.warning(_("umitCore.NmapParser.get_mac_address deprecated! Use \ 655 umitCore.NmapParser.get_mac instead.")) 656 return self.get_mac() 657 658 def get_mac(self): 659 addresses = [] 660 for host in self.nmap.get('hosts', []): 661 try: 662 addresses.append(host.get_mac().get('addr', '')) 663 except: 664 pass 665 666 return addresses 443 def get_mac_addresses(self): 444 return self.get_type_addresses('mac') 667 445 668 446 # IPv6 669 def get_ipv6_addresses (self): 670 log.warning(_("umitCore.NmapParser.get_ipv6_address deprecated! Use \ 671 umitCore.NmapParser.get_ipv6 instead.")) 672 return self.get_ipv6() 673 674 def get_ipv6(self): 675 addresses = [] 676 for host in self.nmap.get('hosts', []): 677 try: 678 addresses.append(host.get_ipv6().get('addr', '')) 679 except: 680 pass 681 682 return addresses 683 684 def get_hostnames (self): 447 def get_ipv6_addresses(self): 448 return self.get_type_addresses('ipv6') 449 450 451 def get_hostnames(self): 685 452 hostnames = [] 686 453 for host in self.nmap.get('hosts', []): 687 hostnames += host.get_hostnames()454 hostnames.extend(host.hostnames) 688 455 return hostnames 689 456 … … 691 458 ports = [] 692 459 for port in self.nmap.get('hosts', []): 693 ports.append(port. get_ports())694 460 ports.append(port.ports) 461 695 462 return ports 696 463 … … 698 465 return self.nmap.get('hosts', None) 699 466 700 # TRACEROUTE701 def get_hops(self):702 return self.nmap.get('hops', None)703 704 def get_trace(self):705 return self.nmap.get('trace', None)706 707 708 467 def get_runstats(self): 709 468 return self.nmap.get('runstats', None) … … 711 470 def set_runstats(self, stats): 712 471 self.nmap['runstats'] = stats 713 472 714 473 def get_hosts_down(self): 715 return int(self.nmap['runstats'].get('hosts_down', '0'))474 return self.nmap['runstats']['hosts'].get('down', 0) 716 475 717 476 def set_hosts_down(self, down): 718 self.nmap['runstats']['hosts _down'] = int(down)719 477 self.nmap['runstats']['hosts']['down'] = int(down) 478 720 479 def get_hosts_up(self): 721 return int(self.nmap['runstats'].get('hosts_up', '0'))480 return self.nmap['runstats']['hosts'].get('up', 0) 722 481 723 482 def set_hosts_up(self, up): 724 self.nmap['runstats']['hosts_up'] = int(up) 725 726 def get_hosts_scanned(self): 727 return int(self.nmap['runstats'].get('hosts_scanned', '0')) 728 729 def set_hosts_scanned(self, scanned): 730 self.nmap['runstats']['hosts_scanned'] = int(scanned) 731 732 def get_finish_time (self): 733 return time.localtime(int(self.nmap['runstats'].get('finished_time', 734 '0'))) 483 self.nmap['runstats']['hosts']['up'] = int(up) 484 485 def get_hosts_total(self): 486 return self.nmap['runstats']['hosts'].get('total', 0) 487 488 def set_hosts_total(self, scanned): 489 self.nmap['runstats']['hosts']['total'] = int(scanned) 490 491 def get_finish_time(self): 492 return self.nmap['runstats']['finished'].get('timestr', '') 735 493 736 494 def set_finish_time(self, finish): 737 self.nmap['runstats']['finished _time'] = int(finish)738 739 def get_finish_epoc _time(self):740 return int(self.nmap['runstats'].get('finished_time', '0'))741 742 def set_finish_epoc _time(self,time):743 self.nmap['runstats']['finished _time'] = time495 self.nmap['runstats']['finished']['timestr'] = finish 496 497 def get_finish_epoch_time(self): 498 return time.localtime(self.nmap['runstats']['finished'].get('time', 0)) 499 500 def set_finish_epoch_time(self, epoch_time): 501 self.nmap['runstats']['finished']['time'] = float(epoch_time) 744 502 745 503 def get_scan_name(self): 746 return self.nmap.get( "scan_name", "")504 return self.nmap.get('scan_name', '') 747 505 748 506 def set_scan_name(self, scan_name): 749 self.nmap[ "scan_name"] = scan_name750 507 self.nmap['scan_name'] = scan_name 508 751 509 def get_formated_finish_date(self): 752 date = self. get_finish_time()753 return "%s %s, %s - %s:%s" % (months[date[1]],754 str(date[2]), 510 date = self.finish_epoch_time 511 return '%s %s, %s - %s:%s' % (calendar.month_name[date[1]], 512 str(date[2]), 755 513 str(date[0]), 756 str(date[3]).zfill(2), 514 str(date[3]).zfill(2), 757 515 str(date[4]).zfill(2)) 758 516 759 def _verify_output_options (self, command):760 found = re.findall ('(-o[XGASN]{1}) {0,1}', command)761 splited = command.split (' ')762 517 def _verify_output_options(self, command): 518 found = re.findall('(-o[XGASN]{1}) {0,1}', command) 519 splited = command.split(' ') 520 763 521 if found: 764 522 for option in found: 765 523 pos = splited.index(option) 766 del (splited[pos+1])767 del (splited[pos])768 769 return ' '.join (splited)524 del splited[pos+1] 525 del splited[pos] 526 527 return ' '.join(splited) 770 528 771 529 def get_comments(self): … … 774 532 profile = property(get_profile, set_profile) 775 533 profile_name = property(get_profile_name, set_profile_name) 776 profile_description = property(get_profile_description, 534 profile_description = property(get_profile_description, 777 535 set_profile_description) 778 536 profile_hint = property(get_profile_hint, set_profile_hint) 779 profile_annotation = property(get_profile_annotation, 537 profile_annotation = property(get_profile_annotation, 780 538 set_profile_annotation) 781 539 profile_options = property(get_profile_options, set_profile_options) … … 785 543 verbose_level = property(get_verbose_level, set_verbose_level) 786 544 scaninfo = property(get_scaninfo, set_scaninfo) 787 services_scanned = property(get_services_scanned , set_services_scanned)545 services_scanned = property(get_services_scanned) 788 546 nmap_command = property(get_nmap_command, set_nmap_command) 789 547 scan_type = property(get_scan_type) 790 548 protocol = property(get_protocol) 791 num_services = property(get_num_services , set_num_services)549 num_services = property(get_num_services) 792 550 date = property(get_date, set_date) 793 551 open_ports = property(get_open_ports) … … 797 555 scanner = property(get_scanner, set_scanner) 798 556 scanner_version = property(get_scanner_version, set_scanner_version) 799 ipv4 = property(get_ipv4 )800 mac = property(get_mac )801 ipv6 = property(get_ipv6 )557 ipv4 = property(get_ipv4_addresses) 558 mac = property(get_mac_addresses) 559 ipv6 = property(get_ipv6_addresses) 802 560 hostnames = property(get_hostnames) 803 561 ports = property(get_ports) … … 806 564 hosts_down = property(get_hosts_down, set_hosts_down) 807 565 hosts_up = property(get_hosts_up, set_hosts_up) 808 hosts_ scanned = property(get_hosts_scanned, set_hosts_scanned)566 hosts_total = property(get_hosts_total, set_hosts_total) 809 567 finish_time = property(get_finish_time, set_finish_time) 810 finish_epoc _time = property(get_finish_epoc_time, set_finish_epoc_time)568 finish_epoch_time = property(get_finish_epoch_time, set_finish_epoch_time) 811 569 formated_finish_date = property(get_formated_finish_date) 812 570 comments = property(get_comments) 813 571 start = property(get_start, set_start) 814 572 scan_name = property(get_scan_name, set_scan_name) 815 trace = property(get_trace)816 hops = property(get_hops)817 818 _num_services = None819 _services_scanned = None820 573 821 574 … … 830 583 self.in_port = False 831 584 self.in_os = False 832 self.list_extraports = []833 834 # Creating a traceroute condition835 585 self.in_trace = False 836 586 587 # _tmp_port is used while parsing a port entity 588 self._tmp_port = {} 589 837 590 self.nmap_xml_file = None 838 591 self.unsaved = False … … 846 599 def parse(self): 847 600 if self.nmap_xml_file: 848 if type(self.nmap_xml_file) in StringTypes:601 if isinstance(self.nmap_xml_file, basestring): 849 602 self.parser.parse(self.nmap_xml_file) 850 603 else: 851 log.debug(">>> XML content: %s" % self.nmap_xml_file.read())852 604 self.nmap_xml_file.seek(0) 853 605 self.parser.parse(self.nmap_xml_file) … … 858 610 raise Exception("There's no file to be parsed!") 859 611 860 def _parse_nmaprun(self, attrs):861 run_tag = "nmaprun"862 863 self.nmap[run_tag]["nmap_output"] = attrs.get("nmap_output", "")864 self.nmap[run_tag]["profile"] = attrs.get("profile", "")865 self.nmap[run_tag]["profile_name"] = attrs.get("profile_name", "")866 self.nmap[run_tag]["hint"] = attrs.get("hint", "")867 self.nmap[run_tag]["description"] = attrs.get("description", "")868 self.nmap[run_tag]["annotation"] = attrs.get("annotation", "")869 self.nmap[run_tag]["options"] = attrs.get("options", "")870 self.nmap[run_tag]["target"] = attrs.get("target", "")871 self.nmap[run_tag]["start"] = attrs.get("start", "")872 self.nmap[run_tag]["args"] = attrs.get("args", "")873 self.nmap[run_tag]["scanner"] = attrs.get("scanner", "")874 self.nmap[run_tag]["version"] = attrs.get("version", "")875 self.nmap[run_tag]["xmloutputversion"] = attrs.get("xmloutputversion",876 "")877 self.nmap["scan_name"] = attrs.get("scan_name", "")878 879 def _parse_scaninfo(self, attrs):880 dic = {}881 882 dic["type"] = attrs.get("type", "")883 dic["protocol"] = attrs.get("protocol", "")884 dic["numservices"] = attrs.get("numservices", "")885 dic["services"] = attrs.get("services", "")886 887 self.nmap["scaninfo"].append(dic)888 889 def _parse_verbose(self, attrs):890 self.nmap["verbose"] = attrs.get("level", "")891 892 def _parse_debugging(self, attrs):893 self.nmap["debugging"] = attrs.get("level", "")894 895 def _parse_runstats_finished(self, attrs):896 self.nmap["runstats"]["finished_time"] = attrs.get("time", "")897 898 def _parse_runstats_hosts(self, attrs):899 self.nmap["runstats"]["hosts_up"] = attrs.get("up", "")900 self.nmap["runstats"]["hosts_down"] = attrs.get("down", "")901 self.nmap["runstats"]["hosts_scanned"] = attrs.get("total", "")902 903 612 def generate_id(self): 904 613 self.id_sequence += 1 905 614 return self.id_sequence 906 615 616 def _parse_nmaprun(self, attrs): 617 d = self.nmap['nmaprun'] 618 619 self.scanner = attrs.get('scanner', '') 620 self.scanner_version = attrs.get('version', '') 621 self.start = attrs.get('start', '') 622 self.nmap_command = attrs.get('args', '') 623 d['xmloutputversion'] = attrs.get('xmloutputversion', '') 624 625 # Umit extension 626 self.nmap_output = attrs.get('nmap_output', '') 627 self.profile = attrs.get('profile', '') 628 self.profile_name = attrs.get('profile_name', '') 629 self.profile_hint = attrs.get('hint', '') 630 self.profile_description = attrs.get('description', '') 631 self.profile_annotation = attrs.get('annotation', '') 632 self.profile_options = attrs.get('options', '') 633 self.target = attrs.get('target', '') 634 self.scan_name = attrs.get('scan_name', '') 635 636 def _parse_runstats_finished(self, attrs): 637 self.finish_time = attrs.get('timestr', '') 638 self.finish_epoch_time = attrs.get('time', 0) 639 640 def _parse_runstats_hosts(self, attrs): 641 self.hosts_up = attrs.get('up', 0) 642 self.hosts_down = attrs.get('down', 0) 643 self.hosts_total = attrs.get('total', 0) 644 907 645 def _parse_host(self, attrs): 908 646 self.host_info = HostInfo(self.generate_id()) 909 self.host_info.comment = attrs.get("comment", "") 910 911 def _parse_host_status(self, attrs): 912 self.host_info.set_state(attrs.get("state", "")) 913 914 def _parse_host_address(self, attrs): 915 address_attributes = {"type":attrs.get("addrtype", ""), 916 "vendor":attrs.get("vendor", ""), 917 "addr":attrs.get("addr", "")} 918 919 if address_attributes["type"] == "ipv4": 920 self.host_info.set_ip(address_attributes) 921 elif address_attributes["type"] == "ipv6": 922 self.host_info.set_ipv6(address_attributes) 923 elif address_attributes["type"] == "mac": 924 self.host_info.set_mac(address_attributes) 925 926 def _parse_host_hostname(self, attrs): 927 self.list_hostnames.append({"hostname":attrs.get("name", ""), 928 "hostname_type":attrs.get("type", "")}) 929 930 def _parse_host_extraports(self, attrs): 931 self.list_extraports.append({"state":attrs.get("state", ""), 932 "count":attrs.get("count", "")}) 933 934 def _parse_host_port(self, attrs): 935 self.dic_port = {"protocol":attrs.get("protocol", ""), 936 "portid":attrs.get("portid", "")} 937 938 def _parse_host_port_state(self, attrs): 939 self.dic_port["port_state"] = attrs.get("state", "") 940 941 def _parse_host_port_service(self, attrs): 942 self.dic_port["service_name"] = attrs.get("name", "") 943 self.dic_port["service_method"] = attrs.get("method", "") 944 self.dic_port["service_conf"] = attrs.get("conf", "") 945 self.dic_port["service_product"] = attrs.get("product", "") 946 self.dic_port["service_version"] = attrs.get("version", "") 947 self.dic_port["service_extrainfo"] = attrs.get("extrainfo", "") 948 949 def _parse_host_osmatch(self, attrs): 950 tmp = self._parsing(attrs, ['name', 'accuracy']) 951 if tmp != {} and self.list_osmatches == []: 952 self.host_info.set_osmatch(tmp) 953 elif tmp != {} and tmp.has_key('accuracy'): 954 last_osmatch = self.host_info.get_osmatch() 955 if last_osmatch.has_key('accuracy') and \ 956 tmp['accuracy'] > last_osmatch['accuracy']: 957 self.host_info.set_osmatch(tmp) 958 959 self.list_osmatches.append(tmp) 960 961 def _parse_host_portused(self, attrs): 962 self.list_portused.append(self._parsing(attrs, 963 ['state','proto','portid'])) 964 965 def _parse_host_osclass(self, attrs): 966 self.list_osclass.append(self._parsing(attrs, ['type', 967 'vendor', 968 'osfamily', 969 'osgen', 970 'accuracy'])) 971 972 def _parse_host_osfingerprint(self, attrs): 973 self.host_info.set_osfingerprint(self._parsing(attrs, ['fingerprint'])) 974 975 976 def _parsing(self, attrs, attrs_list): 977 # Returns a dict with the attributes of a given tag with the 978 # atributes names as keys and their respective values 979 dic = {} 980 for at in attrs_list: 981 dic[at] = attrs.get(at, "") 982 return dic 983 984 def _parse_host_uptime(self, attrs): 985 self.host_info.set_uptime(self._parsing(attrs, ["seconds", "lastboot"])) 986 987 988 def _parse_host_tcpsequence(self, attrs): 989 self.host_info.set_tcpsequence(self._parsing(attrs, ['index', 990 'class', 991 'difficulty', 992 'values'])) 993 994 def _parse_host_tcptssequence(self, attrs): 995 self.host_info.set_tcptssequence(self._parsing(attrs, ['class', 996 'values'])) 997 998 def _parse_host_ipidsequence(self, attrs): 999 self.host_info.set_ipidsequence(self._parsing(attrs, ['class', 1000 'values'])) 1001 def _parse_host_trace(self, attrs): 1002 self.host_info.set_trace(self._parsing(attrs, ['port', 'proto'])) 1003 1004 def _parse_host_trace_hop(self, attrs): 1005 tmp = self._parsing(attrs, ['ttl', 'rtt', 'ipaddr', 'host']) 1006 self.list_hop.append(tmp) 1007 1008 647 # Umit extension 648 self.host_info.comment = attrs.get('comment', '') 649 650 1009 651 def startElement(self, name, attrs): 1010 if name == "nmaprun": 652 attrs = AttributesImplDict(attrs) 653 654 if name == 'nmaprun': 1011 655 self._parse_nmaprun(attrs) 1012 elif name == "scaninfo": 1013 self._parse_scaninfo(attrs) 1014 elif name == "verbose": 1015 self._parse_verbose(attrs) 1016 elif name == "debugging": 1017 self._parse_debugging(attrs) 1018 elif name == "runstats": 656 657 elif name in ('verbose', 'debugging'): 658 getattr(self, 'set_%s' % name)(attrs.copy()) 659 660 elif name in ('scaninfo', 'taskbegin', 'taskprogress', 'taskend'): 661 self.nmap[name].append(attrs.copy()) 662 663 # Parse runstats 664 elif name == 'runstats': 1019 665 self.in_run_stats = True 1020 elif self.in_run_stats and name == "finished":666 elif self.in_run_stats and name == 'finished': 1021 667 self._parse_runstats_finished(attrs) 1022 elif self.in_run_stats and name == "hosts":668 elif self.in_run_stats and name == 'hosts': 1023 669 self._parse_runstats_hosts(attrs) 1024 elif name == "host": 670 671 # Parse hosts 672 elif name == 'host': 1025 673 self.in_host = True 1026 674 self._parse_host(attrs) 1027 self.list_ports = []1028 elif self.in_host and name == "status":1029 se lf._parse_host_status(attrs)1030 elif self.in_host and name == "address":1031 self._parse_host_address(attrs)1032 elif self.in_host and name == "hostnames":675 elif self.in_host and name in ('status', 'times', 'smurf', 'distance', 676 'uptime', 'tcpsequence', 'tcptssequence', 'ipidsequence'): 677 setattr(self.host_info, name, attrs.copy()) 678 elif self.in_host and name in ('address', 'hostscript'): 679 getattr(self.host_info, name).append(attrs.copy()) 680 elif self.in_host and name == 'hostnames': 1033 681 self.in_hostnames = True 1034 self.list_hostnames = [] 1035 elif self.in_host and self.in_hostnames and name == "hostname": 1036 self._parse_host_hostname(attrs) 1037 elif self.in_host and name == "ports": 1038 self.list_extraports = [] 1039 self.list_port = [] 682 elif self.in_host and self.in_hostnames and name == 'hostname': 683 self.host_info.hostnames.append(attrs.copy()) 684 # port 685 elif self.in_host and name == 'ports': 1040 686 self.in_ports = True 1041 elif self.in_host and self.in_ports and name == "extraports": 1042 self._parse_host_extraports(attrs) 1043 elif self.in_host and self.in_ports and name == "port": 687 elif self.in_host and self.in_ports and name == 'extraports': 688 # XXX extrareasons not supported yet 689 self.host_info.extraports.append(attrs.copy()) 690 elif self.in_host and self.in_ports and name == 'port': 1044 691 self.in_port = True 1045 self._ parse_host_port(attrs)692 self._tmp_port.update(attrs) 1046 693 elif self.in_host and self.in_ports and \ 1047 self.in_port and name == "state": 1048 self._parse_host_port_state(attrs) 1049 elif self.in_host and self.in_ports and \ 1050 self.in_port and name == "service": 1051 self._parse_host_port_service(attrs) 1052 elif self.in_host and name == "os": 694 self.in_port and name in ('state', 'service'): 695 self._tmp_port.update(attrs) 696 # os 697 elif self.in_host and name == 'os': 1053 698 self.in_os = True 1054 self.list_portused = [] 1055 self.list_osclass = [] 1056 self.list_osmatches = [] 1057 elif self.in_host and self.in_os and name == "osmatch": 1058 self._parse_host_osmatch(attrs) 1059 elif self.in_host and self.in_os and name == "portused": 1060 self._parse_host_portused(attrs) 1061 elif self.in_host and self.in_os and name == "osclass": 1062 self._parse_host_osclass(attrs) 1063 elif self.in_host and self.in_os and name == "osfingerprint": 1064 self._parse_host_osfingerprint(attrs) 1065 elif self.in_host and name == "uptime": 1066 self._parse_host_uptime(attrs) 1067 elif self.in_host and name == "tcpsequence": 1068 self._parse_host_tcpsequence(attrs) 1069 elif self.in_host and name == "tcptssequence": 1070 self._parse_host_tcptssequence(attrs) 1071 elif self.in_host and name == "ipidsequence": 1072 self._parse_host_ipidsequence(attrs) 1073 # Creating a traceroute condition 1074 elif self.in_host and name == "trace": 699 elif self.in_host and self.in_os and name in ('osmatch', 700 'osclass', 'portused', 'osfingerprint'): 701 getattr(self.host_info, name).append(attrs.copy()) 702 # trace 703 elif self.in_host and name == 'trace': 1075 704 self.in_trace = True 1076 self.list_hop = [] 1077 self._parse_host_trace(attrs) 1078 elif self.in_trace and name == "hop": 1079 self._parse_host_trace_hop(attrs) 705 self.host_info.trace.update(attrs.copy()) 706 elif self.in_trace and name == 'hop': 707 self.host_info.trace['hop'].append(attrs.copy()) 1080 708 1081 709 1082 710 def endElement(self, name): 1083 if name == "runstats":711 if name == 'runstats': 1084 712 self.in_run_stats = False 1085 elif name == "host":713 elif name == 'host': 1086 714 self.in_host = False 1087 self.host_info.set_ports(self.list_ports) 1088 self.nmap["hosts"].append(self.host_info) 1089 del(self.list_ports) 1090 elif self.in_host and name == "hostnames": 715 self.nmap['hosts'].append(self.host_info) 716 del self.host_info 717 elif self.in_host and name == 'hostnames': 1091 718 self.in_hostnames = False 1092 self.host_info.set_hostnames(self.list_hostnames) 1093 elif self.in_host and name == "ports": 719 elif self.in_host and name == 'ports': 1094 720 self.in_ports = False 1095 self.list_ports.append({"extraports":self.list_extraports, 1096 "port":self.list_port}) 1097 self.host_info.set_extraports(self.list_extraports) 1098 elif self.in_host and self.in_ports and name == "port": 721 elif self.in_host and self.in_ports and name == 'port': 1099 722 self.in_port = False 1100 self. list_port.append(self.dic_port)1101 del(self.dic_port)1102 elif self.in_host and self.in_os and name == "os":723 self.host_info.ports.append(self._tmp_port.copy()) 724 self._tmp_port.clear() 725 elif self.in_host and self.in_os and name == 'os': 1103 726 self.in_os = False 1104 self.host_info.set_ports_used(self.list_portused) 1105 self.host_info.set_osclasses(self.list_osclass) 1106 self.host_info.set_osmatches(self.list_osmatches) 1107 1108 del(self.list_portused) 1109 del(self.list_osclass) 1110 del(self.list_osmatches) 1111 1112 # Creating a traceroute condition 1113 elif self.in_host and name == "trace": 727 elif self.in_host and name == 'trace': 1114 728 self.in_trace = False 1115 self.host_info.set_hops(self.list_hop)1116 1117 del(self.list_hop)1118 729 1119 730 … … 1144 755 1145 756 # End of the xml file: 1146 self.write_parser.endElement( "nmaprun")757 self.write_parser.endElement('nmaprun') 1147 758 self.write_parser.endDocument() 1148 759 … … 1150 761 ################## 1151 762 # Runstats element 1152 self.write_parser.startElement( "runstats", Attributes(dict()))763 self.write_parser.startElement('runstats', AttributesImpl(dict())) 1153 764 1154 765 ## Finished element 1155 self.write_parser.startElement("finished", 1156 Attributes(dict(time = str(self.finish_epoc_time)))) 1157 self.write_parser.endElement("finished") 766 self.write_parser.startElement('finished', 767 AttributesImpl(dict( 768 time=str(time.mktime(self.finish_epoch_time)), 769 timestr=self.finish_time))) 770 self.write_parser.endElement('finished') 1158 771 1159 772 ## Hosts element 1160 self.write_parser.startElement("hosts", 1161 Attributes(dict(up = str(self.hosts_up), 1162 down = str(self.hosts_down), 1163 total = str(self.hosts_scanned)))) 1164 self.write_parser.endElement("hosts") 1165 1166 1167 self.write_parser.endElement("runstats") 773 self.write_parser.startElement('hosts', 774 AttributesImpl(dict( 775 up=str(self.hosts_up), 776 down=str(self.hosts_down), 777 total=str(self.hosts_total)))) 778 self.write_parser.endElement('hosts') 779 780 781 self.write_parser.endElement('runstats') 1168 782 # End of Runstats element 1169 783 ######################### … … 1172 786 for host in self.hosts: 1173 787 # Start host element 1174 self.write_parser.startElement( "host",1175 Attributes (dict(comment=host.comment)))788 self.write_parser.startElement('host', 789 AttributesImpl(dict(comment=host.comment))) 1176 790 1177 791 # Status element 1178 self.write_parser.startElement("status", 1179 Attributes(dict(state=host.state))) 1180 self.write_parser.endElement("status") 792 self.write_parser.startElement('status', 793 AttributesImpl(dict( 794 state=host.status['state']))) 795 self.write_parser.endElement('status') 1181 796 1182 797 1183 798 ################## 1184 799 # Address elements 1185 ## IPv4 1186 if type(host.ip) == type({}): 1187 ## Remove None value items 1188 self.__remove_none_keys(host.ip) 1189 self.write_parser.startElement("address", 1190 Attributes(dict(addr=host.ip.get("addr", ""), 1191 vendor=host.ip.get("vendor", ""), 1192 addrtype=host.ip.get("type", "")))) 1193 self.write_parser.endElement("address") 1194 1195 ## IPv6 1196 if type(host.ipv6) == type({}): 1197 self.write_parser.startElement("address", 1198 Attributes(dict(addr=host.ipv6.get("addr", ""), 1199 vendor=host.ipv6.get("vendor", ""), 1200 addrtype=host.ipv6.get("type", "")))) 1201 self.write_parser.endElement("address") 1202 1203 ## MAC 1204 if type(host.mac) == type({}): 1205 self.write_parser.startElement("address", 1206 Attributes(dict(addr=host.mac.get("addr", ""), 1207 vendor=host.mac.get("vendor", ""), 1208 addrtype=host.mac.get("type", "")))) 1209 self.write_parser.endElement("address") 800 for address in host.address: 801 self.__remove_none_keys(address) # XXX when is this needed ? 802 self.write_parser.startElement('address', 803 AttributesImpl(dict( 804 addr=address.get('addr', ''), 805 vendor=address.get('vendor', ''), 806 addrtype=address.get('addrtype', '')))) 807 self.write_parser.endElement('address') 1210 808 # End of Address elements 1211 809 ######################### … … 1214 812 ################### 1215 813 # Hostnames element 1216 self.write_parser.startElement( "hostnames", Attributes({}))814 self.write_parser.startElement('hostnames', AttributesImpl({})) 1217 815 1218 816 for hname in host.hostnames: 1219 817 if type(hname) == type({}): 1220 self.write_parser.startElement("hostname", 1221 Attributes(dict(name = hname.get("hostname", ""), 1222 type = hname.get("hostname_type", "")))) 1223 1224 self.write_parser.endElement("hostname") 1225 1226 self.write_parser.endElement("hostnames") 818 self.write_parser.startElement('hostname', 819 AttributesImpl( 820 dict(name = hname.get('hostname', ''), 821 type = hname.get('hostname_type', '')))) 822 823 self.write_parser.endElement('hostname') 824 825 self.write_parser.endElement('hostnames') 1227 826 # End of Hostnames element 1228 827 ########################## … … 1231 830 ############### 1232 831 # Ports element 1233 self.write_parser.startElement( "ports", Attributes({}))1234 1235 for ps in host.ports:1236 ## Extraports elements1237 for ext in ps["extraports"]:1238 if type(ext) == type({}):1239 self.__remove_none_keys(ext)1240 self.write_parser.startElement("extraports",1241 Attributes(dict(count = str(ext.get("count", "")),1242 state = ext.get("state", ""))))1243 self.write_parser.endElement("extraports") 1244 1245 ## Port elements1246 for p in ps["port"]:1247 if type(p) == type({}):1248 self.__remove_none_keys(p)1249 self.write_parser.startElement("port",1250 Attributes(dict(portid = p.get("portid", ""),1251 protocol = p.get("protocol", "")))) 1252 1253 ### Port state1254 self.write_parser.startElement("state",1255 Attributes(dict(state=p.get("port_state", ""))))1256 self.write_parser.endElement("state") 1257 1258 ### Port service info1259 self.write_parser.startElement("service",1260 Attributes(dict(conf = p.get("service_conf", ""),1261 method = p.get("service_method", ""),1262 name = p.get("service_name", ""),1263 product = p.get("service_product", ""),1264 version = p.get("service_version", ""),1265 extrainfo = p.get("service_extrainfo", "")\1266 )))1267 self.write_parser.endElement("service")1268 1269 self.write_parser.endElement("port")1270 1271 self.write_parser.endElement( "ports")832 self.write_parser.startElement('ports', AttributesImpl({})) 833 834 ## Extraports elements 835 for export in host.extraports: 836 self.__remove_none_keys(export) 837 self.write_parser.startElement('extraports', 838 AttributesImpl(dict( 839 count=str(export.get('count', '')), 840 state=export.get('state', '')))) 841 self.write_parser.endElement('extraports') 842 843 ## Port elements 844 for port in host.ports: 845 self.__remove_none_keys(port) 846 self.write_parser.startElement('port', 847 AttributesImpl(dict( 848 portid = port.get('portid', ''), 849 protocol = port.get('protocol', '')))) 850 851 ### Port state 852 self.write_parser.startElement('state', 853 AttributesImpl(dict(state=port.get('state', '')))) 854 self.write_parser.endElement('state') 855 856 ### Port service info 857 self.write_parser.startElement('service', 858 AttributesImpl(dict( 859 conf=port.get('conf', ''), 860 method=port.get('method', ''), 861 name=port.get('name', ''), 862 product=port.get('product', ''), 863 version=port.get('version', ''), 864 extrainfo=port.get('extrainfo', '') 865 ))) 866 self.write_parser.endElement('service') 867 868 self.write_parser.endElement('port') 869 870 self.write_parser.endElement('ports') 1272 871 # End of Ports element 1273 872 ###################### … … 1276 875 ############ 1277 876 # OS element 1278 self.write_parser.startElement( "os", Attributes({}))1279 877 self.write_parser.startElement('os', AttributesImpl({})) 878 1280 879 ## Ports used elements 1281 for pu in host.port s_used:880 for pu in host.portused: 1282 881 if type(pu) == type({}): 1283 882 self.__remove_none_keys(pu) 1284 self.write_parser.startElement( "portused",1285 Attributes (dict(state = pu.get("state", ""),1286 proto = pu.get( "proto", ""),1287 portid = pu.get( "portid", ""))))1288 self.write_parser.endElement( "portused")883 self.write_parser.startElement('portused', 884 AttributesImpl(dict(state = pu.get('state', ''), 885 proto = pu.get('proto', ''), 886 portid = pu.get('portid', '')))) 887 self.write_parser.endElement('portused') 1289 888 1290 889 ## Osclass elements 1291 for oc in host.osclass es:890 for oc in host.osclass: 1292 891 if type(oc) == type({}): 1293 892 self.__remove_none_keys(oc) 1294 self.write_parser.startElement( "osclass",1295 Attributes (dict(vendor = oc.get("vendor", ""),1296 osfamily = oc.get( "osfamily", ""),1297 type = oc.get( "type", ""),1298 osgen = oc.get( "osgen", ""),1299 accuracy = oc.get( "accuracy", ""))))1300 self.write_parser.endElement( "osclass")893 self.write_parser.startElement('osclass', 894 AttributesImpl(dict(vendor = oc.get('vendor', ''), 895 osfamily = oc.get('osfamily', ''), 896 type = oc.get('type', ''), 897 osgen = oc.get('osgen', ''), 898 accuracy = oc.get('accuracy', '')))) 899 self.write_parser.endElement('osclass') 1301 900 1302 901 ## Osmatch elements 1303 for om in host.osmatch es:902 for om in host.osmatch: 1304 903 if type(om) == type({}): 1305 904 self.__remove_none_keys(om) 1306 self.write_parser.startElement( "osmatch",1307 Attributes (dict(name = om.get("name", ""),1308 accuracy = om.get( "accuracy", ""))))1309 self.write_parser.endElement( "osmatch")1310 905 self.write_parser.startElement('osmatch', 906 AttributesImpl(dict(name = om.get('name', ''), 907 accuracy = om.get('accuracy', '')))) 908 self.write_parser.endElement('osmatch') 909 1311 910 ## Osfingerprint element 1312 911 if type(host.osfingerprint) == type({}): 1313 912 self.__remove_none_keys(host.osfingerprint) 1314 self.write_parser.startElement( "osfingerprint",1315 Attributes (dict(fingerprint = \1316 host.osfingerprint.get("fingerprint", ""))))1317 self.write_parser.endElement( "osfingerprint")1318 1319 1320 self.write_parser.endElement( "os")913 self.write_parser.startElement('osfingerprint', 914 AttributesImpl(dict( 915 fingerprint=host.osfingerprint.get('fingerprint', '')))) 916 self.write_parser.endElement('osfingerprint') 917 918 919 self.write_parser.endElement('os') 1321 920 # End of OS element 1322 921 ################### … … 1324 923 # Uptime element 1325 924 if type(host.uptime) == type({}): 1326 self.write_parser.startElement("uptime", 1327 Attributes(dict(seconds = host.uptime.get("seconds", ""), 1328 lastboot = host.uptime.get("lastboot", "")))) 1329 self.write_parser.endElement("uptime") 925 self.write_parser.startElement('uptime', 926 AttributesImpl(dict( 927 seconds = host.uptime.get('seconds', ''), 928 lastboot = host.uptime.get('lastboot', '')))) 929 self.write_parser.endElement('uptime') 1330 930 1331 931 ##################### … … 1334 934 # Cannot use dict() here, because of the 'class' attribute. 1335 935 if type(host.tcpsequence) == type({}): 1336 self.write_parser.startElement("tcpsequence", 1337 Attributes({"index":host.tcpsequence.get("index", ""), 1338 "class":host.tcpsequence.get("class", ""), 1339 "difficulty":host.tcpsequence.get("difficulty", ""), 1340 "values":host.tcpsequence.get("values", "")})) 1341 self.write_parser.endElement("tcpsequence") 936 self.write_parser.startElement('tcpsequence', 937 AttributesImpl({ 938 'index': host.tcpsequence.get('index', ''), 939 'class': host.tcpsequence.get('class', ''), 940 'difficulty': host.tcpsequence.get('difficulty', ''), 941 'values': host.tcpsequence.get('values', '')})) 942 self.write_parser.endElement('tcpsequence') 1342 943 1343 944 ## IP ID Sequence element 1344 945 if type(host.ipidsequence) == type({}): 1345 self.write_parser.startElement("ipidsequence", 1346 Attributes({"class":host.ipidsequence.get("class", ""), 1347 "values":host.ipidsequence.get("values", "")})) 1348 self.write_parser.endElement("ipidsequence") 946 self.write_parser.startElement('ipidsequence', 947 AttributesImpl({ 948 'class': host.ipidsequence.get('class', ''), 949 'values': host.ipidsequence.get('values', '')})) 950 self.write_parser.endElement('ipidsequence') 1349 951 1350 952 ## TCP TS Sequence element 1351 953 if type(host.tcptssequence) == type({}): 1352 self.write_parser.startElement("tcptssequence", 1353 Attributes({"class":host.tcptssequence.get("class", ""), 1354 "values":host.tcptssequence.get("values", "")})) 1355 self.write_parser.endElement("tcptssequence") 954 self.write_parser.startElement('tcptssequence', 955 AttributesImpl({ 956 'class': host.tcptssequence.get('class', ''), 957 'values': host.tcptssequence.get('values', '')})) 958 self.write_parser.endElement('tcptssequence') 1356 959 # End of sequences elements 1357 960 ########################### 1358 961 1359 962 # End host element 1360 self.write_parser.endElement( "host")963 self.write_parser.endElement('host') 1361 964 1362 965 def _write_debugging(self): 1363 self.write_parser.startElement( "debugging", Attributes(dict(966 self.write_parser.startElement('debugging', AttributesImpl(dict( 1364 967 level=str(self.debugging_level)))) 1365 self.write_parser.endElement( "debugging")968 self.write_parser.endElement('debugging') 1366 969 1367 970 def _write_verbose(self): 1368 self.write_parser.startElement( "verbose", Attributes(dict(971 self.write_parser.startElement('verbose', AttributesImpl(dict( 1369 972 level=str(self.verbose_level)))) 1370 self.write_parser.endElement( "verbose")973 self.write_parser.endElement('verbose') 1371 974 1372 975 def _write_scaninfo(self): 1373 976 for scan in self.scaninfo: 1374 977 if type(scan) == type({}): 1375 self.write_parser.startElement( "scaninfo",1376 Attributes (dict(type = scan.get("type", ""),1377 protocol = scan.get( "protocol", ""),1378 numservices = scan.get( "numservices", ""),1379 services = scan.get( "services", ""))))1380 self.write_parser.endElement( "scaninfo")978 self.write_parser.startElement('scaninfo', 979 AttributesImpl(dict(type = scan.get('type', ''), 980 protocol = scan.get('protocol', ''), 981 numservices = scan.get('numservices', ''), 982 services = scan.get('services', '')))) 983 self.write_parser.endElement('scaninfo') 1381 984 1382 985 def _write_nmaprun(self): 1383 self.write_parser.startElement( "nmaprun",1384 Attributes (dict(annotation = str(self.profile_annotation),986 self.write_parser.startElement('nmaprun', 987 AttributesImpl(dict(annotation = str(self.profile_annotation), 1385 988 args = str(self.nmap_command), 1386 989 description = str(self.profile_description), … … 1398 1001 1399 1002 def _verify_file(self, xml_file): 1400 if type(xml_file) in StringTypes: 1401 if os.access(os.path.split(xml_file)[0], os.W_OK): 1402 xml_file = open(xml_file, "w") 1003 # let errors be raised 1004 if isinstance(xml_file, basestring): 1005 xml_file = open(xml_file, 'w') 1006 xml_file.seek(0) 1007 return xml_file 1008 else: 1009 mode = xml_file.mode 1010 if mode in ('r+', 'w', 'w+'): 1403 1011 xml_file.seek(0) 1404 return xml_file 1405 else: 1406 raise Exception("Don't have write permissions to given path.") 1407 elif type(xml_file) not in StringTypes: 1408 try: 1409 mode = xml_file.mode 1410 if mode == "r+" or mode == "w" or mode == "w+": 1411 xml_file.seek(0) 1412 except IOError: 1413 raise Exception("File descriptor is not able to write!") 1414 else: 1415 return xml_file 1416 1012 return xml_file 1013 1417 1014 def __remove_none_keys(self, dic): 1418 pop_list = [] 1419 for k in dic: 1420 if dic[k] == None: 1421 pop_list.append(k) 1422 for k in pop_list: 1423 dic.pop(k) 1424 1425 def set_unsaved(self): 1426 self.unsaved = True 1015 for k in dic.keys(): 1016 if k is None: 1017 dic.pop(k) 1427 1018 1428 1019 def is_unsaved(self): 1429 1020 return self.unsaved 1021 1430 1022 1431 1023 def nmap_parser_sax(nmap_xml_file=""): 1432 1024 parser = make_parser() 1433 1025 nmap_parser = NmapParserSAX() 1434 1026 1435 1027 parser.setContentHandler(nmap_parser) 1436 1028 nmap_parser.set_parser(parser) … … 1440 1032 1441 1033 NmapParser = nmap_parser_sax 1442 1443 if __name__ == '__main__':1444 #file_to_parse = open("/home/adriano/umit/test/diff1.usr")1445 file_to_parse = \1446 "../../umit-within-radialnet/RadialNet2/share/sample/nmap_example.xml"1447 file_to_write = open("/tmp/teste_write.xml", "w+")1448 np = NmapParser(file_to_parse)1449 np.parse()1450 1451 from pprint import pprint1452 1453 1454 print "Trace:"1455 for host in np.nmap["hosts"]:1456 print host.get_osmatches()1457 print host.get_osmatch()1458 #print host.get_osfingerprint()1459 #number_of_hops = host.get_number_of_hops()1460 #for ttl in range(1, number_of_hops + 1):1461 #hop = host.get_hop_by_ttl(ttl)1462 #print hop1463 1464 print "Comment:",1465 pprint(np.nmap["hosts"][-1].comment)1466 #comment = property(get_comment, set_comment)1467 1468 print "TCP sequence:",1469 pprint(np.nmap["hosts"][-1].tcpsequence)1470 #tcpsequence = property(get_tcpsequence, set_tcpsequence)1471 1472 print "TCP TS sequence:",1473 pprint(np.nmap["hosts"][-1].tcptssequence)1474 #tcptssequence = property(get_tcptssequence, set_tcptssequence)1475 1476 print "IP ID sequence:",1477 pprint(np.nmap["hosts"][-1].ipidsequence)1478 #ipidsequence = property(get_ipidsequence, set_ipidsequence)1479 1480 print "Uptime:",1481 pprint(np.nmap["hosts"][-1].uptime)1482 #uptime = property(get_uptime, set_uptime)1483 1484 print "OS Match:",1485 pprint(np.nmap["hosts"][-1].osmatch)1486 #osmatch = property(get_osmatch, set_osmatch)1487 1488 print "Ports:",1489 pprint(np.nmap["hosts"][-1].ports)1490 #ports = property(get_ports, set_ports)1491 1492 print "Ports used:",1493 pprint(np.nmap["hosts"][-1].ports_used)1494 #ports_used = property(get_ports_used, set_ports_used)1495 1496 print "OS Class:",1497 pprint(np.nmap["hosts"][-1].osclasses)1498 #osclasses = property(get_osclasses, set_osclasses)1499 1500 print "Hostnames:",1501 pprint(np.nmap["hosts"][-1].hostnames)1502 #hostnames = property(get_hostnames, set_hostnames)1503 1504 print "IP:",1505 pprint(np.nmap["hosts"][-1].ip)1506 #ip = property(get_ip, set_ip)1507 1508 print "IPv6:",1509 pprint(np.nmap["hosts"][-1].ipv6)1510 #ipv6 = property(get_ipv6, set_ipv6)1511 1512 print "MAC:",1513 pprint(np.nmap["hosts"][-1].mac)1514 #mac = property(get_mac, set_mac)1515 1516 print "State:",1517 pprint(np.nmap["hosts"][-1].state)1518 #state = property(get_state, set_state)1519 np.write_xml("../hahah.xml")1520 1521 """1522 print "Profile:", np.profile1523 print "Profile name:", np.profile_name1524 print "Profile description:", np.profile_description1525 print "Profile hint:", np.profile_hint1526 print "Profile annotation:", np.profile_annotation1527 print "Profile options:", np.profile_options1528 print "Target:", np.target1529 print "Nmap output:", np.nmap_output1530 print "Debugging:", np.debugging_level1531 print "Verbose:", np.verbose_level1532 print "Scaninfo:", np.scaninfo1533 print "Services scanned:", np.services_scanned1534 print "Nmap command:", np.nmap_command1535 print "Scan type:", np.scan_type1536 print "Protocol:", np.protocol1537 print "Num services:", np.num_services1538 print "Date:", np.date1539 print "Open ports:", np.open_ports1540 print "Filtered ports:", np.filtered_ports1541 print "Closed ports:", np.closed_ports1542 print "Formated date:", np.formated_date1543 print "Scanner:", np.scanner1544 print "Scanner version:", np.scanner_version1545 print "IPv4:", np.ipv41546 print "MAC:", np.mac1547 print "IPv6:", np.ipv61548 print "Hostnames", np.hostnames1549 print "Ports:", np.ports1550 print "Hosts:", np.hosts1551 print "Runstats:", np.runstats1552 print "Hosts down:", np.hosts_down1553 print "Hosts up:", np.hosts_up1554 print "Hosts scanned:", np.hosts_scanned1555 print "Finished time:", np.finish_time1556 print "Finished epoc time:", np.finish_epoc_time1557 print "Formated finish date:", np.formated_finish_date1558 print "Comments:", np.comments1559 print "Start:", np.start1560 """ -
trunk/umitCore/SearchResult.py
r3177 r3927 159 159 ports = [] 160 160 161 for p in self.parsed_scan.ports: 162 for port_dic in p: 163 for portid in port_dic["port"]: 164 if self.port_open and portid["port_state"] == "open": 165 ports.append(portid["portid"]) 166 elif self.port_filtered and\ 167 portid["port_state"] == "filtered": 168 ports.append(portid["portid"]) 169 elif self.port_closed and portid["port_state"] == "closed": 170 ports.append(portid["portid"]) 171 elif not self.port_open and \ 172 not self.port_filtered and \ 173 not self.port_closed: 174 # In case every port state is False, add every port 175 ports.append(portid["portid"]) 161 for port in self.parsed_scan.ports: 162 if self.port_open and portid["state"] == "open": 163 ports.append(portid["portid"]) 164 elif self.port_filtered and portid["state"] == "filtered": 165 ports.append(portid["portid"]) 166 elif self.port_closed and portid["state"] == "closed": 167 ports.append(portid["portid"]) 168 elif not self.port_open and \ 169 not self.port_filtered and \ 170 not self.port_closed: 171 # In case every port state is False, add every port 172 ports.append(portid["portid"]) 176 173 177 174 for keyport in port: … … 187 184 188 185 services = [] 189 for first in self.parsed_scan.ports: 190 for ports in first: 191 for port in ports["port"]: 192 if port.has_key('service_name'): 193 if port["service_name"] not in services: 194 services.append(port["service_name"]) 195 186 for port in self.parsed_scan.ports: 187 if 'name' in port and port['name'] not in services: 188 services.append(port["service_name"]) 189 196 190 if service in services: 197 191 return True # Given service name matched current result … … 221 215 222 216 def match_osmatch(self, osmatch): 217 # XXX only the last osmatch is being used 223 218 log.debug("Match osmatch: %s" % osmatch) 224 219 if osmatch == "" or osmatch == "*": … … 226 221 227 222 for host in self.parsed_scan.hosts: 228 match = host.osmatch.get("name", False) 223 if not host.osmatch: 224 continue 225 match = host.osmatch[-1].get("name", False) 229 226 if match and fnmatch(match.lower(), "*%s*" % osmatch.lower()): 230 227 return True … … 342 339 parsed.set_xml_file(scan_file) 343 340 parsed.parse() 344 parsed.set_scan_name("Unsaved " + \ 345 sbook_page.get_tab_label()) 346 parsed.set_unsaved() 341 parsed.scan_name = "Unsaved " + sbook_page.get_tab_label() 342 parsed.unsaved = True 347 343 except: 348 344 pass -
trunk/umitGUI/DiffCompare.py
r3177 r3927 714 714 self.diff_it(parent, "", _("Hosts Down"), parsed1.hosts_down, 715 715 parsed2.hosts_down) 716 self.diff_it(parent, "", _("Hosts Scanned"), parsed1.hosts_ scanned,717 parsed2.hosts_ scanned)716 self.diff_it(parent, "", _("Hosts Scanned"), parsed1.hosts_total, 717 parsed2.hosts_total) 718 718 self.diff_it(parent, "", _("Finish date"), parsed1.formated_finish_date, 719 719 parsed2.formated_finish_date) … … 759 759 host.uptime.get("lastboot", ""), 760 760 host2.uptime.get("lastboot", "")) 761 # XXX Comparing only the last os match 762 h_match = {} 763 h2_match = {} 764 if host.osmatch: 765 h_match = host.osmatch[-1] 766 if host2.osmatch: 767 h2_match = host2.osmatch[-1] 761 768 self.diff_it(parent, 762 769 "", 763 770 _("OS Match"), 764 host.osmatch.get("name", ""), 765 host2.osmatch.get("name", "")) 766 767 768 host_ports = host.ports[:] 769 host2_ports = host2.ports[:] 770 for port in xrange(len(host_ports)): 771 # Making sure that extraports1 will get a sanity 772 # value to be processed 773 try: 774 extraports1 = host_ports[port].get("extraports", []) 775 except: 776 extraports1 = {} 777 else: 778 if len(extraports1) == 0: 779 extraports1 = {} 780 elif len(extraports1) == 1: 781 extraports1 = extraports1[0] 782 783 # Making sure that extraports2 will get a sanity 784 # value to be processed 785 try: 786 extraports2 = host2_ports[port].get("extraports", []) 787 except: 788 extraports2 = {} 789 else: 790 if len(extraports2) == 0: 791 extraports2 = {} 792 elif len(extraports2) == 1: 793 extraports2 = extraports2[0] 794 795 796 if extraports1 and extraports2: 797 self.add_extraports_diff(parent, 798 "", 799 extraports1, 800 extraports2) 801 elif extraports1 and not extraports2: 802 self.add_extraports_diff(parent, 803 "N", 804 extraports1, 805 extraports2) 806 elif not extraports1 and extraports2: 807 self.add_extraports_diff(parent, 808 "A", 809 extraports1, 810 extraports2) 811 812 section = _("Ports") 813 parent = self.append_parent(parent, section, "") 814 815 816 # Making sure that ports1 will get a sanity 817 # value to be processed 818 try: 819 ports1 = host_ports[port].get("port", []) 820 except: 821 ports1 = {} 822 else: 823 if len(ports1) == 0: 824 ports1 = {} 825 elif len(ports1) == 1: 826 ports1 = ports1[0] 827 828 # Making sure that ports2 will get a sanity 829 # value to be processed 830 try: 831 ports2 = host2_ports[port].get("port", []) 832 except: 833 ports2 = {} 834 else: 835 if len(ports2) == 0: 836 ports2 = [{}] 837 elif len(ports2) == 1: 838 ports2 = ports2[0] 839 840 if type(ports2)!= type([]): 841 ports2 = [ports2] 842 843 if type(ports1) != type([]): 844 ports1 = [ports1] 845 846 for p1 in ports1: 847 if not p1: 848 continue 849 850 p2 = [port2 for port2 in ports2 \ 851 if port2.get("portid", "a") == p1.get("portid", "b")] 852 853 if p2: # Removing found port 854 ports2.remove(p2[0]) 855 856 if p1 and p2: 857 self.add_port_diff(parent, "", p1, p2[0]) 858 elif p1 and not p2: 859 self.add_port_diff(parent, "N", p1, {}) 860 861 for p2 in ports2: # If there is something left... 862 self.add_port_diff(parent, "A", {}, p2) 863 771 h_match.get("name", ""), 772 h2_match.get("name", "")) 773 774 775 # XXX only the first extraports are being compared 776 extraports1 = {} 777 extraports2 = {} 778 if host.extraports: 779 extraports1 = host.extraports[0] 780 if host2.extraports: 781 extraports2 = host2.extraports[0] 782 783 if extraports1 and extraports2: 784 self.add_extraports_diff(parent, "", 785 extraports1, extraports2) 786 elif extraports1 and not extraports2: 787 self.add_extraports_diff(parent, "N", 788 extraports1, extraports2) 789 elif not extraports1 and extraports2: 790 self.add_extraports_diff(parent, "A", 791 extraports1, extraports2) 792 793 section = _("Ports") 794 parent = self.append_parent(parent, section, "") 795 796 ports1 = host.ports[:] 797 ports2 = host2.ports[:] 798 799 for p1 in ports1: 800 if not p1: 801 continue 802 803 p2 = [port2 for port2 in ports2 \ 804 if port2.get("portid", "a") == p1.get("portid", "b")] 805 806 if p2: # Removing found port 807 ports2.remove(p2[0]) 808 809 if p1 and p2: 810 self.add_port_diff(parent, "", p1, p2[0]) 811 elif p1 and not p2: 812 self.add_port_diff(parent, "N", p1, {}) 813 814 for p2 in ports2: # If there is something left... 815 self.add_port_diff(parent, "A", {}, p2) 816 864 817 865 818 def add_port_diff(self, port_parent, state, port1, port2): … … 873 826 874 827 self.diff_it(parent, "", 875 _("State"), port1.get(" port_state", ""),876 port2.get(" port_state", ""))828 _("State"), port1.get("state", ""), 829 port2.get("state", "")) 877 830 878 831 self.diff_it(parent, "", 879 _("Service Name"), port1.get(" service_name", ""),880 port2.get(" service_name", ""))832 _("Service Name"), port1.get("name", ""), 833 port2.get("name", "")) 881 834 882 835 self.diff_it(parent, "", 883 _("Product"), port1.get(" service_product", ""),884 port2.get(" service_product", ""))836 _("Product"), port1.get("product", ""), 837 port2.get("product", "")) 885 838 886 839 self.diff_it(parent, "", 887 _("Service Version"), port1.get(" service_version", ""),888 port2.get(" service_version", ""))840 _("Service Version"), port1.get("version", ""), 841 port2.get("version", "")) 889 842 890 843 self.diff_it(parent, "", … … 893 846 894 847 self.diff_it(parent, "", 895 _("Extra Info"), port1.get(" service_extrainfo", ""),896 port2.get(" service_extrainfo", ""))848 _("Extra Info"), port1.get("extrainfo", ""), 849 port2.get("extrainfo", "")) 897 850 898 851 self.diff_it(parent, "", 899 _("Service Conf"), port1.get(" service_conf", ""),900 port2.get(" service_conf", ""))852 _("Service Conf"), port1.get("conf", ""), 853 port2.get("conf", "")) 901 854 902 855 # Last parent status modification -
trunk/umitGUI/ScanHostDetailsPage.py
r3765 r3927 285 285 286 286 # Setting current os_match accuracy 287 if os_match. has_key("accuracy"):287 if os_match.get("accuracy", ''): 288 288 self.os_progress.set_fraction(float(os_match['accuracy']) / 100.0) 289 289 self.os_progress.set_text(os_match['accuracy'] + '%') … … 374 374 table.attach(HIGEntryLabel(o['vendor']),1,2,y1,y2) 375 375 table.attach(HIGEntryLabel(o['osfamily']),2,3,y1,y2) 376 table.attach(HIGEntryLabel(o ['osgen']),3,4,y1,y2)376 table.attach(HIGEntryLabel(o.get('osgen', '')),3,4,y1,y2) 377 377 378 378 progress = gtk.ProgressBar() … … 388 388 self.tcp_expander.set_use_markup(True) 389 389 table, hbox = self.create_table_hbox() 390 390 391 391 combo = gtk.combo_box_new_text() 392 392 for v in tcpseq['values'].split(','): 393 393 combo.append_text(v) 394 394 395 395 table.attach(HIGEntryLabel(_('Class:')),0,1,0,1) 396 table.attach(HIGEntryLabel(tcpseq ['class']),1,2,0,1)396 table.attach(HIGEntryLabel(tcpseq.get('class', '')),1,2,0,1) 397 397 398 398 table.attach(HIGEntryLabel(_('Difficulty:')),0,1,1,2) … … 431 431 self.tcpts_expander.set_use_markup(True) 432 432 table, hbox = self.create_table_hbox() 433 433 434 434 combo = gtk.combo_box_new_text() 435 436 for i in tcptsseq ['values'].split(','):435 436 for i in tcptsseq.get('values', '').split(','): 437 437 combo.append_text(i) 438 438 -
trunk/umitGUI/ScanNotebook.py
r3798 r3927 759 759 self.parsed = parsed_result 760 760 761 if int(self.parsed. get_hosts_up()):762 for host in self.parsed. get_hosts():761 if int(self.parsed.hosts_up): 762 for host in self.parsed.hosts: 763 763 hostname = host.get_hostname() 764 764 host_page = self.set_host_details(host) … … 956 956 957 957 run_details.set_general_info( 958 {'start': self.parsed. get_formated_date(),959 'finish': self.parsed. get_formated_finish_date(),960 'hosts_up': str(self.parsed. get_hosts_up()),961 'hosts_down': str(self.parsed. get_hosts_down()),962 'hosts_scanned': str(self.parsed. get_hosts_scanned()),963 'open_ports': str(self.parsed. get_open_ports()),964 'filtered_ports': str(self.parsed. get_filtered_ports()),965 'closed_ports': str(self.parsed. get_closed_ports())958 {'start': self.parsed.formated_date, 959 'finish': self.parsed.formated_finish_date, 960 'hosts_up': str(self.parsed.hosts_up), 961 'hosts_down': str(self.parsed.hosts_down), 962 'hosts_scanned': str(self.parsed.hosts_total), 963 'open_ports': str(self.parsed.open_ports), 964 'filtered_ports': str(self.parsed.filtered_ports), 965 'closed_ports': str(self.parsed.closed_ports) 966 966 }) 967 967 968 run_details.set_scan_infos(self.parsed. get_scaninfo())968 run_details.set_scan_infos(self.parsed.scaninfo) 969 969 970 970 return run_details … … 1115 1115 1116 1116 1117 self.comments[host.get_hostname()] = host. get_comment()1118 1119 uptime = host. get_uptime()1120 1121 host_details.set_host_status({'state':host. get_state(),1117 self.comments[host.get_hostname()] = host.comment 1118 1119 uptime = host.uptime 1120 1121 host_details.set_host_status({'state':host.status['state'], 1122 1122 'open':str(host.get_open_ports()), 1123 1123 'filtered':str(host.get_filtered_ports()), … … 1128 1128 1129 1129 1130 ipv4 = host.get_ip().get('addr', '') 1131 ipv6 = host.get_ipv6().get('addr', '') 1132 mac = host.get_mac().get('addr', '') 1133 1134 host_details.set_addresses({'ipv4': ipv4, 'ipv6': ipv6, 'mac': mac}) 1135 host_details.set_hostnames(host.get_hostnames()) 1136 1137 os = host.get_osmatch() 1138 if os: 1139 os['portsused'] = host.get_ports_used() 1140 os['osclass'] = host.get_osclasses() 1141 1142 host_details.set_os_list(host.get_osmatches(), os) 1143 host_details.set_tcpseq(host.get_tcpsequence()) 1144 host_details.set_ipseq(host.get_ipidsequence()) 1145 host_details.set_tcptsseq(host.get_tcptssequence()) 1130 ipv4, ipv6, mac = '', '', '' 1131 for addr in host.address: 1132 addrtype, addr = addr['addrtype'], addr['addr'] 1133 if addrtype == 'ipv4': 1134 ipv4 = addr 1135 elif addrtype == 'ipv6': 1136 ipv6 = addr 1137 elif addrtype == 'mac': 1138 mac = addr 1139 1140 host_details.set_addresses({'ipv4': ipv4, 'ipv6': ipv6, 'mac': mac}) 1141 host_details.set_hostnames(host.hostnames) 1142 1143 # XXX 1144 os = {} 1145 if host.osmatch: 1146 os = host.osmatch[0] 1147 os['portsused'] = host.portused 1148 os['osclass'] = host.osclass 1149 1150 host_details.set_os_list(host.osmatch, os) 1151 host_details.set_tcpseq(host.tcpsequence) 1152 host_details.set_ipseq(host.ipidsequence) 1153 host_details.set_tcptsseq(host.tcptssequence) 1146 1154 1147 1155 return host_page … … 1151 1159 host_page.switch_port_to_list_store() 1152 1160 1153 p = host.get_ports()1154 ports = []1155 for port in p:1156 ports += port['port']1157 1158 1161 host_page.clear_port_list() 1159 for p inports:1160 host_page.add_port([self.findout_service_icon(p ),1161 int(p .get('portid', '0')),1162 p .get('protocol', ''),1163 p .get('port_state', ''),1164 p .get('service_name', ''),1165 p .get('service_product', '')])1162 for port in host.ports: 1163 host_page.add_port([self.findout_service_icon(port), 1164 int(port.get('portid', '0')), 1165 port.get('protocol', ''), 1166 port.get('state', ''), 1167 port.get('name', ''), 1168 port.get('product', '')]) 1166 1169 1167 1170 def set_single_service_host(self, service): -
trunk/umitGUI/SearchGUI.py
r3177 r3927 23 23 import gtk 24 24 import os.path 25 import calendar 25 26 26 27 from higwidgets.higwindows import HIGWindow … … 38 39 from umitCore.I18N import _ 39 40 from umitCore.UmitLogging import log 40 from umitCore.NmapParser import months41 41 from umitCore.SearchResult import SearchDir, SearchDB, SearchTabs 42 42 from umitCore.UmitConf import SearchConfig … … 463 463 date = localtime(float(parsed_result.start)) 464 464 date_field = "%02d %s %04d" % (date[2], 465 months[date[1]][:3],465 calendar.month_name[date[1]][:3], 466 466 date[0]) 467 467 except ValueError: … … 733 733 def set_date(self, date): 734 734 # Localtime Format: (year, month, day) 735 self.date_button.set_label("%02d %s %04d" % (date[2], 736 months[date[1]][:3], 737 date[0])) 735 self.date_button.set_label("%02d %s %04d" % ( 736 date[2], calendar.month_name[date[1]][:3], date[0])) 738 737 self._date = date 739 738 -
trunk/umitGUI/radialnet/GraphBuilder.py
r3802 r3927 51 51 """ 52 52 """ 53 ports = host.get_ports() 54 number_ports = 0 55 for port in ports: 56 number_ports = number_ports + len(port['port']) 53 ports = host.ports 54 number_ports = len(host.ports) 57 55 58 56 node.set_info({'number_of_scanned_ports': number_ports}) … … 81 79 82 80 # getting address and hostnames 83 host_addresses = host.get_ip() 81 for addr in host.address: 82 if addr['addrtype'] == 'ipv4': 83 host_addresses = addr 84 break 85 else: 86 host_addresses = {} 84 87 if host_addresses.has_key('vendor') and host_addresses['vendor'] == '': 85 88 host_addresses['vendor'] = None 86 89 87 90 addresses = list() 88 91 … … 92 95 node.set_info({'ip': addresses[0]['addr']}) 93 96 94 host_hostnames = host.get_hostnames() 95 if len(host_hostnames) > 0: 96 97 host_hostnames = host.hostnames 98 if host_hostnames: 97 99 hostnames = list() 98 99 100 for host_hostname in host_hostnames: 100 101 hostname = dict() 102 103 hostname['name'] = host_hostname['hostname'] 104 hostname['type'] = host_hostname['hostname_type'] 105 106 hostnames.append(hostname) 101 hostnames.append(host_hostname.copy()) 102 107 103 node.set_info({'hostnames': hostnames}) 108 104 node.set_info({'hostname': hostnames[0]['name']}) … … 118 114 os = {} 119 115 120 host_osfingerprint = host. get_osfingerprint()121 host_osclasses = host. get_osclasses()122 host_osmatches = host. get_osmatches()123 host_portsused = host. get_ports_used()116 host_osfingerprint = host.osfingerprint 117 host_osclasses = host.osclass 118 host_osmatches = host.osmatch 119 host_portsused = host.portused 124 120 os['fingerprint'] = "" 125 if host_osfingerprint .has_key('fingerprint'):126 os['fingerprint'] = host_osfingerprint[ 'fingerprint']127 121 if host_osfingerprint and host_osfingerprint[0].has_key('fingerprint'): 122 os['fingerprint'] = host_osfingerprint[0]['fingerprint'] 123 128 124 if len(host_osclasses) > 0: 129 125 … … 152 148 os['classes'] = os_classes 153 149 if len(host_osmatches) > 0: 154 155 150 os_matches = [] 156 151 … … 159 154 os_match = {} 160 155 os_match['name'] = host_osmatch['name'] 161 if host_osmatch.has_key('accuracy') and \ 162 type(host_osmatch['accuracy']) != type(0): 156 if host_osmatch.get('accuracy', None): 163 157 os_match['accuracy'] = int(host_osmatch['accuracy']) 164 158 # TODO/FIXME: … … 181 175 node.set_info({'os': os}) 182 176 183 # getting sequences information184 host_tcpsequence = host. get_tcpsequence()185 host_ipidsequence = host. get_ipidsequence()186 host_tcptssequence = host. get_tcptssequence()177 # getting (copies of) sequences information 178 host_tcpsequence = host.tcpsequence.copy() 179 host_ipidsequence = host.ipidsequence.copy() 180 host_tcptssequence = host.tcptssequence.copy() 187 181 188 182 sequences = {} … … 201 195 202 196 if host_tcptssequence: 203 if host_tcptssequence.has_key('values') and \ 204 host_tcptssequence['values'] != None: 197 if host_tcptssequence.get('values', None): 205 198 host_tcptssequence['values'] = \ 206 host_tcptssequence['values'].split(',')199 host_tcptssequence['values'].split(',') 207 200 208 201 sequences['tcp_ts'] = host_tcptssequence 209 202 210 203 node.set_info({'sequences': sequences}) 211 204 … … 213 206 filtered = False 214 207 215 host_filtered = host. get_state()208 host_filtered = host.status['state'] 216 209 if host_filtered=="filtered": 217 210 filtered=True … … 225 218 226 219 # getting ports information 227 228 _host_ports = host.get_ports() 229 host_extraports = host.get_extraports() 230 ports = list() 231 232 host_ports = _host_ports[0] 233 for i in _host_ports: 234 if i.has_key('port'): 235 host_ports = i 236 break 237 238 if host_ports.has_key('port'): 239 host_port = host_ports['port'] 240 port = dict() 241 state = dict() 242 scripts = list() 243 service = dict() 244 245 for port in host_port: 246 #xml_service = xml_port.search_children('service', True, True) 247 248 port['id'] = int(port['portid']) 249 250 # TODO: Needs more fields in NmapParser 251 if port.has_key('port_state'): 252 state['state'] = port['port_state'] 253 254 # Remove useless (key, value) 255 port.pop('port_state') 256 257 # TODO: Not ready to integrate right now 258 #for script in xml_scripts: 259 260 #scripts.append(dict()) 261 262 #for key in script.get_keys(): 263 #scripts[-1][key] = script.get_attr(key) 264 265 # TODO: Get another information - NmapParser update need. 266 if port.has_key('service_name'): 267 service['name'] = port['service_name'] 268 service['version'] = port['service_version'] 269 service['method'] = port['service_method'] 270 service['product'] = port['service_product'] 271 service['extrainfo'] = port['service_extrainfo'] 272 service['conf'] = port['service_conf'] 273 274 # Remove useless (key, values) 275 port.pop('service_name') 276 port.pop('service_version') 277 port.pop('service_method') 278 port.pop('service_product') 279 port.pop('service_extrainfo') 280 port.pop('service_conf') 281 282 283 port['state'] = state 284 port['scripts'] = {} 285 port['service'] = service 286 220 221 host_ports = host.ports 222 host_extraports = host.extraports 223 ports = [] 224 225 for port in host_ports: 226 port = port.copy() # Do not change the original port 227 port['id'] = int(port['portid']) 228 # TODO: Not ready to integrate right now 229 #for script in xml_scripts: 230 #scripts.append(dict()) 231 #for key in script.get_keys(): 232 #scripts[-1][key] = script.get_attr(key) 233 234 service = {} 235 # TODO: Get another information - NmapParser update need. 236 if 'name' in port: 237 service['name'] = port.pop('name') 238 service['version'] = port.pop('version', '') 239 service['method'] = port.pop('method', '') 240 service['product'] = port.pop('product', '') 241 service['extrainfo'] = port.pop('extrainfo', '') 242 service['conf'] = port.pop('conf', '') 243 244 port['state'] = {'state': port['state']} 245 port['scripts'] = {} 246 port['service'] = service 247 287 248 ports.append(port) 288 249 289 250 node.set_info({'ports':ports}) 290 251 291 252 all_extraports = list() 292 253 #print host_extraports 293 254 for extraports in host_extraports: 294 255 extraports = extraports.copy() # Do not change the original eport 295 256 extraports['count'] = int(extraports['count']) 296 257 extraports['reason'] = list() … … 322 283 323 284 # getting traceroute information 324 trace = host. get_trace()325 if trace != []:326 327 host_hops = host.get_hops()285 trace = host.trace 286 if trace and trace['hop']: 287 288 host_hops = trace['hop'] 328 289 hops = [] 329 290 330 291 for host_hop in host_hops: 331 292 hop = host_hop 332 hostname = host_hop ['host']293 hostname = host_hop.get('host', None) 333 294 hop['ttl'] = int(hop['ttl']) 334 295 hop['hostname'] = (hostname, '')[hostname == None] 335 if hop.has_key('host'):296 if 'host' in hop: 336 297 hop.pop('host') 337 298 … … 362 323 # for each host in hosts just mount the graph 363 324 for host in hosts: 364 trace = host. get_trace()325 trace = host.trace 365 326 # if host has traceroute information mount graph 366 if trace != []:327 if trace and trace['hop']: 367 328 368 329 prev_node = nodes[0] 369 330 370 hops = host.get_hops()331 hops = trace['hop'] 371 332 ttls = [int(hop['ttl']) for hop in hops] 372 333 … … 423 384 for host in hosts: 424 385 425 ip = host.get_ip() 426 427 386 for addr in host.address: 387 if addr['addrtype'] == 'ipv4': 388 ip = addr 389 break 390 else: 391 ip = {} 428 392 for node in nodes: 429 393 if ip.has_key('addr') and ip['addr'] == node.get_info('ip'): -
trunk/umitGUI/radialnet/NodeNotebook.py
r3803 r3927 149 149 150 150 for port in self.__node.get_info('ports'): 151 color = SERVICE_COLORS[port['state']['state']] 151 pstate = port['state']['state'] 152 if pstate: 153 color = SERVICE_COLORS[port['state']['state']] 154 else: 155 # XXX port state is not always available 156 color = '#fff' 152 157 153 158 if port['service'].has_key('name'): … … 356 361 for address in self.__node.get_info('addresses'): 357 362 358 params = address[' type'], address['addr']363 params = address['addrtype'], address['addr'] 359 364 address_text = SYSTEM_ADDRESS_TEXT % params 360 365 361 if address ['vendor'] != None:366 if address.get('vendor', None): 362 367 address_text += " (%s)" % address['vendor'] 363 368 … … 433 438 tcp = sequences['tcp'] 434 439 435 tcp_class = HIGLabel(tcp ['class'])440 tcp_class = HIGLabel(tcp.get('class', '')) 436 441 tcp_class.set_selectable(True) 437 442 … … 451 456 tcp_note.set_line_wrap(False) 452 457 tcp_note.set_alignment(1.0, 0.5) 453 tcp_note.set_markup(TCP_SEQ_NOTE % (tcp['index'], tcp['difficulty'])) 458 if tcp['index']: 459 tcp_note.set_markup( 460 TCP_SEQ_NOTE % (tcp['index'], tcp['difficulty'])) 454 461 455 462 self.__sequences.attach(tcp_note, 0, 3, 4, 5) … … 480 487 self.__sequences.attach(tcp_ts_class, 1, 2, 3, 4) 481 488 482 if tcp_ts ['values'] !=None:489 if tcp_ts.get('values', None) is not None: 483 490 484 491 tcp_ts_values = gtk.combo_box_entry_new_text() … … 513 520 514 521 for os_match in os['matches']: 515 522 if 'accuracy' not in os_match: 523 # this may happen with older .usr 524 continue 516 525 self.__match_store.append([os_match['accuracy'], 517 526 os_match['name'],
