Add a new rule to an existing security group.

    CLI example::

        salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
193658
def authorize(name=None, source_group_name=None,
              source_group_owner_id=None, ip_protocol=None,
              from_port=None, to_port=None, cidr_ip=None, group_id=None,
              source_group_group_id=None, region=None, key=None, keyid=None,
              profile=None, vpc_id=None, vpc_name=None, egress=False):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
                       group_id=group_id, region=region, key=key, keyid=keyid,
                       profile=profile)
    if group:
        try:
            added = None
            if not egress:
                added = conn.authorize_security_group(
                    src_security_group_name=source_group_name,
                    src_security_group_owner_id=source_group_owner_id,
                    ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
                    cidr_ip=cidr_ip, group_id=group.id,
                    src_security_group_group_id=source_group_group_id)
            else:
                added = conn.authorize_security_group_egress(
                    ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
                    cidr_ip=cidr_ip, group_id=group.id,
                    src_group_id=source_group_group_id)
            if added:
                log.info('Added rule to security group %s with id %s',
                         group.name, group.id)
                return True
            else:
                msg = ('Failed to add rule to security group {0} with id {1}.'
                       .format(group.name, group.id))
                log.error(msg)
                return False
        except boto.exception.EC2ResponseError as e:
            # if we are trying to add the same rule then we are already in the desired state, return true
            if e.error_code == 'InvalidPermission.Duplicate':
                return True
            msg = ('Failed to add rule to security group {0} with id {1}.'
                   .format(group.name, group.id))
            log.error(msg)
            log.error(e)
            return False
    else:
        log.error('Failed to add rule to security group.')
        return False
1098272
def grant(self, source_cidr):
        
        self.manager.api.secgroup_rules.create(self.id, source_cidr)
249452
def _check_security_group(self, name):
        
        connection = self._connect()

        filters = {}
        if self._vpc:
            filters = {'vpc-id': self._vpc_id}

        security_groups = connection.get_all_security_groups(filters=filters)

        matching_groups = [
            group
            for group
             in security_groups
             if name in [group.name, group.id]
        ]
        if len(matching_groups) == 0:
            raise SecurityGroupError(
                "the specified security group %s does not exist" % name)
        elif len(matching_groups) == 1:
            return matching_groups[0].id
        elif self._vpc and len(matching_groups) > 1:
            raise SecurityGroupError(
                "the specified security group name %s matches "
                "more than one security group" % name)
1333988
def cli(env, group_id, name, description):
    """"""
    mgr = SoftLayer.NetworkManager(env.client)
    data = {}
    if name:
        data['name'] = name
    if description:
        data['description'] = description

    if not mgr.edit_securitygroup(group_id, **data):
        raise exceptions.CLIAbort("Failed to edit security group")
786351
def cidr_netmask(cidr):
    '''
    
    '''
    ips = netaddr.IPNetwork(cidr)
    return six.text_type(ips.netmask)
142108
def add_host_with_group(self, ip, mac, groupname):
		
		msg = OmapiMessage.open(b"host")
		msg.message.append(("create", struct.pack("!I", 1)))
		msg.message.append(("exclusive", struct.pack("!I", 1)))
		msg.obj.append(("hardware-address", pack_mac(mac)))
		msg.obj.append(("hardware-type", struct.pack("!I", 1)))
		msg.obj.append(("ip-address", pack_ip(ip)))
		msg.obj.append(("group", groupname))
		response = self.query_server(msg)
		if response.opcode != OMAPI_OP_UPDATE:
			raise OmapiError("add failed")
137505
def get_delete_security_group_commands(self, sg_id):
        """"""
        cmds = []
        cmds.append("no ip access-list %s" %
                    self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
        cmds.append("no ip access-list %s" %
                    self._acl_name(sg_id, n_const.EGRESS_DIRECTION))
        return cmds
555346
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
                            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    ret = {'result': True, 'comment': '', 'changes': {}}
    exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
                                              profile, vpc_id, vpc_name)
    if not exists:
        if __opts__['test']:
            ret['comment'] = 'Security group {0} is set to be created.'.format(name)
            ret['result'] = None
            return ret
        created = __salt__['boto_secgroup.create'](name=name, description=description,
                                                   vpc_id=vpc_id, vpc_name=vpc_name,
                                                   region=region, key=key, keyid=keyid,
                                                   profile=profile)
        if created:
            ret['changes']['old'] = {'secgroup': None}
            sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
                                              keyid=keyid, profile=profile, vpc_id=vpc_id,
                                              vpc_name=vpc_name)
            ret['changes']['new'] = {'secgroup': sg}
            ret['comment'] = 'Security group {0} created.'.format(name)
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to create {0} security group.'.format(name)
    else:
        ret['comment'] = 'Security group {0} present.'.format(name)
    return ret
274465
def _apply_dvportgroup_security_policy(pg_name, sec_policy, sec_policy_conf):
    '''
    
    '''
    log.trace('Building portgroup\'s \'%s\' security policy ', pg_name)
    if 'allow_promiscuous' in sec_policy_conf:
        sec_policy.allowPromiscuous = vim.BoolPolicy()
        sec_policy.allowPromiscuous.value = \
                sec_policy_conf['allow_promiscuous']
    if 'forged_transmits' in sec_policy_conf:
        sec_policy.forgedTransmits = vim.BoolPolicy()
        sec_policy.forgedTransmits.value = sec_policy_conf['forged_transmits']
    if 'mac_changes' in sec_policy_conf:
        sec_policy.macChanges = vim.BoolPolicy()
        sec_policy.macChanges.value = sec_policy_conf['mac_changes']
1060032
def _check_security_groups(self, names):
        
        self._init_os_api()
        log.debug("Checking existence of security group(s) %s ...", names)
        try:
            # python-novaclient < 8.0.0
            security_groups = self.nova_client.security_groups.list()
            existing = set(sg.name for sg in security_groups)
        except AttributeError:
            security_groups = self.neutron_client.list_security_groups()['security_groups']
            existing = set(sg[u'name'] for sg in security_groups)

        # TODO: We should be able to create the security group if it
        # doesn't exist and at least add a rule to accept ssh access.
        # Also, we should be able to add new rules to a security group
        # if needed.
        nonexisting = set(names) - existing
        if nonexisting:
            raise SecurityGroupError(
                "Security group(s) `{0}` do not exist"
                .format(', '.join(nonexisting)))

        # if we get to this point, all sec groups exist
        return True
737055
def build_ports_dict(nsg, direction_key, ip_protocol):
        
        rules = nsg['properties']['securityRules']
        rules = sorted(rules, key=lambda k: k['properties']['priority'])
        ports = {}

        for rule in rules:
            # Skip rules with different direction
            if not StringUtils.equal(direction_key, rule['properties']['direction']):
                continue

            # Check the protocol: possible values are 'TCP', 'UDP', '*' (both)
            # Skip only if rule and ip_protocol are 'TCP'/'UDP' pair.
            protocol = rule['properties']['protocol']
            if not StringUtils.equal(protocol, "*") and \
               not StringUtils.equal(ip_protocol, "*") and \
               not StringUtils.equal(protocol, ip_protocol):
                continue

            IsAllowed = StringUtils.equal(rule['properties']['access'], 'allow')
            ports_set = PortsRangeHelper.get_ports_set_from_rule(rule)

            for p in ports_set:
                if p not in ports:
                    ports[p] = IsAllowed

        return ports
773849
def allow(ip,
        port=None,
        proto='tcp',
        direction='in',
        port_origin='d',
        ip_origin='s',
        ttl=None,
        comment=''):
    '''
    
    '''
    return _access_rule('allow',
                        ip,
                        port=port,
                        proto=proto,
                        direction=direction,
                        port_origin=port_origin,
                        ip_origin=ip_origin,
                        comment=comment)
1060835
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
           keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not vpc_id and vpc_name:
        try:
            vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
                                key=key, keyid=keyid, profile=profile)
        except boto.exception.BotoServerError as e:
            log.debug(e)
            return False

    created = conn.create_security_group(name, description, vpc_id)
    if created:
        log.info('Created security group %s.', name)
        return True
    else:
        msg = 'Failed to create security group {0}.'.format(name)
        log.error(msg)
        return False
1028511
def setup(self):
        self.client = self._get_client()
        sg = self._create_isolation_security_group()
        if self.exists is not True:
            acl = self._create_network_acl()
            self._add_network_acl_entries(acl)
            self._add_security_group_rule(sg)
        self._add_security_group_to_instance(sg)

        """"""
        if self.dry_run is not False:
            self._add_security_group_rule(sg)
            self._add_security_group_to_instance(sg)
97636
def update_instance_security_group(self, instance_id,
                                       new_security_group_ids):
        """"""
        ports = port_list(self.request, device_id=instance_id)
        for p in ports:
            params = {'security_groups': new_security_group_ids}
            port_update(self.request, p.id, **params)
661562
def add(env, securitygroup_id, network_component, server, interface):
    """"""
    _validate_args(network_component, server, interface)

    mgr = SoftLayer.NetworkManager(env.client)
    component_id = _get_component_id(env, network_component, server, interface)

    ret = mgr.attach_securitygroup_component(securitygroup_id,
                                             component_id)
    if not ret:
        raise exceptions.CLIAbort("Could not attach network component")

    table = formatting.Table(REQUEST_COLUMNS)
    table.add_row([ret['requestId']])

    env.fout(table)
1059197
def check_network(session, configure_network, network, subnet,
                  dns_nameservers=None, allocation_pool=None):
    
    nclient = neutron.Client('2', session=session,
                             region_name=os.environ['OS_REGION_NAME'])

    # Check the security groups
    secgroups = nclient.list_security_groups()['security_groups']
    secgroup_name = SECGROUP_NAME
    if secgroup_name not in list(map(itemgetter('name'), secgroups)):
        secgroup = {'name': secgroup_name,
                    'description': 'Enos Security Group'}
        res = nclient.create_security_group({'security_group': secgroup})
        secgroup = res['security_group']
        logger.info("[neutron]: %s security group created" % secgroup_name)
        # create the rules
        tcp = {'protocol': 'tcp',
               'direction': 'ingress',
               'port_range_min': '1',
               'port_range_max': '65535',
               'security_group_id': secgroup['id']}
        icmp = {'protocol': 'icmp',
                'direction': 'ingress',
                'security_group_id': secgroup['id']}
        nclient.create_security_group_rule({'security_group_rule': tcp})
        logger.info("[neutron]: %s rule (all tcp) created" % secgroup_name)
        nclient.create_security_group_rule({'security_group_rule': icmp})
        logger.info("[neutron]: %s rule (all icmp) created" % secgroup_name)
    else:
        logger.info("[neutron]: Reusing security-groups %s " % secgroup_name)

    networks = nclient.list_networks()['networks']
    network_name = network['name']
    if network_name not in list(map(itemgetter('name'), networks)):
        network = {'name': network_name}
        res = nclient.create_network({'network': network})
        network = res['network']
        logger.info("[neutron]: %s network created" % network_name)
    else:
        network = [n for n in networks if n['name'] == network_name][0]
        logger.info("[neutron]: Reusing existing %s network", network)

    # find ext_net
    ext_net = [n for n in networks if n['router:external']]
    if len(ext_net) < 1:
        raise Exception("No external network found")
    ext_net = ext_net[0]

    subnets = nclient.list_subnets()['subnets']
    subnet_name = subnet['name']
    if (subnet_name not in list(map(itemgetter('name'), subnets))
            and configure_network):
        subnet = {'name': subnet['name'],
                  'network_id': network['id'],
                  # NOTE(msimonin): using the dns of chameleon
                  # for a generic openstack provider we should think to
                  # parameteried this or use public available dns
                  'cidr': subnet['cidr'],
                  'ip_version': 4}
        if dns_nameservers is not None:
            subnet.update({'dns_nameservers': dns_nameservers})
        if allocation_pool is not None:
            subnet.update({'allocation_pools': [allocation_pool]})

        s = nclient.create_subnet({'subnet': subnet})
        logger.debug(s)
        subnet = s['subnet']
        logger.info("[neutron]: %s subnet created" % subnet_name)
    else:
        subnet = [s for s in subnets if s['name'] == subnet_name][0]
        logger.info("[neutron]: Reusing %s subnet", subnet)

    # create a router
    routers = nclient.list_routers()
    router_name = ROUTER_NAME
    logger.debug(routers)
    router_present = router_name not in [r['name'] for r in routers['routers']]
    if (router_present and configure_network):
        router = {
            'name': router_name,
            'external_gateway_info': {
                'network_id': ext_net['id']
            }
        }
        r = nclient.create_router({'router': router})
        logger.info("[neutron]  %s router created" % router_name)
        # NOTE(msimonin): We should check the interface outside this block
        # in case the router is created but the interface is not added
        interface = {
            'subnet_id': subnet['id'].encode('UTF-8')
        }
        nclient.add_interface_router(str(r['router']['id']), interface)

    return (ext_net, network, subnet)