Skip to content

Enhancing Security and Compliance with AWS CDK and CDK-Nag: A Complete Guide

Security and compliance are two critical pillars when designing and deploying infrastructure in the cloud. AWS provides robust security frameworks, but it’s essential to ensure that the infrastructure-as-code (IaC) templates you write using AWS Cloud Development Kit (CDK) adhere to these security standards. That’s where CDK-Nag comes into play.

In this blog post, we’ll explore how to use CDK-Nag to enforce security and compliance best practices in your AWS CDK projects. We will also look at how to integrate CDK-Nag into your unit tests to ensure that security checks are part of your CI/CD pipeline and overall quality assurance strategy.


What is CDK-Nag?

CDK-Nag is an open-source library for AWS CDK that allows you to apply best practice rules to your CDK stacks. These rules are based on AWS’s Well-Architected Framework pillars and CIS benchmarks, helping you catch potential security, operational, and cost inefficiencies early in the development process.

With CDK-Nag, you can:

  • Enforce security policies.
  • Ensure compliance with industry standards.
  • Get recommendations to improve operational efficiency.
  • Automatically scan CDK stacks to check for security vulnerabilities.

Why Use CDK-Nag?

Security gaps are common in fast-moving development environments where cloud infrastructure changes frequently. CDK-Nag helps prevent these gaps by running audits as part of your CI/CD pipeline or during development.

Compliance checks ensure that your infrastructure meets internal and external security requirements. This is particularly important for industries with strict regulatory requirements, such as healthcare or finance.

Proactive issue identification helps you find potential issues before they hit production, leading to more secure and compliant deployments.

Understanding Aspects in AWS CDK

To effectively use CDK-Nag and other tools like it in AWS CDK projects, it’s important to understand the concept of Aspects in the CDK framework. Aspects allow you to apply reusable logic, such as security checks or validations, across multiple resources in your CDK stacks without having to modify each resource individually.

What Are Aspects?

Aspects are a feature in AWS CDK that enable you to inspect or modify all resources in a stack during the synthesis phase (before the CloudFormation template is generated). This means you can apply certain rules, policies, or validations globally to any resource type, such as S3 buckets, Lambda functions, DynamoDB tables, and more.

When using Aspects, you can traverse through a CDK construct tree (the structure that holds all resources in a stack) and apply actions to any resource that matches your desired criteria.

How Do Aspects Work?

Aspects work by visiting each construct in a stack. Think of Aspects as a visitor pattern that walks through your stack’s resource tree and applies rules or checks to each resource, one by one. This makes Aspects ideal for cross-cutting concerns like security enforcement, cost-saving recommendations, and compliance validations—things you want to apply universally across your stack.

CDK-Nag uses Aspects to apply security and compliance checks to all resources in your stack. You simply attach the AwsSolutionsChecks (or other rule packs) via Aspects to enforce those rules.

Applying Aspects in AWS CDK

In AWS CDK, you can apply Aspects by using the Aspects.of method. Here’s how you apply CDK-Nag’s compliance checks using Aspects:

Aspects.of(this).add(new AwsSolutionsChecks());

This tells CDK to apply the AwsSolutionsChecks aspect to the entire construct tree of the current stack (this). As a result, every resource in the stack will be evaluated against the compliance checks provided by CDK-Nag.

When Should You Use Aspects?

Aspects are useful when:

  • Global Policies: You want to enforce a global security or compliance policy across your entire stack.
  • Consistency: You want to ensure that every resource is consistently configured according to best practices without needing to manually configure each resource.
  • Auditing: You want to run security audits or best-practice checks without manually verifying each resource’s configuration.
  • Cross-Cutting Concerns: Aspects are ideal for concerns that span multiple resource types, such as encryption requirements, public access controls, or logging configurations.

Setting Up CDK-Nag in Your Project

Let’s start by integrating CDK-Nag into your AWS CDK project.

1. Install CDK-Nag

You can install CDK-Nag in your existing CDK project using npm:

npm install cdk-nag

Or, if you’re using Yarn:

yarn add cdk-nag

2. Import CDK-Nag in Your Stack

Next, import the necessary CDK-Nag classes in your CDK stack:

import { AwsSolutionsChecks } from 'cdk-nag';
import { Aspects } from 'aws-cdk-lib';

3. Apply CDK-Nag to Your Stack

You can apply CDK-Nag checks globally across your entire stack by adding the following line:

Aspects.of(this).add(new AwsSolutionsChecks());

This enables AWS Well-Architected Framework security checks to be applied to all resources within the stack.

Example:

Here’s an example of how to use CDK-Nag in a simple CDK stack with an S3 bucket:

import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import { AwsSolutionsChecks } from 'cdk-nag';
import { Aspects } from 'aws-cdk-lib';

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

    // Define an S3 bucket
    const myBucket = new s3.Bucket(this, 'MySecureBucket', {
      encryption: s3.BucketEncryption.S3_MANAGED, // Adding encryption to the bucket
    });

    // Apply CDK-Nag checks
    Aspects.of(this).add(new AwsSolutionsChecks());
  }
}

In this example, we defined a secure S3 bucket with server-side encryption enabled. CDK-Nag will run security checks to ensure that this bucket complies with best practices and that no issues, such as public access or lack of encryption, are present.

Running CDK Synth to Apply CDK-Nag Checks

Once you’ve added CDK-Nag to your stack, you can run the cdk synth command to synthesize the CloudFormation template and apply the security checks. This process generates the CloudFormation template and ensures that all CDK-Nag rules are evaluated during synthesis.

cdk synth

During synthesis, CDK-Nag will analyze your stack and output any warnings or errors related to compliance and security best practices directly in the console. This makes it easy to catch and address issues early in the development process before they are deployed to production.


CDK-Nag Rule Packs

CDK-Nag provides multiple rule packs to enforce different types of best practices. Here are some of the common rule packs you can use:

  • AwsSolutionsChecks: Enforces rules from the AWS Solutions Architecture best practices.
  • NIST80053R5Checks: Implements security requirements based on the NIST 800-53 Rev 5 standard.
  • PCI-DSS v3_2_1Checks: Applies rules for PCI-DSS compliance.

You can apply specific rule packs depending on your needs. For example:

Aspects.of(this).add(new NIST80053R5Checks());

This will apply NIST 800-53 security controls to your CDK stack.


Running CDK-Nag in CI/CD Pipelines

CDK-Nag can be integrated into your CI/CD pipelines to automatically enforce security and compliance checks during your build process. This ensures that any deployment must pass the necessary security checks before going live.

Here’s an example using AWS CodePipeline:

  1. Add a build step in your pipeline that runs cdk synth and includes CDK-Nag checks.
  2. Fail the build if any high-severity issues are found by analyzing the logs.

Alternatively, you can integrate CDK-Nag into a GitHub Actions workflow or other CI/CD tools like Jenkins or CircleCI.


Ignoring Specific Rules

In some cases, you might need to ignore specific rules for valid reasons. CDK-Nag allows you to suppress certain findings by specifying rule suppressions in your CDK resources:

import { NagSuppressions } from 'cdk-nag';

// Create an S3 bucket with a suppression
const myBucket = new s3.Bucket(this, 'MySecureBucket', {
  encryption: s3.BucketEncryption.S3_MANAGED,
});

// Suppress specific CDK-Nag findings
NagSuppressions.addResourceSuppressions(myBucket, [
  {
    id: 'AwsSolutions-S1', // Suppressing a specific rule
    reason: 'This bucket does not require server access logging due to internal use only.'
  }
]);

Be sure to provide a valid reason for suppressions to maintain transparency and avoid unintentional security gaps.


Integrating CDK-Nag into Unit Tests

Integrating CDK-Nag into your unit tests ensures that your security and compliance checks are not only part of your infrastructure but also part of your quality assurance process. This enables your team to catch compliance and security issues at the earliest stages of development.

Here’s how you can integrate CDK-Nag into your unit tests using Jest for a TypeScript-based CDK project.

1. Install Jest

First, you need to install Jest if you don’t already have it in your project:

npm install jest @types/jest ts-jest --save-dev

2. Create a Test for CDK-Nag

In your tests folder, create a test file to check if your CDK stack passes the security and compliance checks. For example, let’s create a file named securityCompliance.test.ts.

import { Annotations, Match } from 'aws-cdk-lib/assertions';
import { App, Aspects, Stack } from 'aws-cdk-lib';
import { AwsSolutionsChecks } from 'cdk-nag';
import { SecurityComplianceTestStack } from '../lib/security-compliance-test-stack';

describe('cdk-nag AwsSolutions Pack', () => {
  let stack: Stack;
  let app: App;
  beforeAll(() => {
    // GIVEN
    app = new App();
    stack = new SecurityComplianceTestStack(app, 'test');

    // WHEN
    Aspects.of(stack).add(new AwsSolutionsChecks());
  });

  // THEN
  test('No unsuppressed Warnings', () => {
    const warnings = Annotations.fromStack(stack).findWarning(
      '*',
      Match.stringLikeRegexp('AwsSolutions-.*')
    );
    expect(warnings).toHaveLength(0);
  });

  test('No unsuppressed Errors', () => {
    const errors = Annotations.fromStack(stack).findError(
      '*',
      Match.stringLikeRegexp('AwsSolutions-.*')
    );
    expect(errors).toHaveLength(0);
  });
});

3. Run the Unit Test

To run the test, use the following command:

npm run test

The test will validate that your stack has the required security configuration (in this case, S3 encryption), and it will also apply CDK-Nag checks to ensure that your infrastructure complies with best practices. Any violations will cause the test to fail, alerting you early in the development process.

4. Automate in CI/CD

You can further integrate these tests into your CI/CD pipeline to ensure that every code commit is validated against both the business logic and compliance standards.


Conclusion

CDK-Nag is a powerful tool for applying security and compliance best practices directly in your AWS CDK projects. By incorporating CDK-Nag into your stacks, you can automatically enforce rules and catch potential security vulnerabilities before they impact production. Whether you’re developing an application for internal use or handling sensitive customer data, CDK-Nag helps keep your infrastructure compliant with security standards like AWS Well-Architected Framework and NIST 800-53.

By integrating CDK-Nag into your unit tests and CI/CD pipelines, you can ensure that security checks are applied continuously and automatically, reducing the risk of human error and non-compliant infrastructure reaching production.

Start applying CDK-Nag in your projects today and enhance the security of your AWS infrastructure from the ground up!

Leave a Reply

Your email address will not be published. Required fields are marked *