A web page that handed over its keys
In 2019 an attacker made a bank's server fetch an address inside its own cloud machine. The answer was the machine's temporary cloud keys.
With those keys the attacker copied data about roughly 100 million people from storage buckets. No password was guessed.
The one rule
Warning
Every attack in this lesson is on a toy you run in your own lab, and nothing real is contacted. Trying it on a service you do not own needs written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can stop an SSRF from reaching a cloud machine's metadata service.
Key words
| Word | What it means | Example |
|---|---|---|
| Metadata service | an address a cloud machine asks about itself | 169.254.169.254 |
| Instance role | the role a cloud machine's programs use | |
| SSRF | making a server fetch an address the attacker picks | |
| IMDSv2 | the metadata service that wants a token first | |
| Egress rule | a rule about where traffic may go out to | |
| Link-local | an address that only works on the local network |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsA cloud machine asks for its keys
A virtual machine on AWS can ask the address 169.254.169.254 about itself. One answer is a set of temporary keys for its instance role.
That is on purpose: programs on the machine use those keys instead of a stored password. The address only answers from inside the machine.
SSRF turns your server into the asker
Advanced web attacks taught SSRF: a feature fetches an address the user gives, and the attacker gives an internal one.
On a cloud machine the worst internal address is the metadata service. The server asks it, gets the keys and shows them to the attacker.
Try it: internal or public?
import ipaddress
for text in ["169.254.169.254", "127.0.0.1", "10.0.0.5", "8.8.8.8"]:
address = ipaddress.ip_address(text)
inside = address.is_private or address.is_loopback or address.is_link_local
print(text, "internal" if inside else "public")
# Add "192.168.1.20" to the list. Which kind is it?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsA toy shop server with a link preview
shoplink.py runs two toys in one process. One plays the metadata service on 127.0.0.1:8169, in place of the real address, with made-up keys. The other is a link preview on port 8080 that fetches any address.
Its first word picks a mode: v1, v2 or guard. The second is the address you ask the preview to fetch.
Write the toy shop server, part 1
mkdir -p ~/cs && printf '%s\n' 'import ipaddress' 'import json' 'import socket' 'import sys' 'import threading' 'import urllib.error' 'import urllib.parse' 'import urllib.request' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' '' 'MODE = sys.argv[1]' 'ROLE = "shop-role"' 'CREDS = {"AccessKeyId": "TOY-KEY-0001", "SecretAccessKey": "toy-not-a-real-key", "Token": "toy-session-0001"}' 'TOKENS = set()' '' '' 'class Metadata(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def answer(self, code, text):' ' self.send_response(code)' ' self.end_headers()' ' self.wfile.write(text.encode())' '' ' def do_PUT(self):' ' if self.path == "/latest/api/token":' ' TOKENS.add("tok-1")' ' return self.answer(200, "tok-1")' ' self.answer(404, "not found")' '' ' def do_GET(self):' > ~/cs/shoplink.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the toy shop server, part 2
printf '%s\n' ' if MODE in ["v2", "guard"] and self.headers.get("X-aws-ec2-metadata-token") not in TOKENS:' ' return self.answer(401, "401 Unauthorized: a token is required")' ' base = "/latest/meta-data/iam/security-credentials/"' ' if self.path == base:' ' return self.answer(200, ROLE)' ' if self.path == base + ROLE:' ' return self.answer(200, json.dumps(CREDS))' ' self.answer(404, "not found")' '' '' 'def private(host):' ' try:' ' address = ipaddress.ip_address(socket.gethostbyname(host))' ' except OSError:' ' return True' ' return address.is_private or address.is_loopback or address.is_link_local' '' '' 'class Preview(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def do_GET(self):' ' url = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)["url"][0]' ' with open("preview.log", "a") as log:' >> ~/cs/shoplink.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the toy shop server, part 3
printf '%s\n' ' print("preview", url, file=log)' ' parts = urllib.parse.urlparse(url)' ' if MODE == "guard" and (not parts.scheme == "https" or private(parts.hostname)):' ' text, code = "refused: " + url + " is not a public https address", 403' ' else:' ' try:' ' text, code = urllib.request.urlopen(url, timeout=3).read().decode(), 200' ' except urllib.error.HTTPError as error:' ' text, code = error.read().decode(), 502' ' self.send_response(code)' ' self.end_headers()' ' self.wfile.write(text[:300].encode())' '' '' 'for server in [ThreadingHTTPServer(("127.0.0.1", 8169), Metadata), ThreadingHTTPServer(("127.0.0.1", 8080), Preview)]:' ' threading.Thread(target=server.serve_forever, daemon=True).start()' 'if sys.argv[2] == "as-instance":' ' put = urllib.request.Request("http://127.0.0.1:8169/latest/api/token", method="PUT")' >> ~/cs/shoplink.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the toy shop server, part 4
printf '%s\n' ' token = urllib.request.urlopen(put).read().decode()' ' get = urllib.request.Request("http://127.0.0.1:8169/latest/meta-data/iam/security-credentials/" + ROLE)' ' get.add_header("X-aws-ec2-metadata-token", token)' ' print("the instance itself, with a token:", json.loads(urllib.request.urlopen(get).read())["AccessKeyId"])' ' sys.exit(0)' 'asked = "http://127.0.0.1:8080/preview?url=" + urllib.parse.quote(sys.argv[2], safe="")' 'try:' ' print(urllib.request.urlopen(asked).read().decode())' 'except urllib.error.HTTPError as error:' ' print(error.code, error.read().decode())' >> ~/cs/shoplink.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask the preview for the role name
cd ~/cs && python3 shoplink.py v1 http://127.0.0.1:8169/latest/meta-data/iam/security-credentials/Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask the preview for the role's keys
cd ~/cs && python3 shoplink.py v1 http://127.0.0.1:8169/latest/meta-data/iam/security-credentials/shop-roleShown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask the preview for a stored invoice
cd ~/cs && python3 shoplink.py v1 http://cloud:4566/shop-invoices/2026/1042.txtShown here, not run. Press Start lab to type it into your own lab’s terminal.
What the preview fetched for you
| You asked for | It printed |
|---|---|
| security-credentials/ | shop-role |
| security-credentials/shop-role | {"AccessKeyId": "TOY-KEY-0001", ...} |
| an object in your stack | invoice 1042 |
The cells students fill in are left blank in this preview.
A common mistake
Warning
Many people think the metadata service is safe because the internet cannot reach it. It answers any program on the machine, and an SSRF makes your own server that program. Treat every fetch of a user's address as a request from inside.
Check
Have a go
Check
3 questionsFix one: a token from a PUT first
IMDSv2 answers only a request that carries a token, and the token comes from a PUT with a special header. An SSRF can usually make only a plain GET, so it gets 401.
The machine's own programs still work. On AWS, set HttpTokens to required and the hop limit to 1.
Attack v2, then ask as the machine
cd ~/cs && python3 shoplink.py v2 http://127.0.0.1:8169/latest/meta-data/iam/security-credentials/shop-role && python3 shoplink.py v2 as-instanceShown here, not run. Press Start lab to type it into your own lab’s terminal.
Fix two: refuse internal addresses going out
The preview should fetch only public https addresses. It looks the host up first and refuses a private, loopback or link-local answer.
Add an egress rule in the network too, so the app's machine or container cannot reach the metadata address at all. guard mode does both checks.
Try both addresses against the guarded preview
cd ~/cs && python3 shoplink.py guard http://127.0.0.1:8169/latest/meta-data/iam/security-credentials/shop-role && python3 shoplink.py guard http://cloud:4566/shop-invoices/2026/1042.txtShown here, not run. Press Start lab to type it into your own lab’s terminal.
Log every address the preview fetched
The preview writes each address it was asked for to preview.log. An alert on any internal address in it catches an attack, even a refused one.
On AWS, the MetadataNoToken metric counts v1 requests, and GuardDuty reports instance keys used outside AWS.
Find the metadata requests in the log
grep meta-data ~/cs/preview.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: a guard for fetched addresses
Write the checks that would have stopped the leak.
is_internal(text) is True for a private, loopback, link-local or reserved address. allowed_url(url, resolve) allows only https to a host that resolve, a dict of host name to address, maps to a public address. metadata_answer(method, path, token, tokens) gives the status a v2 metadata service answers: 401 without a known token, 405 for anything but GET, else 200.
import ipaddress
import urllib.parse
def is_internal(text):
# True for a private, loopback, link-local or reserved address.
return False
def allowed_url(url, resolve):
# Only https, and only a host that resolve maps to a public address.
# resolve is a dict of host name to address. A host not in it is refused.
return True
def metadata_answer(method, path, token, tokens):
# The status code a v2 metadata service gives: 200, 401 or 405.
return 200
Make a free account to save your work and track your progress.
Exit quiz
Have a go