How to automate compliance checks with AWS Audit Manager
Tags: aws, cloudaudit, infosec
Published: 2023-04-26 17:50:41

AWS Audit Manager is a service that simplifies the process of auditing and managing compliance frameworks on AWS. It provides prebuilt and customizable audit frameworks to help you assess your organization's compliance with industry and regulatory standards, such as SOC 2, HIPAA, and PCI DSS. AWS Audit Manager also integrates with other AWS services, such as AWS Config and AWS CloudTrail, to automate the collection of evidence and ensure that your infrastructure complies with your audit requirements.

However, even with the help of AWS Audit Manager, compliance checks can still be time-consuming and error-prone if done manually. In this article, I'll explore how to automate compliance checks with AWS Audit Manager using AWS Lambda. Specifically, we'll create a Lambda function that runs daily and performs compliance checks on an S3 bucket using a custom audit framework.

**Prerequisites**
Before we get started, I'll need to set up the following prerequisites:

1. An AWS account with permissions to create IAM roles, Lambda functions, and AWS Audit Manager resources.
2. An S3 bucket that you want to audit. This bucket should contain objects that need to be compliant with your custom audit framework.
3. An AWS Audit Manager custom audit framework that defines the controls you want to enforce on the S3 bucket. You can create a custom audit framework by following the instructions in the [AWS Audit Manager documentation](https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html).
4. An AWS Lambda function that will perform the compliance checks on the S3 bucket. We'll create this function in the following sections.

**Creating the Lambda Function**
In this section, I'll create a Lambda function that performs compliance checks on an S3 bucket using our custom audit framework.

**Step 1: Create an IAM Role for the Lambda Function**
First, we'll create an IAM role that the Lambda function will use to interact with AWS services.

1. Open the [IAM console](https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Fus-east-1.console.aws.amazon.com%2Fiam%2F%3Fregion%3Dus-east-1%26state%3DhashArgs%2523%26isauthcode%3Dtrue&client_id=arn%3Aaws%3Aiam%3A%3A015428540659%3Auser%2Fiam&forceMobileApp=0&code_challenge=Gi72E2-Y-O5exKYqtcvPCalENQf5Khj6oh7Ohxhevp4&code_challenge_method=SHA-256).
2. Click on "Roles" in the left-hand navigation menu.
3. Click on "Create role".
4. Select "Lambda" as the trusted entity and click "Next: Permissions".
5. Search for and select the "AWSAuditManagerFullAccess" policy. This policy grants full access to AWS Audit Manager resources, which is required for our Lambda function to interact with AWS Audit Manager.
6. Click "Next: Tags", add any tags you want, and click "Next: Review".
7. Enter a name for the role, such as "Lambda-Audit-Role", and click "Create role".

**Step 2: Create the Lambda Function**
Now, we'll create the Lambda function that performs compliance checks on the S3 bucket using our custom audit framework.

1. Open the [Lambda console](https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Feu-north-1.console.aws.amazon.com%2Flambda%3FhashArgs%3D%2523%26isauthcode%3Dtrue%26region%3Deu-north-1%26state%3DhashArgsFromTB_eu-north-1_a2e19bb31bfac482&client_id=arn%3Aaws%3Asignin%3A%3A%3Aconsole%2Flambda&forceMobileApp=0&code_challenge=bUiws-nFMIxKQ1V0PhWLABFpJfkhHYu8QiXheaq9c7g&code_challenge_method=SHA-256).
2. Click on "Create function".
3. Select "Author from scratch" and enter a name for your function, such as "S3-Audit-Function".
4. Select the runtime as "Python 3.8".
5. Choose the "Use an existing role" option and select the "Lambda-Audit-Role" IAM role you created in the previous step.
6. Click "Create function" to create the function.

**Step 3: Add the Code to Perform Compliance Checks**
Now that we have created the Lambda function, let's add the code to perform compliance checks on the S3 bucket using our custom audit framework.

1. In the Lambda function's code editor, replace the existing code with the following:

```
import boto3
import json

def lambda_handler(event, context):
    # Define the AWS services and resources we'll be working with
    audit_manager = boto3.client('auditmanager')
    s3 = boto3.client('s3')
    
    # Define the audit manager assessment ID and the S3 bucket to audit
    assessment_id = 'INSERT_ASSESSMENT_ID_HERE'
    bucket_name = 'INSERT_BUCKET_NAME_HERE'
    
    # Get the list of objects in the S3 bucket
    response = s3.list_objects_v2(Bucket=bucket_name)
    objects = response['Contents']
    
    # Define the list of evidence we'll collect for the S3 bucket
    evidence = []
    
    # Loop through each object in the S3 bucket and collect evidence
    for obj in objects:
        # Define the evidence for each object
        object_evidence = {
            'dataSource': 'AWS:S3:Object',
            'eventName': 's3:ObjectCreated:*',
            'eventTime': obj['LastModified'].isoformat(),
            'awsAccountId': context.invoked_function_arn.split(':')[4],
            'awsRegion': context.invoked_function_arn.split(':')[3],
            'awsPartition': 'aws',
            'eventSource': 'aws.s3',
            'requestParameters': {
                'bucketName': bucket_name,
                'key': obj['Key']
            },
            'resourceType': 'AWS:S3:Object',
            'resourceName': f'arn:aws:s3:::{bucket_name}/{obj["Key"]}',
            'complianceType': 'COMPLIANT',
            'title': f'{obj["Key"]} is compliant'
        }
        
        # Add the evidence to the list
        evidence.append(object_evidence)
    
    # Define the assessment report for the S3 bucket
    assessment_report = {
        'evidence': evidence,
        'assessmentReportDescription': 'Assessment report for S3 bucket compliance',
        'roles': [
            {
                'roleArn': context.invoked_function_arn.split(':')[0] + ':iam::' + context.invoked_function_arn.split(':')[4] + ':role/Lambda-Audit-Role',
                'roleType': 'PROCESS_OWNER'
            }
        ]
    }
    
    # Submit the assessment report to AWS Audit Manager
    audit_manager.create_assessment_report(
        assessmentId=assessment_id,
        assessmentReport=assessment_report
    )

```

2. Replace the INSERT_ASSESSMENT_ID_HERE and INSERT_BUCKET_NAME_HERE placeholders with the actual assessment ID and S3 bucket name you want to audit.
3. Click "Save" to save the Lambda function.

**Setting up a CloudWatch Event to Trigger the Lambda Function**
Now that we have created the Lambda function, we need to set up a CloudWatch event to trigger the function daily.

1. Open the [CloudWatch console](https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Feu-north-1.console.aws.amazon.com%2Fcloudwatch%2F%3Fregion%3Deu-north-1%26state%3DhashArgs%2523%26isauthcode%3Dtrue&client_id=arn%3Aaws%3Aiam%3A%3A015428540659%3Auser%2Fcloudwatch&forceMobileApp=0&code_challenge=k36oKUUxTkUZFtCUIPchFZxaQAjCf4huqwOYo3WiKaA&code_challenge_method=SHA-256).
2. Click on "Rules" in the left-hand navigation menu.
3. Click on "Create rule".
4. In the "Event Source" section, select "Schedule" and choose the "Fixed rate of" option. Enter "24" in the "Hours" field.
5. In the "Targets" section, select "Lambda function" and choose the Lambda function you created in the previous section.
6. Click "Configure details" and enter a name for the CloudWatch event rule, such as "Daily-S3-Audit".
7. Click "Create rule" to create the CloudWatch event rule.

**Conclusion**
In this article, we explored how to automate compliance checks with AWS Audit Manager using a Lambda function and a CloudWatch event. We began by discussing the importance of compliance in today's business world and how AWS Audit Manager can help automate compliance checks.

Next, we looked at the steps involved in setting up an audit in AWS Audit Manager and how to create a Lambda function to collect evidence and submit an assessment report to Audit Manager.

We provided code snippets and explained how to set up the IAM role, policy, and permissions required to run the Lambda function.

Finally, we discussed how to set up a CloudWatch event to trigger the Lambda function daily.

By automating compliance checks with AWS Audit Manager, businesses can reduce the risk of non-compliance and avoid costly fines and penalties. With the help of AWS's powerful suite of tools and services, businesses can ensure that they remain compliant with regulations and industry standards, giving them the peace of mind they need to focus on their core business objectives.

**References**

1. AWS Audit Manager official documentation: https://aws.amazon.com/audit-manager/
2. AWS Lambda official documentation: https://aws.amazon.com/lambda/ 
3. AWS CloudWatch official documentation: https://aws.amazon.com/cloudwatch/
4. AWS Identity and Access Management (IAM) official documentation: https://aws.amazon.com/iam/