Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_iprange_invalid_len_and_alternative():
range1 = IPRange(IPAddress("::0"), IPAddress(_sys_maxint, 6))
with pytest.raises(IndexError):
len(range1)
range2 = IPRange(IPAddress("::0"), IPAddress(_sys_maxint - 1, 6))
assert len(range2) == _sys_maxint
def subAllocateIPv6(self,iplist):
print "IPv6 Request: " + repr(iplist)
# Note that the following may raise an exception!
allocated_pairs = generic_allocate(self.ipv6ResourcesFree,
[], # used list not recorded
iplist,
range_not_prefix=True)
allocated_blocks = [IPRange(IPAddress(x[0],version=6), \
IPAddress(x[1],version=6)) \
for x in allocated_pairs]
# FIXME: maxlength not supported
allocated_blocks.sort()
return allocated_blocks
def subAllocateAS(self, asList):
}
"""
if not isinstance(static_ips, collections.Mapping):
return ["The static IPs input must be a dictionary."]
if not isinstance(pools, collections.Mapping):
return ["The Pools input must be a dictionary."]
errors = []
pool_ranges = []
for pool_name, ranges in six.iteritems(pools):
if not isinstance(ranges, collections.Iterable):
errors.append("The IP ranges in {} must form a list."
.format(pool_name))
continue
for allocation_range in ranges:
try:
ip_range = netaddr.IPRange(allocation_range['start'],
allocation_range['end'])
except Exception:
errors.append("Invalid format of the IP range in {}: {}"
.format(pool_name, allocation_range))
continue
pool_ranges.append((pool_name, ip_range))
for role, services in six.iteritems(static_ips):
if not isinstance(services, collections.Mapping):
errors.append("The {} must be a dictionary.".format(role))
continue
for service, ips in six.iteritems(services):
if not isinstance(ips, collections.Iterable):
errors.append("The {}->{} must be an array."
.format(role, service))
continue
def get_ip_subnets(ip):
"""Get a list of subnets contained in the specified subnet.
:type ip: str
:param ip: The IP that subnets will be returned for.
:list[netaddr.IPNetwork]
"""
ip = ip.strip().replace(" ", "")
if "/" in ip:
return [netaddr.IPNetwork(ip)]
elif "-" in ip:
start_ip, end_ip = ip.split("-")
ip_set_object = netaddr.IPSet(netaddr.IPRange(start_ip, end_ip, flags=netaddr.ZEROFILL))
return [address for address in ip_set_object.iter_cidrs()]
else:
if is_ipv4_string(ip):
return [netaddr.IPNetwork(ip)]
else:
raise ValueError("Invalid IP string '{}'.".format(ip))
if not isinstance(filedata, collections.Mapping):
return ["The `filedata` argument must be a dictionary."]
if not isinstance(pools, collections.Mapping):
return ["The `pools` argument must be a dictionary."]
errors = []
for poolitem, pooldata in six.iteritems(pools):
pool_objs = []
if not isinstance(pooldata, collections.Iterable):
errors.append('The IP ranges in {} must form a list.'
.format(poolitem))
continue
# Check IP range format
for dict_range in pooldata:
try:
pool_objs.append(netaddr.IPRange(
netaddr.IPAddress(dict_range['start']),
netaddr.IPAddress(dict_range['end'])))
except Exception:
errors.append("Invalid format of the IP range in {}: {}"
.format(poolitem, dict_range))
continue
# Check if CIDR is specified and IP network is valid
subnet_item = poolitem.split('AllocationPools')[0] + 'NetCidr'
try:
network = filedata[subnet_item]
subnet_obj = netaddr.IPNetwork(network)
except KeyError:
errors.append('The {} CIDR is not specified for {}.'
.format(subnet_item, poolitem))
continue
# Remove network address and broadcast address
ip_set.remove(ip_network.first)
ip_set.remove(ip_network.last)
# Remove gateway, local_ip, admin_host and public_host addresses
ip_set.remove(netaddr.IPAddress(subnet.get('gateway')))
ip_set.remove(netaddr.IPNetwork(CONF.local_ip).ip)
ip_set.remove(netaddr.IPNetwork(utils.get_single_ip(
CONF.undercloud_admin_host)))
ip_set.remove(netaddr.IPNetwork(utils.get_single_ip(
CONF.undercloud_public_host)))
# Remove dns nameservers
for addr in subnet.get('dns_nameservers', []):
ip_set.remove(netaddr.IPAddress(addr))
# Remove addresses in the inspection_iprange
inspect_start, inspect_end = subnet.get('inspection_iprange').split(',')
ip_set.remove(netaddr.IPRange(inspect_start, inspect_end))
# Remove dhcp_exclude addresses and ip ranges
for exclude in subnet.dhcp_exclude:
if '-' in exclude:
exclude_start, exclude_end = exclude.split('-')
ip_set.remove(netaddr.IPRange(exclude_start, exclude_end))
else:
ip_set.remove(netaddr.IPAddress(exclude))
return [{'start': netaddr.IPAddress(ip_range.first).format(),
'end': netaddr.IPAddress(ip_range.last).format()}
for ip_range in list(ip_set.iter_ipranges())]
def as_netaddr_obj(self):
if self.src.from_ == self.src.to:
src = netaddr.IPNetwork(self.src.from_)
else:
src = netaddr.IPRange(self.src.from_, self.src.to)
return src
def load_whois_cache(self):
""" restore whois cache and remove expired results """
p = Path(config_dir, WHOIS_CACHE)
if Config.get("whois_cache", "FIELDS", get=bool) and p.exists():
event = lazy_print("... loading big WHOIS cache ...") # XX if it's long, postpone via a thread that would block analysis
ip_seen, ranges = jsonpickle.decode(p.read_text(), keys=True)
ranges = {IPRange(k[0], k[1]): v for k, v in ranges.items()
if v[7] + Config.get("whois_ttl", "FIELDS", int) >= time()}
nothing_to_save = True
if Config.get("whois_delete_unknown", get=bool) and IPRange(0, 0) in ranges:
# all IP addresses within an unknown prefix removed from cache
del ranges[IPRange(0, 0)]
nothing_to_save = False
ip_seen = {k: v for k, v in ip_seen.items() if v in ranges}
if nothing_to_save: # count hash now so that we do not re-save whois cache if not changed while processing
self._whois_changed(ranges, ip_seen)
event.set()
return ip_seen, ranges
return {}, {}
def load_gi_org(filename):
with open(filename, 'rb') as f:
org_reader = csv.DictReader(f, fieldnames=['start', 'end', 'org'])
for row in org_reader:
gi_org[row['start']] = (IPRange(row['start'], row['end']), unicode(row['org'], errors='replace'))
return gi_org