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 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 __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 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 __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 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 parse_ipv6_route_target(value): if value == 'default': return IPv6Address('0::/0') elif value[:5] == 'link#': return value else: try: return EthernetMACAddress(value) except ValueError: pass for fmt in IPV6_ROUTE_ADDRESS_FORMATS: m = fmt.match(value) if m: return IPv6Address('%s/%s' % ( m.groupdict()['address'], m.groupdict().get('bitmask', 128), )) break raise ValueError('Error parsing address from %s' % value)
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
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 __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 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
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)