bridgecrewio / checkov

Prevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.
https://www.checkov.io/
Apache License 2.0
6.73k stars 1.08k forks source link

CDKTF - support a way to suppress checks inline #4634

Open gruebel opened 1 year ago

gruebel commented 1 year ago

Describe the issue CDKTF support is currently limited to the synthesized Terraform JSON output and therefore a way to suppress checks should be implemented, which propagates to the synthesized output file.

This could be achieved by leveraging the comment field "//" ex.

    const bucket = new S3Bucket(this, "bucket", {});
    bucket.addOverride("//", {
      checkov: {
        skip: [
          {
            id: "CKV_AWS_18",
            comment: "Access logging not needed"
          }
        ]
      }
    })
stale[bot] commented 9 months ago

Thanks for contributing to Checkov! We've automatically marked this issue as stale to keep our issues list tidy, because it has not had any activity for 6 months. It will be closed in 14 days if no further activity occurs. Commenting on this issue will remove the stale tag. If you want to talk through the issue or help us understand the priority and context, feel free to add a comment or join us in the Checkov slack channel at https://slack.bridgecrew.io Thanks!

stale[bot] commented 8 months ago

Closing issue due to inactivity. If you feel this is in error, please re-open, or reach out to the community via slack: https://slack.bridgecrew.io Thanks!

daniel-caruso-ii commented 6 months ago

@gruebel can we open this and get it fixed and working?

tschaffter commented 4 months ago

Hey, I'm using Terraform CDK and needs to skip a check for a specific resource (S3 bucket). Is there a way to achieve that using the checkov CLI argument or configuration file?

I've found here how to suppress a check but not how to suppress a check for a specific resource.

I see that it's possible by adding comments to a specific resource when using HCL, which I can't edit directly as it's being overwritten when synth with cdktf.

daniel-caruso-ii commented 4 months ago

You have to skip it for all resources using the β€œglobal” checkov config. This issue is still open.

It is pretty annoying :(

On Tue, Feb 27, 2024 at 9:44 AM, Thomas Schaffter @.***(mailto:On Tue, Feb 27, 2024 at 9:44 AM, Thomas Schaffter < wrote:

Hey, I'm using Terraform CDK and needs to skip a check for a specific resource (S3 bucket). Is there a way to achieve that using the checkov CLI argument or configuration file?

I've found here how to suppress a check but not how to suppress a check for a specific resource.

I see that it's possible by adding comments to a specific resource when using HCL, which I can't edit directly as it's being overwritten when synth with cdktf.

β€” Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>

mixam24 commented 2 months ago

Since CDKTF v0.20.0 You can use the following workaround to skip checks on a resource level:

  1. Use addOverride on your resource as follows:

    self._account = StorageAccount(
            scope=self,
            id_="test",
            name="testaccount",
            resource_group_name="test_group",
            location="westeurope",
            account_tier="Standard",
            account_kind="StorageV2",
            account_replication_type="LRS",
        )
    
    self._account.add_override(
            path="#checkov:skip=CKV2_AZURE_1:",
            value="Test if checkov skip is added",
        )
  2. Synthesize the stack using --hcl option:

    cdktf synth --app "..." --hcl
  3. Inspect generated cdk.tf file and check that your resource has checkov skip comment:

    resource "azurerm_storage_account" "test_ABCDEF01" {
     account_kind             = "StorageV2"
     account_replication_type = "LRS"
     account_tier             = "Standard"
     location                 = "westeurope"
     name                     = "testaccount"
     resource_group_name      = "test_group"
     #checkov:skip=CKV2_AZURE_1: = "Test if checkov skip is added"
    }
  4. Run checkov against HCL generated stack.

Hope it helps πŸ™‚

woutervb commented 2 months ago

Before finding this work around, I had opened an issue at the terraform-cdk project to this specific issue https://github.com/hashicorp/terraform-cdk/issues/3609

woutervb commented 2 months ago

After some testing, I found that this 'work around` breaks the testing.

When running a test that uses assert Testing.to_be_valid_terraform(stack), it will fail. With some debugging I found that the error it produced is:

terraform validate
β•·
β”‚ Error: Extraneous JSON object property
β”‚
β”‚   on cdk.tf.json line 38, in resource.aws_dynamodb_table.test_DBA94737:
β”‚   38:         "#checkov:skip=CKV_AWS_119:": "To keep backward compatibility with deployed solutions we don't manage the CMK for the moment.",
β”‚
β”‚ No argument or block type is named "#checkov:skip=CKV_AWS_119:".
mixam24 commented 2 months ago

Hello @woutervb,

I was able to reproduce the error you mentioned.

The reason is that Testing.full_synth method synthesizes JSON not HCL.

I prepared additional hack in order to workaround this :D.

As far as I can see there is no native way to configure Testing library to synth HCL code.

However, you can define SYNTH_HCL_OUTPUT envrironment varable to be equal to 1 or true to force CDKTF to produce HCL code instead of JSON (see app.ts for details).

Now given that SYNTH_HCL_OUTPUT is set, Testing.full_synth(stack) will produce HCL as output but save it with cdk.tf.json name on disk (a bug in CDKTF...).

You need to rename cdk.tf.json to cdk.tf.hcl before running Testing.to_be_valid_terraform(stack): under the hood to_be_valid_terraform simply executes terraform validate that performs validation based on the file extension.

Here is the pytest fixture to perform the steps above:

import pytest
from cdktf import Testing as CDKTFTesting
from cdktf import TerraformStack
from collections.abc import Callable, Generator
from os import environ
from pathlib import Path
from typing import Any

@pytest.fixture(scope="session")
def is_valid_terraform_stack() -> Generator[Callable[[TerraformStack], bool], Any, Any]:
    def _func(stack: TerraformStack) -> bool:
        output = CDKTFTesting.full_synth(stack=stack)
        if environ["SYNTH_HCL_OUTPUT"] in ["1", "true"]:
            for stack in Path(output).glob("**/cdk.tf.json"):
                stack.rename(stack.parent / "cdk.tf.hcl")
        result = CDKTFTesting.to_be_valid_terraform(received=output)

        return result

    yield _func
woutervb commented 1 month ago

@mixam24 thanks for your suggestion. The problem I'm now facing is that the hcl that is rendered isn't valid, so unfortunately I'm stuck with this for the moment.

Falling back to global allow-lists to make sure that things pass for the time being.