Loads the rules from the SSH-Connection
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
        ]
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
274855
def load
      query = (arguments or self).info_sql
      Squirm.exec(query, [name, schema]) do |result|
        validate result
        set_values_from result
      end
      self
    end
372798
def _load_rules(self):
        """"""
        for ruleset in self.active_rulesets:
            section_name = 'sweep_rules_' + ruleset.lower()
            try:
                ruledefs = getattr(self.config, section_name)
            except AttributeError:
                raise error.UserError("There is no [{}] section in your configuration"
                                      .format(section_name.upper()))
            for ruledef, filtercond in ruledefs.items():
                if ruledef.endswith('.filter'):
                    rulename = ruledef.rsplit('.', 1)[0]
                    rule = SweepRule(ruleset, rulename,
                                     int(ruledefs.get(rulename + '.prio', '999')),
                                     ruledefs.get(rulename + '.order', self.default_order),
                                     parse_cond(filtercond))
                    self.rules.append(rule)

        self.rules.sort(key=lambda x: (x.prio, x.name))

        return self.rules
234495
async def _load(self, data, check=True):
        
        log.debug('Load proxies from the raw data')
        if isinstance(data, io.TextIOWrapper):
            data = data.read()
        if isinstance(data, str):
            data = IPPortPatternLine.findall(data)
        proxies = set(data)
        for proxy in proxies:
            await self._handle(proxy, check=check)
        await self._on_check.join()
        self._done()
361637
public function initRbacModules()
    {
        $this->stdout("Init rules, permissions adn data from all modules and extensions\n", Console::BOLD);
        $this->stdout("\t1) Loading config\n", Console::FG_YELLOW);
        if (!$config = $this->loadConfig()) {
            $this->stdout("Start script: not found data for rbac migrations", Console::FG_RED);
            die;
        }
        $this->stdout("\t2) Start migrations\n", Console::FG_YELLOW);
        $this->applyConfig($config);
        $this->stdout("\t3) Assigning roles, privileges, rules\n", Console::FG_YELLOW);
        $this->applyAssigningConfig($config);
    }
1234732
def parse_rules(data, chain):
    
    rules = []
    for line in data.splitlines(True):
        m = re_rule.match(line)
        if m and m.group(3) == chain:
            rule = parse_rule(m.group(4))
            rule.packets = int(m.group(1))
            rule.bytes = int(m.group(2))
            rules.append(rule)
    return rules
767329
protected function loadRules()
    {
        $old_cwd = getcwd();
        chdir(__DIR__);
        $path = 'Validate' . DIRECTORY_SEPARATOR . 'Rules';
        if (! is_dir($path)) {
            throw new ValidateException("Rules Directory " . $path . " isn't a directory...");
        }
        
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY);
        
        foreach ($files as $file) {
            if (! $file->isDir()) {
                $name = '\\JaegerApp\\' . str_replace('/', '\\', str_replace('.php', '', $file->getPathname()));
                $class = $name;
                if (class_exists($class)) {
                    $rule = new $class();
                    if ($rule instanceof Validate\RuleInterface) {
                        self::addRule($rule->getName(), array(
                            $rule,
                            'validate'
                        ), $rule->getErrorMessage());
                    }
                }
            }
        }
        
        chdir($old_cwd);
    }
1187955
def loadRule(rule_json_object):
    
    name = rule_json_object['name']
    rule_type = rule_json_object['rule_type']
    validation_regex = None
    required = False
    removehtml = False
    include_end_regex = False #Default to false for bakward compatibility
    strip_end_regex = None
    sub_rules = []
    begin_stripe_id = None
    end_stripe_id = None
    begin_shift = 0
    end_shift = 0

    if 'sub_rules' in rule_json_object:
        sub_rules = rule_json_object['sub_rules']
    
    if 'validation_regex' in rule_json_object:
        validation_regex = rule_json_object['validation_regex']
    
    if 'required' in rule_json_object:
        required = rule_json_object['required']
    
    if 'removehtml' in rule_json_object:
        removehtml = rule_json_object['removehtml']
        
    if 'include_end_regex' in rule_json_object:
        include_end_regex = rule_json_object['include_end_regex']
    
    if 'strip_end_regex' in rule_json_object:
        strip_end_regex = rule_json_object['strip_end_regex']

    if 'begin_stripe_id' in rule_json_object:
        begin_stripe_id = rule_json_object['begin_stripe_id']

    if 'end_stripe_id' in rule_json_object:
        end_stripe_id = rule_json_object['end_stripe_id']

    if 'begin_shift' in rule_json_object:
        begin_shift = rule_json_object['begin_shift']

    if 'end_shift' in rule_json_object:
        end_shift = rule_json_object['end_shift']

    rule = {}
    
    """ This is where we add our new type """
    if rule_type == ITEM_RULE or rule_type == 'RegexRule':
        begin_regex = rule_json_object['begin_regex']
        end_regex = rule_json_object['end_regex']
        rule = ItemRule(name, begin_regex, end_regex, include_end_regex, strip_end_regex, validation_regex, required,
                        removehtml, sub_rules, begin_stripe_id, end_stripe_id, begin_shift, end_shift)
    if rule_type == ITERATION_RULE or rule_type == 'RegexIterationRule':
        begin_regex = rule_json_object['begin_regex']
        end_regex = rule_json_object['end_regex']
        iter_begin_regex = rule_json_object['iter_begin_regex']
        iter_end_regex = rule_json_object['iter_end_regex']
        no_first_begin_iter_rule = False
        if 'no_first_begin_iter_rule' in rule_json_object:
            no_first_begin_iter_rule = rule_json_object['no_first_begin_iter_rule']
        no_last_end_iter_rule = False
        if 'no_last_end_iter_rule' in rule_json_object:
            no_last_end_iter_rule = rule_json_object['no_last_end_iter_rule']
        
        rule = IterationRule(name, begin_regex, end_regex, iter_begin_regex, iter_end_regex,
                                  include_end_regex, strip_end_regex, no_first_begin_iter_rule,
                                  no_last_end_iter_rule, validation_regex, required, removehtml,
                                  sub_rules, begin_shift=begin_shift, end_shift=end_shift)

    if 'id' in rule_json_object:
        rule.id = rule_json_object['id']
    
    return rule
1072899
def load_rule_definitions(self, ruleset_generator = False, rule_dirs = []):
        

        # Load rules from JSON files
        self.rule_definitions = {}
        for rule_filename in self.rules:
            for rule in self.rules[rule_filename]:
                if not rule.enabled and not ruleset_generator:
                    continue
            self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename, rule_dirs = rule_dirs)
        # In case of the ruleset generator, list all available built-in rules
        if ruleset_generator:
            rule_dirs.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/findings'))
            rule_filenames = []
            for rule_dir in rule_dirs:
                rule_filenames += [f for f in os.listdir(rule_dir) if os.path.isfile(os.path.join(rule_dir, f))]
            for rule_filename in rule_filenames:
                if rule_filename not in self.rule_definitions:
                    self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename)
708568
private void addRuleFiles(List<RuleSource> sources, File directory) throws MojoExecutionException {
        List<RuleSource> ruleSources = readRulesDirectory(directory);
        for (RuleSource ruleSource : ruleSources) {
            getLog().debug("Adding rules from file " + ruleSource);
            sources.add(ruleSource);
        }
    }
1193777
protected function connectRulesToLexer() {
        foreach ($this->rules as $childRule) {
            $childRule->prepare($this->lexer);

            if ($childRule->getName() === $this->startRule->getName()) {
                continue;
            }

            if ($this->startRule->acceptRule($childRule->getName())) {
                $childRule->embedInto($this->startRule->getName(), $this->lexer);
            }

            $childRule->finish($this->lexer);
        }
    }
373493
def _process_rules(self, rules: dict, system: System):
        
        self._source = None # reset the template source
        if not self._shall_proceed(rules):
            return
        self.context.update(rules.get('context', {}))
        self.path = rules.get('path', '')
        self.source = rules.get('source', None)
        self._process_rule(rules.get('system', None), {'system': system})
        for module in system.modules:
            self._process_rule(rules.get('module', None), {'module': module})
            for interface in module.interfaces:
                self._process_rule(rules.get('interface', None), {'interface': interface})
            for struct in module.structs:
                self._process_rule(rules.get('struct', None), {'struct': struct})
            for enum in module.enums:
                self._process_rule(rules.get('enum', None), {'enum': enum})
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
1129493
def import_public_keys(contents):
    """"""
    for line in io.StringIO(contents):
        # Verify this line represents valid SSH public key
        formats.import_public_key(line)
        yield line
1171065
def _load_ssh(self, tag):
        """"""
        for child in tag:
            if child.tag == "server":
                self._vardict["server"] = child.attrib
            elif child.tag == "codes":
                self._load_codes(child, True)
            elif child.tag == "mappings":
                self._load_mapping(child, True)
            elif child.tag == "libraries":
                self._load_includes(child, True)
233772
def _read_ssh_config(ssh_host,
                         ssh_config_file,
                         ssh_username=None,
                         ssh_pkey=None,
                         ssh_port=None,
                         ssh_proxy=None,
                         compression=None,
                         logger=None):
        
        ssh_config = paramiko.SSHConfig()
        if not ssh_config_file:  # handle case where it's an empty string
            ssh_config_file = None

        # Try to read SSH_CONFIG_FILE
        try:
            # open the ssh config file
            with open(os.path.expanduser(ssh_config_file), 'r') as f:
                ssh_config.parse(f)
            # looks for information for the destination system
            hostname_info = ssh_config.lookup(ssh_host)
            # gather settings for user, port and identity file
            # last resort: use the 'login name' of the user
            ssh_username = (
                ssh_username or
                hostname_info.get('user')
            )
            ssh_pkey = (
                ssh_pkey or
                hostname_info.get('identityfile', [None])[0]
            )
            ssh_host = hostname_info.get('hostname')
            ssh_port = ssh_port or hostname_info.get('port')

            proxycommand = hostname_info.get('proxycommand')
            ssh_proxy = ssh_proxy or (paramiko.ProxyCommand(proxycommand) if
                                      proxycommand else None)
            if compression is None:
                compression = hostname_info.get('compression', '')
                compression = True if compression.upper() == 'YES' else False
        except IOError:
            if logger:
                logger.warning(
                    'Could not read SSH configuration file: {0}'
                    .format(ssh_config_file)
                )
        except (AttributeError, TypeError):  # ssh_config_file is None
            if logger:
                logger.info('Skipping loading of ssh configuration file')
        finally:
            return (ssh_host,
                    ssh_username or getpass.getuser(),
                    ssh_pkey,
                    int(ssh_port) if ssh_port else 22,  # fallback value
                    ssh_proxy,
                    compression)