Exemple #1
0
    def create(self, req, body):
        context = req.environ['engine.context']
        group_id = body['security_group_rule']['parent_group_id']

        self.compute_api.ensure_default_security_group(context)
        security_group = db.security_group_get(context, group_id)
        if not security_group:
            raise exception.SecurityGroupNotFound(security_group_id=group_id)

        msg = "Authorize security group ingress %s"
        LOG.audit(_(msg), security_group['name'], context=context)
        values = self._revoke_rule_args_to_dict(context,
                                                **body['security_group_rule'])
        if values is None:
            raise exception.ApiError(
                _("Not enough parameters to build a "
                  "valid rule."))
        values['parent_group_id'] = security_group.id

        if self._security_group_rule_exists(security_group, values):
            raise exception.ApiError(
                _('This rule already exists in group %s') % group_id)

        security_group_rule = db.security_group_rule_create(context, values)

        self.compute_api.trigger_security_group_rules_refresh(
            context, security_group_id=security_group['id'])

        return {
            'security_group_rule':
            self._format_security_group_rule(context, security_group_rule)
        }
Exemple #2
0
    def delete(self, req, id):
        context = req.environ['engine.context']

        self.compute_api.ensure_default_security_group(context)
        try:
            id = int(id)
            rule = db.security_group_rule_get(context, id)
        except ValueError:
            msg = _("Rule id is not integer")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.NotFound as exp:
            msg = _("Rule (%s) not found") % id
            raise exc.HTTPNotFound(explanation=msg)

        group_id = rule.parent_group_id
        self.compute_api.ensure_default_security_group(context)
        security_group = db.security_group_get(context, group_id)

        msg = _("Revoke security group ingress %s")
        LOG.audit(msg, security_group['name'], context=context)

        db.security_group_rule_destroy(context, rule['id'])
        self.compute_api.trigger_security_group_rules_refresh(context,
                                    security_group_id=security_group['id'])

        return webob.Response(status_int=202)
Exemple #3
0
 def show(self, req, id):
     context = req.environ['engine.context']
     security_group = db.security_group_get(context, id)
     return {
         'security_group':
         self._format_security_group(context, security_group)
     }
Exemple #4
0
    def create(self, req, body):
        context = req.environ['engine.context']

        if not body:
            raise exc.HTTPUnprocessableEntity()

        if not 'security_group_rule' in body:
            raise exc.HTTPUnprocessableEntity()

        self.compute_api.ensure_default_security_group(context)

        sg_rule = body['security_group_rule']
        parent_group_id = sg_rule.get('parent_group_id', None)
        try:
            parent_group_id = int(parent_group_id)
            security_group = db.security_group_get(context, parent_group_id)
        except ValueError:
            msg = _("Parent group id is not integer")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.NotFound as exp:
            msg = _("Security group (%s) not found") % parent_group_id
            raise exc.HTTPNotFound(explanation=msg)

        msg = _("Authorize security group ingress %s")
        LOG.audit(msg, security_group['name'], context=context)

        try:
            values = self._rule_args_to_dict(context,
                              to_port=sg_rule.get('to_port'),
                              from_port=sg_rule.get('from_port'),
                              parent_group_id=sg_rule.get('parent_group_id'),
                              ip_protocol=sg_rule.get('ip_protocol'),
                              cidr=sg_rule.get('cidr'),
                              group_id=sg_rule.get('group_id'))
        except Exception as exp:
            raise exc.HTTPBadRequest(explanation=unicode(exp))

        if values is None:
            msg = _("Not enough parameters to build a "
                                       "valid rule.")
            raise exc.HTTPBadRequest(explanation=msg)

        values['parent_group_id'] = security_group.id

        if self._security_group_rule_exists(security_group, values):
            msg = _('This rule already exists in group %s') % parent_group_id
            raise exc.HTTPBadRequest(explanation=msg)

        security_group_rule = db.security_group_rule_create(context, values)

        self.compute_api.trigger_security_group_rules_refresh(context,
                                    security_group_id=security_group['id'])

        return {"security_group_rule": self._format_security_group_rule(
                                                        context,
                                                        security_group_rule)}
Exemple #5
0
 def _get_security_group(self, context, id):
     try:
         id = int(id)
         security_group = db.security_group_get(context, id)
     except ValueError:
         msg = _("Security group id should be integer")
         raise exc.HTTPBadRequest(explanation=msg)
     except exception.NotFound as exp:
         raise exc.HTTPNotFound(explanation=unicode(exp))
     return security_group
Exemple #6
0
 def _format_security_group_rule(self, context, rule):
     r = {}
     r["id"] = rule.id
     r["parent_group_id"] = rule.parent_group_id
     r["group_id"] = rule.group_id
     r["ip_protocol"] = rule.protocol
     r["from_port"] = rule.from_port
     r["to_port"] = rule.to_port
     r["groups"] = []
     r["ip_ranges"] = []
     if rule.group_id:
         source_group = db.security_group_get(context, rule.group_id)
         r["groups"] += [{"name": source_group.name, "tenant_id": source_group.project_id}]
     else:
         r["ip_ranges"] += [{"cidr": rule.cidr}]
     return r
Exemple #7
0
 def _format_security_group_rule(self, context, rule):
     sg_rule = {}
     sg_rule['id'] = rule.id
     sg_rule['parent_group_id'] = rule.parent_group_id
     sg_rule['ip_protocol'] = rule.protocol
     sg_rule['from_port'] = rule.from_port
     sg_rule['to_port'] = rule.to_port
     sg_rule['group'] = {}
     sg_rule['ip_range'] = {}
     if rule.group_id:
         source_group = db.security_group_get(context, rule.group_id)
         sg_rule['group'] = {'name': source_group.name,
                          'tenant_id': source_group.project_id}
     else:
         sg_rule['ip_range'] = {'cidr': rule.cidr}
     return sg_rule
Exemple #8
0
    def delete(self, req, id):
        context = req.environ["engine.context"]
        rule = sqlalchemy_api.security_group_rule_get(context, id)
        if not rule:
            raise exception.ApiError(_("Rule not found"))
        group_id = rule.parent_group_id

        self.compute_api.ensure_default_security_group(context)

        security_group = db.security_group_get(context, group_id)
        if not security_group:
            raise exception.SecurityGroupNotFound(security_group_id=group_id)

        msg = "Revoke security group ingress %s"
        LOG.audit(_(msg), security_group["name"], context=context)

        db.security_group_rule_destroy(context, rule["id"])
        self.compute_api.trigger_security_group_rules_refresh(context, security_group_id=security_group["id"])
        return exc.HTTPAccepted()
Exemple #9
0
 def _format_security_group_rule(self, context, rule):
     r = {}
     r['id'] = rule.id
     r['parent_group_id'] = rule.parent_group_id
     r['group_id'] = rule.group_id
     r['ip_protocol'] = rule.protocol
     r['from_port'] = rule.from_port
     r['to_port'] = rule.to_port
     r['groups'] = []
     r['ip_ranges'] = []
     if rule.group_id:
         source_group = db.security_group_get(context, rule.group_id)
         r['groups'] += [{
             'name': source_group.name,
             'tenant_id': source_group.project_id
         }]
     else:
         r['ip_ranges'] += [{'cidr': rule.cidr}]
     return r
Exemple #10
0
    def delete(self, req, id):
        context = req.environ['engine.context']
        rule = sqlalchemy_api.security_group_rule_get(context, id)
        if not rule:
            raise exception.ApiError(_("Rule not found"))
        group_id = rule.parent_group_id

        self.compute_api.ensure_default_security_group(context)

        security_group = db.security_group_get(context, group_id)
        if not security_group:
            raise exception.SecurityGroupNotFound(security_group_id=group_id)

        msg = "Revoke security group ingress %s"
        LOG.audit(_(msg), security_group['name'], context=context)

        db.security_group_rule_destroy(context, rule['id'])
        self.compute_api.trigger_security_group_rules_refresh(
            context, security_group_id=security_group['id'])
        return exc.HTTPAccepted()
Exemple #11
0
    def security_group_to_nwfilter_xml(security_group_id):
        security_group = db.security_group_get(context.get_admin_context(),
                                               security_group_id)
        rule_xml = ""
        v6protocol = {'tcp': 'tcp-ipv6', 'udp': 'udp-ipv6', 'icmp': 'icmpv6'}
        for rule in security_group.rules:
            rule_xml += "<rule action='accept' direction='in' priority='300'>"
            if rule.cidr:
                version = netutils.get_ip_version(rule.cidr)
                if (FLAGS.use_ipv6 and version == 6):
                    net, prefixlen = netutils.get_net_and_prefixlen(rule.cidr)
                    rule_xml += "<%s srcipaddr='%s' srcipmask='%s' " % \
                                (v6protocol[rule.protocol], net, prefixlen)
                else:
                    net, mask = netutils.get_net_and_mask(rule.cidr)
                    rule_xml += "<%s srcipaddr='%s' srcipmask='%s' " % \
                                (rule.protocol, net, mask)
                if rule.protocol in ['tcp', 'udp']:
                    rule_xml += "dstportstart='%s' dstportend='%s' " % \
                                (rule.from_port, rule.to_port)
                elif rule.protocol == 'icmp':
                    LOG.info(
                        'rule.protocol: %r, rule.from_port: %r, '
                        'rule.to_port: %r', rule.protocol, rule.from_port,
                        rule.to_port)
                    if rule.from_port != -1:
                        rule_xml += "type='%s' " % rule.from_port
                    if rule.to_port != -1:
                        rule_xml += "code='%s' " % rule.to_port

                rule_xml += '/>\n'
            rule_xml += "</rule>\n"
        xml = "<filter name='engine-secgroup-%s' " % security_group_id
        if (FLAGS.use_ipv6):
            xml += "chain='root'>%s</filter>" % rule_xml
        else:
            xml += "chain='ipv4'>%s</filter>" % rule_xml
        return xml
    def security_group_to_nwfilter_xml(security_group_id):
        security_group = db.security_group_get(context.get_admin_context(),
                                               security_group_id)
        rule_xml = ""
        v6protocol = {'tcp': 'tcp-ipv6', 'udp': 'udp-ipv6', 'icmp': 'icmpv6'}
        for rule in security_group.rules:
            rule_xml += "<rule action='accept' direction='in' priority='300'>"
            if rule.cidr:
                version = netutils.get_ip_version(rule.cidr)
                if(FLAGS.use_ipv6 and version == 6):
                    net, prefixlen = netutils.get_net_and_prefixlen(rule.cidr)
                    rule_xml += "<%s srcipaddr='%s' srcipmask='%s' " % \
                                (v6protocol[rule.protocol], net, prefixlen)
                else:
                    net, mask = netutils.get_net_and_mask(rule.cidr)
                    rule_xml += "<%s srcipaddr='%s' srcipmask='%s' " % \
                                (rule.protocol, net, mask)
                if rule.protocol in ['tcp', 'udp']:
                    rule_xml += "dstportstart='%s' dstportend='%s' " % \
                                (rule.from_port, rule.to_port)
                elif rule.protocol == 'icmp':
                    LOG.info('rule.protocol: %r, rule.from_port: %r, '
                             'rule.to_port: %r', rule.protocol,
                             rule.from_port, rule.to_port)
                    if rule.from_port != -1:
                        rule_xml += "type='%s' " % rule.from_port
                    if rule.to_port != -1:
                        rule_xml += "code='%s' " % rule.to_port

                rule_xml += '/>\n'
            rule_xml += "</rule>\n"
        xml = "<filter name='engine-secgroup-%s' " % security_group_id
        if(FLAGS.use_ipv6):
            xml += "chain='root'>%s</filter>" % rule_xml
        else:
            xml += "chain='ipv4'>%s</filter>" % rule_xml
        return xml
Exemple #13
0
    def create(self, req, body):
        context = req.environ["engine.context"]
        group_id = body["security_group_rule"]["parent_group_id"]

        self.compute_api.ensure_default_security_group(context)
        security_group = db.security_group_get(context, group_id)
        if not security_group:
            raise exception.SecurityGroupNotFound(security_group_id=group_id)

        msg = "Authorize security group ingress %s"
        LOG.audit(_(msg), security_group["name"], context=context)
        values = self._revoke_rule_args_to_dict(context, **body["security_group_rule"])
        if values is None:
            raise exception.ApiError(_("Not enough parameters to build a " "valid rule."))
        values["parent_group_id"] = security_group.id

        if self._security_group_rule_exists(security_group, values):
            raise exception.ApiError(_("This rule already exists in group %s") % group_id)

        security_group_rule = db.security_group_rule_create(context, values)

        self.compute_api.trigger_security_group_rules_refresh(context, security_group_id=security_group["id"])

        return {"security_group_rule": self._format_security_group_rule(context, security_group_rule)}
Exemple #14
0
 def show(self, req, id):
     context = req.environ["engine.context"]
     security_group = db.security_group_get(context, id)
     return {"security_group": self._format_security_group(context, security_group)}
Exemple #15
0
    def _rule_args_to_dict(self, context, to_port=None, from_port=None,
                                  parent_group_id=None, ip_protocol=None,
                                  cidr=None, group_id=None):
        values = {}

        if group_id is not None:
            try:
                parent_group_id = int(parent_group_id)
                group_id = int(group_id)
            except ValueError:
                msg = _("Parent or group id is not integer")
                raise exception.InvalidInput(reason=msg)

            if parent_group_id == group_id:
                msg = _("Parent group id and group id cannot be same")
                raise exception.InvalidInput(reason=msg)

            values['group_id'] = group_id
            #check if groupId exists
            db.security_group_get(context, group_id)
        elif cidr:
            # If this fails, it throws an exception. This is what we want.
            try:
                cidr = urllib.unquote(cidr).decode()
            except Exception:
                raise exception.InvalidCidr(cidr=cidr)

            if not utils.is_valid_cidr(cidr):
                # Raise exception for non-valid address
                raise exception.InvalidCidr(cidr=cidr)

            values['cidr'] = cidr
        else:
            values['cidr'] = '0.0.0.0/0'

        if ip_protocol and from_port and to_port:

            ip_protocol = str(ip_protocol)
            try:
                from_port = int(from_port)
                to_port = int(to_port)
            except ValueError:
                if ip_protocol.upper() == 'ICMP':
                    raise exception.InvalidInput(reason="Type and"
                         " Code must be integers for ICMP protocol type")
                else:
                    raise exception.InvalidInput(reason="To and From ports "
                          "must be integers")

            if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
                raise exception.InvalidIpProtocol(protocol=ip_protocol)

            # Verify that from_port must always be less than
            # or equal to to_port
            if from_port > to_port:
                raise exception.InvalidPortRange(from_port=from_port,
                      to_port=to_port, msg="Former value cannot"
                                            " be greater than the later")

            # Verify valid TCP, UDP port ranges
            if (ip_protocol.upper() in ['TCP', 'UDP'] and
                (from_port < 1 or to_port > 65535)):
                raise exception.InvalidPortRange(from_port=from_port,
                      to_port=to_port, msg="Valid TCP ports should"
                                           " be between 1-65535")

            # Verify ICMP type and code
            if (ip_protocol.upper() == "ICMP" and
                (from_port < -1 or to_port > 255)):
                raise exception.InvalidPortRange(from_port=from_port,
                      to_port=to_port, msg="For ICMP, the"
                                           " type:code must be valid")

            values['protocol'] = ip_protocol
            values['from_port'] = from_port
            values['to_port'] = to_port
        else:
            # If cidr based filtering, protocol and ports are mandatory
            if 'cidr' in values:
                return None

        return values