Skip to main content

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

Project description

cdk-nag

Language cdk-nag monocdk-nag
Python PyPI version PyPI version
TypeScript npm version npm version
  • If your project uses cdk version 1.x.x use cdk-nag ^1.0.0
  • If your project uses cdk version 2.x.x use cdk-nag ^2.0.0
  • If your project uses monocdk use monocdk-nag ^1.0.0

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

Available 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

Usage

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

cdk
# Example automatically generated from non-compiling source. May contain errors.
import { App, Aspects } from '@aws-cdk/core';
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 }));
cdk v2
# Example automatically generated from non-compiling source. May contain errors.
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 }));
monocdk
# Example automatically generated from non-compiling source. May contain errors.
import { App, Aspects } from 'monocdk';
import { CdkTestStack } from '../lib/my-stack';
import { AwsSolutionsChecks } from 'monocdk-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
# Example automatically generated from non-compiling source. May contain errors.
import { SecurityGroup, Vpc, Peer, Port } from '@aws-cdk/aws-ec2';
import { Construct, Stack, StackProps } from '@aws-cdk/core';
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) Child Constructs
# Example automatically generated from non-compiling source. May contain errors.
import { User, PolicyStatement } from '@aws-cdk/aws-iam';
import { Construct, Stack, StackProps } from '@aws-cdk/core';
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' }],
      true
    );
  }
}
Example 3) Stack Level
# Example automatically generated from non-compiling source. May contain errors.
import { App, Aspects } from '@aws-cdk/core';
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 4) 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
# Example automatically generated from non-compiling source. May contain errors.
import { Bucket } from '@aws-cdk/aws-s3';
import { BucketDeployment } from '@aws-cdk/aws-s3-deployment';
import { NagSuppressions } from 'cdk-nag';
import { Construct, Stack, StackProps } from '@aws-cdk/core';

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' }]
    );
  }
}

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 the cdk_nag. In this case you should remediate the issue and suppress the issue like in the following example.

Example) Property Overrides
# Example automatically generated from non-compiling source. May contain errors.
import {
  Instance,
  InstanceType,
  InstanceClass,
  MachineImage,
  Vpc,
  CfnInstance,
} from '@aws-cdk/aws-ec2';
import { Construct, Stack, StackProps } from '@aws-cdk/core';
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.',
      },
    ]);
  }
}

Using on CloudFormation templates

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

Example) 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

# Example automatically generated from non-compiling source. May contain errors.
import { App, Aspects } from '@aws-cdk/core';
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

# Example automatically generated from non-compiling source. May contain errors.
import { CfnInclude } from '@aws-cdk/cloudformation-include';
import { NagSuppressions } from 'cdk-nag';
import { Construct, Stack, StackProps } from '@aws-cdk/core';

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',
        },
      ]
    );
  }
}

Contributing

See CONTRIBUTING for more information.

License

This project is licensed under the Apache-2.0 License.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

monocdk-nag-1.4.11.tar.gz (616.0 kB view details)

Uploaded Source

Built Distribution

monocdk_nag-1.4.11-py3-none-any.whl (614.5 kB view details)

Uploaded Python 3

File details

Details for the file monocdk-nag-1.4.11.tar.gz.

File metadata

  • Download URL: monocdk-nag-1.4.11.tar.gz
  • Upload date:
  • Size: 616.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.3

File hashes

Hashes for monocdk-nag-1.4.11.tar.gz
Algorithm Hash digest
SHA256 a3be12cc643b2e5a30f6d47ca069e96d1c7788ad71029a87c6da5085dd1e3d8f
MD5 189e8d54aa95832d17f0b4c319891b66
BLAKE2b-256 3fa7dd31d06d6a09cb671028172ce6e3422a46c808b558337531ba9b0e6c36bf

See more details on using hashes here.

File details

Details for the file monocdk_nag-1.4.11-py3-none-any.whl.

File metadata

  • Download URL: monocdk_nag-1.4.11-py3-none-any.whl
  • Upload date:
  • Size: 614.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.3

File hashes

Hashes for monocdk_nag-1.4.11-py3-none-any.whl
Algorithm Hash digest
SHA256 f1c6edebdcac436068a30cc26698351cd3718486586a1265caa4c7fd13a6abdd
MD5 ce6c36099b3fd8057ea40741913f73e8
BLAKE2b-256 e5910cb8d5d4582a28b4fa95ba4ad3970fb7aefa7e2f4ff9a692ed5980973161

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page