class NMAPSummary(object): def __init__(self): self.files = [] self.hosts = [] def __str__(self): return '%d unique hosts from %d files' % ( len(self.hosts), len(self.files) ) def find_host(self,host): for h in self.hosts: if same_target(host,h): return h return None def read(self,path): try: entry = NMAPXMLOutputFile(path) except ReportParserError,e: raise ReportParserError(e) self.files.append(entry) for h in entry.hosts: host = self.find_host(h) if not host: self.hosts.append(h) continue # Merge details of hosts host.merge(h) self.hosts.sort(lambda y,x: cmp( IPv4Address(y.addresses[0]['addr']).address, IPv4Address(x.addresses[0]['addr']).address, ))
def set_mode(self, mode, client_id=None, ipaddress=None, netmask=None, router=None): """ Set interface mode to given value. Each mode has it's specific allowed flags, see OS/X documentation or source code of this module. Mode can be: dhcp, manual or bootp """ if mode not in [ 'dhcp', 'manual', 'bootp']: raise ValueError('Invalid IPv4 configuratio mode') if mode == 'bootp': try: check_output(['networksetup', '-setbootp', self.name]) except CalledProcessError: raise NetworkSetupError('Error setting {0} to BOOTP mode'.format(self.name)) elif mode == 'dhcp': cmd = ['networksetup', '-setdhcp', self.name] if client_id is not None: cmd.append(client_id) try: check_output(cmd) except CalledProcessError: raise NetworkSetupError('Error setting {0} to DHCP mode'.format(self.name)) elif mode == 'manual': if ipaddress is None: raise NetworkSetupError('Manual mode requires valid ipaddress') else: try: ipaddress = IPv4Address(ipaddress) except ValueError: raise NetworkSetupError('Invalid IPv4 Address: {0}'.format(ipaddress)) if netmask is None: raise NetworkSetupError('Manual mode requires valid netmask') else: try: netmask = IPv4Address(netmask) except ValueError: raise NetworkSetupError('Invalid IPv4 netmask: {0}'.format(netmask)) if router is None: raise NetworkSetupError('Manual mode requires valid router') else: try: router = IPv4Address(router) except ValueError: raise NetworkSetupError('Invalid IPv4 Address: {0}'.format(router)) cmd = ['networksetup', '-setmanual', self.name, ipaddress.ipaddress, netmask.ipaddress, router.ipaddress ] try: return check_output(cmd) except CalledProcessError: raise NetworkSetupError('Error setting {0} to manual mode'.format(self.name))
def lookup_registration_id(self, address): try: address = IPv4Address(address) except ValueError: try: address = IPv6Address(address) except ValueError: raise ValueError('ERROR parsing address %s' % address) c = self.cursor c.execute("""SELECT registration,network FROM netblock""") for entry in c.fetchall(): try: network = IPv4Address(entry[1]) except ValueError: try: network = IPv6Address(enrty[1]) except ValueError: continue if type(network) != type(address): continue if network.hostInNetwork('%s' % address): return entry[0] return None
def parse_options(self, options): if self.family == 'inet': option = None while options: if option is None: option = options[0] elif option in ('netmask', 'broadcast'): try: value = IPv4Address(options[0]) except ValueError: raise NetworkError('Error parsing %s %s' % (option, value)) if option == 'netmask': self.address = IPv4Address(self.address, value) if option == 'broadcast': value = IPv4Address('%s/32' % value) self.broadcast = value option = None options = options[1:] if self.family == 'inet6': try: address, interface = self.address.split('%') self.address = IPv6Address(address) self.interface = interface except ValueError: self.address = IPv6Address(self.address) self.interface = None option = None while options: option = options[0] if option == 'prefixlen': self.address = IPv6Address( '%s/%s' % (self.address.address, options[1])) options = options[1:] elif option == 'scopeid': self.flags['scope_id'] = options[1] options = options[1:] elif option in ( 'deprecated', 'autoconf', 'temporary', ): if option not in self.flags.keys(): self.flags[option] = True options = options[1:]
def parse_ipv4_route_target(value): if value == 'default': return IPv4Address('0.0.0.0/0') elif value[:5] == 'link#': return value else: try: return EthernetMACAddress(value) except ValueError: pass return IPv4Address(value)
def __init__(self, reverse, data): self.reverse = reverse self.description = data['description']['$'] self.type = data['type']['$'] self.mask = int(data['cidrLength']['$']) if reverse.address_format == IPv4Address: self.start = IPv4Address(data['startAddress']['$']) self.end = IPv4Address(data['endAddress']['$']) self.network = IPv4Address('%s/%s' % (self.start.address, self.mask)) elif reverse.address_format == IPv6Address: self.start = IPv6Address(data['startAddress']['$']) self.end = IPv6Address(data['endAddress']['$']) self.network = IPv6Address('%s/%s' % (self.start.address, self.mask))
def __parse_info(self): """ Parser for the device details (called when attributes are requested) """ details = {} try: out = filter(lambda x: x!='', check_output( ['networksetup','-getinfo',self.name] ).split('\n')) except CalledProcessError: return details for l in out: if l == 'Manual Configuration': details['ipv4_mode'] = 'manual' continue if l == 'DHCP Configuration': details['ipv4_mode'] = 'dhcp' continue try: (key,value) = [x.strip() for x in l.split(':',1)] except ValueError: raise ValueError('Error parsing line: %s' % l) if value == 'none': value = None if key in ['Subnet mask','IP address','Router']: value = IPv4Address(value) if key == 'Ethernet Address': value = EthernetMACAddress(value) details[key] = value return details
def map_netblocks(self, values): c = self.cursor c.execute( """SELECT registration,network FROM netblock ORDER BY registration""" ) registration_netblock_map = {} for nb in c.fetchall(): if nb[0] not in registration_netblock_map: registration_netblock_map[nb[0]] = [] try: address = IPv4Address(nb[1]) except ValueError: try: address = IPv6Address(nb[1]) except ValueError: continue if address not in registration_netblock_map[nb[0]]: registration_netblock_map[nb[0]].append(address) for reg in registration_netblock_map: registration_netblock_map[reg].sort() for value in values: value['netblocks'] = [] if value['registration'] in registration_netblock_map: for nb in registration_netblock_map[value['registration']]: if nb.hostInNetwork(value['address']): value['netblocks'].append(nb) return values
def __parse_address__(self, address): try: return IPv4Address(address, oldformat=True) except ValueError: try: (address, interface) = address.split('%') (interface, mask) = interface.split('/') except ValueError: interface = None mask = None pass try: if mask is not None: return IPv6Address('/'.join([address, mask])) else: return IPv6Address(address) except IndexError: pass except ValueError: pass return None
def interface_ipv4_addresses(self, ifindex): if_oid = '.'.join([INTERFACE_IPV4_OID_PREFIX, str(ifindex)]) addresses = [] for (oid, value) in self.walk(if_oid).items(): try: addresses.append(IPv4Address(value)) except ValueError: raise ValueError('Invalid IPv4 address from OID %s' % oid) return addresses
def parse(self, line): """ Parse a configuration line for interface """ for inet_re in RE_INET_LINE: m = inet_re.match(line) if m: data = m.groupdict() data['addr_type'] = 'IPv4' data['address'] = IPv4Address(data['address']) data['netmask'] = IPv4Address(data['netmask']) if 'broadcast' in data: data['broadcast'] = IPv4Address(data['broadcast']) else: data['broadcast'] = None self['addresses'].append(data) return for inet6_re in RE_INET6_LINE: m = inet6_re.match(line) if m: data = m.groupdict() data['addr_type'] = 'IPv6' data['address'] = IPv6Address(data['address']) if 'prefix' in data: data['prefix'] = int(data['prefix']) self['addresses'].append(data) return try: key, value = line.strip().split(None, 1) if key == 'ether': value = EthernetMACAddress(value) except ValueError: try: key, value = line.strip().split('=', 1) except ValueError: raise ValueError('Error splitting line {0}'.format(line)) self[key] = value
def __init__(self, address): try: self.address = IPv4Address(address).ipaddress self.address_format = IPv4Address except ValueError: try: self.address = IPv6Address(address).address self.address_format = IPv6Address except ValueError: raise WhoisError('Unsupported address: %s' % address)
def __getattr__(self, attr): if attr == 'ipv4address': try: return IPv4Address(self.IP) except ValueError: raise ValueError('Invalid IP address: %s' % self.IP) try: return self[attr] except KeyError: pass raise AttributeError
def match(self, address): try: if self.network.addressInNetwork(IPv4Address(address).address): return self except ValueError: try: if self.network.addressInNetwork(IPv6Address(address).address): return self except ValueError: raise WhoisError('Error matching address %s to %s' % (address, self.network)) return None
def load_addresslist(self, values): self.log.debug('Loading address list %s' % values) addresses = [] for address in values: try: address = IPv4Address(address) except ValueError: try: address = IPv6Address(address) except ValueError: raise ReportParserError('Invalid address: %s' % address) addresses.append(address) return addresses
def __init__(self, resultset, host, data): SortedDict.__init__(self) self.resultset = resultset self.host = host self.__cached_properties__ = {} try: self.address = IPv4Address(host) except ValueError: self.address = None self.update(**data)
def __init__(self, report, node): self.report = report self.node = node self.address = node.get('name') self.properties = NessusTargetHostProperties( node.find('HostProperties')) if self.address is None: raise ReportParserError('No address') try: self.address = IPv4Address(self.address) except ValueError: try: self.address = IPv6Address(self.address) except ValueError: self.address = IPv4Address( socket.gethostbyaddr(self.address)[2][0]) try: for i in self.node.findall('ReportItem'): self.append(NessusTargetResultItem(self, i)) except ReportParserError, e: raise ReportParserError('Error parsing %s: %s' % (self.address, e))
def __init__(self, address, ethernet, interface, expires=None, ifscope=None): self.address = IPv4Address(address) try: self.ethernet = EthernetMACAddress(ethernet) except ValueError: self.ethernet = None self.interface = interface self.expires = expires self.ifscope = ifscope.strip('[]')
class IPRoutingTable(object): def __init__(self): self.ipv4 = [] self.ipv6 = [] try: output = check_output(['netstat', '-rn']) except CalledProcessError, emsg: raise RoutingTableError('Error checking netstat -rn output: %s' % emsg) for l in [x.strip() for x in output.split('\n') if x!='']: fields = l.split() if fields[0] == 'default': address = 'default' else: address = self.__parse_address__(fields[0]) if address is None: continue gateway = self.__parse_address__(fields[1]) if gateway is not None: gateway_type = 'route' else: if fields[1][:4]=='link': gateway = fields[1][4:].strip('#') gateway_type = 'link' else: try: gateway = EthernetMACAddress(fields[1]) gateway_type = 'host' except ValueError, emsg: raise RoutingTableError('Error parsing gateway %s: %s' % (fields[1], emsg)) if isinstance(address, IPv4Address) or isinstance(gateway, IPv4Address): if isinstance(address, basestring) and address=='default': address = IPv4Address('default') self.ipv4.append(IPv4Route(address, gateway, gateway_type, *fields[2:])) if isinstance(address, IPv6Address) or isinstance(gateway, IPv6Address): if isinstance(address, basestring) and address=='default': address = IPv6Address('default') self.ipv6.append(IPv6Route(address, gateway, gateway_type, *fields[2:]))
def add(self, rrname, address, expire): """ Adds a A or AAAA RR, associated address and cache expiry value to the server. """ rrname = rrname.upper() if rrname == 'A': try: self.ipv4_addresses.append( RootServerAddressEntry(self, IPv4Address(address), expire)) except ValueError: raise DNSError('Invalid IPv4 address: %s' % address) elif rrname == 'AAAA': try: self.ipv6_addresses.append( RootServerAddressEntry(self, IPv6Address('%s/128' % address), expire)) except ValueError: raise DNSError('Invalid IPv6 address: %s' % address) else: raise DNSError('Unsupported root server address RR: %s' % rrname)
def filter(self, **kwargs): matches = [] for route in self.ipv4 + self.ipv6: nomatch = False for k, v in kwargs.items(): if k=='gateway' and v=='default': if getattr(route, 'gateway_type')!='route': nomatch = True continue k = 'address' if isinstance(route.address, IPv4Address): v = IPv4Address('default') if isinstance(route.address, IPv6Address): v = IPv6Address('default') if not hasattr(route, k) or getattr(route, k)!=v: nomatch = True if not nomatch: matches.append(route) return matches
import errno import select from systematic.shell import Script, ScriptThread, ScriptError from systematic.log import Logger, LoggerError from seine.address import IPv4Address from seine.snmp import SNMPError # Valid SNMP data types SNMP_DATA_TYPE_MAP = { 'integer': lambda x: int(x), 'gauge': lambda x: int(x), 'counter': lambda x: int(x), 'timeticks': lambda x: int(x), 'string': lambda x: str(x), 'ipaddress': lambda x: str(IPv4Address(x)), 'objectid': lambda x: str(x), } class OIDPrefix(object): """Sortable OID base class Base class for OID prefixes, sortable in OID order """ def __init__(self, oid): self.log = Logger('snmp').default_stream self.oid = self.__format_oid__(oid) self.oid_string = self.__format_oid_string__(oid)