Process rules into cidr and non-cidr lists.

        Args:
            rules (list): Allowed Security Group ports and protocols.

        Returns:
            (list, list): Security Group reference rules and custom CIDR rules.
346499
def _process_rules(self, rules):
        
        cidr = []
        non_cidr = []

        for rule in rules:
            if '.' in rule['app']:
                self.log.debug('Custom CIDR rule: %s', rule)
                self._validate_cidr(rule)
                cidr.append(rule)
            else:
                self.log.debug('SG reference rule: %s', rule)
                non_cidr.append(rule)

        self.log.debug('Custom CIDR rules: %s', cidr)
        self.log.debug('SG reference rules: %s', non_cidr)
        return non_cidr, cidr
992753
def list(self, rule, **kwargs):
        
        return '<ul class="pynspect-rule-list">{}</ul>'.format(''.join(['<li class="pynspect-rule-list-item">{}</li>'.format(v.traverse(self, **kwargs)) for v in rule.value]))
1160262
def remove_rule(self, ip_protocol, from_port, to_port,
                    src_group_name, src_group_owner_id, cidr_ip):
        
        target_rule = None
        for rule in self.rules:
            if rule.ip_protocol == ip_protocol:
                if rule.from_port == from_port:
                    if rule.to_port == to_port:
                        target_rule = rule
                        target_grant = None
                        for grant in rule.grants:
                            if grant.name == src_group_name:
                                if grant.owner_id == src_group_owner_id:
                                    if grant.cidr_ip == cidr_ip:
                                        target_grant = grant
                        if target_grant:
                            rule.grants.remove(target_grant)
        if len(rule.grants) == 0:
            self.rules.remove(target_rule)
332981
def parse_volgroup(rule):
    '''
    
    '''
    parser = argparse.ArgumentParser()
    rules = shlex.split(rule)
    rules.pop(0)

    partitions = []
    newrules = []
    for count in range(0, len(rules)):
        if count == 0:
            newrules.append(rules[count])
            continue
        elif rules[count].startswith('--'):
            newrules.append(rules[count])
            continue
        else:
            partitions.append(rules[count])
    rules = newrules

    parser.add_argument('name')
    parser.add_argument('--noformat', dest='noformat', action='store_true')
    parser.add_argument('--useexisting', dest='useexisting',
                        action='store_true')
    parser.add_argument('--pesize', dest='pesize', action='store')
    parser.add_argument('--reserved-space', dest='reserved-space',
                        action='store')
    parser.add_argument('--reserved-percent', dest='reserved-percent',
                        action='store')

    args = clean_args(vars(parser.parse_args(rules)))
    if partitions:
        args['partitions'] = partitions
    parser = None
    return args
970107
def sync(self, rules: list):
        
        self._reset()
        old_rules = self.rules
        to_delete_rules = [
            rule for rule in old_rules
            if rule not in rules
        ]
        new_rules = [
            rule for rule in rules
            if rule not in old_rules
        ]

        for new_rule in new_rules:
            assert isinstance(new_rule, Rule)
            self._exec_command(new_rule.add_command)
        for to_delete_rule in to_delete_rules:
            assert isinstance(to_delete_rule, Rule)
            self._exec_command(
                to_delete_rule.remove_command
            )
        self._update(rules)
583107
def parse_rules(content=None):
    
    rules = content.split(DELIMITER)
    parsed_rules = list()
    order = 1
    for rule in rules:
        if rule.strip() == '':
            continue
        parsed_rule = {}
        lines = rule.split("\n")
        parsed_rule['orderValue'] = order
        order += 1
        for line in lines:
            if line.strip() == '':
                continue
            key_value = line.strip().split(':')
            key = key_value[0].strip()
            value = key_value[1].strip()
            if key == 'action':
                parsed_rule['action'] = value
            elif key == 'protocol':
                parsed_rule['protocol'] = value
            elif key == 'source_ip_address':
                parsed_rule['sourceIpAddress'] = value
            elif key == 'source_ip_subnet_mask':
                parsed_rule['sourceIpSubnetMask'] = value
            elif key == 'destination_ip_address':
                parsed_rule['destinationIpAddress'] = value
            elif key == 'destination_ip_subnet_mask':
                parsed_rule['destinationIpSubnetMask'] = value
            elif key == 'destination_port_range_start':
                parsed_rule['destinationPortRangeStart'] = int(value)
            elif key == 'destination_port_range_end':
                parsed_rule['destinationPortRangeEnd'] = int(value)
            elif key == 'version':
                parsed_rule['version'] = int(value)
        parsed_rules.append(parsed_rule)
    return parsed_rules
226220
def get_loaded_rules(rules_paths):
    
    for path in rules_paths:
        if path.name != '__init__.py':
            rule = Rule.from_path(path)
            if rule.is_enabled:
                yield rule
1129373
def _apply_commit_rules(rules, commit):
        
        all_violations = []
        for rule in rules:
            violations = rule.validate(commit)
            if violations:
                all_violations.extend(violations)
        return all_violations
1014662
def register_rules(self, rules):
    
    if not isinstance(rules, Iterable):
      raise TypeError('The rules must be an iterable, given {!r}'.format(rules))

    # "Index" the rules to normalize them and expand their dependencies.
    normalized_rules = RuleIndex.create(rules).normalized_rules()
    indexed_rules = normalized_rules.rules
    union_rules = normalized_rules.union_rules

    # Store the rules and record their dependency Optionables.
    self._rules.update(indexed_rules)
    self._union_rules.update(union_rules)
    dependency_optionables = {do
                              for rule in indexed_rules
                              for do in rule.dependency_optionables
                              if rule.dependency_optionables}
    self.register_optionables(dependency_optionables)
946721
def _get_rule_port_ranges(rule):
        
        properties = rule['properties']
        if 'destinationPortRange' in properties:
            return [PortsRangeHelper._get_port_range(properties['destinationPortRange'])]
        else:
            return [PortsRangeHelper._get_port_range(r)
                    for r in properties['destinationPortRanges']]
387958
def with_rule(self, rule):
        
        self.rules = self.rules if self.rules != None else []
        self.rules.append(rule)
        return self
328984
def _load_rules(self):
        
        with self._sftp_connection.open(self.RULE_PATH) as file:
            data = file.read()
        lines = (
            line.strip()
            for line in data.split('\n')
        )
        rule_strings = (
            line for line in lines
            if len(line) > 0
        )
        rules = (
            Rule.parse(rule_string)
            for rule_string in rule_strings
        )
        self._rules = [
            rule
            for rule in rules
            if rule is not None
        ]
205577
def find_existing(self):
        
        sg = self.consul.find_secgroup(self.name)

        current = sg.rules
        log.debug('Current rules: %s' % current)
        log.debug('Intended rules: %s' % self.rules)
        exp_rules = []
        for rule in self.rules:
            exp = (
                    rule[A.secgroup.PROTOCOL],
                    rule[A.secgroup.FROM],
                    rule[A.secgroup.TO],
                    rule[A.secgroup.SOURCE],
                    )
            exp_rules.append(exp)
            if exp in current:
                del current[exp]
            else:
                self.create_these_rules.append(exp)

        self.delete_these_rules.extend(current.itervalues())

        log.debug('Create these rules: %s' % self.create_these_rules)
        log.debug('Delete these rules: %s' % self.delete_these_rules)
262069
def _validate_cidr(self, rule):
        
        try:
            network = ipaddress.IPv4Network(rule['app'])
        except (ipaddress.NetmaskValueError, ValueError) as error:
            raise SpinnakerSecurityGroupCreationFailed(error)

        self.log.debug('Validating CIDR: %s', network.exploded)

        return True
966026
def get_rules():
    
    paths = [rule_path for path in get_rules_import_paths()
             for rule_path in sorted(path.glob('*.py'))]
    return sorted(get_loaded_rules(paths),
                  key=lambda rule: rule.priority)
695073
def _get_rules_from_aws(self):
        
        list_of_rules = list()

        if self.profile:
            boto3.setup_default_session(profile_name=self.profile)

        if self.region:
            ec2 = boto3.client('ec2', region_name=self.region)
        else:
            ec2 = boto3.client('ec2')

        security_groups = ec2.describe_security_groups(Filters=self.filters)

        for group in security_groups['SecurityGroups']:
            group_dict = dict()
            group_dict['id'] = group['GroupId']
            group_dict['name'] = group['GroupName']
            group_dict['description'] = group.get('Description', None)

            if (group.get('IpPermissions', None) or
                    group.get('IpPermissionsEgress', None)):
                group_dict['rules'] = list()

            for rule in group.get('IpPermissions', None):
                rule_dict = self._build_rule(rule)
                rule_dict['direction'] = "INGRESS"

                group_dict['rules'].append(rule_dict)

            for rule in group.get('IpPermissionsEgress', None):
                rule_dict = self._build_rule(rule)
                rule_dict['direction'] = "EGRESS"

                group_dict['rules'].append(rule_dict)

            list_of_rules.append(group_dict)

        return list_of_rules
638522
def parse_iptables_rule(line):
    '''
    
    '''

    bits = line.split()

    definition = {}

    key = None
    args = []
    not_arg = False

    def add_args():
        arg_string = ' '.join(args)

        if key in IPTABLES_ARGS:
            definition_key = (
                'not_{0}'.format(IPTABLES_ARGS[key])
                if not_arg
                else IPTABLES_ARGS[key]
            )
            definition[definition_key] = arg_string
        else:
            definition.setdefault('extras', []).extend((key, arg_string))

    for bit in bits:
        if bit == '!':
            if key:
                add_args()
                args = []
                key = None

            not_arg = True

        elif bit.startswith('-'):
            if key:
                add_args()
                args = []
                not_arg = False

            key = bit

        else:
            args.append(bit)

    if key:
        add_args()

    if 'extras' in definition:
        definition['extras'] = set(definition['extras'])

    return definition