Review Pod and container security contexts

Check effective runtime privileges and apply the required security context.

Description

Set the workload’s required privileges in security_context. Use the Pod for shared settings. A container’s value takes precedence when the same field is set at both levels.

Potential impact

Without explicit settings, the image, runtime and admission policies may let a container run as root or with more privileges than it needs.

Remediation

Use run_as_non_root for the execution user and container-level allow_privilege_escalation to restrict privilege gains. Limit capabilities and root filesystem writes as needed. Test the deployed application’s file access and ports as its actual user.

Examples

For var.non_root_image, supply a maintained image with a numeric, nonzero USER. The first example’s nginx:1.7.9 runs as root by default.

Before

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "terraform-example"
  }

  spec {
    container {
      image = "nginx:1.7.9"
      name  = "example"
    }
  }
}

After

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "terraform-example"
  }

  spec {
    security_context {
      run_as_non_root = true
    }

    container {
      image = var.non_root_image
      name  = "example"

      security_context {
        allow_privilege_escalation = false
      }
    }
  }
}

The second example requires non-root execution for the Pod and restricts privilege escalation for the example container.

References