Accelerate security automation using Amazon CodeWhisperer
In an ever-changing security landscape, teams must be able to quickly remediate security risks. Many organizations look for ways to automate the remediation of security findings that are currently handled manually. Amazon CodeWhisperer is an artificial intelligence (AI) coding companion that generates real-time, single-line or full-function code suggestions in your integrated development environment (IDE) to help you quickly build software. By using CodeWhisperer, security teams can expedite the process of writing security automation scripts for various types of findings that are aggregated in AWS Security Hub, a cloud security posture management (CSPM) service.
<p>In this post, we present some of the current challenges with security automation and walk you through how to use CodeWhisperer, together with <a href="https://aws.amazon.com/eventbridge/" target="_blank" rel="noopener">Amazon EventBridge</a> and <a href="https://aws.amazon.com/lambda/" target="_blank" rel="noopener">AWS Lambda</a>, to automate the remediation of Security Hub findings. Before reading further, please read the <a href="https://aws.amazon.com/machine-learning/responsible-ai/policy/" target="_blank" rel="noopener">AWS Responsible AI Policy.</a></p>
<h2>Current challenges with security automation</h2>
<p>Many approaches to security automation, including Lambda and <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation.html" target="_blank" rel="noopener">AWS Systems Manager Automation</a>, require software development skills. Furthermore, the process of manually writing code for remediation can be a time-consuming process for security professionals. To help overcome these challenges, CodeWhisperer serves as a force multiplier for qualified security professionals with development experience to quickly and effectively generate code to help remediate security findings.</p>
<p>Security professionals should still cultivate software development skills to implement robust solutions. Engineers should thoroughly review and validate any generated code, as manual oversight remains critical for security. </p>
<h2>Solution overview</h2>
<p>Figure 1 shows how the findings that <a href="https://aws.amazon.com/security-hub/" target="_blank" rel="noopener">Security Hub</a> produces are ingested by <a href="https://aws.amazon.com/eventbridge/" target="_blank" rel="noopener">EventBridge</a>, which then invokes <a href="https://aws.amazon.com/lambda/" target="_blank" rel="noopener">Lambda</a> functions for processing. The Lambda code is generated with the help of <a href="https://aws.amazon.com/codewhisperer/" target="_blank" rel="noopener">CodeWhisperer</a>.</p>
<div id="attachment_33896" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33896" src="https://infracom.com.sg/wp-content/uploads/2024/04/img1-2-1.png" alt width="780" class="size-full wp-image-33896">
<p id="caption-attachment-33896" class="wp-caption-text">Figure 1: Diagram of the solution</p>
</div>
<p>Security Hub integrates with EventBridge so you can automatically process findings with other services such as Lambda. To begin remediating the findings automatically, you can configure rules to determine where to send findings. This solution will do the following:</p>
<ol>
<li>Ingest an Amazon Security Hub finding into EventBridge.</li>
<li>Use an EventBridge rule to invoke a <a href="https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwj2oNnqqfr_AhWQq8gKHYJjAoYYABAAGgJxdQ&ase=2&ohost=www.google.com&cid=CAESauD2Z2WXlYvMUHVV368VhQ79uK6uow20GUKwE1cFQjxZI0acYkWln_c3azrvTHiNwCErviGlLT4vUS_GdBfCYgr23wBzXJILcpkAn4QYlPtUdkkpThnRbdmnFu4QZEUkANPxHTYjj5mBjmY&sig=AOD64_3pZRsOiUxICSPEBp-66xwnh_XA8g&q&nis=4&adurl&ved=2ahUKEwjHzdHqqfr_AhUTVDUKHbeOC4QQ0Qx6BAgJEAE" target="_blank" rel="noopener">Lambda function</a> for processing. </li>
<li>Use CodeWhisperer to generate the Lambda function code.</li>
</ol>
<p>It is important to note that there are two types of automation for Security Hub finding remediation:</p>
<ul>
<li><strong>Partial automation</strong>, which is initiated when a human worker selects the Security Hub findings manually and applies the automated remediation workflow to the selected findings.</li>
<li><strong>End-to-end automation</strong>, which means that when a finding is generated within Security Hub, this initiates an automated workflow to immediately remediate without human intervention.</li>
</ul>
<blockquote>
<p><strong>Important:</strong> When you use end-to-end automation, we highly recommend that you thoroughly test the efficiency and impact of the workflow in a non-production environment first before moving forward with implementation in a production environment.</p>
</blockquote>
<h2>Prerequisites </h2>
<p>To follow along with this walkthrough, make sure that you have the following prerequisites in place:</p>
<h2>Implement security automation</h2>
<p>In this scenario, you have been tasked with making sure that versioning is enabled across all <a href="https://aws.amazon.com/s3/" target="_blank" rel="noopener">Amazon Simple Storage Service (Amazon S3)</a> buckets in your AWS account. Additionally, you want to do this in a way that is programmatic and automated so that it can be reused in different AWS accounts in the future.</p>
<p>To do this, you will perform the following steps:</p>
<ol>
<li>Generate the remediation script with CodeWhisperer</li>
<li>Create the Lambda function</li>
<li>Integrate the Lambda function with Security Hub by using EventBridge</li>
<li>Create a custom action in Security Hub</li>
<li>Create an EventBridge rule to target the Lambda function</li>
<li>Run the remediation</li>
</ol>
<h3>Generate a remediation script with CodeWhisperer</h3>
<p>The first step is to use VS Code to create a script so that CodeWhisperer generates the code for your Lambda function in Python. You will use this Lambda function to remediate the Security Hub findings generated by the <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/s3-controls.html#s3-8" target="_blank" rel="noopener"><strong>[S3.14] S3 buckets should use versioning</strong></a> control.</p>
<blockquote>
<p><strong>Note:</strong> The underlying model of CodeWhisperer is powered by generative AI, and the output of CodeWhisperer is nondeterministic. As such, the code recommended by the service can vary by user. By modifying the initial code comment to prompt CodeWhisperer for a response, customers can change the corresponding output to help meet their needs. Customers should subject all code generated by CodeWhisperer to typical testing and review protocols to verify that it is free of errors and is in line with applicable organizational security policies. To learn about best practices on prompt engineering with CodeWhisperer, <a href="https://aws.amazon.com/blogs/devops/best-practices-for-prompt-engineering-with-amazon-codewhisperer/" target="_blank" rel="noopener">see this AWS blog post</a>.</p>
</blockquote>
<h4>To generate the remediation script</h4>
<ol>
<li>Open a new VS Code window, and then open or create a new folder for your file to reside in.</li>
<li>Create a Python file called <span>cw-blog-remediation.py</span> as shown in Figure 2.<br>
<div id="attachment_33897" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33897" src="https://infracom.com.sg/wp-content/uploads/2024/04/img2-4.png" alt="Figure 2: New VS Code file created called cw-blog-remediation.py" width="740" class="size-full wp-image-33897">
<p id="caption-attachment-33897" class="wp-caption-text">Figure 2: New VS Code file created called cw-blog-remediation.py</p>
</div> </li>
<li>Add the following imports to the Python file.
<div class="hide-language">
<pre class="unlimited-height-code"><code class="lang-text"><span>import</span> json
import boto3
<li>Because you have the context added to your file, you can now prompt CodeWhisperer by using a natural language comment. In your file, below the import statements, enter the following comment and then press <strong>Enter</strong>.
<div class="hide-language">
<pre class="unlimited-height-code"><code># Create lambda function that turns on versioning for an S3 bucket after the function is triggered from Amazon EventBridge</code></pre>
</div> </li>
<li>Accept the first recommendation that CodeWhisperer provides by pressing <strong>Tab</strong> to use the Lambda function handler, as shown in Figure 3.<br />&ngsp;
<div id="attachment_33899" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33899" src="https://infracom.com.sg/wp-content/uploads/2024/04/img3-4.png" alt="Figure 3: Generation of Lambda handler" width="740" class="size-full wp-image-33899" />
<p id="caption-attachment-33899" class="wp-caption-text">Figure 3: Generation of Lambda handler</p>
</div> </li>
<li>To get the recommendation for the function from CodeWhisperer, press <strong>Enter</strong>. Make sure that the recommendation you receive looks similar to the following. CodeWhisperer is nondeterministic, so its recommendations can vary.
<div class="hide-language">
<pre class="unlimited-height-code"><code class="lang-text"><span>import</span> json
import boto3
# Create lambda function that turns on versioning for an S3 bucket after function is triggered from Amazon EventBridge
def lambda_handler(event, context):
s3 = boto3.client(‘s3’)
bucket = event[‘detail’][‘requestParameters’][‘bucketName’]
response = s3.put_bucket_versioning(
Bucket=bucket,
VersioningConfiguration={
‘Status’: ‘Enabled’
}
)
print(response)
return {
‘statusCode’: 200,
‘body’: json.dumps(‘Versioning enabled for bucket ‘ + bucket)
}
Your function code should look similar to the following:
<h3>Create the Lambda function</h3>
<p>The next step is to use the automation script that you generated to create the Lambda function that will enable versioning on applicable S3 buckets.</p>
<h4>To create the Lambda function</h4>
<ol>
<li>Open the <a href="https://us-east-1.console.aws.amazon.com/lambda/home" target="_blank" rel="noopener">AWS Lambda console</a>.</li>
<li>In the left navigation pane, choose <strong>Functions</strong>, and then choose <strong>Create function</strong>.</li>
<li>Select <strong>Author from Scratch</strong> and provide the following configurations for the function:
<ol>
<li>For <strong>Function name</strong>, select <strong>sec_remediation_function</strong>.</li>
<li>For <strong>Runtime</strong>, select <strong>Python 3.12</strong>.</li>
<li>For <strong>Architecture</strong>, select <strong>x86_64</strong>.</li>
<li>For <strong>Permissions</strong>, select <strong>Create a new role with basic Lambda permissions</strong>.</li>
</ol> </li>
<li>Choose<strong> Create function</strong>.</li>
<li>To upload your local code to Lambda, select <strong>Upload from</strong> and then <strong>.zip file</strong>, and then upload the file that you zipped.</li>
<li>Verify that you created the Lambda function successfully. In the <strong>Code source</strong> section of Lambda, you should see the code from the automation script displayed in a new tab, as shown in Figure 4.<br />
<div id="attachment_33903" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33903" src="https://infracom.com.sg/wp-content/uploads/2024/04/img4-4.png" alt="Figure 4: Source code that was successfully uploaded" width="740" class="size-full wp-image-33903" />
<p id="caption-attachment-33903" class="wp-caption-text">Figure 4: Source code that was successfully uploaded</p>
</div> </li>
<li>Choose the <strong>Code</strong> tab.</li>
<li>Scroll down to the <strong>Runtime settings</strong> pane and choose <strong>Edit</strong>.</li>
<li>For <strong>Handler</strong>, enter <span>cw-blog-remediation.lambda_handler</span> for your function handler, and then choose <strong>Save</strong>, as shown in Figure 5.<br />
<div id="attachment_33904" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33904" loading="lazy" src="https://infracom.com.sg/wp-content/uploads/2024/04/img5-3.png" alt="Figure 5: Updated Lambda handler" width="1410" height="452" class="size-full wp-image-33904" />
<p id="caption-attachment-33904" class="wp-caption-text">Figure 5: Updated Lambda handler</p>
</div> </li>
<li>For security purposes, and to follow the principle of least privilege, you should also add an inline policy to the Lambda function’s role to perform the tasks necessary to enable versioning on S3 buckets.
<ol>
<li>In the Lambda console, navigate to the <strong>Configuration</strong> tab and then, in the left navigation pane, choose <strong>Permissions</strong>. Choose the <strong>Role name</strong>, as shown in Figure 6.<br />
<div id="attachment_33905" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33905" src="https://infracom.com.sg/wp-content/uploads/2024/04/img6-1.png" alt="Figure 6: Lambda role in the AWS console" width="700" class="size-full wp-image-33905" />
<p id="caption-attachment-33905" class="wp-caption-text">Figure 6: Lambda role in the AWS console</p>
</div> </li>
<li>In the <strong>Add permissions </strong>dropdown, select <strong>Create inline policy</strong>.<br />
<div id="attachment_33906" class="wp-caption aligncenter">
<img aria-describedby="caption-attachment-33906" src="https://infracom.com.sg/wp-content/uploads/2024/04/img7.png" alt="Figure 7: Create inline policy" width="700" class="size-full wp-image-33906" />
<p id="caption-attachment-33906" class="wp-caption-text">Figure 7: Create inline policy</p>
</div> </li>
<li>Choose <strong>JSON</strong>, add the following policy to the policy editor, and then choose <strong>Next</strong>.
<div class="hide-language">
<pre class="unlimited-height-code"><code class="lang-text">{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "s3:PutBucketVersioning",
"Resource": "*"
}
]
}
Create a custom action in Security Hub
In this step, you will create a custom action in Security Hub.
To create the custom action
- Open the Security Hub console.
- In the left navigation pane, choose Settings, and then choose Custom actions.
- Choose Create custom action.
- Provide the following information, as shown in Figure 8:
- For Name, enter TurnOnS3Versioning.
- For Description, enter Action that will turn on versioning for a specific S3 bucket.
- For Custom action ID, enter TurnOnS3Versioning.
- Choose Create custom action.
- Make a note of the Custom action ARN. You will need this ARN when you create a rule to associate with the custom action in EventBridge.
Create an EventBridge rule to target the Lambda function
The next step is to create an EventBridge rule to capture the custom action. You will define an EventBridge rule that matches events (in this case, findings) from Security Hub that were forwarded by the custom action that you defined previously.
To create the EventBridge rule
- Navigate to the EventBridge console.
- On the right side, choose Create rule.
- On the Define rule detail page, give your rule a name and description that represents the rule’s purpose—for example, you could use the same name and description that you used for the custom action. Then choose Next.
- Scroll down to Event pattern, and then do the following:
- For Event source, make sure that AWS services is selected.
- For AWS service, select Security Hub.
- For Event type, select Security Hub Findings – Custom Action.
- Select Specific custom action ARN(s) and enter the ARN for the custom action that you created earlier.
As you provide this information, the Event pattern updates.
- Choose Next.
- On the Select target(s) step, in the Select a target dropdown, select Lambda function. Then from the Function dropdown, select sec_remediation_function.
- Choose Next.
- On the Configure tags step, choose Next.
- On the Review and create step, choose Create rule.
Run the automation
Your automation is set up and you can now test the automation. This test covers a partial automation workflow, since you will manually select the finding and apply the remediation workflow to one or more selected findings.
Important: As we mentioned earlier, if you decide to make the automation end-to-end, you should assess the impact of the workflow in a non-production environment. Additionally, you may want to consider creating preventative controls if you want to minimize the risk of event occurrence across an entire environment.
To run the automation
- In the Security Hub console, on the Findings tab, add a filter by entering Title in the search box and selecting that filter. Select IS and enter S3 general purpose buckets should have versioning enabled (case sensitive). Choose Apply.
- In the filtered list, choose the Title of an active finding.
- Before you start the automation, check the current configuration of the S3 bucket to confirm that your automation works. Expand the Resources section of the finding.
- Under Resource ID, choose the link for the S3 bucket. This opens a new tab on the S3 console that shows only this S3 bucket.
- In your browser, go back to the Security Hub tab (don’t close the S3 tab—you will need to return to it), and on the left side, select this same finding, as shown in Figure 10.
- In the Actions dropdown list, choose the name of your custom action.
- When you see a banner that displays Successfully started action…, go back to the S3 browser tab and refresh it. Verify that the S3 versioning configuration on the bucket has been enabled as shown in figure 12.
Conclusion
In this post, you learned how to use CodeWhisperer to produce AI-generated code for custom remediations for a security use case. We encourage you to experiment with CodeWhisperer to create Lambda functions that remediate other Security Hub findings that might exist in your account, such as the enforcement of lifecycle policies on S3 buckets with versioning enabled, or using automation to remove multiple unused Amazon EC2 elastic IP addresses. The ability to automatically set public S3 buckets to private is just one of many use cases where CodeWhisperer can generate code to help you remediate Security Hub findings.
To sum up, CodeWhisperer acts as a tool that can help boost the productivity of security experts who have coding abilities, assisting them to swiftly write code to address security issues. However, security specialists should continue building their software development capabilities to implement robust solutions. Engineers should carefully review and test any generated code, since human oversight is still vital for security.
If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, contact AWS Support.
<!-- '"` -->
You must be logged in to post a comment.