diff --git a/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/README.md b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/README.md new file mode 100644 index 00000000..464f680a --- /dev/null +++ b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/README.md @@ -0,0 +1,75 @@ +# Check `awsvpc` network mode + +When you're running containers on AWS, managing the networking becomes crucial, especially when leveraging the benefits of hosting multiple containers on a single host. There are various network modes to choose from: + +1. **Host mode:** This is the most basic network mode in Amazon ECS. It essentially shares the host's networking stack with the containers. + +2. **Bridge mode:** This mode employs a virtual network bridge to establish a layer between the host and the container's networking. + +3. **AWSVPC mode:** Here, Amazon ECS generates and oversees an Elastic Network Interface (ENI) for each task, providing each task with a distinct private IP address within the VPC. + +By default, the network mode for ECS tasks is set to `bridge`. However, we will opt for the `awsvpc` network mode here. This choice is strategic, as it facilitates controlled traffic flow between tasks and enhances security. `awsvpc` offers task-level network isolation for tasks running on Amazon EC2. Importantly, it's the exclusive network mode allowing the assignment of security groups to tasks. + +To formalize our approach, it's prudent to establish a policy that ensures the usage of 'awsvpc' network mode. This policy aligns with our security strategy by adding an extra layer of protection through task-level isolation and the ability to apply security groups at the task level. Therefore, adopting and enforcing this policy safeguards our containerized infrastructure while optimizing networking capabilities on AWS. + +### Policy Validation Testing Instructions + +To evaluate and test the policy ensuring the presence of the `awsvpc` network mode in the Terraform plan payload, follow the steps outlined below: + +For testing this policy you will need to: +- Make sure you have `kyverno-json` installed on the machine +- Properly authenticate with AWS + +1. **Initialize Terraform:** + ```bash + terraform init + ``` + +2. **Create Binary Terraform Plan:** + ```bash + terraform plan -out tfplan.binary + ``` + +3. **Convert Binary to JSON Payload:** + ```bash + terraform show -json tfplan.binary | jq > payload.json + ``` + +4. **Test the Policy with Kyverno:** + ``` + kyverno-json scan --payload payload.json --policy policy.yaml + ``` + + a. **Test Policy Against Valid Payload:** + ``` + kyverno-json scan --policy check-aws-vpc-network-mode.yaml --payload policy-test/good-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - check-awsvpc-network-mode / check-awsvpc-network-mode / PASSED + Done + ``` + + b. **Test Against Invalid Payload:** + ``` + kyverno-json scan --policy check-aws-vpc-network-mode.yaml --payload policy-test/bad-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - check-awsvpc-network-mode / check-awsvpc-network-mode / FAILED: ECS services and tasks are required to use awsvpc network mode.: all[0].check.values.(network_mode=='awsvpc'): Invalid value: false: Expected value: true + Done + ``` + +--- + +These instructions are designed to systematically assess the compliance of Terraform plans with the defined policy. Following these steps ensures a thorough examination of the `awsvpc` network mode presence in the payload, allowing for effective validation and adherence to the specified policy. \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/check-aws-vpc-network-mode.yaml b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/check-aws-vpc-network-mode.yaml new file mode 100644 index 00000000..7061aebe --- /dev/null +++ b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/check-aws-vpc-network-mode.yaml @@ -0,0 +1,27 @@ +apiVersion: json.kyverno.io/v1alpha1 +kind: ValidatingPolicy +metadata: + name: check-awsvpc-network-mode + labels: + ecs.aws.network.kyverno.io: awsvpc + annotations: + policies.kyverno.io/title: Check awsvpc network mode + policies.kyverno.io/category: ECS Best Practices + policies.kyverno.io/severity: medium + policies.kyverno.io/description: >- + The awsvpc network mode restricts the flow of traffic between different + tasks or between your tasks and other services that run within your Amazon VPC. + The awsvpc network mode provides task-level network isolation for tasks + that run on Amazon EC2. +spec: + rules: + - name: check-awsvpc-network-mode + match: + any: + - (planned_values.root_module.resources[?type=='aws_ecs_task_definition'] | length(@) > `0`): true + assert: + all: + - message: ECS services and tasks are required to use awsvpc network mode. + check: + ~.(planned_values.root_module.resources[?type=='aws_ecs_task_definition'].values): + network_mode: awsvpc diff --git a/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad-payload.json b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad-payload.json new file mode 100644 index 00000000..a7c794c5 --- /dev/null +++ b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad-payload.json @@ -0,0 +1,173 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.6-dev", + "planned_values": { + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 1, + "values": { + "container_definitions": "[{\"cpu\":512,\"essential\":true,\"image\":\"nginx:1.23.1\",\"memory\":2048,\"name\":\"foo-task\",\"portMappings\":[{\"containerPort\":80,\"hostPort\":80}]}]", + "cpu": "512", + "ephemeral_storage": [], + "execution_role_arn": null, + "family": "service", + "inference_accelerator": [], + "ipc_mode": null, + "memory": "2048", + "network_mode": "bridge", + "pid_mode": null, + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": [ + "EC2" + ], + "runtime_platform": [], + "skip_destroy": false, + "tags": null, + "task_role_arn": null, + "volume": [] + }, + "sensitive_values": { + "ephemeral_storage": [], + "inference_accelerator": [], + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": [ + false + ], + "runtime_platform": [], + "tags_all": {}, + "volume": [] + } + } + ] + } + }, + "resource_changes": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "container_definitions": "[{\"cpu\":512,\"essential\":true,\"image\":\"nginx:1.23.1\",\"memory\":2048,\"name\":\"foo-task\",\"portMappings\":[{\"containerPort\":80,\"hostPort\":80}]}]", + "cpu": "512", + "ephemeral_storage": [], + "execution_role_arn": null, + "family": "service", + "inference_accelerator": [], + "ipc_mode": null, + "memory": "2048", + "network_mode": "awsvpc", + "pid_mode": null, + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": [ + "EC2" + ], + "runtime_platform": [], + "skip_destroy": false, + "tags": null, + "task_role_arn": null, + "volume": [] + }, + "after_unknown": { + "arn": true, + "arn_without_revision": true, + "ephemeral_storage": [], + "id": true, + "inference_accelerator": [], + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": [ + false + ], + "revision": true, + "runtime_platform": [], + "tags_all": true, + "volume": [] + }, + "before_sensitive": false, + "after_sensitive": { + "ephemeral_storage": [], + "inference_accelerator": [], + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": [ + false + ], + "runtime_platform": [], + "tags_all": {}, + "volume": [] + } + } + } + ], + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_config_key": "aws", + "expressions": { + "container_definitions": { + "constant_value": " [\n {\n \"name\" : \"foo-task\",\n \"image\" : \"nginx:1.23.1\",\n \"cpu\" : 512,\n \"memory\" : 2048,\n \"essential\" : true,\n \"portMappings\" : [\n {\n \"containerPort\" : 80,\n \"hostPort\" : 80\n }\n ]\n }\n ]\n" + }, + "cpu": { + "constant_value": 512 + }, + "family": { + "constant_value": "service" + }, + "memory": { + "constant_value": 2048 + }, + "network_mode": { + "constant_value": "awsvpc" + }, + "requires_compatibilities": { + "constant_value": [ + "EC2" + ] + } + }, + "schema_version": 1 + } + ] + } + }, + "timestamp": "2024-01-15T13:25:27Z", + "errored": false +} diff --git a/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad.tf b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad.tf new file mode 100644 index 00000000..78cdbb45 --- /dev/null +++ b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/bad.tf @@ -0,0 +1,46 @@ +resource "aws_ecs_task_definition" "task" { + family = "service" + network_mode = "bridge" + requires_compatibilities = ["EC2"] + cpu = 512 + memory = 2048 + container_definitions = < 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_config_key": "aws", + "expressions": { + "container_definitions": { + "constant_value": " [\n {\n \"name\" : \"foo-task\",\n \"image\" : \"nginx:1.23.1\",\n \"cpu\" : 512,\n \"memory\" : 2048,\n \"essential\" : true,\n \"portMappings\" : [\n {\n \"containerPort\" : 80,\n \"hostPort\" : 80\n }\n ]\n }\n ]\n" + }, + "cpu": { + "constant_value": 512 + }, + "family": { + "constant_value": "service" + }, + "memory": { + "constant_value": 2048 + }, + "network_mode": { + "constant_value": "awsvpc" + }, + "requires_compatibilities": { + "constant_value": [ + "EC2" + ] + } + }, + "schema_version": 1 + } + ] + } + }, + "timestamp": "2024-01-15T13:25:27Z", + "errored": false + } + \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/good.tf b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/good.tf new file mode 100644 index 00000000..31055154 --- /dev/null +++ b/terraform-best-practices/aws/ecs/check-aws-vpc-network-mode/test/good.tf @@ -0,0 +1,46 @@ +resource "aws_ecs_task_definition" "task" { + family = "service" + network_mode = "awsvpc" + requires_compatibilities = ["EC2"] + cpu = 512 + memory = 2048 + container_definitions = < payload.json + ``` + +4. **Test the Policy with Kyverno:** + ``` + kyverno-json scan --payload payload.json --policy policy.yaml + ``` + + a. **Test Policy Against Valid Payload:** + ``` + kyverno-json scan --policy validate-ecs-container-insights-enabled.yaml --payload policy-test/good-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-container-insights-enabled / container-insights / PASSED + Done + ``` + + b. **Test Against Invalid Payload:** + ``` + kyverno-json scan --policy validate-ecs-container-insights-enabled.yaml --payload policy-test/bad-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-container-insights-enabled / container-insights / FAILED: ECS container insights are not enabled: [all[0].check.~.(planned_values.root_module.resources[?type == 'aws_ecs_cluster'])[0].values.(length(setting[?name=='containerInsights'] || `[]`) > `0`): Invalid value: false: Expected value: true, all[0].check.~.(planned_values.root_module.resources[?type == 'aws_ecs_cluster'])[0].values.(!setting): Invalid value: true: Expected value: false] + Done + ``` + +--- + +By enforcing this policy, you ensure that ECS clusters adhere to best practices in containerized environments by leveraging the capabilities of Container Insights for effective monitoring and issue resolution. diff --git a/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad-payload.json new file mode 100644 index 00000000..0b031278 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad-payload.json @@ -0,0 +1,110 @@ +{ + "format_version": "1.2", + "terraform_version": "1.7.0-dev", + "planned_values": { + "root_module": { + "resources": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "configuration": [], + "name": "white-hart", + "service_connect_defaults": [], + "tags": null + }, + "sensitive_values": { + "capacity_providers": [], + "configuration": [], + "default_capacity_provider_strategy": [], + "service_connect_defaults": [], + "setting": [], + "tags_all": {} + } + } + ] + } + }, + "resource_changes": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "configuration": [], + "name": "white-hart", + "service_connect_defaults": [], + "tags": null + }, + "after_unknown": { + "arn": true, + "capacity_providers": true, + "configuration": [], + "default_capacity_provider_strategy": true, + "id": true, + "service_connect_defaults": [], + "setting": true, + "tags_all": true + }, + "before_sensitive": false, + "after_sensitive": { + "capacity_providers": [], + "configuration": [], + "default_capacity_provider_strategy": [], + "service_connect_defaults": [], + "setting": [], + "tags_all": {} + } + } + } + ], + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_config_key": "aws", + "expressions": { + "name": { + "constant_value": "white-hart" + } + }, + "schema_version": 0 + } + ] + } + }, + "timestamp": "2024-01-18T17:47:42Z", + "errored": false + } diff --git a/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad.tf b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad.tf new file mode 100644 index 00000000..afc9a7ec --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/bad.tf @@ -0,0 +1,25 @@ +resource "aws_ecs_cluster" "foo" { + name = "white-hart" +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + docker = { + source = "kreuzwerker/docker" + version = "~>2.20.0" + } + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers +provider "docker" {} + +provider "aws" { + region = "us-west-1" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good-payload.json new file mode 100644 index 00000000..949a9134 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good-payload.json @@ -0,0 +1,138 @@ +{ + "format_version": "1.2", + "terraform_version": "1.7.0-dev", + "planned_values": { + "root_module": { + "resources": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "configuration": [], + "name": "white-hart", + "service_connect_defaults": [], + "setting": [ + { + "name": "containerInsights", + "value": "enabled" + } + ], + "tags": null + }, + "sensitive_values": { + "capacity_providers": [], + "configuration": [], + "default_capacity_provider_strategy": [], + "service_connect_defaults": [], + "setting": [ + {} + ], + "tags_all": {} + } + } + ] + } + }, + "resource_changes": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "configuration": [], + "name": "white-hart", + "service_connect_defaults": [], + "setting": [ + { + "name": "containerInsights", + "value": "enabled" + } + ], + "tags": null + }, + "after_unknown": { + "arn": true, + "capacity_providers": true, + "configuration": [], + "default_capacity_provider_strategy": true, + "id": true, + "service_connect_defaults": [], + "setting": [ + {} + ], + "tags_all": true + }, + "before_sensitive": false, + "after_sensitive": { + "capacity_providers": [], + "configuration": [], + "default_capacity_provider_strategy": [], + "service_connect_defaults": [], + "setting": [ + {} + ], + "tags_all": {} + } + } + } + ], + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_cluster.foo", + "mode": "managed", + "type": "aws_ecs_cluster", + "name": "foo", + "provider_config_key": "aws", + "expressions": { + "name": { + "constant_value": "white-hart" + }, + "setting": [ + { + "name": { + "constant_value": "containerInsights" + }, + "value": { + "constant_value": "enabled" + } + } + ] + }, + "schema_version": 0 + } + ] + } + }, + "timestamp": "2024-01-18T15:48:00Z", + "errored": false + } diff --git a/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good.tf b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good.tf new file mode 100644 index 00000000..5052109e --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/test/good.tf @@ -0,0 +1,30 @@ +resource "aws_ecs_cluster" "foo" { + name = "white-hart" + + setting { + name = "containerInsights" + value = "enabled" + } +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + docker = { + source = "kreuzwerker/docker" + version = "~>2.20.0" + } + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers +provider "docker" {} + +provider "aws" { + region = "us-west-1" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/validate-ecs-container-insights-enabled.yaml b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/validate-ecs-container-insights-enabled.yaml new file mode 100644 index 00000000..efd48b0f --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-container-insights-enabled/validate-ecs-container-insights-enabled.yaml @@ -0,0 +1,26 @@ +apiVersion: json.kyverno.io/v1alpha1 +kind: ValidatingPolicy +metadata: + name: validate-ecs-container-insights-enabled + annotations: + policies.kyverno.io/title: Validate ECS container insights are enabled + policies.kyverno.io/category: ECS Best Practices + policies.kyverno.io/severity: medium + policies.kyverno.io/description: >- + This Policy ensures that ECS clusters have container + insights enabled. +spec: + rules: + - name: container-insights + match: + any: + - (planned_values.root_module.resources[?type=='aws_ecs_cluster'] | length(@) > `0`): true + assert: + all: + - message: ECS container insights are not enabled + check: + ~.(planned_values.root_module.resources[?type == 'aws_ecs_cluster']): + values: + (!setting): false + ~.(setting || `[]`): + value: enabled diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/README.md b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/README.md new file mode 100644 index 00000000..1a076db1 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/README.md @@ -0,0 +1,65 @@ +# ECS containers should run as non-privileged + +It is important to ensure that ECS containers run without elevated privileges to enhance security. The policy checks the privileged parameter in the container definition and raises a concern if it is set to `true`. When a container is granted elevated permissions (similar to the root user) by having privileged set to true, it poses potential security risks on the host container instance. + +It is advised against running containers with elevated privileges, as this may compromise the overall security of your ECS task definitions. It is recommended to avoid using privileged and, instead, specify precise privileges using specific parameters. This approach allows for a more controlled and secure execution environment, minimizing the risks associated with running containers with unnecessary elevated privileges. + +### Policy Validation Testing Instructions + +To evaluate and test the policy ensuring if the privileged parameter in the container definition is set to `false` (is default) in the Terraform plan payload, follow the steps outlined below: + +For testing this policy you will need to: +- Make sure you have `kyverno-json` installed on the machine +- Properly authenticate with AWS + +1. **Initialize Terraform:** + ```bash + terraform init + ``` + +2. **Create Binary Terraform Plan:** + ```bash + terraform plan -out tfplan.binary + ``` + +3. **Convert Binary to JSON Payload:** + ```bash + terraform show -json tfplan.binary | jq > payload.json + ``` + +4. **Test the Policy with Kyverno:** + ``` + kyverno-json scan --payload payload.json --policy policy.yaml + ``` + + a. **Test Policy Against Valid Payload:** + ``` + kyverno-json scan --policy validate-ecs-containers-nonprivileged.yaml --payload policy-test/good-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-containers-nonprivileged / validate-ecs-containers-nonprivileged / PASSED + Done + ``` + + b. **Test Against Invalid Payload:** + ``` + kyverno-json scan --policy validate-ecs-containers-nonprivileged.yaml --payload policy-test/bad-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-containers-nonprivileged / validate-ecs-containers-nonprivileged / FAILED: Containers must be set to non privileged.: any[0].check.(configuration.root_module.module_calls.ecs_container_definition.expressions.privileged || `{}` | length(keys(@)) > `0`): Invalid value: true: Expected value: false; any[1].check.configuration.root_module.module_calls.ecs_container_definition.expressions.privileged.constant_value: Invalid value: true: Expected value: false + Done + ``` + +--- diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad-payload.json new file mode 100644 index 00000000..b256ca1f --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad-payload.json @@ -0,0 +1,469 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.6-dev", + "planned_values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "kms_key_id": null, + "name": "/aws/ecs//example", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + }, + "resource_changes": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "module_address": "module.ecs_container_definition", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "kms_key_id": null, + "name": "/aws/ecs//example", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after_unknown": { + "arn": true, + "id": true, + "name_prefix": true, + "tags": {}, + "tags_all": {} + }, + "before_sensitive": false, + "after_sensitive": { + "tags": {}, + "tags_all": {} + } + } + } + ], + "prior_state": { + "format_version": "1.0", + "terraform_version": "1.6.6", + "values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "description": "US West (N. California)", + "endpoint": "ec2.us-west-1.amazonaws.com", + "id": "us-west-1", + "name": "us-west-1" + }, + "sensitive_values": {} + } + ], + "address": "module.ecs_container_definition" + } + ] + } + } + }, + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "module_calls": { + "ecs_container_definition": { + "source": "terraform-aws-modules/ecs/aws//modules/container-definition", + "expressions": { + "image": { + "constant_value": "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + }, + "name": { + "constant_value": "example" + }, + "port_mappings": { + "constant_value": [ + { + "containerPort": 80, + "name": "ecs-sample", + "protocol": "tcp" + } + ] + }, + "privileged": { + "constant_value": true + }, + "tags": { + "constant_value": { + "Environment": "dev", + "Terraform": "true" + } + } + }, + "module": { + "outputs": { + "cloudwatch_log_group_arn": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].arn", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Arn of cloudwatch log group created" + }, + "cloudwatch_log_group_name": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].name", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Name of cloudwatch log group created" + }, + "container_definition": { + "expression": { + "references": [ + "local.container_definition" + ] + }, + "description": "Container definition" + } + }, + "resources": [ + { + "address": "aws_cloudwatch_log_group.this", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "provider_config_key": "aws", + "expressions": { + "kms_key_id": { + "references": [ + "var.cloudwatch_log_group_kms_key_id" + ] + }, + "name": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "name_prefix": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "retention_in_days": { + "references": [ + "var.cloudwatch_log_group_retention_in_days" + ] + }, + "tags": { + "references": [ + "var.tags" + ] + } + }, + "schema_version": 0, + "count_expression": { + "references": [ + "var.create_cloudwatch_log_group", + "var.enable_cloudwatch_logging" + ] + } + }, + { + "address": "data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_config_key": "aws", + "schema_version": 0 + } + ], + "variables": { + "cloudwatch_log_group_kms_key_id": { + "default": null, + "description": "If a KMS Key ARN is set, this key will be used to encrypt the corresponding log group. Please be sure that the KMS Key has an appropriate key policy (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)" + }, + "cloudwatch_log_group_retention_in_days": { + "default": 30, + "description": "Number of days to retain log events. Default is 30 days" + }, + "cloudwatch_log_group_use_name_prefix": { + "default": false, + "description": "Determines whether the log group name should be used as a prefix" + }, + "command": { + "default": [], + "description": "The command that's passed to the container" + }, + "cpu": { + "default": null, + "description": "The number of cpu units to reserve for the container. This is optional for tasks using Fargate launch type and the total amount of `cpu` of all containers in a task will need to be lower than the task-level cpu value" + }, + "create_cloudwatch_log_group": { + "default": true, + "description": "Determines whether a log group is created by this module. If not, AWS will automatically create one if logging is enabled" + }, + "dependencies": { + "default": [], + "description": "The dependencies defined for container startup and shutdown. A container can contain multiple dependencies. When a dependency is defined for container startup, for container shutdown it is reversed. The condition can be one of START, COMPLETE, SUCCESS or HEALTHY" + }, + "disable_networking": { + "default": null, + "description": "When this parameter is true, networking is disabled within the container" + }, + "dns_search_domains": { + "default": [], + "description": "Container DNS search domains. A list of DNS search domains that are presented to the container" + }, + "dns_servers": { + "default": [], + "description": "Container DNS servers. This is a list of strings specifying the IP addresses of the DNS servers" + }, + "docker_labels": { + "default": {}, + "description": "A key/value map of labels to add to the container" + }, + "docker_security_options": { + "default": [], + "description": "A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems. This field isn't valid for containers in tasks using the Fargate launch type" + }, + "enable_cloudwatch_logging": { + "default": true, + "description": "Determines whether CloudWatch logging is configured for this container definition. Set to `false` to use other logging drivers" + }, + "enable_execute_command": { + "default": false, + "description": "Specifies whether to enable Amazon ECS Exec for the tasks within the service" + }, + "entrypoint": { + "default": [], + "description": "The entry point that is passed to the container" + }, + "environment": { + "default": [], + "description": "The environment variables to pass to the container" + }, + "environment_files": { + "default": [], + "description": "A list of files containing the environment variables to pass to a container" + }, + "essential": { + "default": null, + "description": "If the `essential` parameter of a container is marked as `true`, and that container fails or stops for any reason, all other containers that are part of the task are stopped" + }, + "extra_hosts": { + "default": [], + "description": "A list of hostnames and IP address mappings to append to the `/etc/hosts` file on the container" + }, + "firelens_configuration": { + "default": {}, + "description": "The FireLens configuration for the container. This is used to specify and configure a log router for container logs. For more information, see [Custom Log Routing](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html) in the Amazon Elastic Container Service Developer Guide" + }, + "health_check": { + "default": {}, + "description": "The container health check command and associated configuration parameters for the container. See [HealthCheck](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_HealthCheck.html)" + }, + "hostname": { + "default": null, + "description": "The hostname to use for your container" + }, + "image": { + "default": null, + "description": "The image used to start a container. This string is passed directly to the Docker daemon. By default, images in the Docker Hub registry are available. Other repositories are specified with either `repository-url/image:tag` or `repository-url/image@digest`" + }, + "interactive": { + "default": false, + "description": "When this parameter is `true`, you can deploy containerized applications that require `stdin` or a `tty` to be allocated" + }, + "links": { + "default": [], + "description": "The links parameter allows containers to communicate with each other without the need for port mappings. This parameter is only supported if the network mode of a task definition is `bridge`" + }, + "linux_parameters": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "log_configuration": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "memory": { + "default": null, + "description": "The amount (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. The total amount of memory reserved for all containers within a task must be lower than the task `memory` value, if one is specified" + }, + "memory_reservation": { + "default": null, + "description": "The soft limit (in MiB) of memory to reserve for the container. When system memory is under heavy contention, Docker attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs to, up to either the hard limit specified with the `memory` parameter (if applicable), or all of the available memory on the container instance" + }, + "mount_points": { + "default": [], + "description": "The mount points for data volumes in your container" + }, + "name": { + "default": null, + "description": "The name of a container. If you're linking multiple containers together in a task definition, the name of one container can be entered in the links of another container to connect the containers. Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are allowed" + }, + "operating_system_family": { + "default": "LINUX", + "description": "The OS family for task" + }, + "port_mappings": { + "default": [], + "description": "The list of port mappings for the container. Port mappings allow containers to access ports on the host container instance to send or receive traffic. For task definitions that use the awsvpc network mode, only specify the containerPort. The hostPort can be left blank or it must be the same value as the containerPort" + }, + "privileged": { + "default": false, + "description": "When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user)" + }, + "pseudo_terminal": { + "default": false, + "description": "When this parameter is true, a `TTY` is allocated" + }, + "readonly_root_filesystem": { + "default": true, + "description": "When this parameter is true, the container is given read-only access to its root file system" + }, + "repository_credentials": { + "default": {}, + "description": "Container repository credentials; required when using a private repo. This map currently supports a single key; \"credentialsParameter\", which should be the ARN of a Secrets Manager's secret holding the credentials" + }, + "resource_requirements": { + "default": [], + "description": "The type and amount of a resource to assign to a container. The only supported resource is a GPU" + }, + "secrets": { + "default": [], + "description": "The secrets to pass to the container. For more information, see [Specifying Sensitive Data](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html) in the Amazon Elastic Container Service Developer Guide" + }, + "service": { + "default": "", + "description": "The name of the service that the container definition is associated with" + }, + "start_timeout": { + "default": 30, + "description": "Time duration (in seconds) to wait before giving up on resolving dependencies for a container" + }, + "stop_timeout": { + "default": 120, + "description": "Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own" + }, + "system_controls": { + "default": [], + "description": "A list of namespaced kernel parameters to set in the container" + }, + "tags": { + "default": {}, + "description": "A map of tags to add to all resources" + }, + "ulimits": { + "default": [], + "description": "A list of ulimits to set in the container. If a ulimit value is specified in a task definition, it overrides the default values set by Docker" + }, + "user": { + "default": null, + "description": "The user to run as inside the container. Can be any of these formats: user, user:group, uid, uid:gid, user:gid, uid:group. The default (null) will use the container's configured `USER` directive or root if not set" + }, + "volumes_from": { + "default": [], + "description": "Data volumes to mount from another container" + }, + "working_directory": { + "default": null, + "description": "The working directory to run commands inside the container" + } + } + } + } + } + } + }, + "relevant_attributes": [ + { + "resource": "module.ecs_container_definition.data.aws_region.current", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "arn" + ] + } + ], + "timestamp": "2024-01-15T18:19:18Z", + "errored": false + } + \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad.tf b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad.tf new file mode 100644 index 00000000..1152f8e5 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/bad.tf @@ -0,0 +1,40 @@ +module "ecs_container_definition" { + source = "terraform-aws-modules/ecs/aws//modules/container-definition" + name = "example" + privileged = false + image = "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + port_mappings = [ + { + name = "ecs-sample" + containerPort = 80 + protocol = "tcp" + } + ] + + tags = { + Environment = "dev" + Terraform = "true" + } +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + docker = { + source = "kreuzwerker/docker" + version = "~>2.20.0" + } + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers +provider "docker" {} + +provider "aws" { + region = "us-west-1" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good-payload.json new file mode 100644 index 00000000..9f677097 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good-payload.json @@ -0,0 +1,469 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.6-dev", + "planned_values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "kms_key_id": null, + "name": "/aws/ecs//example", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + }, + "resource_changes": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "module_address": "module.ecs_container_definition", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "kms_key_id": null, + "name": "/aws/ecs//example", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after_unknown": { + "arn": true, + "id": true, + "name_prefix": true, + "tags": {}, + "tags_all": {} + }, + "before_sensitive": false, + "after_sensitive": { + "tags": {}, + "tags_all": {} + } + } + } + ], + "prior_state": { + "format_version": "1.0", + "terraform_version": "1.6.6", + "values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "description": "US West (N. California)", + "endpoint": "ec2.us-west-1.amazonaws.com", + "id": "us-west-1", + "name": "us-west-1" + }, + "sensitive_values": {} + } + ], + "address": "module.ecs_container_definition" + } + ] + } + } + }, + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "module_calls": { + "ecs_container_definition": { + "source": "terraform-aws-modules/ecs/aws//modules/container-definition", + "expressions": { + "image": { + "constant_value": "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + }, + "name": { + "constant_value": "example" + }, + "port_mappings": { + "constant_value": [ + { + "containerPort": 80, + "name": "ecs-sample", + "protocol": "tcp" + } + ] + }, + "privileged": { + "constant_value": false + }, + "tags": { + "constant_value": { + "Environment": "dev", + "Terraform": "true" + } + } + }, + "module": { + "outputs": { + "cloudwatch_log_group_arn": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].arn", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Arn of cloudwatch log group created" + }, + "cloudwatch_log_group_name": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].name", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Name of cloudwatch log group created" + }, + "container_definition": { + "expression": { + "references": [ + "local.container_definition" + ] + }, + "description": "Container definition" + } + }, + "resources": [ + { + "address": "aws_cloudwatch_log_group.this", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "provider_config_key": "aws", + "expressions": { + "kms_key_id": { + "references": [ + "var.cloudwatch_log_group_kms_key_id" + ] + }, + "name": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "name_prefix": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "retention_in_days": { + "references": [ + "var.cloudwatch_log_group_retention_in_days" + ] + }, + "tags": { + "references": [ + "var.tags" + ] + } + }, + "schema_version": 0, + "count_expression": { + "references": [ + "var.create_cloudwatch_log_group", + "var.enable_cloudwatch_logging" + ] + } + }, + { + "address": "data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_config_key": "aws", + "schema_version": 0 + } + ], + "variables": { + "cloudwatch_log_group_kms_key_id": { + "default": null, + "description": "If a KMS Key ARN is set, this key will be used to encrypt the corresponding log group. Please be sure that the KMS Key has an appropriate key policy (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)" + }, + "cloudwatch_log_group_retention_in_days": { + "default": 30, + "description": "Number of days to retain log events. Default is 30 days" + }, + "cloudwatch_log_group_use_name_prefix": { + "default": false, + "description": "Determines whether the log group name should be used as a prefix" + }, + "command": { + "default": [], + "description": "The command that's passed to the container" + }, + "cpu": { + "default": null, + "description": "The number of cpu units to reserve for the container. This is optional for tasks using Fargate launch type and the total amount of `cpu` of all containers in a task will need to be lower than the task-level cpu value" + }, + "create_cloudwatch_log_group": { + "default": true, + "description": "Determines whether a log group is created by this module. If not, AWS will automatically create one if logging is enabled" + }, + "dependencies": { + "default": [], + "description": "The dependencies defined for container startup and shutdown. A container can contain multiple dependencies. When a dependency is defined for container startup, for container shutdown it is reversed. The condition can be one of START, COMPLETE, SUCCESS or HEALTHY" + }, + "disable_networking": { + "default": null, + "description": "When this parameter is true, networking is disabled within the container" + }, + "dns_search_domains": { + "default": [], + "description": "Container DNS search domains. A list of DNS search domains that are presented to the container" + }, + "dns_servers": { + "default": [], + "description": "Container DNS servers. This is a list of strings specifying the IP addresses of the DNS servers" + }, + "docker_labels": { + "default": {}, + "description": "A key/value map of labels to add to the container" + }, + "docker_security_options": { + "default": [], + "description": "A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems. This field isn't valid for containers in tasks using the Fargate launch type" + }, + "enable_cloudwatch_logging": { + "default": true, + "description": "Determines whether CloudWatch logging is configured for this container definition. Set to `false` to use other logging drivers" + }, + "enable_execute_command": { + "default": false, + "description": "Specifies whether to enable Amazon ECS Exec for the tasks within the service" + }, + "entrypoint": { + "default": [], + "description": "The entry point that is passed to the container" + }, + "environment": { + "default": [], + "description": "The environment variables to pass to the container" + }, + "environment_files": { + "default": [], + "description": "A list of files containing the environment variables to pass to a container" + }, + "essential": { + "default": null, + "description": "If the `essential` parameter of a container is marked as `true`, and that container fails or stops for any reason, all other containers that are part of the task are stopped" + }, + "extra_hosts": { + "default": [], + "description": "A list of hostnames and IP address mappings to append to the `/etc/hosts` file on the container" + }, + "firelens_configuration": { + "default": {}, + "description": "The FireLens configuration for the container. This is used to specify and configure a log router for container logs. For more information, see [Custom Log Routing](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html) in the Amazon Elastic Container Service Developer Guide" + }, + "health_check": { + "default": {}, + "description": "The container health check command and associated configuration parameters for the container. See [HealthCheck](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_HealthCheck.html)" + }, + "hostname": { + "default": null, + "description": "The hostname to use for your container" + }, + "image": { + "default": null, + "description": "The image used to start a container. This string is passed directly to the Docker daemon. By default, images in the Docker Hub registry are available. Other repositories are specified with either `repository-url/image:tag` or `repository-url/image@digest`" + }, + "interactive": { + "default": false, + "description": "When this parameter is `true`, you can deploy containerized applications that require `stdin` or a `tty` to be allocated" + }, + "links": { + "default": [], + "description": "The links parameter allows containers to communicate with each other without the need for port mappings. This parameter is only supported if the network mode of a task definition is `bridge`" + }, + "linux_parameters": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "log_configuration": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "memory": { + "default": null, + "description": "The amount (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. The total amount of memory reserved for all containers within a task must be lower than the task `memory` value, if one is specified" + }, + "memory_reservation": { + "default": null, + "description": "The soft limit (in MiB) of memory to reserve for the container. When system memory is under heavy contention, Docker attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs to, up to either the hard limit specified with the `memory` parameter (if applicable), or all of the available memory on the container instance" + }, + "mount_points": { + "default": [], + "description": "The mount points for data volumes in your container" + }, + "name": { + "default": null, + "description": "The name of a container. If you're linking multiple containers together in a task definition, the name of one container can be entered in the links of another container to connect the containers. Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are allowed" + }, + "operating_system_family": { + "default": "LINUX", + "description": "The OS family for task" + }, + "port_mappings": { + "default": [], + "description": "The list of port mappings for the container. Port mappings allow containers to access ports on the host container instance to send or receive traffic. For task definitions that use the awsvpc network mode, only specify the containerPort. The hostPort can be left blank or it must be the same value as the containerPort" + }, + "privileged": { + "default": false, + "description": "When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user)" + }, + "pseudo_terminal": { + "default": false, + "description": "When this parameter is true, a `TTY` is allocated" + }, + "readonly_root_filesystem": { + "default": true, + "description": "When this parameter is true, the container is given read-only access to its root file system" + }, + "repository_credentials": { + "default": {}, + "description": "Container repository credentials; required when using a private repo. This map currently supports a single key; \"credentialsParameter\", which should be the ARN of a Secrets Manager's secret holding the credentials" + }, + "resource_requirements": { + "default": [], + "description": "The type and amount of a resource to assign to a container. The only supported resource is a GPU" + }, + "secrets": { + "default": [], + "description": "The secrets to pass to the container. For more information, see [Specifying Sensitive Data](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html) in the Amazon Elastic Container Service Developer Guide" + }, + "service": { + "default": "", + "description": "The name of the service that the container definition is associated with" + }, + "start_timeout": { + "default": 30, + "description": "Time duration (in seconds) to wait before giving up on resolving dependencies for a container" + }, + "stop_timeout": { + "default": 120, + "description": "Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own" + }, + "system_controls": { + "default": [], + "description": "A list of namespaced kernel parameters to set in the container" + }, + "tags": { + "default": {}, + "description": "A map of tags to add to all resources" + }, + "ulimits": { + "default": [], + "description": "A list of ulimits to set in the container. If a ulimit value is specified in a task definition, it overrides the default values set by Docker" + }, + "user": { + "default": null, + "description": "The user to run as inside the container. Can be any of these formats: user, user:group, uid, uid:gid, user:gid, uid:group. The default (null) will use the container's configured `USER` directive or root if not set" + }, + "volumes_from": { + "default": [], + "description": "Data volumes to mount from another container" + }, + "working_directory": { + "default": null, + "description": "The working directory to run commands inside the container" + } + } + } + } + } + } + }, + "relevant_attributes": [ + { + "resource": "module.ecs_container_definition.data.aws_region.current", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "arn" + ] + } + ], + "timestamp": "2024-01-15T18:19:18Z", + "errored": false + } + \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good.tf b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good.tf new file mode 100644 index 00000000..1152f8e5 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/test/good.tf @@ -0,0 +1,40 @@ +module "ecs_container_definition" { + source = "terraform-aws-modules/ecs/aws//modules/container-definition" + name = "example" + privileged = false + image = "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + port_mappings = [ + { + name = "ecs-sample" + containerPort = 80 + protocol = "tcp" + } + ] + + tags = { + Environment = "dev" + Terraform = "true" + } +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + docker = { + source = "kreuzwerker/docker" + version = "~>2.20.0" + } + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers +provider "docker" {} + +provider "aws" { + region = "us-west-1" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/validate-ecs-containers-nonprivileged.yaml b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/validate-ecs-containers-nonprivileged.yaml new file mode 100644 index 00000000..c274b19e --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-nonprivileged/validate-ecs-containers-nonprivileged.yaml @@ -0,0 +1,31 @@ +apiVersion: json.kyverno.io/v1alpha1 +kind: ValidatingPolicy +metadata: + name: validate-ecs-containers-nonprivileged + annotations: + policies.kyverno.io/title: Validate ECS containers are set to non privileged. + policies.kyverno.io/category: ECS Best Practices + policies.kyverno.io/severity: medium + policies.kyverno.io/description: >- + When privileged is set to true, the container is given elevated permissions on the host container instance (similar to the root user). + This policy checks if the privileged parameter in the container definition is set to false. +spec: + rules: + - name: validate-ecs-containers-nonprivileged + match: + any: + - (configuration.root_module.module_calls.ecs_container_definition != null): true + assert: + any: + - check: + (configuration.root_module.module_calls.ecs_container_definition.expressions.privileged == null): true + message: Containers `privileged` must be set to `false`. + - check: + configuration: + root_module: + module_calls: + ecs_container_definition: + expressions: + privileged: + constant_value: false + message: Containers must be set to non privileged. diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/README.md b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/README.md new file mode 100644 index 00000000..15fce543 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/README.md @@ -0,0 +1,76 @@ +# Validate ECS Containers Readonly Policy + +When managing containers within AWS ECS, it's crucial to enforce security measures to prevent unauthorized modifications. One significant aspect is restricting write access to the containers' root filesystems. To achieve this, AWS ECS provides a parameter called `readonlyRootFilesystem` in the container definition. This parameter, when set to `false`, allows write access, and when set to `true`, ensures read-only access. The default value of `readonlyRootFilesystem` is `true`. + +Our policy, named "validate-ecs-containers-readonly," ensures that ECS containers follow best practices by having read-only access to their root filesystems. + +## Policy Details: + +- **Policy Name:** validate-ecs-containers-readonly +- **Check Description:** Ensure ECS containers are limited to read-only access to root filesystems. + +## How It Works: + +The policy checks if the ECS task definition's container definitions have the `readonlyRootFilesystem` parameter set to `false`. If this parameter is not present or set to `false`, the policy marks the configuration as non-compliant. On the other hand, if the parameter is set to `true` or if the information is not available, the policy considers the configuration compliant. + +### Policy Validation Testing Instructions + +To evaluate and test the policy, follow the steps outlined below: + +For testing this policy you will need to: +- Make sure you have `kyverno-json` installed on the machine +- Properly authenticate with AWS + +1. **Initialize Terraform:** + ``` + terraform init + ``` + +2. **Create Binary Terraform Plan:** + ``` + terraform plan -out tfplan.binary + ``` + +3. **Convert Binary to JSON Payload:** + ``` + terraform show -json tfplan.binary | jq > payload.json + ``` + +4. **Test the Policy with Kyverno:** + ``` + kyverno-json scan --payload payload.json --policy policy.yaml + ``` + + a. **Test Policy Against Valid Payload:** + ``` + kyverno-json scan --policy validate-ecs-containers-readonly.yaml --payload policy-test/good-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-containers-readonly / validate-ecs-containers-readonly / PASSED + Done + ``` + + b. **Test Against Invalid Payload:** + ``` + kyverno-json scan --policy validate-ecs-containers-readonly.yaml --payload policy-test/bad-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-containers-readonly / validate-ecs-containers-readonly / FAILED: any[0].check.(configuration.root_module.module_calls.ecs_container_definition.expressions.readonly_root_filesystem == null): Invalid value: false: Expected value: true; ECS Containers should have read-only access to its root filesystems: any[1].check.configuration.root_module.module_calls.ecs_container_definition.expressions.readonly_root_filesystem.constant_value: Invalid value: false: Expected value: true + Done + ``` + +--- + +By following these instructions, you can systematically validate and enforce read-only access to ECS containers' root filesystems, aligning your infrastructure with security best practices. \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad-payload.json new file mode 100644 index 00000000..42ff75d2 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad-payload.json @@ -0,0 +1,513 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.6-dev", + "planned_values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + }, + "resource_changes": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "module_address": "module.ecs_container_definition", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "no-op" + ], + "before": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after_unknown": {}, + "before_sensitive": { + "tags": {}, + "tags_all": {} + }, + "after_sensitive": { + "tags": {}, + "tags_all": {} + } + } + } + ], + "prior_state": { + "format_version": "1.0", + "terraform_version": "1.6.6", + "values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "description": "US West (N. California)", + "endpoint": "ec2.us-west-1.amazonaws.com", + "id": "us-west-1", + "name": "us-west-1" + }, + "sensitive_values": {} + }, + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + } + }, + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + } + }, + "root_module": { + "module_calls": { + "ecs_container_definition": { + "source": "terraform-aws-modules/ecs/aws//modules/container-definition", + "expressions": { + "image": { + "constant_value": "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + }, + "name": { + "constant_value": "example" + }, + "port_mappings": { + "constant_value": [ + { + "containerPort": 80, + "name": "ecs-sample", + "protocol": "tcp" + } + ] + }, + "readonly_root_filesystem": { + "constant_value": false + }, + "tags": { + "constant_value": { + "Environment": "dev", + "Terraform": "true" + } + } + }, + "module": { + "outputs": { + "cloudwatch_log_group_arn": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].arn", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Arn of cloudwatch log group created" + }, + "cloudwatch_log_group_name": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].name", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Name of cloudwatch log group created" + }, + "container_definition": { + "expression": { + "references": [ + "local.container_definition" + ] + }, + "description": "Container definition" + } + }, + "resources": [ + { + "address": "aws_cloudwatch_log_group.this", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "provider_config_key": "aws", + "expressions": { + "kms_key_id": { + "references": [ + "var.cloudwatch_log_group_kms_key_id" + ] + }, + "name": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "name_prefix": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "retention_in_days": { + "references": [ + "var.cloudwatch_log_group_retention_in_days" + ] + }, + "tags": { + "references": [ + "var.tags" + ] + } + }, + "schema_version": 0, + "count_expression": { + "references": [ + "var.create_cloudwatch_log_group", + "var.enable_cloudwatch_logging" + ] + } + }, + { + "address": "data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_config_key": "aws", + "schema_version": 0 + } + ], + "variables": { + "cloudwatch_log_group_kms_key_id": { + "default": null, + "description": "If a KMS Key ARN is set, this key will be used to encrypt the corresponding log group. Please be sure that the KMS Key has an appropriate key policy (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)" + }, + "cloudwatch_log_group_retention_in_days": { + "default": 30, + "description": "Number of days to retain log events. Default is 30 days" + }, + "cloudwatch_log_group_use_name_prefix": { + "default": false, + "description": "Determines whether the log group name should be used as a prefix" + }, + "command": { + "default": [], + "description": "The command that's passed to the container" + }, + "cpu": { + "default": null, + "description": "The number of cpu units to reserve for the container. This is optional for tasks using Fargate launch type and the total amount of `cpu` of all containers in a task will need to be lower than the task-level cpu value" + }, + "create_cloudwatch_log_group": { + "default": true, + "description": "Determines whether a log group is created by this module. If not, AWS will automatically create one if logging is enabled" + }, + "dependencies": { + "default": [], + "description": "The dependencies defined for container startup and shutdown. A container can contain multiple dependencies. When a dependency is defined for container startup, for container shutdown it is reversed. The condition can be one of START, COMPLETE, SUCCESS or HEALTHY" + }, + "disable_networking": { + "default": null, + "description": "When this parameter is true, networking is disabled within the container" + }, + "dns_search_domains": { + "default": [], + "description": "Container DNS search domains. A list of DNS search domains that are presented to the container" + }, + "dns_servers": { + "default": [], + "description": "Container DNS servers. This is a list of strings specifying the IP addresses of the DNS servers" + }, + "docker_labels": { + "default": {}, + "description": "A key/value map of labels to add to the container" + }, + "docker_security_options": { + "default": [], + "description": "A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems. This field isn't valid for containers in tasks using the Fargate launch type" + }, + "enable_cloudwatch_logging": { + "default": true, + "description": "Determines whether CloudWatch logging is configured for this container definition. Set to `false` to use other logging drivers" + }, + "enable_execute_command": { + "default": false, + "description": "Specifies whether to enable Amazon ECS Exec for the tasks within the service" + }, + "entrypoint": { + "default": [], + "description": "The entry point that is passed to the container" + }, + "environment": { + "default": [], + "description": "The environment variables to pass to the container" + }, + "environment_files": { + "default": [], + "description": "A list of files containing the environment variables to pass to a container" + }, + "essential": { + "default": null, + "description": "If the `essential` parameter of a container is marked as `true`, and that container fails or stops for any reason, all other containers that are part of the task are stopped" + }, + "extra_hosts": { + "default": [], + "description": "A list of hostnames and IP address mappings to append to the `/etc/hosts` file on the container" + }, + "firelens_configuration": { + "default": {}, + "description": "The FireLens configuration for the container. This is used to specify and configure a log router for container logs. For more information, see [Custom Log Routing](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html) in the Amazon Elastic Container Service Developer Guide" + }, + "health_check": { + "default": {}, + "description": "The container health check command and associated configuration parameters for the container. See [HealthCheck](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_HealthCheck.html)" + }, + "hostname": { + "default": null, + "description": "The hostname to use for your container" + }, + "image": { + "default": null, + "description": "The image used to start a container. This string is passed directly to the Docker daemon. By default, images in the Docker Hub registry are available. Other repositories are specified with either `repository-url/image:tag` or `repository-url/image@digest`" + }, + "interactive": { + "default": false, + "description": "When this parameter is `true`, you can deploy containerized applications that require `stdin` or a `tty` to be allocated" + }, + "links": { + "default": [], + "description": "The links parameter allows containers to communicate with each other without the need for port mappings. This parameter is only supported if the network mode of a task definition is `bridge`" + }, + "linux_parameters": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "log_configuration": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "memory": { + "default": null, + "description": "The amount (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. The total amount of memory reserved for all containers within a task must be lower than the task `memory` value, if one is specified" + }, + "memory_reservation": { + "default": null, + "description": "The soft limit (in MiB) of memory to reserve for the container. When system memory is under heavy contention, Docker attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs to, up to either the hard limit specified with the `memory` parameter (if applicable), or all of the available memory on the container instance" + }, + "mount_points": { + "default": [], + "description": "The mount points for data volumes in your container" + }, + "name": { + "default": null, + "description": "The name of a container. If you're linking multiple containers together in a task definition, the name of one container can be entered in the links of another container to connect the containers. Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are allowed" + }, + "operating_system_family": { + "default": "LINUX", + "description": "The OS family for task" + }, + "port_mappings": { + "default": [], + "description": "The list of port mappings for the container. Port mappings allow containers to access ports on the host container instance to send or receive traffic. For task definitions that use the awsvpc network mode, only specify the containerPort. The hostPort can be left blank or it must be the same value as the containerPort" + }, + "privileged": { + "default": false, + "description": "When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user)" + }, + "pseudo_terminal": { + "default": false, + "description": "When this parameter is true, a `TTY` is allocated" + }, + "readonly_root_filesystem": { + "default": true, + "description": "When this parameter is true, the container is given read-only access to its root file system" + }, + "repository_credentials": { + "default": {}, + "description": "Container repository credentials; required when using a private repo. This map currently supports a single key; \"credentialsParameter\", which should be the ARN of a Secrets Manager's secret holding the credentials" + }, + "resource_requirements": { + "default": [], + "description": "The type and amount of a resource to assign to a container. The only supported resource is a GPU" + }, + "secrets": { + "default": [], + "description": "The secrets to pass to the container. For more information, see [Specifying Sensitive Data](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html) in the Amazon Elastic Container Service Developer Guide" + }, + "service": { + "default": "", + "description": "The name of the service that the container definition is associated with" + }, + "start_timeout": { + "default": 30, + "description": "Time duration (in seconds) to wait before giving up on resolving dependencies for a container" + }, + "stop_timeout": { + "default": 120, + "description": "Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own" + }, + "system_controls": { + "default": [], + "description": "A list of namespaced kernel parameters to set in the container" + }, + "tags": { + "default": {}, + "description": "A map of tags to add to all resources" + }, + "ulimits": { + "default": [], + "description": "A list of ulimits to set in the container. If a ulimit value is specified in a task definition, it overrides the default values set by Docker" + }, + "user": { + "default": null, + "description": "The user to run as inside the container. Can be any of these formats: user, user:group, uid, uid:gid, user:gid, uid:group. The default (null) will use the container's configured `USER` directive or root if not set" + }, + "volumes_from": { + "default": [], + "description": "Data volumes to mount from another container" + }, + "working_directory": { + "default": null, + "description": "The working directory to run commands inside the container" + } + } + } + } + } + } + }, + "relevant_attributes": [ + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "arn" + ] + }, + { + "resource": "module.ecs_container_definition.data.aws_region.current", + "attribute": [ + "name" + ] + } + ], + "timestamp": "2024-01-16T22:10:52Z", + "errored": false + } + \ No newline at end of file diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad.tf b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad.tf new file mode 100644 index 00000000..3b949134 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/bad.tf @@ -0,0 +1,35 @@ +module "ecs_container_definition" { + source = "terraform-aws-modules/ecs/aws//modules/container-definition" + name = "example" + readonly_root_filesystem = false + image = "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + port_mappings = [ + { + name = "ecs-sample" + containerPort = 80 + protocol = "tcp" + } + ] + tags = { + Environment = "dev" + Terraform = "true" + } +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers + +provider "aws" { + region = "us-west-1" + profile = "foo" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good-payload.json new file mode 100644 index 00000000..9d4f1190 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good-payload.json @@ -0,0 +1,512 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.6-dev", + "planned_values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + }, + "resource_changes": [ + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "module_address": "module.ecs_container_definition", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "no-op" + ], + "before": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "after_unknown": {}, + "before_sensitive": { + "tags": {}, + "tags_all": {} + }, + "after_sensitive": { + "tags": {}, + "tags_all": {} + } + } + } + ], + "prior_state": { + "format_version": "1.0", + "terraform_version": "1.6.6", + "values": { + "root_module": { + "child_modules": [ + { + "resources": [ + { + "address": "module.ecs_container_definition.data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "description": "US West (N. California)", + "endpoint": "ec2.us-west-1.amazonaws.com", + "id": "us-west-1", + "name": "us-west-1" + }, + "sensitive_values": {} + }, + { + "address": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "index": 0, + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 0, + "values": { + "arn": "arn:aws:logs:us-west-1:844333597536:log-group:/aws/ecs//example", + "id": "/aws/ecs//example", + "kms_key_id": "", + "name": "/aws/ecs//example", + "name_prefix": "", + "retention_in_days": 30, + "skip_destroy": false, + "tags": { + "Environment": "dev", + "Terraform": "true" + }, + "tags_all": { + "Environment": "dev", + "Terraform": "true" + } + }, + "sensitive_values": { + "tags": {}, + "tags_all": {} + } + } + ], + "address": "module.ecs_container_definition" + } + ] + } + } + }, + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "region": { + "constant_value": "us-west-1" + } + } + } + }, + "root_module": { + "module_calls": { + "ecs_container_definition": { + "source": "terraform-aws-modules/ecs/aws//modules/container-definition", + "expressions": { + "image": { + "constant_value": "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + }, + "name": { + "constant_value": "example" + }, + "port_mappings": { + "constant_value": [ + { + "containerPort": 80, + "name": "ecs-sample", + "protocol": "tcp" + } + ] + }, + "readonly_root_filesystem": { + "constant_value": true + }, + "tags": { + "constant_value": { + "Environment": "dev", + "Terraform": "true" + } + } + }, + "module": { + "outputs": { + "cloudwatch_log_group_arn": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].arn", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Arn of cloudwatch log group created" + }, + "cloudwatch_log_group_name": { + "expression": { + "references": [ + "aws_cloudwatch_log_group.this[0].name", + "aws_cloudwatch_log_group.this[0]", + "aws_cloudwatch_log_group.this" + ] + }, + "description": "Name of cloudwatch log group created" + }, + "container_definition": { + "expression": { + "references": [ + "local.container_definition" + ] + }, + "description": "Container definition" + } + }, + "resources": [ + { + "address": "aws_cloudwatch_log_group.this", + "mode": "managed", + "type": "aws_cloudwatch_log_group", + "name": "this", + "provider_config_key": "aws", + "expressions": { + "kms_key_id": { + "references": [ + "var.cloudwatch_log_group_kms_key_id" + ] + }, + "name": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "name_prefix": { + "references": [ + "var.cloudwatch_log_group_use_name_prefix", + "local.log_group_name" + ] + }, + "retention_in_days": { + "references": [ + "var.cloudwatch_log_group_retention_in_days" + ] + }, + "tags": { + "references": [ + "var.tags" + ] + } + }, + "schema_version": 0, + "count_expression": { + "references": [ + "var.create_cloudwatch_log_group", + "var.enable_cloudwatch_logging" + ] + } + }, + { + "address": "data.aws_region.current", + "mode": "data", + "type": "aws_region", + "name": "current", + "provider_config_key": "aws", + "schema_version": 0 + } + ], + "variables": { + "cloudwatch_log_group_kms_key_id": { + "default": null, + "description": "If a KMS Key ARN is set, this key will be used to encrypt the corresponding log group. Please be sure that the KMS Key has an appropriate key policy (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)" + }, + "cloudwatch_log_group_retention_in_days": { + "default": 30, + "description": "Number of days to retain log events. Default is 30 days" + }, + "cloudwatch_log_group_use_name_prefix": { + "default": false, + "description": "Determines whether the log group name should be used as a prefix" + }, + "command": { + "default": [], + "description": "The command that's passed to the container" + }, + "cpu": { + "default": null, + "description": "The number of cpu units to reserve for the container. This is optional for tasks using Fargate launch type and the total amount of `cpu` of all containers in a task will need to be lower than the task-level cpu value" + }, + "create_cloudwatch_log_group": { + "default": true, + "description": "Determines whether a log group is created by this module. If not, AWS will automatically create one if logging is enabled" + }, + "dependencies": { + "default": [], + "description": "The dependencies defined for container startup and shutdown. A container can contain multiple dependencies. When a dependency is defined for container startup, for container shutdown it is reversed. The condition can be one of START, COMPLETE, SUCCESS or HEALTHY" + }, + "disable_networking": { + "default": null, + "description": "When this parameter is true, networking is disabled within the container" + }, + "dns_search_domains": { + "default": [], + "description": "Container DNS search domains. A list of DNS search domains that are presented to the container" + }, + "dns_servers": { + "default": [], + "description": "Container DNS servers. This is a list of strings specifying the IP addresses of the DNS servers" + }, + "docker_labels": { + "default": {}, + "description": "A key/value map of labels to add to the container" + }, + "docker_security_options": { + "default": [], + "description": "A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems. This field isn't valid for containers in tasks using the Fargate launch type" + }, + "enable_cloudwatch_logging": { + "default": true, + "description": "Determines whether CloudWatch logging is configured for this container definition. Set to `false` to use other logging drivers" + }, + "enable_execute_command": { + "default": false, + "description": "Specifies whether to enable Amazon ECS Exec for the tasks within the service" + }, + "entrypoint": { + "default": [], + "description": "The entry point that is passed to the container" + }, + "environment": { + "default": [], + "description": "The environment variables to pass to the container" + }, + "environment_files": { + "default": [], + "description": "A list of files containing the environment variables to pass to a container" + }, + "essential": { + "default": null, + "description": "If the `essential` parameter of a container is marked as `true`, and that container fails or stops for any reason, all other containers that are part of the task are stopped" + }, + "extra_hosts": { + "default": [], + "description": "A list of hostnames and IP address mappings to append to the `/etc/hosts` file on the container" + }, + "firelens_configuration": { + "default": {}, + "description": "The FireLens configuration for the container. This is used to specify and configure a log router for container logs. For more information, see [Custom Log Routing](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html) in the Amazon Elastic Container Service Developer Guide" + }, + "health_check": { + "default": {}, + "description": "The container health check command and associated configuration parameters for the container. See [HealthCheck](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_HealthCheck.html)" + }, + "hostname": { + "default": null, + "description": "The hostname to use for your container" + }, + "image": { + "default": null, + "description": "The image used to start a container. This string is passed directly to the Docker daemon. By default, images in the Docker Hub registry are available. Other repositories are specified with either `repository-url/image:tag` or `repository-url/image@digest`" + }, + "interactive": { + "default": false, + "description": "When this parameter is `true`, you can deploy containerized applications that require `stdin` or a `tty` to be allocated" + }, + "links": { + "default": [], + "description": "The links parameter allows containers to communicate with each other without the need for port mappings. This parameter is only supported if the network mode of a task definition is `bridge`" + }, + "linux_parameters": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "log_configuration": { + "default": {}, + "description": "Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html)" + }, + "memory": { + "default": null, + "description": "The amount (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. The total amount of memory reserved for all containers within a task must be lower than the task `memory` value, if one is specified" + }, + "memory_reservation": { + "default": null, + "description": "The soft limit (in MiB) of memory to reserve for the container. When system memory is under heavy contention, Docker attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs to, up to either the hard limit specified with the `memory` parameter (if applicable), or all of the available memory on the container instance" + }, + "mount_points": { + "default": [], + "description": "The mount points for data volumes in your container" + }, + "name": { + "default": null, + "description": "The name of a container. If you're linking multiple containers together in a task definition, the name of one container can be entered in the links of another container to connect the containers. Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are allowed" + }, + "operating_system_family": { + "default": "LINUX", + "description": "The OS family for task" + }, + "port_mappings": { + "default": [], + "description": "The list of port mappings for the container. Port mappings allow containers to access ports on the host container instance to send or receive traffic. For task definitions that use the awsvpc network mode, only specify the containerPort. The hostPort can be left blank or it must be the same value as the containerPort" + }, + "privileged": { + "default": false, + "description": "When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user)" + }, + "pseudo_terminal": { + "default": false, + "description": "When this parameter is true, a `TTY` is allocated" + }, + "readonly_root_filesystem": { + "default": true, + "description": "When this parameter is true, the container is given read-only access to its root file system" + }, + "repository_credentials": { + "default": {}, + "description": "Container repository credentials; required when using a private repo. This map currently supports a single key; \"credentialsParameter\", which should be the ARN of a Secrets Manager's secret holding the credentials" + }, + "resource_requirements": { + "default": [], + "description": "The type and amount of a resource to assign to a container. The only supported resource is a GPU" + }, + "secrets": { + "default": [], + "description": "The secrets to pass to the container. For more information, see [Specifying Sensitive Data](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html) in the Amazon Elastic Container Service Developer Guide" + }, + "service": { + "default": "", + "description": "The name of the service that the container definition is associated with" + }, + "start_timeout": { + "default": 30, + "description": "Time duration (in seconds) to wait before giving up on resolving dependencies for a container" + }, + "stop_timeout": { + "default": 120, + "description": "Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own" + }, + "system_controls": { + "default": [], + "description": "A list of namespaced kernel parameters to set in the container" + }, + "tags": { + "default": {}, + "description": "A map of tags to add to all resources" + }, + "ulimits": { + "default": [], + "description": "A list of ulimits to set in the container. If a ulimit value is specified in a task definition, it overrides the default values set by Docker" + }, + "user": { + "default": null, + "description": "The user to run as inside the container. Can be any of these formats: user, user:group, uid, uid:gid, user:gid, uid:group. The default (null) will use the container's configured `USER` directive or root if not set" + }, + "volumes_from": { + "default": [], + "description": "Data volumes to mount from another container" + }, + "working_directory": { + "default": null, + "description": "The working directory to run commands inside the container" + } + } + } + } + } + } + }, + "relevant_attributes": [ + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "name" + ] + }, + { + "resource": "module.ecs_container_definition.aws_cloudwatch_log_group.this[0]", + "attribute": [ + "arn" + ] + }, + { + "resource": "module.ecs_container_definition.data.aws_region.current", + "attribute": [ + "name" + ] + } + ], + "timestamp": "2024-01-16T22:10:52Z", + "errored": false +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good.tf b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good.tf new file mode 100644 index 00000000..9c545d65 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/test/good.tf @@ -0,0 +1,35 @@ +module "ecs_container_definition" { + source = "terraform-aws-modules/ecs/aws//modules/container-definition" + name = "example" + readonly_root_filesystem = true + image = "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50" + port_mappings = [ + { + name = "ecs-sample" + containerPort = 80 + protocol = "tcp" + } + ] + tags = { + Environment = "dev" + Terraform = "true" + } +} + +# Setting up the configuration for using Docker and AWS providers + +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 4.0" + } + } +} + +# Configuring docker and AWS as providers + +provider "aws" { + region = "us-west-1" + profile = "foo" +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/validate-ecs-containers-readonly.yaml b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/validate-ecs-containers-readonly.yaml new file mode 100644 index 00000000..7398f0a1 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-containers-readonly/validate-ecs-containers-readonly.yaml @@ -0,0 +1,33 @@ +apiVersion: json.kyverno.io/v1alpha1 +kind: ValidatingPolicy +metadata: + name: validate-ecs-containers-readonly + annotations: + policies.kyverno.io/title: Validate if ECS Containers only have read-only access to its root filesystems + policies.kyverno.io/category: ECS Best Practices + policies.kyverno.io/severity: medium + policies.kyverno.io/description: >- + This policy checks if ECS Containers only have read-only + access to its root filesystems. +spec: + rules: + - name: validate-ecs-containers-readonly + match: + any: + - (configuration.root_module.module_calls.ecs_container_definition.expressions | length(@) > `0`): true + assert: + any: + - check: + (configuration.root_module.module_calls.ecs_container_definition.expressions.readonly_root_filesystem == null): true + message: >- + ECS Containers should have read-only access to its root filesystems + - check: + configuration: + root_module: + module_calls: + ecs_container_definition: + expressions: + readonly_root_filesystem: + constant_value: true + message: >- + `readonly_root_filesystem` should be set to `true` diff --git a/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/README.md b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/README.md new file mode 100644 index 00000000..c4a7db18 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/README.md @@ -0,0 +1,89 @@ +# Validate ECS Task Definition PID Mode Policy + +This policy ensures that Amazon ECS task definitions do not share the host's process namespace, aligning with security standards (NIST 800-53 controls CA-9(1) and CM-2). If the host PID mode is used, there's a heightened risk of undesired process namespace exposure. + +## Policy Details: + +- **Policy Name:** validate-ecs-task-definition-pid-mode-check +- **Check Description:** This policy ensures that ECS task definitions do not share the host's process namespace +- **Policy Category:** AWS ECS Best Practices + +## How It Works: + +### Validation Criteria: + +**Key** : pid_mode +**Valid Values** : host | task | null +**Type** : string +**Required** : No + +- **Condition:** `pid_mode` is set to `task` + - **Result:** PASS + - **Reason:** If task is specified, all containers within the specified task share the same process namespace. + + +- **Condition:** `pid_mode` is set to `null` + - **Result:** PASS + - **Reason:** If no value is specified, the default is a private namespace for each container. + +- **Condition:** `pid_mode` is set to `host` + - **Result:** FAIL + - **Reason:** If host is specified, all containers within the tasks that specified the host PID mode on the same container instance share the same process namespace with the host Amazon EC2 instance. + +### Policy Validation Testing Instructions + +To evaluate and test the policy ensuring ECS task definitions meet security standards: + +1. **Initialize Terraform:** + ```bash + terraform init + ``` + +2. **Create Binary Terraform Plan:** + ```bash + terraform plan -out tfplan.binary + ``` + +3. **Convert Binary to JSON Payload:** + ```bash + terraform show -json tfplan.binary | jq > payload.json + ``` + +4. **Test the Policy with Kyverno:** + ```bash + kyverno-json scan --payload payload.json --policy validate-ecs-task-definition-pid-mode-check.yaml + ``` + + a. **Test Policy Against Valid Payload:** + ```bash + kyverno-json scan --policy validate-ecs-task-definition-pid-mode-check.yaml --payload test/good-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-task-definition-pid-mode-check / validate-ecs-task-definition-pid-mode-check / PASSED + Done + ``` + + b. **Test Against Invalid Payload:** + ```bash + kyverno-json scan --policy validate-ecs-task-definition-pid-mode-check.yaml --payload test/bad-payload.json + ``` + + This produces the output: + ``` + Loading policies ... + Loading payload ... + Pre processing ... + Running ( evaluating 1 resource against 1 policy ) ... + - validate-ecs-task-definition-pid-mode-check / validate-ecs-task-definition-pid-mode-check / FAILED: ECS task definitions shares the host's process namespace: all[0].check.~.(planned_values.root_module.resources[?type=='aws_ecs_task_definition'].values)[0].(pid_mode || 'task'): Invalid value: "host": Expected value: "task" + Done + ``` + +--- + +This way you can ensure that your ECS task definitions adhere to security standards regarding the sharing of the host's process namespace. diff --git a/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad-payload.json b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad-payload.json new file mode 100644 index 00000000..b6ef552b --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad-payload.json @@ -0,0 +1,151 @@ +{ + "format_version": "1.2", + "terraform_version": "1.7.0-dev", + "planned_values": { + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_name": "registry.terraform.io/hashicorp/aws", + "schema_version": 1, + "values": { + "container_definitions": "[{\"cpu\":512,\"essential\":true,\"image\":\"nginx:1.23.1\",\"memory\":2048,\"name\":\"foo-task\",\"portMappings\":[{\"containerPort\":80,\"hostPort\":80}]}]", + "cpu": null, + "ephemeral_storage": [], + "execution_role_arn": null, + "family": "service", + "inference_accelerator": [], + "ipc_mode": null, + "memory": null, + "pid_mode": "host", + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": null, + "runtime_platform": [], + "skip_destroy": false, + "tags": null, + "task_role_arn": null, + "volume": [] + }, + "sensitive_values": { + "ephemeral_storage": [], + "inference_accelerator": [], + "placement_constraints": [], + "proxy_configuration": [], + "runtime_platform": [], + "tags_all": {}, + "volume": [] + } + } + ] + } + }, + "resource_changes": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_name": "registry.terraform.io/hashicorp/aws", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "container_definitions": "[{\"cpu\":512,\"essential\":true,\"image\":\"nginx:1.23.1\",\"memory\":2048,\"name\":\"foo-task\",\"portMappings\":[{\"containerPort\":80,\"hostPort\":80}]}]", + "cpu": null, + "ephemeral_storage": [], + "execution_role_arn": null, + "family": "service", + "inference_accelerator": [], + "ipc_mode": null, + "memory": null, + "pid_mode": "host", + "placement_constraints": [], + "proxy_configuration": [], + "requires_compatibilities": null, + "runtime_platform": [], + "skip_destroy": false, + "tags": null, + "task_role_arn": null, + "volume": [] + }, + "after_unknown": { + "arn": true, + "arn_without_revision": true, + "ephemeral_storage": [], + "id": true, + "inference_accelerator": [], + "network_mode": true, + "placement_constraints": [], + "proxy_configuration": [], + "revision": true, + "runtime_platform": [], + "tags_all": true, + "volume": [] + }, + "before_sensitive": false, + "after_sensitive": { + "ephemeral_storage": [], + "inference_accelerator": [], + "placement_constraints": [], + "proxy_configuration": [], + "runtime_platform": [], + "tags_all": {}, + "volume": [] + } + } + } + ], + "configuration": { + "provider_config": { + "aws": { + "name": "aws", + "full_name": "registry.terraform.io/hashicorp/aws", + "version_constraint": "~> 4.0", + "expressions": { + "profile": { + "constant_value": "fyka" + }, + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_config_key": "aws", + "expressions": { + "container_definitions": { + "constant_value": " [\n {\n \"name\" : \"foo-task\",\n \"image\" : \"nginx:1.23.1\",\n \"cpu\" : 512,\n \"memory\" : 2048,\n \"essential\" : true,\n \"portMappings\" : [\n {\n \"containerPort\" : 80,\n \"hostPort\" : 80\n }\n ]\n }\n ]\n" + }, + "family": { + "constant_value": "service" + }, + "pid_mode": { + "constant_value": "host" + } + }, + "schema_version": 1 + } + ] + } + }, + "timestamp": "2024-01-23T08:06:18Z", + "errored": false +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad.tf b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad.tf new file mode 100644 index 00000000..419f3187 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/bad.tf @@ -0,0 +1,43 @@ +resource "aws_ecs_task_definition" "task" { + family = "service" + pid_mode = "host" + container_definitions = < 4.0", + "expressions": { + "profile": { + "constant_value": "fyka" + }, + "region": { + "constant_value": "us-west-1" + } + } + }, + "docker": { + "name": "docker", + "full_name": "registry.terraform.io/kreuzwerker/docker", + "version_constraint": "~> 2.20.0" + } + }, + "root_module": { + "resources": [ + { + "address": "aws_ecs_task_definition.task", + "mode": "managed", + "type": "aws_ecs_task_definition", + "name": "task", + "provider_config_key": "aws", + "expressions": { + "container_definitions": { + "constant_value": " [\n {\n \"name\" : \"foo-task\",\n \"image\" : \"nginx:1.23.1\",\n \"cpu\" : 512,\n \"memory\" : 2048,\n \"essential\" : true,\n \"portMappings\" : [\n {\n \"containerPort\" : 80,\n \"hostPort\" : 80\n }\n ]\n }\n ]\n" + }, + "family": { + "constant_value": "service" + } + }, + "schema_version": 1 + } + ] + } + }, + "timestamp": "2024-01-23T08:04:28Z", + "errored": false +} diff --git a/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/good.tf b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/good.tf new file mode 100644 index 00000000..b368ee24 --- /dev/null +++ b/terraform-best-practices/aws/ecs/validate-ecs-task-definition-pid-mode-check/test/good.tf @@ -0,0 +1,43 @@ +resource "aws_ecs_task_definition" "task" { + family = "service" + # pid_mode = "task" + container_definitions = <- + This policy ensures that ECS task definitions do not share the host's process namespace +spec: + rules: + - name: validate-ecs-task-definition-pid-mode-check + match: + any: + - (planned_values.root_module.resources[?type=='aws_ecs_task_definition'] | length(@) > `0`): true + assert: + all: + - message: ECS task definitions shares the host's process namespace + check: + ~.(planned_values.root_module.resources[?type=='aws_ecs_task_definition'].values): + (pid_mode || 'task'): task