Перейти к основному содержимому
Infrastructure as Code (IaC) Security with Terraform
Урок 7 из 11

Infrastructure as Code (IaC) Security with Terraform

Identify insecure Terraform configurations before deployment using Checkov and tfsec, protect sensitive state data, and enforce least privilege in cloud modules.

Продвинутый 26 мин Облака и DevSecOps
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Explain how declarative IaC templates propagate cloud misconfigurations at scale
  • Identify high-risk Terraform patterns across IAM, networking, and storage resources
  • Run static analysis with Checkov and tfsec to catch policy violations before apply
  • Configure encrypted remote state, locking, and pinned module versions

Рекомендуется заранее: Cloud IAM: Policies, Roles, Federation & Privilege PathsCloud Networking (VPCs, Security Groups) & Storage Security

#Why this matters

Cloud misconfigurations in IAM roles, security groups, and storage buckets rarely begin in a web console today. Engineering teams define entire cloud accounts in HashiCorp Configuration Language (HCL) using Terraform and reuse those templates across development, staging, and production.

That automation cuts both ways. A single insecure default inside a shared module replicates across dozens of accounts in minutes. Conversely, auditing HCL before terraform apply runs lets defenders eliminate whole classes of exposure while the infrastructure is still plain text in a pull request.

#How IaC shifts the cloud threat surface

Terraform reads .tf files, builds a dependency graph, compares desired resources against recorded state, and calls cloud provider APIs. Because the configuration lives in Git, security teams can inspect infrastructure changes with the same automated gates used for application code.

  1. Author HCLWrite Terraform modules
  2. Static ScanRun Checkov and tfsec
  3. Plan ReviewInspect terraform plan diff
  4. Remote StateLock and encrypt state file
  5. ApplyProvision cloud resources

Three IaC-specific failure modes deserve special attention:

  • Default-open resource definitions: Copy-pasted examples often omit encryption, access logging, or public-access blocks.
  • Unpinned external modules: Pulling a module from a Git branch or unpinned registry version allows upstream changes to alter your cloud permissions silently.
  • Exposed state files: Terraform records resource metadata in terraform.tfstate, which can include initial database passwords, private keys, or token outputs in plaintext JSON.

#Common Terraform misconfigurations

Most high-severity findings in cloud posture audits map directly back to a few recurring HCL patterns.

Resource area Insecure HCL pattern Cloud impact Hardened pattern
Object storage Bucket without public-access block or encryption Public data leak or unencrypted objects at rest Enforce aws_s3_bucket_public_access_block and KMS/AES encryption
Network ingress Security group with 0.0.0.0/0 on port 22 or 3389 Internet-wide brute force against management ports Restrict CIDR blocks to bastion or VPN ranges
IAM policies Wildcard "Action": "*" on "Resource": "*" Full account compromise if workload is breached Scope actions and resource ARNs to least privilege
Compute metadata EC2 instance allowing IMDSv1 (http_tokens = "optional") SSRF vulnerabilities can steal instance role tokens Set http_tokens = "required" to enforce IMDSv2

Consider this vulnerable security group and storage configuration in a lab module:

hcl
resource "aws_security_group" "admin_sg" {
  name        = "lab-admin-sg"
  description = "Admin access"

  ingress {
    description = "SSH from anywhere"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_s3_bucket" "artifacts" {
  bucket = "lab-local-build-artifacts"
}

Here, admin_sg opens SSH to the entire internet, and artifacts relies on defaults without explicit public-access blocks, encryption configuration, or versioning. Fixing the security group narrows the CIDR block to the lab management subnet 10.10.10.0/24 and adds a clear description. Fixing the bucket pairs aws_s3_bucket with aws_s3_bucket_public_access_block (all four flags set to true) and aws_s3_bucket_server_side_encryption_configuration.

hcl
resource "aws_security_group" "admin_sg" {
  name        = "lab-admin-sg"
  description = "Admin access from management subnet"
  vpc_id      = aws_vpc.lab.id

  ingress {
    description = "SSH from lab management subnet"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["10.10.10.0/24"]
  }
}

resource "aws_s3_bucket_public_access_block" "artifacts_block" {
  bucket                  = aws_s3_bucket.artifacts.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

#Static scanning with Checkov and tfsec

Static IaC scanners parse HCL (and optionally rendered terraform plan JSON) into an abstract graph and evaluate built-in security rules without touching a live cloud account. Checkov and tfsec (now also integrated into Trivy) are widely used in pull-request pipelines because they run in seconds and return a non-zero exit code when checks fail.

Scanning a Terraform lab directory with Checkov and tfsec
$ checkov -d ./infra --framework terraform --compact
terraform scan results:

Passed checks: 14, Failed checks: 2, Skipped checks: 0

Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
	FAILED for resource: aws_security_group.admin_sg
	File: /network.tf:1-12
Check: CKV_AWS_145: "Ensure that S3 buckets are encrypted with KMS by default"
	FAILED for resource: aws_s3_bucket.artifacts
	File: /storage.tf:1-3

$ tfsec ./infra --no-color
Result #1 HIGH Security group rule allows ingress from public internet.
  /network.tf:9

Scanning raw .tf files catches static mistakes, but dynamic expressions using var.*, for_each, or locals may only resolve at plan time. Exporting a binary plan and converting it to JSON lets Checkov inspect resolved values before any resource is created:

Evaluating resolved plan values
$ terraform plan -out=tfplan.binary
$ terraform show -json tfplan.binary > tfplan.json
$ checkov -f tfplan.json

When a rule genuinely does not apply (for example, a dedicated public CDN origin bucket), never disable the scanner globally. Use an inline suppression with an explicit reason so reviewers can audit the exception:

hcl
#checkov:skip=CKV_AWS_145:Lab artifact bucket uses SSE-S3 AES256 per baseline policy

#Protecting state files, variables, and modules

Even flawless resource definitions fail if the surrounding Terraform workflow leaks secrets or drifts from reviewed code.

  1. Keep state out of Git: Add *.tfstate, *.tfstate.*, and .terraform/ to .gitignore. Store state in a remote backend (such as an encrypted S3 bucket with access logging and DynamoDB or native lockfile locking, or Terraform Cloud) restricted to the deployment role.
  2. Never hardcode secrets in .tf or .tfvars: Pass credentials via short-lived OIDC roles or a secrets manager data source rather than plaintext variables. Remember that marking a variable sensitive = true hides it from CLI stdout, not from terraform.tfstate.
  3. Pin providers and modules: Commit .terraform.lock.hcl to version control so every runner verifies the same provider checksums. Pin third-party module versions (version = "5.1.2") or immutable Git commit hashes instead of floating branches.

#Defending and common mistakes

  • Skipping terraform plan inspection: Attackers or accidental edits can trigger destructive recreations or IAM changes. Always review the plan diff in pull requests before approval.
  • Adding blank suppressions: Writing #checkov:skip=CKV_AWS_... without a reason bypasses policy enforcement. Require peer review on any suppression comment.
  • Scanning only .tf and ignoring tfplan.json: Variable defaults may look harmless in a module while production .tfvars pass 0.0.0.0/0. Scan the rendered plan in CI.
  • Running terraform apply from laptops: Developer workstations accumulate cached admin keys and stale state. Execute applies only from hardened CI runners with least-privilege roles.

#Summary

Terraform turns cloud architecture into reviewable code, which means security controls can be verified before any API call runs. Static scanners like Checkov and tfsec detect open security groups, unencrypted storage, and wildcard IAM policies directly in HCL and rendered JSON plans. Combining automated policy gates with encrypted remote state, locked provider checksums, and pinned modules prevents misconfigurations from scaling across environments.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему