def _validate_and_cleanse_policy(self, context, policy_data):
        """Validate every field of the policy and raise exceptions if any.

        This is a simple syntax validation. Actual funtional validation is
        performed at the backend by BCF and error message returned is bubbled
        up to the Horizon GUI.

        :param context: context of the transaction
        :param policy_data: the policy resource to be validated
        """
        policy_data['tenant_id'] = Util.get_tenant_id_for_create(
            context, policy_data)
        V4ANY = '0.0.0.0/0'
        CIDRALL = ['any', 'external']
        source = (V4ANY if policy_data['source'] in CIDRALL else
                  policy_data['source'])
        destination = (V4ANY if policy_data['destination'] in CIDRALL else
                       policy_data['destination'])
        errors = [
            validators.validate_subnet(source),
            validators.validate_subnet(destination),
            self._validate_nexthops(policy_data['nexthops']),
            self._validate_action(policy_data['action']),
            self._validate_priority(policy_data['priority']),
            self._validate_port_number(policy_data['source_port']),
            self._validate_port_number(policy_data['destination_port']),
            self._validate_port_protocol(policy_data)
        ]
        errors = [m for m in errors if m]
        if errors:
            LOG.debug(errors)
            raise n_exc.InvalidInput(error_message=errors)

        return self._cleanse_policy(policy_data)
示例#2
0
 def _check_peer_cidrs(self, peer_cidrs):
     """Ensure all CIDRs have the valid format."""
     for peer_cidr in peer_cidrs:
         msg = validators.validate_subnet(peer_cidr)
         if msg:
             raise vpnaas.IPsecSiteConnectionPeerCidrError(
                 peer_cidr=peer_cidr)
示例#3
0
 def _check_peer_cidrs(self, peer_cidrs):
     """Ensure all CIDRs have the valid format."""
     for peer_cidr in peer_cidrs:
         msg = validators.validate_subnet(peer_cidr)
         if msg:
             raise vpnaas.IPsecSiteConnectionPeerCidrError(
                 peer_cidr=peer_cidr)
 def _validate_cidrs(self, cidrs):
     """Ensure valid IPv4/6 CIDRs."""
     for cidr in cidrs:
         msg = validators.validate_subnet(cidr)
         if msg:
             raise vpnaas.InvalidEndpointInEndpointGroup(
                 group_type=constants.CIDR_ENDPOINT, endpoint=cidr,
                 why=_("Invalid CIDR"))
示例#5
0
 def _validate_cidrs(self, cidrs):
     """Ensure valid IPv4/6 CIDRs."""
     for cidr in cidrs:
         msg = validators.validate_subnet(cidr)
         if msg:
             raise vpnaas.InvalidEndpointInEndpointGroup(
                 group_type=constants.CIDR_ENDPOINT,
                 endpoint=cidr,
                 why=_("Invalid CIDR"))
示例#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)
示例#7
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}
示例#8
0
 def validate(self, value, context, template=None):
     try:
         netaddr.IPNetwork(value, implicit_prefix=True)
         msg = validators.validate_subnet(value)
         if msg is not None:
             self._error_message = msg
             return False
         return True
     except Exception as ex:
         self._error_message = 'Invalid net cidr %s ' % six.text_type(ex)
         return False
示例#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}
示例#10
0
 def validate(self, value, context, template=None):
     try:
         netaddr.IPNetwork(value, implicit_prefix=True)
         msg = validators.validate_subnet(value)
         if msg is not None:
             self._error_message = msg
             return False
         return True
     except Exception as ex:
         self._error_message = 'Invalid net cidr %s ' % six.text_type(ex)
         return False
def convert_to_valid_router_rules(data):
    """Validates and converts router rules to the appropriate data structure

    Example argument = [{'source': 'any', 'destination': 'any',
                         'action':'deny'},
                        {'source': '1.1.1.1/32', 'destination': 'external',
                         'action':'permit',
                         'nexthops': ['1.1.1.254', '1.1.1.253']}
                       ]
    """
    V4ANY = '0.0.0.0/0'
    CIDRALL = ['any', 'external']
    if not isinstance(data, list):
        emsg = _("Invalid data format for router rule: '%s'") % data
        LOG.debug(emsg)
        raise nexception.InvalidInput(error_message=emsg)
    _validate_uniquerules(data)
    rules = []
    expected_keys = ['source', 'destination', 'action', 'priority']
    for rule in data:
        rule['nexthops'] = rule.get('nexthops', [])
        if not isinstance(rule['nexthops'], list):
            rule['nexthops'] = rule['nexthops'].split('+')

        src = V4ANY if rule['source'] in CIDRALL else rule['source']
        dst = V4ANY if rule['destination'] in CIDRALL else rule['destination']

        errors = [
            validators._verify_dict_keys(expected_keys, rule, False),
            validators.validate_subnet(dst),
            validators.validate_subnet(src),
            _validate_nexthops(rule['nexthops']),
            _validate_action(rule['action']),
            _validate_priority(rule['priority'])
        ]
        errors = [m for m in errors if m]
        if errors:
            LOG.debug(errors)
            raise nexception.InvalidInput(error_message=errors)
        rules.append(rule)
    return rules
def convert_to_valid_router_rules(data):
    """Validates and converts router rules to the appropriate data structure

    Example argument = [{'source': 'any', 'destination': 'any',
                         'action':'deny'},
                        {'source': '1.1.1.1/32', 'destination': 'external',
                         'action':'permit',
                         'nexthops': ['1.1.1.254', '1.1.1.253']}
                       ]
    """
    V4ANY = '0.0.0.0/0'
    CIDRALL = ['any', 'external']
    if not isinstance(data, list):
        emsg = _("Invalid data format for router rule: '%s'") % data
        LOG.debug(emsg)
        raise nexception.InvalidInput(error_message=emsg)
    _validate_uniquerules(data)
    rules = []
    expected_keys = ['source', 'destination', 'action', 'priority']
    for rule in data:
        rule['nexthops'] = rule.get('nexthops', [])
        if not isinstance(rule['nexthops'], list):
            rule['nexthops'] = rule['nexthops'].split('+')

        src = V4ANY if rule['source'] in CIDRALL else rule['source']
        dst = V4ANY if rule['destination'] in CIDRALL else rule['destination']

        errors = [validators._verify_dict_keys(expected_keys, rule, False),
                  validators.validate_subnet(dst),
                  validators.validate_subnet(src),
                  _validate_nexthops(rule['nexthops']),
                  _validate_action(rule['action']),
                  _validate_priority(rule['priority'])]
        errors = [m for m in errors if m]
        if errors:
            LOG.debug(errors)
            raise nexception.InvalidInput(error_message=errors)
        rules.append(rule)
    return rules
示例#13
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 _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)
示例#15
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)