Member post originally published on Nirmata’s blog by Anusha Hegde

Securing OpenTofu with Nirmata Powered by Kyverno banner

As Infrastructure as Code (IaC) continues to gain popularity among DevOps practitioners for its efficiency and scalability, the recent Terraform license ambiguity has prompted the emergence of alternative solutions. OpenTofu, marking its first stable release, enters the scene as a robust IaC tool, providing users with a reliable option for managing and provisioning cloud infrastructure. Whether you are just beginning your journey with OpenTofu or contemplating a migration from other tools, it’s essential to enhance your infrastructure’s security and compliance posture. A key recommendation is to seamlessly integrate Policy-as-Code (PaC) into your OpenTofu workflows if they still need to be put in place.

Why scan your OpenTofu workflows?

As with any IaC, scanning OpenTofu files is crucial for ensuring the security, reliability, and compliance of cloud infrastructure deployments. By regularly scanning these files, organizations can proactively identify and rectify security vulnerabilities, misconfigurations, and compliance violations before they manifest in deployed environments.

How does Kyverno help?

Kyverno is the most popular cloud-native policy engine. If you’ve been keeping up with cloud-native security trends, Kyverno’s name has likely crossed your path, and how it simplifies policy enforcement for Kubernetes clusters with its low-code YAML syntax. Now, with the latest announcement of Kyverno for any JSON, you can leverage the benefits of the simplicity of Kyverno to write policies for scanning any OpenTofu file. 

This blog post demonstrates the power of Kyverno to scan OpenTofu files using NCTL (a command line tool developed by Nirmata). The CLI can be utilized in CI pipelines for the proactive detection of misconfigurations, enabling timely mitigation of issues and preempting potential security risks before they escalate.

NCTL and OpenTofu

Prerequisites

Before we get started, you need to install the following tools –

OpenTofu file to create an ECS task

The following is a Terraform file snippet for creating an ECS task. The image used here is `nginx:latest`.

resource "aws_ecs_task_definition" "service" {
  family = "service"
  container_definitions = jsonencode([
    {
      name      = "foo-service"
      image     = "nginx:latest"
      cpu       = 10
      memory    = 512
      essential = true
      portMappings = [
        {
          containerPort = 80
          hostPort      = 80
        }
      ]
    }
  ])
}

Kyverno Policy

The following Kyverno policy validates the `image` field specified in the `container_definitions` section and validates that a tag has to be present, and it should not be a mutable tag, i.e., `latest`

apiVersion: json.kyverno.io/v1alpha1
kind: ValidatingPolicy
metadata:
  name: check-ecs-image-tag
  annotations:
    policies.kyverno.io/title: Check ECS Image Tag 
    policies.kyverno.io/category: OpenTofu ECS Best Practices
    policies.kyverno.io/severity: High
    policies.kyverno.io/description: >-
      The ':latest' tag is mutable and can lead to unexpected errors if the
      image changes. A best practice is to use an immutable tag that maps to
      a specific version of an application. This policy validates that the image
      specifies a tag and that it is not called `latest`.
spec:
  rules:
    - name: check-ecs-image-tag-latest
      match:
        all:
        - type: (planned_values.root_module.resources[?type=='aws_ecs_task_definition'])
      assert:
        all:
        - message: An image tag or digest should be specified
          check:
             ~.(planned_values.root_module.resources[?type=='aws_ecs_task_definition'].values):
                  ~.(json_parse(container_definitions)):
                    image:
                      (contains(@, ':') || contains(@, '@sha256:')): true
        - message: Image tag `latest` should not be used
          check:
            ~.(planned_values.root_module.resources[?type=='aws_ecs_task_definition'].values):
                  ~.(json_parse(container_definitions)):
                    image:
                      (contains(@, ':latest')): false

Scan OpenTofu using NCTL

First, we will convert the Terraform file to a JSON format. Perform the following steps –

tofu init
tofu plan -out tofuplan.binary
tofu show -json tofuplan.binary | jq > tofuplan.json

Use NCTL to scan the `tofuplan.json` with the policy we defined above.

nctl scan terraform -r tofuplan.json -p check-ecs-image-tag.yaml

If the `image` does not contain any tag or a digest or contains the `latest` tag, then it will be reported as a failure. If any other tag is present, then the policy evaluates to pass.

Conclusion

With this simple yet powerful example, we saw how Kyverno is leveraged to write low-code policies to secure your OpenTofu files. NCTL can be used to build workflows that can integrate with your existing CI pipelines and detect misconfigurations as early as possible. Nirmata provides out-of-the-box policy sets that you can utilize to enforce security best practices in your organization. Watch out this space for more updates on policy and governance of cloud infrastructure!

To know more about Nirmata and our product offerings, visit our website or contact us! We would be happy to assist you in your Policy and Governance journey.

References