Skip to content

cloudfront

Sample rules

A few rules that use objects from this package:

non_car_cloudfront_protocol_version
from typing import List, Dict

from packaging import version

from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext
from cloudrail.knowledge.rules.aws.aws_base_rule import AwsBaseRule
from cloudrail.knowledge.rules.base_rule import Issue
from cloudrail.knowledge.rules.rule_parameters.base_paramerter import ParameterType


class CloudFrontEnsureVersionRule(AwsBaseRule):

    def get_id(self) -> str:
        return 'non_car_cloudfront_protocol_version'

    def execute(self, env_context: AwsEnvironmentContext, parameters: Dict[ParameterType, any]) -> List[Issue]:
        issues: List[Issue] = []

        for distribution_list in env_context.cloudfront_distribution_list:
            if self._version_check(distribution_list.viewer_cert.minimum_protocol_version):
                issues.append(
                    Issue(
                        f'The {distribution_list.get_type()} `{distribution_list.get_friendly_name()}` is set to use a minimum protocol version'
                        f' of `{distribution_list.viewer_cert.minimum_protocol_version}` whereas TLSv1.2_2019 is the recommended '
                        f'minimum', distribution_list, distribution_list))
        return issues

    def should_run_rule(self, environment_context: AwsEnvironmentContext) -> bool:
        return bool(environment_context.cloudfront_distribution_list)

    @staticmethod
    def _version_check(proto_version: str) -> bool:
        if proto_version != 'SSLv3':
            version_num = proto_version.replace('TLSv', '').replace('_', '.')
            return version.parse(version_num) < version.parse('1.2.2019')
        else:
            return True
non_car_cloudfront_distribution_encrypt_in_transit
from typing import List, Dict

from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext
from cloudrail.knowledge.context.aws.resources.cloudfront.cloudfront_distribution_list import CacheBehavior
from cloudrail.knowledge.rules.aws.aws_base_rule import AwsBaseRule
from cloudrail.knowledge.rules.base_rule import Issue
from cloudrail.knowledge.rules.rule_parameters.base_paramerter import ParameterType


class EnsureCloudfrontDistributionEncryptInTransitRule(AwsBaseRule):

    def get_id(self) -> str:
        return 'non_car_cloudfront_distribution_encrypt_in_transit'

    def execute(self, env_context: AwsEnvironmentContext, parameters: Dict[ParameterType, any]) -> List[Issue]:
        issues: List[Issue] = []

        for distribution in env_context.cloudfront_distribution_list:
            default_behavior_restricted = self._is_https_restricted(distribution.get_default_behavior().viewer_protocol_policy)
            ordered_behavior_list = distribution.get_ordered_behavior_list()
            ordered_cache_list = self._get_messages(ordered_behavior_list)
            ordered_cache_restricted = len(ordered_cache_list) == 0

            if not default_behavior_restricted and ordered_cache_restricted:
                issues.append(
                    Issue(
                        f"The {distribution.get_type()} `{distribution.get_friendly_name()}` is not set to use HTTPS to protect"
                        f" data in transit in default_cache_behavior", distribution, distribution))
            elif default_behavior_restricted and not ordered_cache_restricted:
                issues.append(
                    Issue(
                        f"The {distribution.get_type()} `{distribution.get_friendly_name()}` is not set to use HTTPS to protect"
                        f" data in transit in {ordered_cache_list}", distribution, distribution))
            elif not (default_behavior_restricted or ordered_cache_restricted):
                issues.append(
                    Issue(
                        f"The {distribution.get_type()} `{distribution.get_friendly_name()}` is not set to use HTTPS to protect"
                        f" data in transit default_cache_behavior"
                        f" and in {ordered_cache_list}", distribution, distribution))
        return issues

    @staticmethod
    def _is_https_restricted(protocol: str) -> bool:
        secure_values = ['redirect-to-https', 'https-only']
        return protocol in secure_values

    @classmethod
    def _get_messages(cls, ordered_behavior_list: List[CacheBehavior]) -> List[str]:
        return [f'ordered_cache_behavior #{cache.precedence}' for cache in ordered_behavior_list
                if not cls._is_https_restricted(cache.viewer_protocol_policy)]

    def should_run_rule(self, environment_context: AwsEnvironmentContext) -> bool:
        return bool(environment_context.cloudfront_distribution_list)

CacheBehavior dataclass

Attributes:

Name Type Description
allowed_methods List[str]

The list of HTTP methods allowed.

cached_methods List[str]

The list of HTTP methods whose responses are cached.

target_origin_id str

The origin this cache is targeting.

viewer_protocol_policy str

One of allow-all, redirect-to-https, https-only.

precedence int

The order of the cache behavior.

path_partern

The URL pattern to match.

trusted_signers List[str]

A list of AWS account IDs whose public keys CloudFront can use to validate signed URLs or signed cookies.

field_level_encryption_id str

The value of ID for the field-level encryption configuration to use, may be None.

CloudFrontDistribution (AwsResource, ConnectionInstance)

Attributes:

Name Type Description
arn str

The ARN of the CloudFront Distribution.

name str

The name of the distribution.

distribution_id str

The ID of the distribution.

viewer_cert ViewerCertificate

An object of type ViewerCertificate representing the viewer certificate used with this distribution.

origin_config_list List[OriginConfig]

A list of OriginConfig, the order is not guaranteed.

web_acl_id str

The ID of the AWS WAF web ACL, to associate with this distribution.

logs_settings Optional[CloudfrontDistributionLogging]

The logs settings of the CloudFront Distribution, if configured.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

get_default_behavior(self)

Returns:

Type Description
Optional[cloudrail.knowledge.context.aws.resources.cloudfront.cloudfront_distribution_list.CacheBehavior]

the default cache behavior.

get_ordered_behavior_list(self)

Returns:

Type Description
List[cloudrail.knowledge.context.aws.resources.cloudfront.cloudfront_distribution_list.CacheBehavior]

A list of CacheBehavior, if caching is configured. The order of the list is - first the default cache behavior, and then the specific cache behaviors by their defined order.

OriginConfig

Attributes:

Name Type Description
domain_name

The domain name for the origin.

origin_id

The ID of the origin.

oai_path

An optional path that CloudFront appends to the origin domain name when CloudFront requests content from the origin.

origin_access_identity_list

List of OriginAccessIdentity configurations.

ViewerCertificate dataclass

Attributes:

Name Type Description
cloudfront_default_certificate bool

Is this the default certificate.

minimum_protocol_version str

One of SSLv3 | TLSv1 | TLSv1_2016 | TLSv1.1_2016 | TLSv1.2_2018 | TLSv1.2_2019.

OriginAccessIdentity (AwsResource)

Attributes:

Name Type Description
oai_id str

The ID of this origin access identity.

cloudfront_access_identity_path str

The access identity's path.

iam_arn str

The ARN of the IAM entity to use.

s3_canonical_user_id str

The Amazon S3 canonical user ID for the origin access identity, used when giving the origin access identity read permission to an object in Amazon S3.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

CloudfrontDistributionLogging (AwsResource)

Attributes:

Name Type Description
name str

The name of the workgroup.

arn str

The ARN of the CloudFront Distribution.

distribution_id str

The ID of the distribution.

include_cookies bool

Specifies whether CloudFront will include cookies in access logs.

s3_bucket Optional[str]

The S3 bucket to store access logs into.

prefix Optional[str]

String to add as a prefix to access log file names.

logging_enabled bool

Indication if access logging is enabled.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process