Esempio n. 1
0
def isipaddress(data):
    """
        Checks if the passed string is
        a valid IPv4 or IPv6 address
    """
    isipaddress = True

    try:
        ipaddress.ip_address(data)
    except ValueError:
        isipaddress = False

    return isipaddress
    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
 def _normalize_san(self, san):
     if san.startswith('IP Address:'):
         san = 'IP:' + san[len('IP Address:'):]
     if san.startswith('IP:'):
         ip = compat_ipaddress.ip_address(san[3:])
         san = 'IP:{0}'.format(ip.compressed)
     return san
 def address(self):
     if self._values['address'] is None:
         return None
     if is_valid_ip(self._values['address']):
         ip = str(ip_address(u'{0}'.format(self._values['address'])))
         return ip
     raise F5ModuleError("Specified 'address' is not an IP address.")
Esempio n. 5
0
def is_ipv6_address(address):
    """ test if address is a valid ipv6 address """
    try:
        addr = ip_address(u'{0}'.format(address))
        return isinstance(addr, IPv6Address)
    except ValueError:
        pass
    return False
Esempio n. 6
0
 def _normalize_san(self, san):
     # apparently openssl returns 'IP address' not 'IP' as specifier when converting the subjectAltName to string
     # although it won't accept this specifier when generating the CSR. (https://github.com/openssl/openssl/issues/4004)
     if san.startswith('IP Address:'):
         san = 'IP:' + san[len('IP Address:'):]
     if san.startswith('IP:'):
         ip = compat_ipaddress.ip_address(san[3:])
         san = 'IP:{0}'.format(ip.compressed)
     return san
Esempio n. 7
0
    def check_params(self):
        rules_by_host = {}
        for host in self.hosts:
            rules_by_host[host.name] = self.firewall_facts[host.name].keys()

        for rule_option in self.rule_options:
            rule_name = rule_option.get('name')
            if rule_name is None:
                self.module.fail_json(
                    msg="Please specify rule.name for rule set"
                    " as it is required parameter.")
            hosts_with_rule_name = [
                h for h, r in rules_by_host.items() if rule_name in r
            ]
            hosts_without_rule_name = set([i.name for i in self.hosts
                                           ]) - set(hosts_with_rule_name)
            if hosts_without_rule_name:
                self.module.fail_json(
                    msg="rule named '%s' wasn't found on hosts: %s" %
                    (rule_name, hosts_without_rule_name))

            if 'enabled' not in rule_option:
                self.module.fail_json(
                    msg="Please specify rules.enabled for rule set"
                    " %s as it is required parameter." % rule_name)

            allowed_hosts = rule_option.get('allowed_hosts', {})
            ip_addresses = allowed_hosts.get('ip_address', [])
            ip_networks = allowed_hosts.get('ip_network', [])
            for ip_address in ip_addresses:
                try:
                    ipaddress.ip_address(ip_address)
                except ValueError:
                    self.module.fail_json(
                        msg="The provided IP address %s is not a valid IP"
                        " for the rule %s" % (ip_address, rule_name))

            for ip_network in ip_networks:
                try:
                    ipaddress.ip_network(ip_network)
                except ValueError:
                    self.module.fail_json(
                        msg="The provided IP network %s is not a valid network"
                        " for the rule %s" % (ip_network, rule_name))
Esempio n. 8
0
def normalize_ip(ip, ip_version):
    if ip is None:
        return ip
    if '/' in ip:
        ip, range = ip.split('/')
    else:
        ip, range = ip, ''
    ip_addr = to_native(compat_ipaddress.ip_address(to_text(ip)).compressed)
    if range == '':
        range = '32' if ip_version.lower() == 'ipv4' else '128'
    return ip_addr + '/' + range
Esempio n. 9
0
    def address_ranges(self):
        result = []
        for item in self._values['addresses']:
            if '-' not in item['name']:
                continue
            start, stop = item['name'].split('-')
            start = start.strip()
            stop = stop.strip()

            start = ip_address(u'{0}'.format(start))
            stop = ip_address(u'{0}'.format(stop))
            if start.version != stop.version:
                raise F5ModuleError(
                    "When specifying a range, IP addresses must be of the same type; IPv4 or IPv6."
                )
            if int(start) > int(stop):
                stop, start = start, stop
            item = '{0}-{1}'.format(str(start), str(stop))
            result.append(item)
        result = sorted(result)
        return result
Esempio n. 10
0
def is_ipv4_address(data):
    """
        Checks if the passed string is
        a valid IPv4 address
    """
    if "/" in data:
        data = data.split("/")[0]

    if not isipaddress(to_text(data)):
        raise ValueError("{0} is not a valid IP address".format(data))

    return ipaddress.ip_address(to_text(data)).version == 4
Esempio n. 11
0
def get_ip_address_version(address):
    """
    This function returns the version of IP address
    :param address: IP address
    :return:
    """
    try:
        address = unicode(address)
    except NameError:
        address = str(address)
    version = ipaddress.ip_address(address.split("/")[0]).version
    return version
Esempio n. 12
0
 def addresses(self):
     if self._values['addresses'] is None:
         return None
     result = []
     for x in self._values['addresses']:
         if is_valid_ip(x):
             result.append(str(ip_address(u'{0}'.format(x))))
         elif is_valid_ip_interface(x):
             result.append(str(ip_interface(u'{0}'.format(x))))
         else:
             raise F5ModuleError(
                 "Address {0} must be either an IPv4 or IPv6 address or network."
                 .format(x))
     result = sorted(result)
     return result
Esempio n. 13
0
def is_within_local_networks(self, address):
    """ test if address is contained in our local networks """
    networks = self.get_interfaces_networks()
    try:
        addr = ip_address(u'{0}'.format(address))
    except ValueError:
        return False

    for network in networks:
        try:
            net = ip_network(u'{0}'.format(network), strict=False)
            if addr in net:
                return True
        except ValueError:
            pass
    return False
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 _check_subnet(self):
        """ check if addr lies into interface subnets """
        def _check_vips():
            virtualips = self.pfsense.get_element('virtualip')
            if virtualips is None:
                return False

            for vip_elt in virtualips:
                if vip_elt.find('interface').text != self.interface_elt.tag or vip_elt.find('mode').text != 'other' or vip_elt.find('type').text != 'network':
                    continue

                subnet = ip_network(u'{0}/{1}'.format(vip_elt.find('subnet').text, vip_elt.find('subnet_bits').text), strict=False)
                if addr in subnet:
                    return True
            return False

        if self.params['ipprotocol'] == 'inet':
            inet_type = 'IPv4'
            f1_elt = self.interface_elt.find('ipaddr')
            f2_elt = self.interface_elt.find('subnet')
        else:
            inet_type = 'IPv6'
            f1_elt = self.interface_elt.find('ipaddrv6')
            f2_elt = self.interface_elt.find('subnetv6')
        if f1_elt is None or f1_elt.text is None or f2_elt is None or f2_elt.text is None:
            self.module.fail_json(msg='Cannot add {0} Gateway Address because no {0} address could be found on the interface.'.format(inet_type))

        try:
            if self.params['nonlocalgateway']:
                return

            addr = ip_address(u'{0}'.format(self.params['gateway']))
            subnet = ip_network(u'{0}/{1}'.format(f1_elt.text, f2_elt.text), strict=False)
            if addr in subnet or _check_vips():
                return

            self.module.fail_json(msg="The gateway address {0} does not lie within one of the chosen interface's subnets.".format(self.params['gateway']))
        except ValueError:
            self.module.fail_json(msg='Cannot add {0} Gateway Address because no {0} address could be found on the interface.'.format(inet_type))
    def parse_attribs(self, conf):
        config = {}
        ipaddrs = re.findall(r"address (\S+)", conf, re.M)
        config["ipv4"] = []
        config["ipv6"] = []

        for item in ipaddrs:
            item = item.strip("'")
            if item == "dhcp":
                config["ipv4"].append({"address": item})
            elif item == "dhcpv6":
                config["ipv6"].append({"address": item})
            else:
                ip_version = ipaddress.ip_address(item.split("/")[0]).version
                if ip_version == 4:
                    config["ipv4"].append({"address": item})
                else:
                    config["ipv6"].append({"address": item})

        for key, value in iteritems(config):
            if value == []:
                config[key] = None

        return utils.remove_empties(config)
Esempio n. 17
0
def _normalize_ip(ip):
    try:
        return to_native(compat_ipaddress.ip_address(to_text(ip)).compressed)
    except ValueError:
        # We don't want to error out on something IPAddress() can't parse
        return ip