Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 50 minutes

Stop a web flaw from reaching the metadata service

After this lesson you can
  • Explain what the instance metadata service is and how its two versions differ
  • Show on a local mock how an unsafe fetch hands out the credentials of a role
  • Fix the fetch with an allow-list and require the session token on the service
Lab files of this lesson (16)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The intruder of lesson 7 used a role from a machine that they had started. Your lead looks at the next risk: "Our own web server has a role too. The shop has a feature that fetches a book cover from a URL that the customer types. Could a customer make our server fetch its own credentials?" You will test that on your own machine only, with a stand-in for the service, then fix the code and the setting. You met this flaw, server-side request forgery, in "Web applications and APIs", lesson 6. Here you see why it is worse on a cloud machine.

Recall

Lesson 4: how do temporary credentials differ from an access key of a user?

They have three parts (key ID, secret and session token), their ID starts with ASIA, and they end by themselves after minutes or hours. A program inside AWS gets them through a role.

Lesson 7: what does the session name of a role that a machine uses tell you?

It is the ID of the machine. A record with assumed-role/ROLE/i-... was made by a program on that machine, with the temporary credentials of the role.

The idea

A program on a cloud machine needs credentials, and lesson 4 said that it should not store any. The answer is the instance metadata service (IMDS): a small web service that only the machine itself can reach, at the fixed address 169.254.169.254. That address is link-local: it is never routed to another network. A program asks the service "which role do I have?" and "give me its current credentials", and gets temporary credentials as JSON. The AWS libraries do this for you.

The weak point is the word "only the machine itself". A web application runs on the machine. If it fetches a URL that a visitor chooses, the visitor can make it fetch from the metadata service. That is server-side request forgery (SSRF): the server sends a request that the attacker wrote.

AWS has two versions of the service.

IMDSv1IMDSv2
How to askOne plain GETFirst a PUT to /latest/api/token with the header X-aws-ec2-metadata-token-ttl-seconds. It returns a session token. Then each GET carries the token in the header X-aws-ec2-metadata-token.
Why it helpsNothing stops a forged GETA typical SSRF flaw can send a GET to a URL. It cannot send a PUT and it cannot add a header.
More guardsA PUT with an X-Forwarded-For header is refused, which stops many proxies. The answer to the PUT has a hop limit (a count of network hops) of 1 by default, so it cannot leave the machine. An image that is registered as IMDSv2-only sets the hop limit to 2, so that containers on the machine can still ask.

Each machine has a setting, HttpTokens. With optional, both versions work. With required, only IMDSv2 works and a plain GET gets the status 401. Whether a new machine starts with required depends on the image and on a default that the account can set, and this has changed over time: take the current behaviour from the EC2 documentation, and check the setting, never assume it.

A forged request reaches the metadata service
AttackerWeb appMetadata servicefetch the cover at 169.254.169.254GET, sent from the machine itselftemporary credentials of the roleshows what it fetchedAttackerWeb appMetadataservice1234
  1. Attacker → Web app: fetch the cover at 169.254.169.254
  2. Web app → Metadata service: GET, sent from the machine itself
  3. Metadata service → Web app: temporary credentials of the role
  4. Web app → Attacker: shows what it fetched

There are two fixes, and you want both. The application must fetch only from places that it knows (an allow-list), and the machine must require the token. Then one mistake is not enough.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Metadata serviceIMDS at 169.254.169.254Instance Metadata Service at 169.254.169.254Metadata server, metadata.google.internal
Guard against a forged requestA session token from a PUT (IMDSv2)The header Metadata: true is required, and a request with X-Forwarded-For is refusedThe header Metadata-Flavor: Google is required

Worked example

Everything in this lesson runs on your own machine, against your own programs. Do not send such requests to a system that is not yours.

1. Start the mock service

imds_mock.py is a stand-in for the metadata service. It listens on 127.0.0.1, port 8700, because your laptop has no 169.254.169.254. It knows the paths and the two header names of the real service, and the credentials that it returns are invented. Its first argument is the setting: optional or required. Its second argument is the port. If port 8700 is not free on your machine, use another port and change 8700 in every command of this lesson. Open the block and save the file.

The finished file: imds_mock.py

imds_mock.py

"""imds_mock.py: a local stand-in for the instance metadata service of a cloud machine. For your own lab only.

    python3 imds_mock.py [optional|required] [port]        default: optional 8700

optional: the old way (a plain GET) and the token way both work.   required: only the token way works.
Every credential that it returns is invented and opens nothing.
"""
import json
import secrets
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

MODE = sys.argv[1] if len(sys.argv) > 1 else "optional"
PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8700
ROLE = "web-app-role"
CREDENTIALS = {"Code": "Success", "LastUpdated": "2026-11-21T09:00:00Z", "Type": "AWS-HMAC",
               "AccessKeyId": "ASIAKRLAB7MOCK" + "EXAMPLE", "SecretAccessKey": "kr/lab/mock/secret/that/opens/n0" + "EXAMPLEKEY",
               "Token": "kr-lab-mock-session-token-" + "EXAMPLE", "Expiration": "2026-11-21T15:00:00Z"}
BASE = "/latest/meta-data/"
PAGES = {BASE: "iam/\ninstance-id\n", BASE + "instance-id": "i-0a11b22c33d44e551",
         BASE + "iam/security-credentials/": ROLE, BASE + "iam/security-credentials/" + ROLE: json.dumps(CREDENTIALS, indent=2)}
tokens = {}  # token: the time at which it ends


class Handler(BaseHTTPRequestHandler):
    def reply(self, code, text):
        body = (text + "\n").encode()
        self.send_response(code)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_PUT(self):
        """The token way, step 1: a PUT with a lifetime in seconds returns a session token."""
        if self.path != "/latest/api/token":
            return self.reply(404, "not found")
        if self.headers.get("X-Forwarded-For"):
            return self.reply(403, "forbidden: the request came through a proxy")
        ttl = self.headers.get("X-aws-ec2-metadata-token-ttl-seconds", "")
        if not ttl.isdigit() or not 1 <= int(ttl) <= 21600:
            return self.reply(400, "bad request: give a lifetime of 1 to 21600 seconds")
        token = secrets.token_urlsafe(32)
        tokens[token] = time.time() + int(ttl)
        self.reply(200, token)

    def do_GET(self):
        token = self.headers.get("X-aws-ec2-metadata-token")
        if token or MODE == "required":  # the token way, step 2: every GET carries the token
            if tokens.get(token, 0) < time.time():
                return self.reply(401, "unauthorized: a valid session token is required")
        if self.path in PAGES:
            return self.reply(200, PAGES[self.path])
        self.reply(404, "not found")

    def log_message(self, fmt, *args):
        print(self.command, self.path, args[1], flush=True)


if __name__ == "__main__":
    print(f"mock metadata service on http://127.0.0.1:{PORT} (tokens {MODE})", flush=True)
    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

The & at the end starts the program in the background. $! is the process number of the last background program: the command saves it in a file, so that you can stop the service later. sleep 1 waits one second for it to start.

python3 imds_mock.py optional 8700 > imds.log 2>&1 &
echo $! > imds.pid
sleep 1
cat imds.log
mock metadata service on http://127.0.0.1:8700 (tokens optional)

2. Ask the service the way a program on the machine does

curl -s fetches a URL and prints the answer without a progress bar ("Networking hands-on", lesson 8). First the name of the role, then its credentials.

curl -s http://127.0.0.1:8700/latest/meta-data/iam/security-credentials/
curl -s http://127.0.0.1:8700/latest/meta-data/iam/security-credentials/web-app-role
web-app-role
{
  "Code": "Success",
  "LastUpdated": "2026-11-21T09:00:00Z",
  "Type": "AWS-HMAC",
  "AccessKeyId": "ASIAKRLAB7MOCKEXAMPLE",
  "SecretAccessKey": "kr/lab/mock/secret/that/opens/n0EXAMPLEKEY",
  "Token": "kr-lab-mock-session-token-EXAMPLE",
  "Expiration": "2026-11-21T15:00:00Z"
}

These are the field names of the real answer. Whoever holds these three values can act as the role web-app-role until the time in Expiration.

3. Save the flawed feature and misuse it

preview.py is the feature as a developer first wrote it: it fetches whatever URL it gets and returns the start of the answer.

preview.py

"""preview.py: the "fetch a cover picture from a URL" feature of the shop, as a developer first wrote it. It has a flaw."""
import sys
import urllib.error
import urllib.request


def fetch(url):
    """Fetch any URL that the customer gives and return (status, first 600 characters)."""
    try:
        with urllib.request.urlopen(url, timeout=3) as answer:
            return answer.status, answer.read(600).decode(errors="replace")
    except urllib.error.HTTPError as err:
        return err.code, err.read(600).decode(errors="replace")


if __name__ == "__main__":
    status, text = fetch(sys.argv[1])
    print(status)
    print(text.strip())

Play the attacker against your own program. In place of a cover picture, give it the address of the metadata service.

python3 preview.py http://127.0.0.1:8700/latest/meta-data/iam/security-credentials/web-app-role | head -n 6
200
{
  "Code": "Success",
  "LastUpdated": "2026-11-21T09:00:00Z",
  "Type": "AWS-HMAC",
  "AccessKeyId": "ASIAKRLAB7MOCKEXAMPLE",

The application handed out the credentials of its own role. Nothing was broken into: the feature did what it was written to do.

4. Require the token

Stop the service and start it again with required, as a machine with HttpTokens set to required behaves.

kill $(cat imds.pid)
python3 imds_mock.py required 8700 > imds.log 2>&1 &
echo $! > imds.pid
sleep 1
python3 preview.py http://127.0.0.1:8700/latest/meta-data/iam/security-credentials/web-app-role
401
unauthorized: a valid session token is required

The flaw is still in the application, and it gets nothing. A program that is meant to use the service does two steps. -X PUT sets the method, -H adds a header, and $(...) puts the output of a command into a variable.

TOKEN=$(curl -s -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 60" http://127.0.0.1:8700/latest/api/token)
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://127.0.0.1:8700/latest/meta-data/instance-id
i-0a11b22c33d44e551

5. Fix the feature

The setting protects the metadata service. The flawed fetch can still reach every other internal address, so the code must be fixed too. safe_fetch.py decides before it sends anything. The function check_url reads only the text of the URL.

def check_url(url):
    """Return (True, "ok") or (False, reason). This function sends nothing: it only reads the text of the URL."""
    parts = urlsplit(url)
    if parts.scheme != "https":
        return False, "only https is allowed"
    host = parts.hostname or ""
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        address = None
    if address is not None:
        kind = ("link-local" if address.is_link_local else "loopback" if address.is_loopback
                else "private" if address.is_private else "public")
        return False, f"an address ({kind}), not a name on the allow-list"
    if host not in ALLOWED_HOSTS:
        return False, "the host is not on the allow-list"
    try:
        port = parts.port
    except ValueError:
        return False, "the port is not a number"
    if port not in (None, 443):
        return False, "only port 443 is allowed"
    return True, "ok"

urlsplit takes a URL apart, and .hostname is the host in lower case, without a user name or a port. The order matters: only https, then no address of any kind, then the host must be on the allow-list, then the port. An allow-list of names is stronger than a list of forbidden addresses, because there are many ways to write 169.254.169.254 and only one way to be covers.example.com. The file also refuses every redirect, with a small class NoRedirect: an allowed host must not be able to send the fetch somewhere else. Open the block and save the file.

The finished file: safe_fetch.py

safe_fetch.py

"""safe_fetch.py: fetch a URL for a customer without becoming a door to the inside.

    python3 safe_fetch.py URL            fetch one URL, or say why not
    python3 safe_fetch.py --list FILE    judge every URL of a file, without any network traffic
"""
import ipaddress
import sys
import urllib.error
import urllib.request
from urllib.parse import urlsplit

ALLOWED_HOSTS = {"covers.example.com"}  # the only place that cover pictures come from


def check_url(url):
    """Return (True, "ok") or (False, reason). This function sends nothing: it only reads the text of the URL."""
    parts = urlsplit(url)
    if parts.scheme != "https":
        return False, "only https is allowed"
    host = parts.hostname or ""
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        address = None
    if address is not None:
        kind = ("link-local" if address.is_link_local else "loopback" if address.is_loopback
                else "private" if address.is_private else "public")
        return False, f"an address ({kind}), not a name on the allow-list"
    if host not in ALLOWED_HOSTS:
        return False, "the host is not on the allow-list"
    try:
        port = parts.port
    except ValueError:
        return False, "the port is not a number"
    if port not in (None, 443):
        return False, "only port 443 is allowed"
    return True, "ok"


class NoRedirect(urllib.request.HTTPRedirectHandler):
    """Refuse every redirect: an allowed host must not send us somewhere else."""

    def redirect_request(self, *args, **kwargs):
        return None


def safe_fetch(url):
    ok, reason = check_url(url)
    if not ok:
        return 0, "refused: " + reason
    opener = urllib.request.build_opener(NoRedirect)
    try:
        with opener.open(url, timeout=3) as answer:
            return answer.status, answer.read(600).decode(errors="replace")
    except urllib.error.HTTPError as err:
        return err.code, "refused: the host answered with a redirect or an error"
    except OSError as err:
        return 0, f"no answer: {err}"


if __name__ == "__main__":
    if sys.argv[1] == "--list":
        with open(sys.argv[2]) as src:
            urls = [line.strip() for line in src if line.strip()]
        results = [(url, *check_url(url)) for url in urls]
        for url, ok, reason in results:
            print(f"{'allow ' if ok else 'refuse'} {url}  ({reason})")
        print(f"{sum(ok for _, ok, _ in results)} allowed, {sum(not ok for _, ok, _ in results)} refused")
    else:
        status, text = safe_fetch(sys.argv[1])
        print(status)
        print(text.strip())
python3 safe_fetch.py http://127.0.0.1:8700/latest/meta-data/iam/security-credentials/web-app-role
python3 safe_fetch.py https://169.254.169.254/latest/meta-data/
0
refused: only https is allowed
0
refused: an address (link-local), not a name on the allow-list

Status 0 means that nothing was sent.

Your turn

A tester gives you a list of fourteen URLs that the feature must judge. Save it as urls.txt, and run safe_fetch.py --list urls.txt: this mode judges each URL with check_url and sends nothing. For every URL that is allowed, decide whether that is right, and what else in safe_fetch.py protects you.

urls.txt

https://covers.example.com/9781234567897.png
http://covers.example.com/9781234567897.png
http://169.254.169.254/latest/meta-data/iam/security-credentials/
https://169.254.169.254/latest/meta-data/
http://[fd00:ec2::254]/latest/meta-data/
https://2852039166/latest/meta-data/
https://covers.example.com@169.254.169.254/latest/meta-data/
https://covers.example.com.attacker.example/a.png
https://127.0.0.1:8700/latest/meta-data/
https://COVERS.example.com/b.png
https://covers.example.com:8443/b.png
file:///etc/passwd
https://10.20.21.10:5432/
https://covers.example.com/redirect?to=http://169.254.169.254/latest/meta-data/

Then test the mock service, which still runs with required: ask for a token with a lifetime of 30000 seconds, and send a GET with no token. curl -s -o /dev/null -w "%{http_code}\n" prints only the status code of an answer. When you have your answers, stop the service with kill $(cat imds.pid).

Check yourself

The list holds https://covers.example.com/redirect?to=http://169.254.169.254/... and check_url allows it. Is the feature unsafe?

Not through check_url alone, and that is the point of the second guard. The host is the allowed one, so the URL passes. If that host answers with a redirect to the metadata address, a fetch that follows redirects would go there. safe_fetch refuses every redirect, so the fetch ends at the allowed host.

Why does IMDSv2 stop most SSRF flaws although the service is still reachable from the machine?

Most such flaws let the attacker choose a URL for a GET. To use IMDSv2, the caller must first send a PUT and then add a header with the token to each GET. A flaw that controls only the URL can do neither. A flaw that lets the attacker choose the method and the headers still works, so the application must be fixed as well.

A developer proposes a deny-list: refuse URLs that contain 169.254.169.254. Why is that weak?

The same address can be written as one decimal number, in hexadecimal, as an IPv6 address, or behind a host name that the attacker controls and that resolves to it. A deny-list must know every form. An allow-list of the few hosts that the feature needs has nothing to forget.

Field notes

  • Set HttpTokens to required for every machine and as the default of the account, and find the machines that still accept IMDSv1. The EC2 metric MetadataNoToken in CloudWatch counts calls without a token, so you can see which programs still use the old way before you switch.
  • Give the role of a web server the smallest policy that its task needs (lesson 3). Stolen credentials can do what the role can do, and nothing more.
  • The name-based allow-list of this lesson does not protect against a name that resolves to an internal address later. For a full defence, resolve the name once, check the address, and connect to that address. "Web applications and APIs", lesson 6, names this defence in its Field notes.
  • Containers on a machine can reach the metadata service of the machine too. The hop limit of 1 exists to stop that path, and it is why some container set-ups ask for a hop limit of 2. Decide that on purpose.
  • Credentials of a role that are used from an address outside the cloud are a strong signal. GuardDuty has findings for it, and you can deny it with a condition on the network that the request comes from.