• Stars
    star
    782
  • Rank 58,164 (Top 2 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Check CDK applications for best practices using a combination of available rule packs

cdk-nag

PyPI version npm version Maven version NuGet version Go version

View on Construct Hub

Check CDK applications or CloudFormation templates for best practices using a combination of available rule packs. Inspired by cfn_nag.

Check out this blog post for a guided overview!

demo

Available Rules and Packs

See RULES for more information on all the available packs.

  1. AWS Solutions
  2. HIPAA Security
  3. NIST 800-53 rev 4
  4. NIST 800-53 rev 5
  5. PCI DSS 3.2.1

RULES also includes a collection of additional rules that are not currently included in any of the pre-built NagPacks, but are still available for inclusion in custom NagPacks.

Read the NagPack developer docs if you are interested in creating your own pack.

Usage

For a full list of options See NagPackProps in the API.md

Including in an application
import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { AwsSolutionsChecks } from 'cdk-nag';

const app = new App();
new CdkTestStack(app, 'CdkNagDemo');
// Simple rule informational messages
Aspects.of(app).add(new AwsSolutionsChecks());
// Additional explanations on the purpose of triggered rules
// Aspects.of(stack).add(new AwsSolutionsChecks({ verbose: true }));

Suppressing a Rule

Example 1) Default Construct
import { SecurityGroup, Vpc, Peer, Port } from 'aws-cdk-lib/aws-ec2';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const test = new SecurityGroup(this, 'test', {
      vpc: new Vpc(this, 'vpc'),
    });
    test.addIngressRule(Peer.anyIpv4(), Port.allTraffic());
    NagSuppressions.addResourceSuppressions(test, [
      { id: 'AwsSolutions-EC23', reason: 'lorem ipsum' },
    ]);
  }
}
Example 2) On Multiple Constructs
import { SecurityGroup, Vpc, Peer, Port } from 'aws-cdk-lib/aws-ec2';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const vpc = new Vpc(this, 'vpc');
    const test1 = new SecurityGroup(this, 'test', { vpc });
    test1.addIngressRule(Peer.anyIpv4(), Port.allTraffic());
    const test2 = new SecurityGroup(this, 'test', { vpc });
    test2.addIngressRule(Peer.anyIpv4(), Port.allTraffic());
    NagSuppressions.addResourceSuppressions(
      [test1, test2],
      [{ id: 'AwsSolutions-EC23', reason: 'lorem ipsum' }]
    );
  }
}
Example 3) Child Constructs
import { User, PolicyStatement } from 'aws-cdk-lib/aws-iam';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const user = new User(this, 'rUser');
    user.addToPolicy(
      new PolicyStatement({
        actions: ['s3:PutObject'],
        resources: ['arn:aws:s3:::bucket_name/*'],
      })
    );
    // Enable adding suppressions to child constructs
    NagSuppressions.addResourceSuppressions(
      user,
      [
        {
          id: 'AwsSolutions-IAM5',
          reason: 'lorem ipsum',
          appliesTo: ['Resource::arn:aws:s3:::bucket_name/*'], // optional
        },
      ],
      true
    );
  }
}
Example 4) Stack Level
import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { AwsSolutionsChecks, NagSuppressions } from 'cdk-nag';

const app = new App();
const stack = new CdkTestStack(app, 'CdkNagDemo');
Aspects.of(app).add(new AwsSolutionsChecks());
NagSuppressions.addStackSuppressions(stack, [
  { id: 'AwsSolutions-EC23', reason: 'lorem ipsum' },
]);
Example 5) Construct path

If you received the following error on synth/deploy

[Error at /StackName/Custom::CDKBucketDeployment8675309/ServiceRole/Resource] AwsSolutions-IAM4: The IAM user, role, or group uses AWS managed policies
import { Bucket } from 'aws-cdk-lib/aws-s3';
import { BucketDeployment } from 'aws-cdk-lib/aws-s3-deployment';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    new BucketDeployment(this, 'rDeployment', {
      sources: [],
      destinationBucket: Bucket.fromBucketName(this, 'rBucket', 'foo'),
    });
    NagSuppressions.addResourceSuppressionsByPath(
      this,
      '/StackName/Custom::CDKBucketDeployment8675309/ServiceRole/Resource',
      [{ id: 'AwsSolutions-IAM4', reason: 'at least 10 characters' }]
    );
  }
}
Example 6) Granular Suppressions of findings

Certain rules support granular suppressions of findings. If you received the following errors on synth/deploy

[Error at /StackName/rFirstUser/DefaultPolicy/Resource] AwsSolutions-IAM5[Action::s3:*]: The IAM entity contains wildcard permissions and does not have a cdk-nag rule suppression with evidence for those permission.
[Error at /StackName/rFirstUser/DefaultPolicy/Resource] AwsSolutions-IAM5[Resource::*]: The IAM entity contains wildcard permissions and does not have a cdk-nag rule suppression with evidence for those permission.
[Error at /StackName/rSecondUser/DefaultPolicy/Resource] AwsSolutions-IAM5[Action::s3:*]: The IAM entity contains wildcard permissions and does not have a cdk-nag rule suppression with evidence for those permission.
[Error at /StackName/rSecondUser/DefaultPolicy/Resource] AwsSolutions-IAM5[Resource::*]: The IAM entity contains wildcard permissions and does not have a cdk-nag rule suppression with evidence for those permission.

By applying the following suppressions

import { User } from 'aws-cdk-lib/aws-iam';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const firstUser = new User(this, 'rFirstUser');
    firstUser.addToPolicy(
      new PolicyStatement({
        actions: ['s3:*'],
        resources: ['*'],
      })
    );
    const secondUser = new User(this, 'rSecondUser');
    secondUser.addToPolicy(
      new PolicyStatement({
        actions: ['s3:*'],
        resources: ['*'],
      })
    );
    const thirdUser = new User(this, 'rSecondUser');
    thirdUser.addToPolicy(
      new PolicyStatement({
        actions: ['sqs:CreateQueue'],
        resources: [`arn:aws:sqs:${this.region}:${this.account}:*`],
      })
    );
    NagSuppressions.addResourceSuppressions(
      firstUser,
      [
        {
          id: 'AwsSolutions-IAM5',
          reason:
            "Only suppress AwsSolutions-IAM5 's3:*' finding on First User.",
          appliesTo: ['Action::s3:*'],
        },
      ],
      true
    );
    NagSuppressions.addResourceSuppressions(
      secondUser,
      [
        {
          id: 'AwsSolutions-IAM5',
          reason: 'Suppress all AwsSolutions-IAM5 findings on Second User.',
        },
      ],
      true
    );
    NagSuppressions.addResourceSuppressions(
      thirdUser,
      [
        {
          id: 'AwsSolutions-IAM5',
          reason: 'Suppress AwsSolutions-IAM5 on the SQS resource.',
          appliesTo: [
            {
              regex: '/^Resource::arn:aws:sqs:(.*):\\*$/g',
            },
          ],
        },
      ],
      true
    );
  }
}

You would see the following error on synth/deploy

[Error at /StackName/rFirstUser/DefaultPolicy/Resource] AwsSolutions-IAM5[Resource::*]: The IAM entity contains wildcard permissions and does not have a cdk-nag rule suppression with evidence for those permission.

Suppressing aws-cdk-lib/pipelines Violations

The aws-cdk-lib/pipelines.CodePipeline construct and its child constructs are not guaranteed to be "Visited" by Aspects, as they are not added during the "Construction" phase of the cdk lifecycle. Because of this behavior, you may experience problems such as rule violations not appearing or the inability to suppress violations on these constructs.

You can remediate these rule violation and suppression problems by forcing the pipeline construct creation forward by calling .buildPipeline() on your CodePipeline object. Otherwise you may see errors such as:

Error: Suppression path "/this/construct/path" did not match any resource. This can occur when a resource does not exist or if a suppression is applied before a resource is created.

See this issue for more information.

Example) Supressing Violations in Pipelines

example-app.ts

import { App, Aspects } from 'aws-cdk-lib';
import { AwsSolutionsChecks } from 'cdk-nag';
import { ExamplePipeline } from '../lib/example-pipeline';

const app = new App();
new ExamplePipeline(app, 'example-cdk-pipeline');
Aspects.of(app).add(new AwsSolutionsChecks({ verbose: true }));
app.synth();

example-pipeline.ts

import { Stack, StackProps } from 'aws-cdk-lib';
import { Repository } from 'aws-cdk-lib/aws-codecommit';
import {
  CodePipeline,
  CodePipelineSource,
  ShellStep,
} from 'aws-cdk-lib/pipelines';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';

export class ExamplePipeline extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const exampleSynth = new ShellStep('ExampleSynth', {
      commands: ['yarn build --frozen-lockfile'],
      input: CodePipelineSource.codeCommit(
        new Repository(this, 'ExampleRepo', { repositoryName: 'ExampleRepo' }),
        'main'
      ),
    });

    const ExamplePipeline = new CodePipeline(this, 'ExamplePipeline', {
      synth: exampleSynth,
    });

    // Force the pipeline construct creation forward before applying suppressions.
    // @See https://github.com/aws/aws-cdk/issues/18440
    ExamplePipeline.buildPipeline();

    // The path suppression will error if you comment out "ExamplePipeline.buildPipeline();""
    NagSuppressions.addResourceSuppressionsByPath(
      this,
      '/example-cdk-pipeline/ExamplePipeline/Pipeline/ArtifactsBucket/Resource',
      [
        {
          id: 'AwsSolutions-S1',
          reason: 'Because I said so',
        },
      ]
    );
  }
}

Rules and Property Overrides

In some cases L2 Constructs do not have a native option to remediate an issue and must be fixed via Raw Overrides. Since raw overrides take place after template synthesis these fixes are not caught by cdk-nag. In this case you should remediate the issue and suppress the issue like in the following example.

Example) Property Overrides
import {
  Instance,
  InstanceType,
  InstanceClass,
  MachineImage,
  Vpc,
  CfnInstance,
} from 'aws-cdk-lib/aws-ec2';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NagSuppressions } from 'cdk-nag';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const instance = new Instance(this, 'rInstance', {
      vpc: new Vpc(this, 'rVpc'),
      instanceType: new InstanceType(InstanceClass.T3),
      machineImage: MachineImage.latestAmazonLinux(),
    });
    const cfnIns = instance.node.defaultChild as CfnInstance;
    cfnIns.addPropertyOverride('DisableApiTermination', true);
    NagSuppressions.addResourceSuppressions(instance, [
      {
        id: 'AwsSolutions-EC29',
        reason: 'Remediated through property override.',
      },
    ]);
  }
}

Conditionally Ignoring Suppressions

You can optionally create a condition that prevents certain rules from being suppressed. You can create conditions for any variety of reasons. Examples include a condition that always ignores a suppression, a condition that ignores a suppression based on the date, a condition that ignores a suppression based on the reason. You can read the developer docs for more information on creating your own conditions.

Example) Using the pre-built `SuppressionIgnoreErrors` class to ignore suppressions on any `Error` level rules.
import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { AwsSolutionsChecks, SuppressionIgnoreErrors } from 'cdk-nag';

const app = new App();
new CdkTestStack(app, 'CdkNagDemo');
// Ignore Suppressions on any errors
Aspects.of(app).add(
  new AwsSolutionsChecks({
    suppressionIgnoreCondition: new SuppressionIgnoreErrors(),
  })
);

Customizing Logging

NagLoggers give NagPack authors and users the ability to create their own custom reporting mechanisms. All pre-built NagPackscome with the AnnotationsLoggerand the NagReportLogger (with CSV reports) enabled by default.

See the NagLogger developer docs for more information.

Example) Adding the `ExtremelyHelpfulConsoleLogger` example from the NagLogger docs
import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { ExtremelyHelpfulConsoleLogger } from './docs/NagLogger';
import { AwsSolutionsChecks } from 'cdk-nag';

const app = new App();
new CdkTestStack(app, 'CdkNagDemo');
Aspects.of(app).add(
  new AwsSolutionsChecks({
    additionalLoggers: [new ExtremelyHelpfulConsoleLogger()],
  })
);

Using on CloudFormation templates

You can use cdk-nag on existing CloudFormation templates by using the cloudformation-include module.

Example 1) CloudFormation template with suppression

Sample CloudFormation template with suppression

{
  "Resources": {
    "rBucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": "some-bucket-name"
      },
      "Metadata": {
        "cdk_nag": {
          "rules_to_suppress": [
            {
              "id": "AwsSolutions-S1",
              "reason": "at least 10 characters"
            }
          ]
        }
      }
    }
  }
}

Sample App

import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { AwsSolutionsChecks } from 'cdk-nag';

const app = new App();
new CdkTestStack(app, 'CdkNagDemo');
Aspects.of(app).add(new AwsSolutionsChecks());

Sample Stack with imported template

import { CfnInclude } from 'aws-cdk-lib/cloudformation-include';
import { NagSuppressions } from 'cdk-nag';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    new CfnInclude(this, 'Template', {
      templateFile: 'my-template.json',
    });
    // Add any additional suppressions
    NagSuppressions.addResourceSuppressionsByPath(
      this,
      '/CdkNagDemo/Template/rBucket',
      [
        {
          id: 'AwsSolutions-S2',
          reason: 'at least 10 characters',
        },
      ]
    );
  }
}
Example 2) CloudFormation template with granular suppressions

Sample CloudFormation template with suppression

{
  "Resources": {
    "myPolicy": {
      "Type": "AWS::IAM::Policy",
      "Properties": {
        "PolicyDocument": {
          "Statement": [
            {
              "Action": [
                "kms:Decrypt",
                "kms:DescribeKey",
                "kms:Encrypt",
                "kms:ReEncrypt*",
                "kms:GenerateDataKey*"
              ],
              "Effect": "Allow",
              "Resource": ["some-key-arn"]
            }
          ],
          "Version": "2012-10-17"
        }
      },
      "Metadata": {
        "cdk_nag": {
          "rules_to_suppress": [
            {
              "id": "AwsSolutions-IAM5",
              "reason": "Allow key data access",
              "applies_to": [
                "Action::kms:ReEncrypt*",
                "Action::kms:GenerateDataKey*"
              ]
            }
          ]
        }
      }
    }
  }
}

Sample App

import { App, Aspects } from 'aws-cdk-lib';
import { CdkTestStack } from '../lib/cdk-test-stack';
import { AwsSolutionsChecks } from 'cdk-nag';

const app = new App();
new CdkTestStack(app, 'CdkNagDemo');
Aspects.of(app).add(new AwsSolutionsChecks());

Sample Stack with imported template

import { CfnInclude } from 'aws-cdk-lib/cloudformation-include';
import { NagSuppressions } from 'cdk-nag';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class CdkTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    new CfnInclude(this, 'Template', {
      templateFile: 'my-template.json',
    });
    // Add any additional suppressions
    NagSuppressions.addResourceSuppressionsByPath(
      this,
      '/CdkNagDemo/Template/myPolicy',
      [
        {
          id: 'AwsSolutions-IAM5',
          reason: 'Allow key data access',
          appliesTo: ['Action::kms:ReEncrypt*', 'Action::kms:GenerateDataKey*'],
        },
      ]
    );
  }
}

Contributing

See CONTRIBUTING for more information.

License

This project is licensed under the Apache-2.0 License.

More Repositories

1

cdk-watchful

Watching what's up with your CDK apps since 2019
TypeScript
531
star
2

cdk-monitoring-constructs

Easy-to-use CDK constructs for monitoring your AWS infrastructure
TypeScript
456
star
3

aws-delivlib

setup and manage continuous delivery pipelines for code libraries in multiple languages
TypeScript
372
star
4

cdk-pipelines-github

TypeScript
321
star
5

construct-hub

AWS CDK construct library that can be used to deploy instances of the Construct Hub in any AWS Account.
TypeScript
200
star
6

cdk-ecr-deployment

A CDK construct to deploy docker image to Amazon ECR
Go
152
star
7

cdk-dynamo-table-viewer

A CDK construct which exposes an endpoint with the contents of a DynamoDB table
TypeScript
124
star
8

cdk-stacksets

TypeScript
80
star
9

cdk-docker-image-deployment

TypeScript
75
star
10

cdk-triggers

TypeScript
73
star
11

cdk-validator-cfnguard

TypeScript
67
star
12

cdk-cloudformation

TypeScript
60
star
13

decdk

Define AWS CDK applications declaratively
TypeScript
60
star
14

cdk-ecs-service-extensions

TypeScript
59
star
15

cdk-from-cfn

A cloudformation json -> cdk typescript transpiler.
Rust
58
star
16

cdk-import

Generates CDK level 1 constructs for public CloudFormation Registry types and modules
TypeScript
52
star
17

cdk-app-cli

The operator CLI for CDK apps.
TypeScript
52
star
18

publib

A unified toolchain for publishing libraries to popular package managers (formally jsii-release)
TypeScript
52
star
19

cdk-drift-monitor

Monitors for CloudFormation stack drifts.
TypeScript
48
star
20

jsii-docgen

Generates reference documentation for jsii modules
TypeScript
48
star
21

aws-cdk-testing-examples

Java
39
star
22

cdk-ecs-codedeploy

TypeScript
34
star
23

cdk-enterprise-iac

Utilities for using CDK within enterprise constraints
TypeScript
33
star
24

cdk-tweet-queue

SQS queue fed with a stream of tweets from a Twitter search
TypeScript
29
star
25

cdk-ssm-documents

TypeScript
27
star
26

awscdk-service-spec

TypeScript
25
star
27

awscdk-appsync-utils

TypeScript
24
star
28

aws-secrets-github-sync

Sync GitHub repository secrets from AWS Secrets Manager
TypeScript
22
star
29

cdk-amazon-chime-resources

TypeScript
22
star
30

construct-hub-webapp

React web app for Construct Hub
TypeScript
21
star
31

json2jsii

Generates jsii-compatible structs from JSON schemas
TypeScript
20
star
32

node-sscaff

Stupid scaffolding: copies an entire directory with variable substitution
TypeScript
20
star
33

cdk-cicd-wrapper

This repository contains the infrastructure as code to wrap your AWS CDK project with CI/CD around it.
TypeScript
20
star
34

jsii-srcmak

Generate multi-language object-oriented source code from typescript
TypeScript
19
star
35

awscdk-v1-stack-finder

TypeScript
18
star
36

awscdk-asset-kubectl

TypeScript
18
star
37

cdk-skylight

CDK Skylight is a set of Level 3 constructs for the Microsoft products on AWS
TypeScript
17
star
38

markmac

Embed program outputs in markdown
TypeScript
17
star
39

cdk-verified-permissions

Amazon Verified Permissions L2 CDK Constructs
TypeScript
16
star
40

awscdk-change-analyzer

A toolkit that analyzes the differences between two cloud infrastructures states.
HTML
13
star
41

cdk-ethereum-node

CDK construct to deploy an Ethereum node running on Amazon Managed Blockchain
TypeScript
11
star
42

aws-lambda-rust

TypeScript
10
star
43

cdk-appflow

This repository contains L2 AWS CDK constructs for Amazon AppFlow
TypeScript
9
star
44

aws-cdk-notices

Static website for the distribution of notices to AWS CDK users.
TypeScript
8
star
45

cdk-hyperledger-fabric-network

CDK construct to deploy a Hyperledger Fabric network running on Amazon Managed Blockchain
TypeScript
7
star
46

cfn-resources

TypeScript
7
star
47

cdk-nag-go

cdk-nag bindings for Go.
Go
7
star
48

awscdk-asset-awscli

TypeScript
7
star
49

cdk-codepipeline-extensions

Go
7
star
50

cdk-aws-sagemaker-role-manager

Create roles and policies for ML Activities and ML Personas
TypeScript
6
star
51

cdklabs-projen-project-types

TypeScript
6
star
52

cdk-golden-signals-dashboard

TypeScript
6
star
53

awscdk-lambda-dotnet

TypeScript
5
star
54

cdk-deployer

A CDK construct library for deploying artifacts via CodeDeploy.
TypeScript
4
star
55

awscdk-dynamodb-global-tables

TypeScript
4
star
56

node-backpack

TypeScript
3
star
57

cfunctions

TypeScript
3
star
58

cdk-dynamo-table-viewer-go

A CDK construct which exposes an endpoint with the contents of a DynamoDB table Topics Resources License
Go
3
star
59

cdk-cdk8s-reinvent-2021

Java
2
star
60

construct-hub-probe

Probe package intended to test construct hub instances
TypeScript
2
star
61

construct-hub-cli

TypeScript
1
star
62

cdk-assets

TypeScript
1
star
63

cloud-assembly-schema

TypeScript
1
star
64

cdk-ecs-codedeploy-go

Go
1
star
65

cdk-generate-synthetic-examples

Find all classes in the JSII assembly that don't yet have any example code associated with them, and generate a synthetic example that shows how to instantiate the type.
TypeScript
1
star
66

cdk-ecs-service-extensions-go

Go
1
star
67

cdk-aws-sagemaker-role-manager-go

Go
1
star