def glob_to_ip_range(globs): """Convert string of globs to a string of ip ranges in CIDR format. Example: >>> glob_to_ip_range('10.0.0.0/23') '10.0.0.0/24, 10.0.1.0/24' >>> glob_to_ip_range('10.108.0.0/16') '10.108.0.0/16' """ globs = globs.split(',') ip_ranges = '' for i in globs: logging.debug('i = %s' % (i)) try: i = netaddr.glob_to_cidrs(i) for j in i: ip_ranges += '%s, ' % (str(j)) except ValueError, e: # Not a glob. logging.debug('ValueError: %s' % (e)) ip_ranges += '%s, ' % (i) except netaddr.core.AddrFormatError, e: logging.debug(e) i = ip_range_to_cidr(i) for j in i: ip_ranges += '%s, ' % (str(j))
def parse_cidr(self, cidr): cidr = str(cidr) if '*' in cidr or '-' in cidr: return netaddr.glob_to_cidrs(cidr)[0] if '/' not in cidr: cidr = "{}/32".format(cidr) return netaddr.IPNetwork(cidr, implicit_prefix = True)
def _sanity_check(value, field): if field == 'priority': try: if isinstance(value, int) and value >= 0 and value < 65536: return value except: return value if field == 'port': if '-' in value and value != '0-65535': first, second = value.split('-') if first.isdigit() and second.isdigit(): return value elif value.isdigit(): return value return '*' # 'ANY' or '*' or '0-65535': if field == 'dl_type': if value.upper() in ['ARP', 'IPv4', 'IPv6']: return value.upper() return 'IPv4' if field == 'ipv4': if '-' in value: first, second = value.split('-') if second.isdigit(): second = first[:first.rindex('.') + 1] + second if valid_ipv4(first) and valid_ipv4(second): return first + '-' + second if valid_glob(value): return str(glob_to_cidrs(value)[0]).replace('/32', '') if valid_ipv4(value) or \ ('/'in value and valid_ipv4(value[:value.find('/')])): return value.replace('/32', '') return '*' # 'ANY' if field == 'nw_proto': if value.upper() in ['TCP', 'UDP', 'ICMP', 'ICMPv6']: return value.upper() return 'TCP' if field == 'direction': if value.upper() in ['IN']: return 'IN' if value.upper() in ['OUT']: return 'OUT' return 'IN' if field == 'action': if value.upper() in ['DENY', 'REJECT']: return 'DENY' if value.upper() in ['ALLOW', 'ACCEPT']: return 'ALLOW' return 'DENY'
def _convert_ipstring_to_ipn(ipstring): """Transform a single ip string into a list of IPNetwork objects.""" if netaddr.valid_glob(ipstring): ipns = netaddr.glob_to_cidrs(ipstring) else: try: ipns = [netaddr.IPNetwork(ipstring)] except netaddr.AddrFormatError: msg = (_('Invalid IP access string %s.') % ipstring) LOG.error(msg) raise exception.GPFSGaneshaException(msg) return ipns
def clean(self): ips = [] invalid = [] bulk = self.cleaned_data.get('bulk') for value in bulk.strip().split('\n'): if value == '' or value[0] not in '1234567890': continue if '*' in value: parts = str(value.strip()).split('.') for x in range(len(parts), 4): parts.append('*') value = '.'.join(parts) for ip in glob_to_cidrs(value): ips.append(str(ip)) continue ip = address_or_network(value) if ip and (not hasattr(ip, 'prefixlen') or ip.prefixlen in NETRANGE): ips.append(ip) else: invalid.append(value) if invalid: raise forms.ValidationError('Invalid IPs: %s - Enabled: %s' % (', '.join(invalid), ' '.join([ '/%d' % d for d in NETRANGE ]))) ips = collapse_networks(ips) self._new = [] self._updated = [] dups = [] for ip in ips: try: address = Address.objects.get(ip=str(ip)) if int(address.flag) != int(self.flag): dups.append((ip, address.ip, FLAGS_DICT[int(address.flag)])) else: self._updated.append(address) except Address.DoesNotExist: address = Address(ip=ip, flag=self.flag) self._new.append(address) if dups: raise forms.ValidationError('Duplicate IPs: %s' % ', '.join([ '%s (%s %s)' % d for d in dups ])) return self.cleaned_data
def test_glob_to_cidrs(): assert glob_to_cidrs('10.0.0.1') == [IPNetwork('10.0.0.1/32')] assert glob_to_cidrs('192.0.2.*') == [IPNetwork('192.0.2.0/24')] assert glob_to_cidrs('172.16-31.*.*') == [IPNetwork('172.16.0.0/12')] assert glob_to_cidrs('*.*.*.*') == [IPNetwork('0.0.0.0/0')]