Deep Dive into AWS IMDSv2 Architecture and Exploitation
Why session-oriented metadata requests prevent SSRF and how to enforce it at scale. Cloud infrastructure security is not just about protecting public endpoints. Some of the most sensitive information is available throug
Why session-oriented metadata requests prevent SSRF and how to enforce it at scale.
Cloud infrastructure security is not just about protecting public endpoints. Some of the most sensitive information is available through internal services that applications use every day.
One important example is the Amazon EC2 Instance Metadata Service (IMDS). It provides running EC2 instances with information about their environment, including instance identity and temporary IAM credentials.
When an application contains a Server-Side Request Forgery (SSRF) vulnerability, attackers may attempt to use it to access internal metadata endpoints. If successful, this can expose sensitive information and potentially provide access to AWS resources.
AWS introduced Instance Metadata Service Version 2 (IMDSv2) to make this attack path harder through session-oriented authentication, request validation, and additional network protections.
This guide explores how IMDSv2 works, how SSRF can target metadata endpoints, and how to enforce secure configurations using AWS CLI, Terraform, and AWS Organizations Service Control Policies (SCPs).
1. Understanding AWS IMDS Architecture
The Instance Metadata Service is an internal endpoint available to applications running on EC2 instances.
The standard IPv4 endpoint is:
http://169.254.169.254/latest/meta-data/
Applications use this endpoint to retrieve information such as:
- Instance ID and instance type.
- Availability zone and region.
- Network interface information.
- IAM role names and temporary credentials.
- Instance identity documents.
AWS supports two metadata service versions:
IMDSv1: Uses direct HTTP GET requests without requiring a session token.
IMDSv2: Requires a session token before metadata can be retrieved.
The difference is important because an attacker exploiting an SSRF vulnerability may be able to trigger a simple HTTP request but may not be able to perform the additional operations required by IMDSv2.
IMDSv2 introduces a two-stage authentication process:
- Send an HTTP PUT request to the token endpoint.
- Receive a temporary session token.
- Include that token in the HTTP header of subsequent GET requests.
- Retrieve metadata while the token remains valid.
The token can have a lifetime between one second and six hours.
This session-oriented design provides an additional security layer against common SSRF techniques.
2. How SSRF Exploitation Targets IMDS
SSRF occurs when an application makes server-side HTTP requests to destinations controlled or influenced by user input.
Consider an application that accepts a URL and fetches its contents without validating the destination.
A vulnerable implementation might look like this:
from flask import Flask, request
import requests
app = Flask(__name__)
@app.route("/fetch")
def fetch_url():
target = request.args.get("url")
response = requests.get(target, timeout=5)
return response.text
The problem is that the application does not restrict which destinations can be accessed.
In an authorized security lab, an attacker could attempt to make the application request an internal metadata endpoint:
http://169.254.169.254/latest/meta-data/
If the instance permits IMDSv1 and the application can reach the endpoint, metadata may be exposed.
Potential consequences include:
- Exposure of instance information.
- Access to temporary IAM credentials.
- Unauthorized access to AWS resources, depending on the attached IAM permissions.
- Further compromise of cloud workloads.
How IMDSv2 changes the attack path
IMDSv2 requires a PUT request to obtain a token before metadata requests can succeed.
A simple SSRF vulnerability that only permits ordinary GET requests is therefore less likely to retrieve metadata.
However, IMDSv2 does not eliminate SSRF. If an attacker can control both HTTP methods and headers, or abuse another internal service to obtain a token, additional attack paths may remain.
IMDSv2 should therefore be combined with application-level SSRF protection, restricted IAM permissions, and network controls.
3. Reproducing IMDSv2 Requests Using AWS CLI and cURL
The following commands demonstrate legitimate metadata access from an authorized EC2 instance.
First, request an IMDSv2 session token:
TOKEN=$(curl -sS -X PUT \
"http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
Next, use the token to retrieve the instance ID:
curl -sS \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"http://169.254.169.254/latest/meta-data/instance-id"
Retrieve the instance type:
curl -sS \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"http://169.254.169.254/latest/meta-data/instance-type"
To check the current metadata configuration from an authorized administrative workstation:
aws ec2 describe-instances \
--instance-ids i-xxxxxxxxxxxxxxxxx \
--query 'Reservations[].Instances[].MetadataOptions'
To require IMDSv2 on an existing instance:
aws ec2 modify-instance-metadata-options \
--instance-id i-xxxxxxxxxxxxxxxxx \
--http-tokens required \
--http-endpoint enabled
Replace the example instance ID with an actual instance ID.
Expected security behaviour: When IMDSv2 is required, metadata requests without a valid token should fail.
These commands follow AWS's documented command syntax. They have not been executed against a live AWS account as part of this article.
4. Enforcing IMDSv2 Through Terraform and Launch Templates
Configuring individual instances manually is not a scalable security strategy.
Infrastructure as Code (IaC) makes it possible to enforce security settings consistently across environments.
A Terraform EC2 launch template can require IMDSv2 by configuring its metadata options.
Terraform launch template example:
resource "aws_launch_template" "secure_instance" {
name_prefix = "secure-imdsv2-"
image_id = var.ami_id
instance_type = "t3.micro"
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 2
}
tag_specifications {
resource_type = "instance"
tags = {
Name = "Secure-EC2"
Environment = "Production"
}
}
}
Important configuration settings:
-
http_endpoint = enabledkeeps metadata access available. -
http_tokens = requireddisables IMDSv1 access. -
http_put_response_hop_limit = 2allows the token response to travel two network hops.
A hop limit of 2 is often appropriate for container workloads, but it should be evaluated against the actual network architecture. A smaller hop limit can provide additional isolation where compatible.
Validate the Terraform configuration:
terraform init
terraform fmt -check
terraform validate
terraform plan
Review the plan before applying it:
terraform apply
For Auto Scaling Groups, use the secure launch template as the instance configuration source.
This ensures newly launched instances inherit the required metadata settings.
5. Enforcing IMDSv2 at Scale Using AWS SCPs and Remediation
Terraform protects infrastructure managed through its configuration, but organizations also need controls against manual changes and alternative deployment methods.
AWS Organizations Service Control Policies provide an additional governance layer.
An SCP can deny EC2 launch and metadata modification operations when IMDSv2 is not required.
Example SCP policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RequireIMDSv2",
"Effect": "Deny",
"Action": [
"ec2:RunInstances",
"ec2:ModifyInstanceMetadataOptions"
],
"Resource": "*",
"Condition": {
"StringNotEquals": {
"ec2:MetadataHttpTokens": "required"
}
}
}
]
}
This policy demonstrates the use of the ec2:MetadataHttpTokens condition key to reject operations that do not require IMDSv2.
Test the policy carefully in a non-production organizational unit before attaching it broadly. An SCP does not grant permissions, and it can block legitimate infrastructure changes if deployed without checking existing workloads.
Additional enforcement through account-level defaults
AWS also provides an account-level mechanism to require IMDSv2.
For example:
aws ec2 modify-instance-metadata-defaults \
--region us-east-1 \
--http-tokens required \
--http-tokens-enforced enabled
This prevents new instances from launching with IMDSv1-enabled configurations in the specified Region.
Verify the settings:
aws ec2 get-instance-metadata-defaults \
--region us-east-1
Account-level enforcement should be rolled out after identifying applications and agents that still depend on IMDSv1.
Final security checklist
- [ ] Require IMDSv2 on EC2 instances.
- [ ] Use secure Terraform launch templates.
- [ ] Enforce metadata requirements through SCPs or account-level controls.
- [ ] Restrict IAM instance-profile permissions.
- [ ] Validate user-controlled URLs in applications.
- [ ] Block unnecessary access to internal network destinations.
- [ ] Review metadata access logs and CloudWatch metrics.
- [ ] Test existing workloads before organization-wide enforcement.
Conclusion
IMDSv2 adds an important layer of protection to AWS infrastructure by requiring session tokens for metadata requests.
However, strong cloud security requires more than changing one EC2 setting. Application-level SSRF prevention, least-privilege IAM permissions, secure launch templates, and organization-wide policies must work together.
By combining Terraform, AWS CLI, and Service Control Policies, engineering teams can make IMDSv2 enforcement part of their standard infrastructure deployment process rather than relying on manual configuration.
Secure the infrastructure before attackers find the gaps.
Download IMDSv2 Terraform Template: https://hackmywebsite.io/?utm_source=med&utm_campaign=aws_imdsv2_guide
References
- AWS EC2 β How IMDSv2 works
- AWS β Configure instance metadata options
- AWS Organizations β EC2 policy syntax
- HashiCorp β Terraform AWS Launch Template
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.