def get_imdsv2_token(): url = "http://169.254.169.254/latest/api/token" headers = "X-aws-ec2-metadata-token-ttl-seconds": "21600" response = requests.put(url, headers=headers) response.raise_for_status() return response.text
You can modify existing EC2 instances to require IMDSv2 exclusively using the AWS Command Line Interface:
The command is a fundamental tool for working with cloud metadata services , specifically designed to retrieve an authentication token required to access instance metadata [1]. Purpose of the Command
While convenient, this model introduced severe security vulnerabilities. If an attacker exploited a vulnerability in a web application running on the server, they could trick the application into fetching the metadata—including administrative IAM role credentials—and exfiltrate them. IMDSv2: The Session-Oriented Model curl-url-http-3A-2F-2F169.254.169.254-2Flatest-2Fapi-2Ftoken
: Set the IMDSv2 response hop limit to 1 if your applications are running directly on the instance, or 2 if you are utilizing container environments like Amazon ECS. This prevents the token from traversing outside its intended network boundary.
If you are a developer or security researcher:
: Pass that token in an HTTP header ( X-aws-ec2-metadata-token ) during subsequent GET requests. Breaking Down the Command def get_imdsv2_token(): url = "http://169
| Location | Risk Level | Why | |----------|------------|-----| | Public GitHub | Critical | Automated scanners search for 169.254.169.254 | | CI build logs | High | Logs often persist in S3 or Elasticsearch | | Shell history ( .bash_history ) inside containers | High | If container image is leaked | | Web application error logs | Medium | If an SSRF attempt logs the request URL | | Marketing/SEO keyword lists (ironically) | Low | Not directly executable, but indicates awareness |
AWS introduced IMDSv2 in late 2019 to mitigate this. The new flow:
: The instance sends an HTTP PUT request to the metadata endpoint. IMDSv2: The Session-Oriented Model : Set the IMDSv2
So, the decoded meaning is effectively:
This example retrieves the instance ID. The metadata service provides a wide range of information, and you can access it by specifying the path in the URL.