Audit Collector Instance built with required config settings
508842
public static AuditCollector prototype(List<String> servers) {
        AuditCollector protoType = new AuditCollector();
        protoType.setName("AuditCollector");
        protoType.setCollectorType(CollectorType.Audit);
        protoType.setOnline(true);
        protoType.setEnabled(true);
        protoType.auditServers.addAll(servers);
        return protoType;
    }
38029
function useDefaultConfig(){
	logger.info(process.cwd());
	if(fileutil.isExist(path.join(process.cwd() , "/config.json"))){
		var jsonconfig = require(path.join(process.cwd() ,'/config.json'));
		buildFromJsonConfig(jsonconfig);
	}else{
		logger.warn("config.json is not found. Checking for directory structure");
		buildFromDirectory(process.cwd());
	}
}
781467
def __store_config(self, args, kwargs):
        
        signature = (
            'schema',
            'ignore_none_values',
            'allow_unknown',
            'require_all',
            'purge_unknown',
            'purge_readonly',
        )
        for i, p in enumerate(signature[: len(args)]):
            if p in kwargs:
                raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
            else:
                kwargs[p] = args[i]
        self._config = kwargs
        """ This dictionary holds the configuration arguments that were used to
            initialize the :class:`Validator` instance except the
            ``error_handler``. """
776370
public DescribeAccountAuditConfigurationResult withAuditCheckConfigurations(java.util.Map<String, AuditCheckConfiguration> auditCheckConfigurations) {
        setAuditCheckConfigurations(auditCheckConfigurations);
        return this;
    }
1182939
def get_registered_instances(self, include_removed=False):
        
        rval = []
        configs = self.state.get('config_files', {}).values()
        if include_removed:
            configs.extend(self.state.get('remove_configs', {}).values())
        for config in configs:
            if config['instance_name'] not in rval:
                rval.append(config['instance_name'])
        return rval
748237
def audit(anchore_config, ctx, image, imagefile, include_allanchore):
    

    global config, imagelist, nav
    ecode = 0
    success = True
    config = anchore_config

    #include_allanchore = True

    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    #if image or imagefile:
    #    include_allanchore = False

    try:
        imagedict = build_image_list(anchore_config, image, imagefile, not (image or imagefile), include_allanchore)
        imagelist = imagedict.keys()
        try:
            ret = anchore_utils.discover_imageIds(imagelist)
        except ValueError as err:
            raise err
        else:
            imagelist = ret

    except Exception as err:
        anchore_print_err("could not load input images")
        sys.exit(1)
914463
def configure(self, options, conf):
        
        super(LeakDetectorPlugin, self).configure(options, conf)
        if options.leak_detector_level:
            self.reporting_level = int(options.leak_detector_level)
        self.report_delta = options.leak_detector_report_delta
        self.patch_mock = options.leak_detector_patch_mock
        self.ignore_patterns = options.leak_detector_ignore_patterns
        self.save_traceback = options.leak_detector_save_traceback
        self.multiprocessing_enabled = bool(getattr(options, 'multiprocess_workers', False))
622026
def process_config(self):
        
        if 'byte_unit' in self.config:
            if isinstance(self.config['byte_unit'], basestring):
                self.config['byte_unit'] = self.config['byte_unit'].split()

        if 'enabled' in self.config:
            self.config['enabled'] = str_to_bool(self.config['enabled'])

        if 'measure_collector_time' in self.config:
            self.config['measure_collector_time'] = str_to_bool(
                self.config['measure_collector_time'])

        # Raise an error if both whitelist and blacklist are specified
        if ((self.config.get('metrics_whitelist', None) and
             self.config.get('metrics_blacklist', None))):
            raise DiamondException(
                'Both metrics_whitelist and metrics_blacklist specified ' +
                'in file %s' % self.configfile)

        if self.config.get('metrics_whitelist', None):
            self.config['metrics_whitelist'] = re.compile(
                self.config['metrics_whitelist'])
        elif self.config.get('metrics_blacklist', None):
            self.config['metrics_blacklist'] = re.compile(
                self.config['metrics_blacklist'])
740986
def get_default_config(self):
        
        config = super(IPMISensorCollector, self).get_default_config()
        config.update({
            'bin':              '/usr/bin/ipmitool',
            'use_sudo':         False,
            'sudo_cmd':         '/usr/bin/sudo',
            'path':             'ipmi.sensors',
            'thresholds':       False,
            'delimiter':        '.'
        })
        return config
1258159
def get_default_config(self):
        
        config = super(ChronydCollector, self).get_default_config()
        config.update({
            'path':             'chrony',
            'bin':              '/usr/bin/chronyc',
            'use_sudo':         False,
            'sudo_cmd':         '/usr/bin/sudo',
        })
        return config
23351
def get_default_config(self):
        
        config = super(ArchiveHandler, self).get_default_config()

        config.update({
            'log_file': '',
            'when': 'midnight',
            'days': 7,
            'rollover_interval': 1,
            'encoding': None,
            'propagate': False,
        })

        return config
1283386
def get_audits():
    
    audits = [TemplatedFile('/etc/login.defs', LoginContext(),
                            template_dir=TEMPLATES_DIR,
                            user='root', group='root', mode=0o0444)]
    return audits
1275589
def init_auditlog(portal):
    
    # reindex the auditlog folder to display the icon right in the setup
    portal.bika_setup.auditlog.reindexObject()

    # Initialize contents for audit logging
    start = time.time()
    uid_catalog = api.get_tool("uid_catalog")
    brains = uid_catalog()
    total = len(brains)

    logger.info("Initializing {} objects for the audit trail...".format(total))
    for num, brain in enumerate(brains):
        # Progress notification
        if num and num % 1000 == 0:
            transaction.commit()
            logger.info("{}/{} ojects initialized for audit logging"
                        .format(num, total))
        # End progress notification
        if num + 1 == total:
            end = time.time()
            duration = float(end-start)
            logger.info("{} ojects initialized for audit logging in {:.2f}s"
                        .format(total, duration))

        if api.get_portal_type(brain) in SKIP_TYPES_FOR_AUDIT_LOG:
            continue

        obj = api.get_object(brain)

        if not supports_snapshots(obj):
            continue

        if has_snapshots(obj):
            continue

        # Take one snapshot per review history item
        rh = api.get_review_history(obj, rev=False)
        for item in rh:
            actor = item.get("actor")
            user = get_user(actor)
            if user:
                # remember the roles of the actor
                item["roles"] = get_roles(user)
            # The review history contains the variable "time" which we will set
            # as the "modification" time
            timestamp = item.pop("time", DateTime())
            item["time"] = timestamp.ISO()
            item["modified"] = timestamp.ISO()
            item["remote_address"] = None
            take_snapshot(obj, **item)
397813
def get_audits():
    
    audits = []
    settings = utils.get_settings('os')

    # Ensure that the /etc/security/limits.d directory is only writable
    # by the root user, but others can execute and read.
    audits.append(DirectoryPermissionAudit('/etc/security/limits.d',
                                           user='root', group='root',
                                           mode=0o755))

    # If core dumps are not enabled, then don't allow core dumps to be
    # created as they may contain sensitive information.
    if not settings['security']['kernel_enable_core_dump']:
        audits.append(TemplatedFile('/etc/security/limits.d/10.hardcore.conf',
                                    SecurityLimitsContext(),
                                    template_dir=TEMPLATES_DIR,
                                    user='root', group='root', mode=0o0440))
    return audits
1046130
def archive_bird_conf(config_file, changes_counter):
    
    log = logging.getLogger(PROGRAM_NAME)
    history_dir = os.path.join(os.path.dirname(config_file), 'history')
    dst = os.path.join(history_dir, str(time.time()))
    log.debug("coping %s to %s", config_file, dst)

    history = [x for x in os.listdir(history_dir)
               if os.path.isfile(os.path.join(history_dir, x))]

    if len(history) > changes_counter:
        log.info("threshold of %s is reached, removing old files",
                 changes_counter)
        for _file in sorted(history, reverse=True)[changes_counter - 1:]:
            _path = os.path.join(history_dir, _file)
            try:
                os.remove(_path)
            except OSError as exc:
                log.warning("failed to remove %s: %s", _file, exc)
            else:
                log.info("removed %s", _path)

    try:
        shutil.copy2(config_file, dst)
    except OSError as exc:
        log.warning("failed to copy %s to %s: %s", config_file, dst, exc)
1073185
def run(self, *args, **kwargs):
        
        try:
            zones = list(DNSZone.get_all().values())
            buckets = {k.lower(): v for k, v in S3Bucket.get_all().items()}
            dists = list(CloudFrontDist.get_all().values())
            ec2_public_ips = [x.public_ip for x in EC2Instance.get_all().values() if x.public_ip]
            beanstalks = {x.cname.lower(): x for x in BeanStalk.get_all().values()}

            existing_issues = DomainHijackIssue.get_all()
            issues = []

            # List of different types of domain audits
            auditors = [
                ElasticBeanstalkAudit(beanstalks),
                S3Audit(buckets),
                S3WithoutEndpointAudit(buckets),
                EC2PublicDns(ec2_public_ips),
            ]

            # region Build list of active issues
            for zone in zones:
                for record in zone.records:
                    for auditor in auditors:
                        if auditor.match(record):
                            issues.extend(auditor.audit(record, zone))

            for dist in dists:
                for org in dist.origins:
                    if org['type'] == 's3':
                        bucket = self.return_resource_name(org['source'], 's3')

                        if bucket not in buckets:
                            key = '{} ({})'.format(bucket, dist.type)
                            issues.append({
                                'key': key,
                                'value': 'S3Bucket {} doesnt exist on any known account. Referenced by {} on {}'.format(
                                    bucket,
                                    dist.domain_name,
                                    dist.account,
                                )
                            })
            # endregion

            # region Process new, old, fixed issue lists
            old_issues = {}
            new_issues = {}
            fixed_issues = []

            for data in issues:
                issue_id = get_resource_id('dhi', ['{}={}'.format(k, v) for k, v in data.items()])

                if issue_id in existing_issues:
                    issue = existing_issues[issue_id]

                    if issue.update({'state': 'EXISTING', 'end': None}):
                        db.session.add(issue.issue)

                    old_issues[issue_id] = issue

                else:
                    properties = {
                        'issue_hash': issue_id,
                        'state': 'NEW',
                        'start': datetime.now(),
                        'end': None,
                        'source': data['key'],
                        'description': data['value']
                    }
                    new_issues[issue_id] = DomainHijackIssue.create(issue_id, properties=properties)
            db.session.commit()

            for issue in list(existing_issues.values()):
                if issue.id not in new_issues and issue.id not in old_issues:
                    fixed_issues.append(issue.to_json())
                    db.session.delete(issue.issue)
            # endregion

            # Only alert if its been more than a day since the last alert
            alert_cutoff = datetime.now() - timedelta(hours=self.alert_frequency)
            old_alerts = []
            for issue_id, issue in old_issues.items():
                if issue.last_alert and issue.last_alert < alert_cutoff:
                    if issue.update({'last_alert': datetime.now()}):
                        db.session.add(issue.issue)

                    old_alerts.append(issue)

            db.session.commit()

            self.notify(
                [x.to_json() for x in new_issues.values()],
                [x.to_json() for x in old_alerts],
                fixed_issues
            )
        finally:
            db.session.rollback()
20419
function ImmutableAccessControl (args) {
    // make sure args are object
    args = requireValidOptionalObject(args)
    // return global singleton if it exists
    if (args.global !== false && global.__immutable_access_control__) {
        return global.__immutable_access_control__
    }
    // initialize new instance
    else {
        // store new instance as global singleton
        if (args.global !== false) {
            global.__immutable_access_control__ = this
        }
        // id will be calculated from rules after they are set
        this.id = undefined
        // names of properties use for determining ownership of model records
        // map of model name -> property name - default is accountId
        this.accessIdNames = {}
        // list of rules set with default flag
        this.defaultRules = []
        // rules object is a map of resources and roles 
        this.rules = {}
        // use strict mode by default which will throw error if requesting
        // access without a valid session
        this.strict = args.strict === undefined ? true : !!args.strict
        // audit will be create for each allow request
        this.audit = undefined
        // audit enabled by default
        this.auditEnabled = args.audit === false ? false : true
    }
}