A Guide to Securing Your Terraform Code with Checkov

aws Jul 12, 2024

In today’s rapidly evolving technological landscape, Infrastructure as Code (IaC) has revolutionized the way organizations manage and deploy their infrastructure. From small startups to large multinational corporations, IaC tools like Terraform have become indispensable. However, with the adoption of IaC comes the critical responsibility of ensuring the security and integrity of the infrastructure code. This blog will explore the importance of IaC security and how static code analysis tools like Checkov can be leveraged to prevent potential security and compliance issues before they expose your infrastructure to risks.

The Importance of IaC Security

IaC allows teams to define and manage their infrastructure using code, bringing the benefits of version control, automation, and scalability. Yet, this approach also introduces significant security challenges. Ensuring the security and quality of IaC is crucial to protect infrastructure from vulnerabilities and compliance violations.

Introducing checkov

Checkov is a powerful static code analysis tool specifically designed to analyze IaC files. By integrating Checkov into the development workflow, organizations can identify and mitigate potential security and compliance issues early in the deployment process. This proactive approach helps in maintaining a secure and compliant infrastructure from the very beginning.

Key Features of Checkov

  • Comprehensive Rule Set
    Checkov offers an extensive array of pre-built rules that cover popular cloud platforms like AWS, Azure, and GCP, ensuring thorough checks across different environments.
  • IaC Language Support
    Checkov supports multiple IaC languages, including Terraform, CloudFormation, Kubernetes YAML, and more, making it versatile for various infrastructure setups.
  • Customizable Policies
    Checkov allows you to define custom policies, enabling enforcement of organization-specific security and compliance requirements tailored to your unique needs.
  • Easy Integration
    Checkov integrates effortlessly with CI/CD pipelines and IDEs, providing automated scanning and instant feedback to streamline your development process.

Benefits of Using Checkov

  • Early Detection of Security Risks
    Checkov identifies potential security vulnerabilities and misconfigurations during the development phase, significantly reducing risk exposure.
  • Compliance Validation
    Checkov enforces compliance with industry standards (e.g., CIS benchmarks, GDPR, HIPAA) and internal policies, ensuring your infrastructure adheres to necessary regulations.
  • Faster Remediation
    Checkov offers actionable insights and recommendations to quickly resolve identified issues, streamlining and improving the development cycle.
  • Cost Reduction
    By detecting misconfigurations and insecure practices early, Checkov helps prevent costly security breaches and non-compliance penalties, leading to significant cost savings.
  • Improved Security Posture
    Using Checkov helps improve the overall cloud infrastructure security posture of an organization by ensuring that infrastructure is configured securely and in compliance with relevant regulations.
  • Continuous Updates and Improvements
    Checkov is regularly updated to include new rules and policies that address emerging security concerns and industry best practices. This ensures that users are always working with the most current guidelines and protections.

Running a Checkov Scan

To perform a Checkov scan, you need to install Checkov and specify the files or directories to be scanned.

Installation

  • Using Pip:
  • Using Homebrew (MacOS):

Scanning

  • Scan a Folder:
  • Scan a Folder with a Specific Check:
  • Combine Specific Check and Suppressing Passed Checks:
  • Scan a Specific File:
  • Scan Multiple Files:
  • Scan a Terraform Plan File in JSON:

You can scan a Terraform plan file to check the final configuration that will be applied, which is useful for identifying issues that may not be apparent from individual configuration files. This method helps in ensuring that the planned infrastructure changes are secure and compliant.

Note: Ensure the plan file is in JSON format by using the terraform show command.

Using Checkov helps ensure your infrastructure code follows best practices and remains secure before deployment. Whether you are working with Terraform, Kubernetes, or other IaC tools, Checkov aids in maintaining a secure and compliant infrastructure.

Different Approaches to Integrate Checkov with Terraform

There are several ways to integrate Checkov with Terraform to enhance the security and compliance of your infrastructure code:

  • Using the Checkov CLI
    Checkov can scan Terraform files via its command-line interface to identify potential issues.
  • IDE Plugins
    There are Checkov plugins available for various IDEs to help detect errors during code creation.
  • CI/CD Automation
    Automate Checkov scans within your CI/CD pipeline to ensure consistent evaluation of Terraform code, providing developers with immediate feedback and maintaining code quality.
Checkov Integration
Checkov Integration

How to Get Started with Checkov

In this blog, we will use the Checkov CLI and CI/CD approaches to scan Terraform files.

Let's start with an example of a misconfigured security group in a Terraform file. This security group allows ingress from any IP address on port 22 (SSH), which is considered insecure.

security_group.tf
security_group.tf

Running Checkov Scan

To scan the above Terraform file with Checkov, save the file as security_group.tf and run the following command:

➜  checkov -f security_group.tf

Sample Output Explanation

Here’s what the output might look like:

Checkov output
Checkov output

Explanation of Output

CKV_AWS_260, CKV_AWS_277, and CKV_AWS_25 are Checkov policy codes that correspond to specific security checks for AWS resources. These codes represent predefined checks that Checkov uses to identify potential security issues in your IaC files.

Here is a brief description of each code:

Passed Checks:

  • CKV_AWS_260: Ensures no security groups allow ingress from 0.0.0.0:0 to port 80.
  • CKV_AWS_277: Ensures no security groups allow ingress from 0.0.0.0:0 to port -1 (all ports).
  • CKV_AWS_25: Ensures no security groups allow ingress from 0.0.0.0:0 to port 3389.

Failed Checks:

  • CKV_AWS_24: Ensures no security groups allow ingress from 0.0.0.0:0 to port 22 (SSH). This is a security risk because it allows SSH access from any IP address.
    !!! Fix: Restrict the CIDR block to a specific IP range.
  • CKV_AWS_23: Ensures every security group rule has a description.
    !!! Fix: Add a description to each security group rule.
  • CKV2_AWS_5: Ensures that security groups are attached to another resource, such as EC2 instances or Elastic Network Interfaces (ENIs).
    !!!Fix: Ensure the security group is attached to a resource.

You can find the details of these and other Checkov policy codes on the Checkov documentation. This page provides a comprehensive list of all the built-in policies that Checkov uses to scan your IaC files, along with descriptions of each policy and the issues they address.

This resource will help you understand what each policy code checks for and how you can use them to secure your infrastructure.

Fixing the Misconfigurations

  • Restrict Ingress CIDR Blocks, add Descriptions and ensure Security Group is Attached to a Resource:
Fixed Misconfigurations
Fixed Misconfigurations

Skipping Checks by Comment

If attaching the security group to a resource is not required for your use case, you can skip this specific check using a comment in your Terraform file. Checkov allows you to skip checks by adding a special comment above the resource.

To skip the check for attaching the security group to a resource (CKV2_AWS_5), add the following comment above the aws_security_group resource:

Skipping Checks
Skipping Checks

This comment tells Checkov to skip the check CKV2_AWS_5 for this specific resource, which can be useful if the resource configuration is valid for your specific requirements but does not adhere to the general best practices enforced by Checkov.

Scan Output After Fixes

After making these changes, running the Checkov scan again would produce the following output:

Integrate Checkov into Your CI/CD Pipeline

To ensure continuous security and compliance checks, integrate Checkov into your CI/CD pipeline. This will automate the scanning process and ensure that your infrastructure code is continuously monitored.

Here’s how you can integrate Checkov into an existing Terraform pipeline, specifically between the plan and apply stages. This setup uses Jenkins and runs Checkov scans for different resources, reporting any misconfigurations directly in the Jenkins console.

In this example, the Checkov Scan stage runs after the Terraform plan stage and before the apply stage. Depending on the resource being deployed, it uses Checkov to scan for specific security and compliance checks. While the results can be reviewed directly in the Jenkins console, the generated report in JSON format can also be pushed to tools like DefectDojo for centralized tracking and management of security findings. This approach simplifies the process of tracking and fixing bugs.

Custom Policy Example

You can also enforce custom policies with Checkov. For instance, ensure RDS instances are created with port 3107 in staging environments and port 3108 in production environments. Here’s how you can define and run a custom policy.

Custom Policy Definition

Create a custom policy file named externalcheck.yaml:

Custom Policy
Custom Policy

Running Custom Policy in CI/CD Pipeline

Add a command in the Jenkins pipeline to run this custom policy:

This command runs the standard Checkov checks for RDS resources and also includes the custom policy check defined in externalcheck.yaml.

Checkov at Halodoc

By integrating Checkov into our CI/CD pipeline, Halodoc has been able to ensure that our AWS resources are secure and compliant at all times. The automated scanning and custom policy enforcement have helped us maintain high security standards without adding significant overhead to our development processes.

The implementation of hard checks ensures that no misconfigured resources are ever deployed, which is crucial for maintaining the integrity and security of our infrastructure. This approach has not only prevented potential security incidents but also instilled greater confidence in our deployment practices.

Overall, the use of Checkov has been a game-changer for Halodoc, allowing us to stay ahead of potential security issues and maintain a resilient infrastructure. By embracing such tools, we continue to uphold our commitment to security and reliability, ensuring that our services remain trustworthy and secure for all our users.

Conclusion

Checkov has proven to be an invaluable tool in ensuring the security and compliance of our AWS infrastructure at Halodoc. By seamlessly integrating into our CI/CD pipeline, it automates the detection of misconfigurations and enforces stringent security policies, preventing insecure deployments. This robust approach not only enhances our overall security posture but also boosts our confidence in the integrity of our infrastructure. Embracing Checkov has allowed us to maintain high standards of reliability and security, ensuring that our services remain trustworthy for all our users.

References

Join us

Scalability, reliability, and maintainability are the three pillars that govern what we build at Halodoc Tech. We are actively looking for engineers at all levels, and if solving hard problems with challenging requirements is your forte, please reach out to us with your resume at careers.india@halodoc.com.

About Halodoc

Halodoc is the number 1 Healthcare application in Indonesia. Our mission is to simplify and bring quality healthcare across Indonesia, from Sabang to Merauke. We connect 20,000+ doctors with patients in need through our Tele-consultation service. We partner with 3500+ pharmacies in 100+ cities to bring medicine to your doorstep. We've also partnered with Indonesia's largest lab provider to provide lab home services, and to top it off we have recently launched a premium appointment service that partners with 500+ hospitals that allow patients to book a doctor appointment inside our application. We are extremely fortunate to be trusted by our investors, such as the Bill & Melinda Gates Foundation, Singtel, UOB Ventures, Allianz, GoJek, Astra, Temasek, and many more. We recently closed our Series D round and in total have raised around USD$100+ million for our mission. Our team works tirelessly to make sure that we create the best healthcare solution personalized for all of our patient's needs, and are continuously on a path to simplify healthcare for Indonesia.

Naveen GS

SDE SR 2 with Terraform expertise. Skilled in scalable infrastructure design, automation, and optimization. Committed to delivering high-quality solutions.