def test_validate_ip_address_with_leading_zero(self):
        ip_addr = '1.1.1.01'
        expected_msg = ("'%(data)s' is not an accepted IP address, "
                        "'%(ip)s' is recommended")
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {
            "data": ip_addr,
            "ip": '1.1.1.1'
        }, msg)

        ip_addr = '1.1.1.011'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {
            "data": ip_addr,
            "ip": '1.1.1.11'
        }, msg)

        ip_addr = '1.1.1.09'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {
            "data": ip_addr,
            "ip": '1.1.1.9'
        }, msg)

        ip_addr = "fe80:0:0:0:0:0:0:0001"
        msg = validators.validate_ip_address(ip_addr)
        self.assertIsNone(msg)
Exemple #2
0
        def ping_remote():
            try:
                result = ping_host(source,
                                   dest,
                                   count,
                                   nic=nic,
                                   mtu=mtu,
                                   fragmentation=fragmentation,
                                   pattern=pattern)

            except lib_exc.SSHExecCommandFailed:
                LOG.warning(
                    'Failed to ping IP: %s via a ssh connection '
                    'from: %s.', dest, source.host)
                return not should_succeed
            LOG.debug('ping result: %s', result)

            if forbid_packet_loss and ' 0% packet loss' not in result:
                LOG.debug('Packet loss detected')
                return not should_succeed

            if (check_response_ip
                    and validators.validate_ip_address(dest) is None):
                # Assert that the return traffic was from the correct
                # source address.
                from_source = 'from %s' % dest
                self.assertIn(from_source, result)
            return should_succeed
 def validate(self, value, context, template=None):
     self._error_message = 'Invalid IP address'
     if not isinstance(value, six.string_types):
         return False
     msg = validators.validate_ip_address(value)
     if msg is not None:
         return False
     return True
Exemple #4
0
 def validate(self, value, context, template=None):
     self._error_message = 'Invalid IP address'
     if not isinstance(value, six.string_types):
         return False
     msg = validators.validate_ip_address(value)
     if msg is not None:
         return False
     return True
def validate_ipv4_address_or_none(data, valid_values=None):
    if data is None:
        return None
    msg_ip = validators.validate_ip_address(data, valid_values)
    if not msg_ip:
        if netaddr.valid_ipv4(data):
            return None
        msg_ip = _("'%s' is not an IPv4 address") % data
    return msg_ip
Exemple #6
0
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    """Validates a list of allowed address pair dicts.

    Validation herein requires the caller to have registered the
    max_allowed_address_pair oslo config option in the global CONF prior
    to having this validator used.

    :param address_pairs: A list of address pair dicts to validate.
    :param valid_values: Not used.
    :returns: None
    :raises: AllowedAddressPairExhausted if the address pairs requested
    exceeds cfg.CONF.max_allowed_address_pair. AllowedAddressPairsMissingIP
    if any address pair dicts are missing and IP address.
    DuplicateAddressPairInRequest if duplicated IPs are in the list of
    address pair dicts. Otherwise a HTTPBadRequest is raised if any of
    the address pairs are invalid.
    """
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise exc.HTTPBadRequest(_("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise exceptions.AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise exceptions.AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise exceptions.DuplicateAddressPairInRequest(
                mac_address=mac, ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(
            ['mac_address', 'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") % ', '.join(
                set(address_pair.keys()) - set(['mac_address', 'ip_address'])))
            raise exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise exc.HTTPBadRequest(msg)
def _validate_nexthops(nexthops):
    seen = []
    for ip in nexthops:
        msg = validators.validate_ip_address(ip)
        if ip in seen:
            msg = _("Duplicate nexthop in rule '%s'") % ip
        seen.append(ip)
        if msg:
            return msg
def _validate_nexthops(nexthops):
    seen = []
    for ip in nexthops:
        msg = validators.validate_ip_address(ip)
        if ip in seen:
            msg = _("Duplicate nexthop in rule '%s'") % ip
        seen.append(ip)
        if msg:
            return msg
Exemple #9
0
def _validate_ip_or_subnet_or_none(data, valid_values=None):
    if data is None:
        return None
    msg_ip = validators.validate_ip_address(data, valid_values)
    if not msg_ip:
        return
    msg_subnet = validators.validate_subnet(data, valid_values)
    if not msg_subnet:
        return
    return _("%(msg_ip)s and %(msg_subnet)s") % {'msg_ip': msg_ip,
                                                 'msg_subnet': msg_subnet}
def _validate_ip_or_subnet_or_none(data, valid_values=None):
    if data is None:
        return None
    msg_ip = validators.validate_ip_address(data, valid_values)
    if not msg_ip:
        return
    msg_subnet = validators.validate_subnet(data, valid_values)
    if not msg_subnet:
        return
    return _("%(msg_ip)s and %(msg_subnet)s") % {'msg_ip': msg_ip,
                                                 'msg_subnet': msg_subnet}
 def test_validate_ip_address_bsd(self):
     # NOTE(yamamoto):  On NetBSD and OS X, netaddr.IPAddress() accepts
     # '1' * 59 as a valid address.  The behaviour is inherited from
     # libc behaviour there.  This test ensures that our validator reject
     # such addresses on such platforms by mocking netaddr to emulate
     # the behaviour.
     ip_addr = '1' * 59
     with mock.patch('netaddr.IPAddress') as ip_address_cls:
         msg = validators.validate_ip_address(ip_addr)
     ip_address_cls.assert_called_once_with(ip_addr,
                                            flags=netaddr.core.ZEROFILL)
     self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
 def test_validate_ip_address_bsd(self):
     # NOTE(yamamoto):  On NetBSD and OS X, netaddr.IPAddress() accepts
     # '1' * 59 as a valid address.  The behaviour is inherited from
     # libc behaviour there.  This test ensures that our validator reject
     # such addresses on such platforms by mocking netaddr to emulate
     # the behaviour.
     ip_addr = '1' * 59
     with mock.patch('netaddr.IPAddress') as ip_address_cls:
         msg = validators.validate_ip_address(ip_addr)
     ip_address_cls.assert_called_once_with(ip_addr,
                                            flags=netaddr.core.ZEROFILL)
     self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
    def test_validate_ip_address_with_leading_zero(self):
        ip_addr = '1.1.1.01'
        expected_msg = ("'%(data)s' is not an accepted IP address, "
                        "'%(ip)s' is recommended")
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.1'},
                         msg)

        ip_addr = '1.1.1.011'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.11'},
                         msg)

        ip_addr = '1.1.1.09'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.9'},
                         msg)

        ip_addr = "fe80:0:0:0:0:0:0:0001"
        msg = validators.validate_ip_address(ip_addr)
        self.assertIsNone(msg)
 def _validate_nexthops(self, nexthops):
     msg = None
     seen = []
     nexthops = nexthops.split(',')
     for ip in nexthops:
         if not ip:
             continue
         msg = validators.validate_ip_address(ip)
         if ip in seen:
             msg = _("Duplicate nexthop in rule '%s'") % ip
             return msg
         seen.append(ip)
     return msg
    def resolve_peer_address(self, ipsec_sitecon, router):
        address = ipsec_sitecon['peer_address']
        # check if address is an ip address or fqdn
        invalid_ip_address = validators.validate_ip_address(address)
        if invalid_ip_address:
            # resolve fqdn
            try:
                addrinfo = socket.getaddrinfo(address, None)[0]
                ipsec_sitecon['peer_address'] = addrinfo[-1][0]
            except socket.gaierror:
                raise vpnaas.VPNPeerAddressNotResolved(peer_address=address)

        ip_version = netaddr.IPAddress(ipsec_sitecon['peer_address']).version
        self._validate_peer_address(ip_version, router)
Exemple #16
0
 def validate(self, value, context, template=None):
     try:
         if '/' in value:
             msg = validators.validate_subnet(value)
         else:
             msg = validators.validate_ip_address(value)
         if msg is not None:
             self._error_message = msg
             return False
         else:
             return True
     except Exception:
         self._error_message = '{} is not a valid IP or CIDR'.format(value)
         return False
    def resolve_peer_address(self, ipsec_sitecon, router):
        address = ipsec_sitecon['peer_address']
        # check if address is an ip address or fqdn
        invalid_ip_address = validators.validate_ip_address(address)
        if invalid_ip_address:
            # resolve fqdn
            try:
                addrinfo = socket.getaddrinfo(address, None)[0]
                ipsec_sitecon['peer_address'] = addrinfo[-1][0]
            except socket.gaierror:
                raise vpnaas.VPNPeerAddressNotResolved(peer_address=address)

        ip_version = netaddr.IPAddress(ipsec_sitecon['peer_address']).version
        self._validate_peer_address(ip_version, router)
Exemple #18
0
 def _get_nexthop(self, address, connection_id):
     # check if address is an ip address or fqdn
     invalid_ip_address = validators.validate_ip_address(address)
     if invalid_ip_address:
         ip_addr = self._resolve_fqdn(address)
         if not ip_addr:
             self._record_connection_status(connection_id, constants.ERROR,
                                            force_status_update=True)
             raise vpnaas.VPNPeerAddressNotResolved(peer_address=address)
     else:
         ip_addr = address
     routes = self._execute(['ip', 'route', 'get', ip_addr])
     if routes.find('via') >= 0:
         return routes.split(' ')[2]
     return address
Exemple #19
0
 def _get_nexthop(self, address, connection_id):
     # check if address is an ip address or fqdn
     invalid_ip_address = validators.validate_ip_address(address)
     if invalid_ip_address:
         ip_addr = self._resolve_fqdn(address)
         if not ip_addr:
             self._record_connection_status(connection_id, constants.ERROR,
                                            force_status_update=True)
             raise vpnaas.VPNPeerAddressNotResolved(peer_address=address)
     else:
         ip_addr = address
     routes = self._execute(['ip', 'route', 'get', ip_addr])
     if routes.find('via') >= 0:
         return routes.split(' ')[2]
     return address
Exemple #20
0
        def ping_remote():
            try:
                result = ping_host(source, dest, nic=nic, mtu=mtu,
                                   fragmentation=fragmentation)

            except lib_exc.SSHExecCommandFailed:
                LOG.warning('Failed to ping IP: %s via a ssh connection '
                            'from: %s.', dest, source.host)
                return not should_succeed
            LOG.debug('ping result: %s', result)

            if validators.validate_ip_address(dest) is None:
                # Assert that the return traffic was from the correct
                # source address.
                from_source = 'from %s' % dest
                self.assertIn(from_source, result)
            return should_succeed
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise webob.exc.HTTPBadRequest(
            _("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise webob.exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise DuplicateAddressPairInRequest(mac_address=mac,
                                                ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(['mac_address',
                                                        'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") %
                   ', '.join(set(address_pair.keys()) -
                             set(['mac_address', 'ip_address'])))
            raise webob.exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise webob.exc.HTTPBadRequest(msg)
Exemple #22
0
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise webob.exc.HTTPBadRequest(
            _("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise webob.exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise DuplicateAddressPairInRequest(mac_address=mac,
                                                ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(
            ['mac_address', 'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") % ', '.join(
                set(address_pair.keys()) - set(['mac_address', 'ip_address'])))
            raise webob.exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise webob.exc.HTTPBadRequest(msg)
    def test_validate_ip_address(self):
        ip_addr = '1.1.1.1'
        msg = validators.validate_ip_address(ip_addr)
        self.assertIsNone(msg)

        ip_addr = '1111.1.1.1'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        # Depending on platform to run UTs, this case might or might not be
        # an equivalent to test_validate_ip_address_bsd.
        ip_addr = '1' * 59
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '1.1.1.1 has whitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '111.1.1.1\twhitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '111.1.1.1\nwhitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        for ws in string.whitespace:
            ip_addr = '%s111.1.1.1' % ws
            msg = validators.validate_ip_address(ip_addr)
            self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        for ws in string.whitespace:
            ip_addr = '111.1.1.1%s' % ws
            msg = validators.validate_ip_address(ip_addr)
            self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)
    def test_validate_ip_address(self):
        ip_addr = '1.1.1.1'
        msg = validators.validate_ip_address(ip_addr)
        self.assertIsNone(msg)

        ip_addr = '1111.1.1.1'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        # Depending on platform to run UTs, this case might or might not be
        # an equivalent to test_validate_ip_address_bsd.
        ip_addr = '1' * 59
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '1.1.1.1 has whitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '111.1.1.1\twhitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        ip_addr = '111.1.1.1\nwhitespace'
        msg = validators.validate_ip_address(ip_addr)
        self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        for ws in string.whitespace:
            ip_addr = '%s111.1.1.1' % ws
            msg = validators.validate_ip_address(ip_addr)
            self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)

        for ws in string.whitespace:
            ip_addr = '111.1.1.1%s' % ws
            msg = validators.validate_ip_address(ip_addr)
            self.assertEqual("'%s' is not a valid IP address" % ip_addr, msg)