Sanchit Dilip Jain/Securing Your Code With Amazon Q Developer ๐Ÿ”

Created Sun, 14 Jul 2024 12:00:00 +0000 Modified Mon, 12 Aug 2024 09:03:58 +0000
1555 Words 7 min

Securing Your Code With Amazon Q Developer

Introduction

  1. What is Amazon Q Developer?
  • Amazon Q Developer is a generative artificial intelligence (AI) powered conversational assistant that can help us understand, build, extend, and operate AWS applications.
  • We can ask questions about AWS architecture, our AWS resources, best practices, documentation, support, and more. Amazon Q is constantly updating its capabilities so our questions get the most contextually relevant and actionable answers.
  1. How Amazon Q Developer help us with secure coding?
  • Amazon Q Developer offers powerful capabilities to enhance code security throughout the development lifecycle. By leveraging its advanced scanning and analysis features, developers can identify and address potential vulnerabilities early in the process.

  • Amazon Q can scan our codebase for security vulnerabilities and code quality issues to improve the posture of our applications throughout the development cycle. You can initiate a scan of an entire codebase, analyzing all files in your local project or workspace, or enable auto scans that assess your code as you write it.

  • This helps our applications to be more secure and resilient by highlighting security issues such as cross-site scripting vulnerabilities, log injections, loose file permissions, hardcoded credentials and more. The earlier security issues are detected, the less work and effort is required to fix the same.

    image1

  1. Code Security Scanning
  • Amazon Q Developer performs comprehensive security scans on our codebase, including static application security testing (SAST), secrets detection, and infrastructure as code (IaC) scanning. Here’s how you can utilize these features:
    • SAST Scanning: Amazon Q identifies security vulnerabilities in the source code, such as resource leaks, SQL injection, and cross-site scripting.
    • Secrets Scanning: It detects hardcoded passwords, database connection strings, and usernames in the code and text files.
    • IaC Scanning: Amazon Q evaluates the security posture of infrastructure files, detecting misconfigurations and compliance issues.

Demo

  • In this section, we will use the Security Scanning features of Q Developer to detect insecure code. Amazon Q can scan an entire codebase, or auto-scan the code as you write it. For the purposes of this demo we will be using project based scanning. Upto 100 MB of code can be scanned at a time.

    • Step 1: Enable Amazon Q Developer in Visual Studio

      • Install the Amazon Q extension for Visual Studio Code

        • Navigate to Extensions icon on the left-hand pane of your VS Code IDE.

        • In the search bar, enter Amazon Q and select Install.

          image2

      • Connecting Using Builder ID

        • In the Amazon Q extension for Visual Studio Code, select Use for free. Choose continue.

          image3

        • At the prompt “Confirm Code for AWS Builder ID” choose Proceed to Browser. Note: if an additional prompt shows, please proceed by clicking Open.

        • At the prompt “Do you want Code to open the external website?”. Choose Open.

        • A browser tab will open, displaying the Authorization requested window. The code should have been already populated. Choose Confirm and continue.

        • A browser tab will open to the Create AWS Builder ID page. Provide your email address, and the password you want to set. Next perform Email verification.

        • After creating AWS Builder ID, A browser tab will open with a message asking you to allow Amazon Q extension for Visual Studio Code to access your data. Choose Allow..

        image5

        • Return to VSCode to start using Amazon Q Developer.

        image6

    • Step 2: Scan your project

      • Choose the text, Amazon Q, from the rectangular area at the bottom of the IDE window.

        image7

      • A drop-down window will appear at the top from which the user may choose Run Project Scan.

        image8

    • Step 3: Open Redirect Vulnerability

      • Open Redirect Vulnerability is an security weakness where an attacker could supply a malicious URL as an input, potentially leading users to phishing or malware sites. This is a common security flaw in web applications that can be exploited to conduct phishing attacks or distribute malware.

        from flask import app
        
        @app.route('/redirect')
        def redirect_url_noncompliant():            
            from flask import request, redirect            
            endpoint = request.args['url']            
            # Noncompliant: redirect to a user-supplied URL without sanitization.             
            return redirect(endpoint)
        
      • Click on Amazon Q in the status bar and run Project Scan to see how the Open Redirect Vulnerability is detected. The following finding will be visible in the status bar

        image9

      • To fix the open redirect issue in the provided code snippet, you should validate and/or sanitize the URL before performing the redirection. For example, only allow redirects to known, safe domains by checking the user-supplied URL against a whitelist.

    • Step 4: SQL Injection

      • SQL injection vulnerability is present within code when user-provided inputs are not sanitized before being used to generate a SQL database query. An attacker can misuse un-trusted input to run query statements that read, modify, or delete database content.

      • Copy the following code within your IDE.

        def execute_query_noncompliant(request):
        
          import sqlite3  
        
          name = request.GET.get("name")         
          query = "SELECT * FROM Users WHERE name = " + name + ";"          
          with sqlite3.connect("example.db") as connection:          
              cursor = connection.cursor()           
              # Noncompliant: user input is used without sanitization.           
              cursor.execute(query)           
              connection.commit()           
              connection.close()
        
      • Click on Amazon Q in the status bar and run Project Scan to see how the SQL Injection Vulnerability is detected. The following finding will be visible in the status bar

        image10

      • To fix the SQL Injection vulnerability in the provided code, you should use parameterized queries, also known as prepared statements. This method ensures that user inputs are handled safely, preventing attackers from injecting malicious SQL code.

    • Step 5: Improper Privilege Management

      • Privilege escalation occurs when a malicious user exploits a bug, design flaw, or configuration error in an application or operating system to gain elevated access to the system. Elevated privileges can be used to delete files, view private information, or install unwanted programs or backdoors.

      • Copy the following code within your IDE.

        def set_user_noncompliant():
        
          import os
        
          root = 0
          # Noncompliant: the process user is set to root.
          os.setuid(root)
        
      • Click on Amazon Q in the status bar and run Project Scan to see how the Improper Privilege Management Vulnerability is detected. The following finding will be visible in the status bar

        image11

      • Running processes as root should be avoided whenever possible because it can lead to severe security vulnerabilities, including unauthorized access, privilege escalation, and potential system compromise.

      • Always follow the principle of least privilege, meaning that processes should run with the minimum permissions necessary to perform their required tasks. This reduces the risk and potential impact of a security breach.

    • Step 6: Path Traversal

      • Constructing path names with unsanitized user input can lead to path traversal attacks (for example, ../../..). This type of attack exploits insufficient security validation/sanitization of user-supplied input file names, allowing attackers to access files or directories that are not intended to be accessible. This can lead to unauthorized access, information disclosure, and even system compromise.

      • Copy the following code within your IDE.

         def verify_file_path_noncompliant():
        
             from flask import request
        
             file_path = request.args["file"]
             # Noncompliant: user input file path is not sanitized.
             file = open(file_path)
             file.close()
        
      • Click on Amazon Q in the status bar and run Project Scan to see how the Path Traversal Vulnerability is detected. The following finding will be visible in the status bar

        image12

      • Path traversal vulnerabilities can be mitigated by sanitizing user input before using it to construct a file path. This approach involves checking if the user-supplied file path is within a predefined list of allowed paths

    • Step 7: OS Command Injection

      • Constructing operating system or shell commands with unsanitized user input can lead to inadvertently running malicious code. This kind of vulnerability allows an attacker to execute arbitrary commands on the host operating system under the privileges of the vulnerable application.

      • Copy the following code within your IDE.

          def exec_command_noncompliant():
        
              from paramiko import client
              from flask import request
        
              address = request.args.get("address")
              cmd = "ping -c 1 %s" % address
              client = client.SSHClient()
              client.connect("ssh.samplehost.com")
              # Noncompliant: address argument is not sanitized.
              client.exec_command(cmd)
        
      • Run Amazon Q Project Scan to see how the OS command injection vulnerability is detected. The following finding will be visible in the status bar

        image13

      • Whenever possible, avoid constructing shell commands with user inputs. Use language-specific APIs or libraries designed to perform the required actions without invoking the shell.

    • Step 8: AWS credentials logged

      • In this vulnerability, unencrypted AWS credentials can be logged which can expose those credentials to an attacker. Encrypt sensitive data, such as credentials, before they are logged to make the code more secure.

      • Copy the following code within your IDE.

        def log_credentials_noncompliant():
        
          import boto3
          import logging
        
          session = boto3.Session()
          credentials = session.get_credentials()
          credentials = credentials.get_frozen_credentials()
          access_key = credentials.access_key
          secret_key = credentials.secret_key
          # Noncompliant: credentials are written to the logger.
          logging.info('Access key: ', access_key)
          logging.info('secret access key: ', secret_key)
        
      • Run Amazon Q Project Scan to see how the this vulnerability is detected. The following finding will be visible in the status bar

        image14

      • Avoid logging sensitive information such as access keys or secret keys. For AWS resource access management, prefer IAM roles over static access and secret keys, especially for applications running on AWS services like EC2, Lambda, etc. IAM roles provide temporary credentials automatically managed by AWS.

Conclusion

  • In this blog we understood how to use Amazon Q Developer to detect security policy violations and vulnerabilities in your code with static application security testing (SAST), secrets detection, and infrastructure as code (IaC) scanning. Security scans in Amazon Q identify security vulnerabilities and suggest how to improve your code.
  • Keep practising with Amazon Q and leveraging the power of AI to help you improve in your security journey.