Infrastructure as Code Security

Infrastructure as Code traz benefícios de versionamento e automação mas introduz riscos se misconfigurations são propagadas automaticamente. Security deve ser shift-left para IaC.

Vulnerabilidades Comuns em IaC

  • Hardcoded secrets: Credenciais em código versionado
  • Overly permissive rules: Security groups 0.0.0.0/0
  • Unencrypted resources: S3 buckets, RDS sem encryption
  • Public access: Recursos expostos desnecessariamente
  • Missing logging: CloudTrail, flow logs desabilitados
  • Weak authentication: MFA não enforçado

Ferramentas de Scanning

Terraform - tfsec, Checkov, Terrascan

      # Exemplo de vulnerabilidade - S3 bucket público
      resource "aws_s3_bucket" "bad_bucket" {
      bucket = "my-public-bucket"
      acl    = "public-read"  # [ERRO] VULNERÁVEL
      }
      # Correção
      resource "aws_s3_bucket" "good_bucket" {
      bucket = "my-private-bucket"
      acl    = "private"  # [OK] Seguro
      server_side_encryption_configuration {
      rule {
      apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
      }
      }
      }
      versioning {
      enabled = true
      }
      }
      resource "aws_s3_bucket_public_access_block" "good_bucket" {
      bucket = aws_s3_bucket.good_bucket.id
      block_public_acls       = true
      block_public_policy     = true
      ignore_public_acls      = true
      restrict_public_buckets = true
      }
      

tfsec - Scanning Terraform

      # Install
      brew install tfsec
      # Scan Terraform files
      tfsec .
      # Output específico
      tfsec --format json --out results.json .
      # CI/CD integration
      tfsec --soft-fail . || exit 1
      

Checkov - Multi-Cloud IaC Scanner

      # Install
      pip install checkov
      # Scan Terraform
      checkov -d ./terraform
      # Scan CloudFormation
      checkov -f template.yaml
      # Scan Kubernetes manifests
      checkov -d ./k8s
      # Skip specific checks
      checkov -d . --skip-check CKV_AWS_20
      # Custom policies
      checkov -d . --external-checks-dir ./custom-policies
      

Policy as Code

Open Policy Agent (OPA)

OPA permite escrever policies em Rego language para enforçar compliance:

      # deny_public_s3.rego
      package terraform.aws.s3
      deny[msg] {
      resource := input.resource_changes[_]
      resource.type == "aws_s3_bucket"
      resource.change.after.acl == "public-read"
      msg := sprintf("S3 bucket %s cannot be public", [resource.address])
      }
      deny[msg] {
      resource := input.resource_changes[_]
      resource.type == "aws_s3_bucket"
      not resource.change.after.server_side_encryption_configuration
      msg := sprintf("S3 bucket %s must have encryption enabled", [resource.address])
      }
      

Sentinel (HashiCorp)

Policy framework integrado com Terraform Cloud/Enterprise:

      # enforce-mandatory-tags.sentinel
      import "tfplan/v2" as tfplan
      mandatory_tags = ["Environment", "Owner", "Project"]
      all_resources = filter tfplan.resource_changes as _, rc {
      rc.mode is "managed"
      }
      deny_resources_without_tags = rule {
      all all_resources as _, resource {
      all mandatory_tags as tag {
      resource.change.after.tags contains tag
      }
      }
      }
      

Secrets Management em IaC

Terraform - Usando AWS Secrets Manager

      # Criar secret no Secrets Manager
      resource "aws_secretsmanager_secret" "db_password" {
      name = "production/db/password"
      recovery_window_in_days = 30
      }
      resource "aws_secretsmanager_secret_version" "db_password" {
      secret_id     = aws_secretsmanager_secret.db_password.id
      secret_string = random_password.db_password.result
      }
      # Referenciar secret (não expõe o valor)
      data "aws_secretsmanager_secret_version" "db_password" {
      secret_id = aws_secretsmanager_secret.db_password.id
      }
      # Usar em RDS (referência, não valor hardcoded)
      resource "aws_db_instance" "main" {
      # ... outras configs
      password = data.aws_secretsmanager_secret_version.db_password.secret_string
      }
      

git-secrets - Prevenir Commits de Secrets

      # Install git-secrets
      brew install git-secrets
      # Setup hooks para repositório
      git secrets --install
      git secrets --register-aws
      # Scan histórico de commits
      git secrets --scan-history
      # Prevenir commits com secrets
      # Automático via pre-commit hook
      

State File Security

  • Remote state: S3 + DynamoDB lock, nunca commit local state
  • Encryption: Server-side encryption no S3
  • Access control: IAM policies restritivas para state bucket
  • Versioning: Habilitar versioning para recovery
  • State locking: DynamoDB para prevenir concurrent modifications

Terraform Remote Backend Seguro

      terraform {
      backend "s3" {
      bucket         = "terraform-state-prod"
      key            = "global/s3/terraform.tfstate"
      region         = "us-east-1"
      encrypt        = true
      dynamodb_table = "terraform-state-lock"
      # MFA delete protection
      versioning {
      enabled = true
      mfa_delete = true
      }
      }
      }
      

CI/CD Integration

GitHub Actions - Terraform Workflow Seguro

      name: 'Terraform Security Scan'
      on:
      pull_request:
      branches: [ main ]
      jobs:
      terraform-security:
      runs-on: ubuntu-latest
      steps:
      - uses: actions/checkout@v3
      - name: Run tfsec
      uses: aquasecurity/tfsec-action@v1.0.0
      with:
      soft_fail: false
      - name: Run Checkov
      uses: bridgecrewio/checkov-action@master
      with:
      directory: .
      framework: terraform
      output_format: sarif
      output_file_path: checkov.sarif
      - name: Upload results to GitHub Security
      uses: github/codeql-action/upload-sarif@v2
      with:
      sarif_file: checkov.sarif
      

Drift Detection

Detectar mudanças manuais fora do IaC que criam security gaps:

  • Terraform Cloud: Health checks automáticos
  • driftctl: Open-source drift detection
  • CloudFormation Drift Detection: Native AWS service
  • Scheduled scans: CI/CD jobs periódicos

Compliance Frameworks

  • CIS Benchmarks: Terraform modules para compliance
  • NIST 800-53: Policy packs para controls
  • PCI-DSS: Policies para payment card processing
  • HIPAA: Healthcare compliance policies
  • SOC 2: Security organization policies

Módulos Terraform Seguros

  • Usar Terraform Registry modules verificados
  • Pin module versions (não usar latest)
  • Review de código de modules internos
  • Private registry para modules customizados
  • Documentar security considerations

Boas Práticas

  • Peer review: PRs obrigatórios para mudanças em prod
  • Plan antes de apply: Review de mudanças propostas
  • Separate environments: Dev/Staging/Prod isolados
  • Tagging strategy: Tags para governança e cost allocation
  • Least privilege: IAM roles específicas para CI/CD
  • Automated testing: Terratest para validação

Recomendações Finais

IaC security deve ser automated e integrada em CI/CD desde o início. Use múltiplas ferramentas de scanning (tfsec, Checkov) para cobertura completa. Implemente policy as code com OPA ou Sentinel. Nunca commite secrets, use secret managers. Monitore drift continuamente. IaC misconfiguration é uma das causas mais comuns de cloud breaches.