Esempio n. 1
0
 def allowed_addresses(self):
     if self._values['allowed_addresses'] is None:
         return None
     result = []
     addresses = self._values['allowed_addresses']
     if isinstance(addresses, string_types):
         if addresses in ['', 'none']:
             return []
         else:
             addresses = [addresses]
     if len(addresses) == 1 and addresses[0] in ['default', '']:
         result = ['127.0.0.0/8']
         return result
     for address in addresses:
         try:
             # Check for valid IPv4 or IPv6 entries
             ip_network(u'%s' % str(address))
             result.append(address)
         except ValueError:
             # else fallback to checking reasonably well formatted hostnames
             if is_valid_hostname(address):
                 result.append(str(address))
                 continue
             raise F5ModuleError(
                 "The provided 'allowed_address' value {0} is not a valid IP or hostname".format(address)
             )
     result = list(set(result))
     result.sort()
     return result
    def netmask(self):
        if self._values['netmask'] is None:
            return None
        try:
            result = int(self._values['netmask'])

            # CIDRs between 0 and 128 are allowed
            if 0 <= result <= 128:
                return result
            else:
                raise F5ModuleError(
                    "The provided netmask must be between 0 and 32 for IPv4, or "
                    "0 and 128 for IPv6.")
        except ValueError:
            # not a number, but that's ok. Further processing necessary
            pass

        if not is_valid_ip(self._values['netmask']):
            raise F5ModuleError(
                'The provided netmask {0} is neither in IP or CIDR format'.
                format(result))

        # Create a temporary address to check if the netmask IP is v4 or v6
        addr = ip_address(u'{0}'.format(str(self._values['netmask'])))
        if addr.version == 4:
            # Create a more real v4 address using a wildcard, so that we can determine
            # the CIDR value from it.
            ip = ip_network(u'0.0.0.0/%s' % str(self._values['netmask']))
            result = ip.prefixlen
        else:
            result = ipv6_netmask_to_cidr(self._values['netmask'])

        return result
Esempio n. 3
0
 def encode_address_from_dict(self, record):
     if is_valid_ip_network(record['key']):
         key = ip_network(u"{0}".format(str(record['key'])))
     elif is_valid_ip(record['key']):
         key = ip_address(u"{0}".format(str(record['key'])))
     elif is_valid_ip_interface(record['key']):
         key = ip_interface(u"{0}".format(str(record['key'])))
     else:
         raise F5ModuleError(
             "When specifying an 'address' type, the value to the left of the separator must be an IP."
         )
     if key and 'value' in record:
         try:
             # Only ip_address's have max_prefixlen
             if key.max_prefixlen in [32, 128]:
                 return self.encode_host(str(key), record['value'])
         except ValueError:
             return self.encode_network(str(key.network_address),
                                        key.prefixlen, record['value'])
     elif key:
         try:
             # Only ip_address's have max_prefixlen
             if key.max_prefixlen in [32, 128]:
                 return self.encode_host(str(key), str(key))
         except ValueError:
             return self.encode_network(str(key.network_address),
                                        key.prefixlen,
                                        str(key.network_address))
Esempio n. 4
0
 def _convert_address(self, item):
     if item == '0.0.0.0/0':
         return 'any', None
     result = ip_network(u'{0}'.format(item))
     if result.prefixlen == 32:
         return str(result.network_address), None
     else:
         return str(result.network_address), str(result.netmask)
 def gateway_address(self):
     if self._values['gateway_address'] is None:
         return None
     try:
         ip = ip_network(u'%s' % str(self._values['gateway_address']))
         return str(ip.network_address)
     except ValueError:
         raise F5ModuleError(
             "The provided gateway_address is not an IP address")
Esempio n. 6
0
 def network(self):
     if self._values['network'] is None:
         return None
     if self._values['network'] == 'default':
         return 'default'
     try:
         addr = ip_network(u"{0}".format(str(self._values['network'])))
         return str(addr)
     except ValueError:
         raise F5ModuleError(
             "The 'network' must either be a network address (with CIDR) or the word 'default'."
         )
    def destination_ip(self):
        if self._values['destination'] is None:
            return None
        destination = self.destination_to_network()

        try:
            pattern = r'(?P<rd>%[0-9]+)'
            addr = re.sub(pattern, '', destination)
            ip = ip_network(u'%s' % str(addr))
            return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
        except ValueError:
            raise F5ModuleError(
                "The provided destination is not an IP address.")
Esempio n. 8
0
 def _convert_netmask(self, item):
     result = -1
     try:
         result = int(item)
         if 0 < result < 256:
             pass
     except ValueError:
         if is_valid_ip(item):
             ip = ip_network(u'0.0.0.0/%s' % str(item))
             result = ip.prefixlen
     if result < 0:
         raise F5ModuleError(
             'The provided netmask {0} is neither in IP or CIDR format'.format(result)
         )
     return result
 def destination_ip(self):
     if self._values['destination'] is None:
         return None
     if self._values['destination'] == 'default':
         self._values['destination'] = '0.0.0.0/0'
     if self._values['destination'] == 'default-inet6':
         self._values['destination'] = '::/::'
     try:
         pattern = r'(?P<rd>%[0-9]+)'
         addr = re.sub(pattern, '', self._values['destination'])
         ip = ip_network(u'%s' % str(addr))
         return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
     except ValueError:
         raise F5ModuleError(
             "The provided destination is not an IP address"
         )
 def destination(self):
     if self._values['destination'] is None:
         return None
     if self._values['destination'].startswith('default'):
         self._values['destination'] = '0.0.0.0/0'
     if self._values['destination'].startswith('default-inet6'):
         self._values['destination'] = '::/0'
     try:
         ip = ip_network(u'%s' % str(self.destination_ip))
         if self.route_domain:
             return '{0}%{1}/{2}'.format(str(ip.network_address),
                                         self.route_domain, ip.prefixlen)
         else:
             return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
     except ValueError:
         raise F5ModuleError(
             "The provided destination is not an IP address")
Esempio n. 11
0
    def decode_address_from_string(self, record):
        matches = self._rd_net_ptrn.match(record)
        if matches:
            # network 192.168.0.0%11 prefixlen 16 := "Network3",
            # network 2402:9400:1000:0::%11 prefixlen 64 := "Network4",
            value = record.split(self._separator)[1].strip().strip('"')
            addr = "{0}%{1}/{2}".format(matches.group('addr'),
                                        matches.group('rd'),
                                        matches.group('prefix'))
            result = dict(name=addr, data=value)
            return result
        matches = self._network_pattern.match(record)
        if matches:
            # network 192.168.0.0 prefixlen 16 := "Network3",
            # network 2402:9400:1000:0:: prefixlen 64 := "Network4",
            key = u"{0}/{1}".format(matches.group('addr'),
                                    matches.group('prefix'))
            addr = ip_network(key)
            value = record.split(self._separator)[1].strip().strip('"')
            result = dict(name=str(addr), data=value)
            return result
        matches = self._rd_host_ptrn.match(record)
        if matches:
            # host 172.16.1.1%11/32 := "Host3"
            # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334%11 := "Host4"
            host = ip_interface(u"{0}".format(matches.group('addr')))
            addr = "{0}%{1}/{2}".format(matches.group('addr'),
                                        matches.group('rd'),
                                        str(host.network.prefixlen))
            value = record.split(self._separator)[1].strip().strip('"')
            result = dict(name=addr, data=value)
            return result
        matches = self._host_pattern.match(record)
        if matches:
            # host 172.16.1.1/32 := "Host3"
            # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4"
            key = matches.group('addr')
            addr = ip_interface(u"{0}".format(str(key)))
            value = record.split(self._separator)[1].strip().strip('"')
            result = dict(name=str(addr), data=value)
            return result

        raise F5ModuleError('The value "{0}" is not an address'.format(record))
Esempio n. 12
0
    def encode_address_from_string(self, record):
        if self._network_pattern.match(record):
            # network 192.168.0.0 prefixlen 16 := "Network3",
            # network 2402:9400:1000:0:: prefixlen 64 := "Network4",
            return record
        elif self._host_pattern.match(record):
            # host 172.16.1.1/32 := "Host3"
            # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4"
            return record
        else:
            # 192.168.0.0/16 := "Network3",
            # 2402:9400:1000:0::/64 := "Network4",
            parts = record.split(self._separator)
            if is_valid_ip_network(parts[0]):
                key = ip_network(u"{0}".format(str(parts[0])))
            elif is_valid_ip(parts[0]):
                key = ip_address(u"{0}".format(str(parts[0])))
            elif is_valid_ip_interface(parts[0]):
                key = ip_interface(u"{0}".format(str(parts[0])))
            elif parts[0] == '':
                pass
            else:
                raise F5ModuleError(
                    "When specifying an 'address' type, the value to the left of the separator must be an IP."
                )

            if len(parts) == 2:
                try:
                    # Only ip_address's have max_prefixlen
                    if key.max_prefixlen in [32, 128]:
                        return self.encode_host(str(key), parts[1])
                except ValueError:
                    return self.encode_network(str(key.network_address),
                                               key.prefixlen, parts[1])
            elif len(parts) == 1 and parts[0] != '':
                try:
                    # Only ip_address's have max_prefixlen
                    if key.max_prefixlen in [32, 128]:
                        return self.encode_host(str(key), str(key))
                except ValueError:
                    return self.encode_network(str(key.network_address),
                                               key.prefixlen,
                                               str(key.network_address))
 def netmask(self):
     if self._values['netmask'] is None:
         return None
     # Check if numeric
     try:
         result = int(self._values['netmask'])
         if 0 <= result < 256:
             return result
         raise F5ModuleError(
             'The provided netmask {0} is neither in IP or CIDR format'.format(result)
         )
     except ValueError:
         try:
             ip = ip_network(u'%s' % str(self._values['netmask']))
         except ValueError:
             raise F5ModuleError(
                 'The provided netmask {0} is neither in IP or CIDR format'.format(self._values['netmask'])
             )
         result = int(ip.prefixlen)
     return result
Esempio n. 14
0
 def netmask(self):
     if self._values['netmask'] is None:
         return None
     result = -1
     try:
         result = int(self._values['netmask'])
         if 0 < result < 256:
             pass
     except ValueError:
         if is_valid_ip(self._values['netmask']):
             addr = ip_address(u'{0}'.format(str(self._values['netmask'])))
             if addr.version == 4:
                 ip = ip_network(u'0.0.0.0/%s' % str(self._values['netmask']))
                 result = ip.prefixlen
             else:
                 result = ipv6_netmask_to_cidr(self._values['netmask'])
     if result < 0:
         raise F5ModuleError(
             'The provided netmask {0} is neither in IP or CIDR format'.format(result)
         )
     return result
Esempio n. 15
0
def is_valid_ip_network(address):
    try:
        ip_network(u'{0}'.format(address))
        return True
    except ValueError:
        return False
 def netmask(self):
     destination = self.destination_to_network()
     ip = ip_network(u'%s' % str(destination))
     return int(ip.prefixlen)
Esempio n. 17
0
def get_netmask(address):
    addr = ip_network(u'{0}'.format(address))
    netmask = addr.netmask.compressed
    return netmask
Esempio n. 18
0
def compress_address(address):
    addr = ip_network(u'{0}'.format(address))
    result = addr.compressed.split('/')[0]
    return result
 def destination_ip(self):
     if self._values['destination']:
         ip = ip_network(u'{0}/{1}'.format(self._values['destination'],
                                           self.netmask))
         return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
Esempio n. 20
0
def is_valid_ip_network(address):
    try:
        ip_network(address)
        return True
    except ValueError:
        return False
Esempio n. 21
0
def get_netmask(address):
    addr = ip_network(address)
    netmask = addr.netmask.compressed
    return netmask
Esempio n. 22
0
def compress_address(address):
    addr = ip_network(address)
    result = addr.compressed.split('/')[0]
    return result
 def netmask(self):
     ip = ip_network(u'%s' % str(self.destination_ip))
     return int(ip.prefixlen)