Package: cdk-nag
cdk-nagCheck CDK applications orCloudFormation templatesfor best practices using a combination of available rule packs. Inspired bycfn_nag.Check outthis blog postfor a guided overview!Available Rules and PacksSeeRULESfor more information on all the available packs.AWS SolutionsHIPAA SecurityNIST 800-53 rev 4NIST 800-53 rev 5PCI DSS 3.2.1RULESalso includes a collection ofadditional rulesthat are not currently included in any of the pre-built NagPacks, but are still available for inclusion in custom NagPacks.Read theNagPack developer docsif you are interested in creating your own pack.UsageFor a full list of options SeeNagPackPropsin theAPI.mdIncluding in an applicationimport{App,Aspects}from'aws-cdk-lib';import{CdkTestStack}from'../lib/cdk-test-stack';import{AwsSolutionsChecks}from'cdk-nag';constapp=newApp();newCdkTestStack(app,'CdkNagDemo');//SimpleruleinformationalmessagesAspects.of(app).add(newAwsSolutionsChecks());//Additionalexplanationsonthepurposeoftriggeredrules//Aspects.of(stack).add(newAwsSolutionsChecks({verbose:true}));Suppressing a RuleExample 1) Default Constructimport{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';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);consttest=newSecurityGroup(this,'test',{vpc:newVpc(this,'vpc'),});test.addIngressRule(Peer.anyIpv4(),Port.allTraffic());NagSuppressions.addResourceSuppressions(test,[{id:'AwsSolutions-EC23',reason:'lorem ipsum'},]);}}Example 2) On Multiple Constructsimport{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';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);constvpc=newVpc(this,'vpc');consttest1=newSecurityGroup(this,'test',{vpc});test1.addIngressRule(Peer.anyIpv4(),Port.allTraffic());consttest2=newSecurityGroup(this,'test',{vpc});test2.addIngressRule(Peer.anyIpv4(),Port.allTraffic());NagSuppressions.addResourceSuppressions([test1,test2],[{id:'AwsSolutions-EC23',reason:'lorem ipsum'}]);}}Example 3) Child Constructsimport{User,PolicyStatement}from'aws-cdk-lib/aws-iam';import{Stack,StackProps}from'aws-cdk-lib';import{Construct}from'constructs';import{NagSuppressions}from'cdk-nag';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);constuser=newUser(this,'rUser');user.addToPolicy(newPolicyStatement({actions:['s3:PutObject'],resources:['arn:aws:s3:::bucket_name/*'],}));//EnableaddingsuppressionstochildconstructsNagSuppressions.addResourceSuppressions(user,[{id:'AwsSolutions-IAM5',reason:'lorem ipsum',appliesTo:['Resource::arn:aws:s3:::bucket_name/*'],//optional},],true);}}Example 4) Stack Levelimport{App,Aspects}from'aws-cdk-lib';import{CdkTestStack}from'../lib/cdk-test-stack';import{AwsSolutionsChecks,NagSuppressions}from'cdk-nag';constapp=newApp();conststack=newCdkTestStack(app,'CdkNagDemo');Aspects.of(app).add(newAwsSolutionsChecks());NagSuppressions.addStackSuppressions(stack,[{id:'AwsSolutions-EC23',reason:'lorem ipsum'},]);Example 5) Construct pathIf you received the following error on synth/deploy[Errorat/StackName/Custom::CDKBucketDeployment8675309/ServiceRole/Resource]AwsSolutions-IAM4:TheIAMuser,role,orgroupusesAWSmanagedpoliciesimport{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';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);newBucketDeployment(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 findingsCertain rules support granular suppressions offindings. If you received the following errors on synth/deploy[Errorat/StackName/rFirstUser/DefaultPolicy/Resource]AwsSolutions-IAM5[Action::s3:*]:TheIAMentitycontainswildcardpermissionsanddoesnothaveacdk-nagrulesuppressionwithevidenceforthosepermission.[Errorat/StackName/rFirstUser/DefaultPolicy/Resource]AwsSolutions-IAM5[Resource::*]:TheIAMentitycontainswildcardpermissionsanddoesnothaveacdk-nagrulesuppressionwithevidenceforthosepermission.[Errorat/StackName/rSecondUser/DefaultPolicy/Resource]AwsSolutions-IAM5[Action::s3:*]:TheIAMentitycontainswildcardpermissionsanddoesnothaveacdk-nagrulesuppressionwithevidenceforthosepermission.[Errorat/StackName/rSecondUser/DefaultPolicy/Resource]AwsSolutions-IAM5[Resource::*]:TheIAMentitycontainswildcardpermissionsanddoesnothaveacdk-nagrulesuppressionwithevidenceforthosepermission.By applying the following suppressionsimport{User}from'aws-cdk-lib/aws-iam';import{Stack,StackProps}from'aws-cdk-lib';import{Construct}from'constructs';import{NagSuppressions}from'cdk-nag';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);constfirstUser=newUser(this,'rFirstUser');firstUser.addToPolicy(newPolicyStatement({actions:['s3:*'],resources:['*'],}));constsecondUser=newUser(this,'rSecondUser');secondUser.addToPolicy(newPolicyStatement({actions:['s3:*'],resources:['*'],}));constthirdUser=newUser(this,'rSecondUser');thirdUser.addToPolicy(newPolicyStatement({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[Errorat/StackName/rFirstUser/DefaultPolicy/Resource]AwsSolutions-IAM5[Resource::*]:TheIAMentitycontainswildcardpermissionsanddoesnothaveacdk-nagrulesuppressionwithevidenceforthosepermission.Suppressingaws-cdk-lib/pipelinesViolationsTheaws-cdk-lib/pipelines.CodePipelineconstruct and its child constructs are not guaranteed to be "Visited" byAspects, as they are not added during the "Construction" phase of thecdk 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 yourCodePipelineobject. 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.Seethis issuefor more information.Example) Suppressing Violations in Pipelinesexample-app.tsimport{App,Aspects}from'aws-cdk-lib';import{AwsSolutionsChecks}from'cdk-nag';import{ExamplePipeline}from'../lib/example-pipeline';constapp=newApp();newExamplePipeline(app,'example-cdk-pipeline');Aspects.of(app).add(newAwsSolutionsChecks({verbose:true}));app.synth();example-pipeline.tsimport{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';exportclassExamplePipelineextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);constexampleSynth=newShellStep('ExampleSynth',{commands:['yarn build --frozen-lockfile'],input:CodePipelineSource.codeCommit(newRepository(this,'ExampleRepo',{repositoryName:'ExampleRepo'}),'main'),});constExamplePipeline=newCodePipeline(this,'ExamplePipeline',{synth:exampleSynth,});//Forcethepipelineconstructcreationforwardbeforeapplyingsuppressions.//@Seehttps://github.com/aws/aws-cdk/issues/18440ExamplePipeline.buildPipeline();//Thepathsuppressionwillerrorifyoucommentout"ExamplePipeline.buildPipeline();""NagSuppressions.addResourceSuppressionsByPath(this,'/example-cdk-pipeline/ExamplePipeline/Pipeline/ArtifactsBucket/Resource',[{id:'AwsSolutions-S1',reason:'Because I said so',},]);}}Rules and Property OverridesIn some cases L2 Constructs do not have a native option to remediate an issue and must be fixed viaRaw 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 Overridesimport{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';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);constinstance=newInstance(this,'rInstance',{vpc:newVpc(this,'rVpc'),instanceType:newInstanceType(InstanceClass.T3),machineImage:MachineImage.latestAmazonLinux(),});constcfnIns=instance.node.defaultChildasCfnInstance;cfnIns.addPropertyOverride('DisableApiTermination',true);NagSuppressions.addResourceSuppressions(instance,[{id:'AwsSolutions-EC29',reason:'Remediated through property override.',},]);}}Conditionally Ignoring SuppressionsYou 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 readthe developer docsfor 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';constapp=newApp();newCdkTestStack(app,'CdkNagDemo');//IgnoreSuppressionsonanyerrorsAspects.of(app).add(newAwsSolutionsChecks({suppressionIgnoreCondition:newSuppressionIgnoreErrors(),}));Customizing LoggingNagLoggers giveNagPackauthors and users the ability to create their own custom reporting mechanisms. All pre-builtNagPackscome with theAnnotationsLoggerand theNagReportLogger(with CSV reports) enabled by default.See theNagLoggerdeveloper docs for more information.Example) Adding the `ExtremelyHelpfulConsoleLogger` example from the NagLogger docsimport{App,Aspects}from'aws-cdk-lib';import{CdkTestStack}from'../lib/cdk-test-stack';import{ExtremelyHelpfulConsoleLogger}from'./docs/NagLogger';import{AwsSolutionsChecks}from'cdk-nag';constapp=newApp();newCdkTestStack(app,'CdkNagDemo');Aspects.of(app).add(newAwsSolutionsChecks({additionalLoggers:[newExtremelyHelpfulConsoleLogger()],}));Using on CloudFormation templatesYou can use cdk-nag on existing CloudFormation templates by using thecloudformation-includemodule.Example 1) CloudFormation template with suppressionSample 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 Appimport{App,Aspects}from'aws-cdk-lib';import{CdkTestStack}from'../lib/cdk-test-stack';import{AwsSolutionsChecks}from'cdk-nag';constapp=newApp();newCdkTestStack(app,'CdkNagDemo');Aspects.of(app).add(newAwsSolutionsChecks());Sample Stack with imported templateimport{CfnInclude}from'aws-cdk-lib/cloudformation-include';import{NagSuppressions}from'cdk-nag';import{Stack,StackProps}from'aws-cdk-lib';import{Construct}from'constructs';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);newCfnInclude(this,'Template',{templateFile:'my-template.json',});//AddanyadditionalsuppressionsNagSuppressions.addResourceSuppressionsByPath(this,'/CdkNagDemo/Template/rBucket',[{id:'AwsSolutions-S2',reason:'at least 10 characters',},]);}}Example 2) CloudFormation template with granular suppressionsSample 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 Appimport{App,Aspects}from'aws-cdk-lib';import{CdkTestStack}from'../lib/cdk-test-stack';import{AwsSolutionsChecks}from'cdk-nag';constapp=newApp();newCdkTestStack(app,'CdkNagDemo');Aspects.of(app).add(newAwsSolutionsChecks());Sample Stack with imported templateimport{CfnInclude}from'aws-cdk-lib/cloudformation-include';import{NagSuppressions}from'cdk-nag';import{Stack,StackProps}from'aws-cdk-lib';import{Construct}from'constructs';exportclassCdkTestStackextendsStack{constructor(scope:Construct,id:string,props?:StackProps){super(scope,id,props);newCfnInclude(this,'Template',{templateFile:'my-template.json',});//AddanyadditionalsuppressionsNagSuppressions.addResourceSuppressionsByPath(this,'/CdkNagDemo/Template/myPolicy',[{id:'AwsSolutions-IAM5',reason:'Allow key data access',appliesTo:['Action::kms:ReEncrypt*','Action::kms:GenerateDataKey*'],},]);}}ContributingSeeCONTRIBUTINGfor more information.LicenseThis project is licensed under the Apache-2.0 License.