How to use the c7n.filters.ValueFilter function in c7n

To help you get started, we’ve selected a few c7n examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cloud-custodian / cloud-custodian / c7n / resources / rds.py View on Github external
Applies value type filter on set db parameter values.
    :example:

    .. code-block:: yaml

            policies:
              - name: rds-pg
                resource: rds
                filters:
                  - type: db-parameter
                    key: someparam
                    op: eq
                    value: someval
    """

    schema = type_schema('db-parameter', rinherit=ValueFilter.schema)
    schema_alias = False
    permissions = ('rds:DescribeDBInstances', 'rds:DescribeDBParameters', )

    @staticmethod
    def recast(val, datatype):
        """ Re-cast the value based upon an AWS supplied datatype
            and treat nulls sensibly.
        """
        ret_val = val
        if datatype == 'string':
            ret_val = str(val)
        elif datatype == 'boolean':
            # AWS returns 1s and 0s for boolean for most of the cases
            if val.isdigit():
                ret_val = bool(int(val))
            # AWS returns 'TRUE,FALSE' for Oracle engine
github cloud-custodian / cloud-custodian / c7n / resources / account.py View on Github external
client = local_session(
            self.manager.session_factory).client('ec2')
        state = self.data.get('state')
        key = self.data.get('key')
        if state:
            client.enable_ebs_encryption_by_default()
        else:
            client.disable_ebs_encryption_by_default()

        if state and key:
            client.modify_ebs_default_kms_key_id(
                KmsKeyId=self.data['key'])


@filters.register('s3-public-block')
class S3PublicBlock(ValueFilter):
    """Check for s3 public blocks on an account.

    https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html
    """

    annotation_key = 'c7n:s3-public-block'
    annotate = False  # no annotation from value filter
    schema = type_schema('s3-public-block', rinherit=ValueFilter.schema)
    schema_alias = False
    permissions = ('s3:GetAccountPublicAccessBlock',)

    def process(self, resources, event=None):
        self.augment([r for r in resources if self.annotation_key not in r])
        return super(S3PublicBlock, self).process(resources, event)

    def augment(self, resources):
github cloud-custodian / cloud-custodian / c7n / resources / account.py View on Github external
schema_alias = False
    permissions = ('iam:GetAccountSummary',)

    def process(self, resources, event=None):
        if not resources[0].get('c7n:iam_summary'):
            client = local_session(
                self.manager.session_factory).client('iam')
            resources[0]['c7n:iam_summary'] = client.get_account_summary(
            )['SummaryMap']
        if self.match(resources[0]['c7n:iam_summary']):
            return resources
        return []


@filters.register('password-policy')
class AccountPasswordPolicy(ValueFilter):
    """Check an account's password policy.

    Note that on top of the default password policy fields, we also add an extra key,
    PasswordPolicyConfigured which will be set to true or false to signify if the given
    account has attempted to set a policy at all.

    :example:

    .. code-block:: yaml

            policies:
              - name: password-policy-check
                resource: account
                region: us-east-1
                filters:
                  - type: password-policy
github cloud-custodian / cloud-custodian / c7n / resources / iam.py View on Github external
user_set = chunks(resources, size=50)
        with self.executor_factory(max_workers=2) as w:
            self.log.debug(
                "Querying %d users policies" % len(resources))
            list(w.map(self.user_policies, user_set))

        matched = []
        for r in resources:
            for p in r['c7n:Policies']:
                if self.match(p) and r not in matched:
                    matched.append(r)
        return matched


@User.filter_registry.register('group')
class GroupMembership(ValueFilter):
    """Filter IAM users based on attached group values

    :example:

    .. code-block:: yaml

        policies:
          - name: iam-users-in-admin-group
            resource: iam-user
            filters:
              - type: group
                key: GroupName
                value: Admins
    """

    schema = type_schema('group', rinherit=ValueFilter.schema)
github cloud-custodian / cloud-custodian / c7n / resources / apigw.py View on Github external
def process(self, resources):
        client = utils.local_session(self.manager.session_factory).client('apigateway')

        for r in resources:
            for i in r.get(ANNOTATION_KEY_MATCHED_INTEGRATIONS, []):
                try:
                    client.delete_integration(
                        restApiId=i['restApiId'],
                        resourceId=i['resourceId'],
                        httpMethod=i['resourceHttpMethod'])
                except client.exceptions.NotFoundException:
                    continue


@RestResource.filter_registry.register('rest-method')
class FilterRestMethod(ValueFilter):
    """Filter rest resources based on a key value for the rest method of the api

    :example:

    .. code-block:: yaml

        policies:
          - name: api-without-key-required
            resource: rest-resource
            filters:
              - type: rest-method
                key: apiKeyRequired
                value: false
    """

    schema = utils.type_schema(
github davidclin / cloudcustodian-policies / custom-site-packages / iam.py View on Github external
value: 30
           op: less-than

    Credential Report Transforms

    We perform some default transformations from the raw
    credential report. Sub-objects (access_key_1, cert_2)
    are turned into array of dictionaries for matching
    purposes with their common prefixes stripped.
    N/A values are turned into None, TRUE/FALSE are turned
    into boolean values.

    """
    schema = type_schema(
        'credential',
        value_type=ValueFilter.schema['properties']['value_type'],

        key={'type': 'string',
             'title': 'report key to search',
             'enum': [
                 'user',
                 'arn',
                 'user_creation_time',
                 'password_enabled',
                 'password_last_used',
                 'password_last_changed',
                 'password_next_rotation',
                 'mfa_active',
                 'access_keys',
                 'access_keys.active',
                 'access_keys.last_used_date',
                 'access_keys.last_used_region',
github cloud-custodian / cloud-custodian / c7n / resources / ecr.py View on Github external
client = local_session(self.manager.session_factory).client('ecr')
        for r in resources:
            if self.policy_annotation in r:
                continue
            try:
                r[self.policy_annotation] = json.loads(
                    client.get_lifecycle_policy(
                        repositoryName=r['repositoryName']).get(
                            'lifecyclePolicyText', ''))
            except client.exceptions.LifecyclePolicyNotFoundException:
                r[self.policy_annotation] = {}

        state = self.data.get('state', False)
        matchers = []
        for matcher in self.data.get('match', []):
            vf = ValueFilter(matcher)
            vf.annotate = False
            matchers.append(vf)

        results = []
        for r in resources:
            found = False
            for rule in r[self.policy_annotation].get('rules', []):
                found = True
                for m in matchers:
                    if not m(rule):
                        found = False
            if found and state:
                results.append(r)
            if not found and not state:
                results.append(r)
        return results
github cloud-custodian / cloud-custodian / c7n / resources / iam.py View on Github external
for r in resources:
            k_matched = []
            for k in r[self.annotation_key]:
                if self.match(k):
                    k_matched.append(k)
            for k in k_matched:
                k['c7n:matched-type'] = 'access'
            self.merge_annotation(r, self.matched_annotation_key, k_matched)
            if k_matched:
                matched.append(r)
        return matched


# Mfa-device filter for iam-users
@User.filter_registry.register('mfa-device')
class UserMfaDevice(ValueFilter):
    """Filter iam-users based on mfa-device status

    :example:

    .. code-block:: yaml

        policies:
          - name: mfa-enabled-users
            resource: iam-user
            filters:
              - type: mfa-device
                key: UserName
                value: not-null
    """

    schema = type_schema('mfa-device', rinherit=ValueFilter.schema)
github cloud-custodian / cloud-custodian / tools / c7n_azure / c7n_azure / resources / cosmos_db.py View on Github external
def get_resource_id(self, resource):
        return resource['c7n:parent-id']

    def get_filter(self, resource):
        container_filter = "DatabaseName eq '%s' and CollectionName eq '%s'" \
            % (resource['c7n:database'], resource['id'])

        if self.filter is not None:
            container_filter = "%s and %s" % (self.filter, container_filter)

        return container_filter


@CosmosDBCollection.filter_registry.register('offer')
@CosmosDBDatabase.filter_registry.register('offer')
class CosmosDBOfferFilter(ValueFilter):
    """CosmosDB Offer Filter

    Allows access to the offer on a collection or database.

    :example:

    This policy will find all collections with a V2 offer which indicates
    throughput is provisioned at the collection scope.

    .. code-block:: yaml

        policies:
          - name: cosmosdb-collection-high-throughput
            resource: azure.cosmosdb-collection
            filters:
              - type: offer
github cloud-custodian / cloud-custodian / tools / c7n_azure / c7n_azure / filters.py View on Github external
.. code-block:: yaml

            policies:
                - name: expensive-sql-servers
                  resource: azure.sqlserver
                  filters:
                  - type: cost
                    timeframe: 30
                    op: gt
                    value: 2000
    """

    preset_timeframes = [i.value for i in TimeframeType if i.value != 'Custom']

    schema = type_schema('cost',
        rinherit=ValueFilter.schema,
        required=['timeframe'],
        key=None,
        **{
            'timeframe': {
                'oneOf': [
                    {'enum': preset_timeframes},
                    {"type": "number", "minimum": 1}
                ]
            }
        })

    schema_alias = True
    log = logging.getLogger('custodian.azure.filters.CostFilter')

    def __init__(self, data, manager=None):
        data['key'] = 'PreTaxCost'  # can also be Currency, but now only PreTaxCost is supported