A saved basket that ran a program
Insecure deserialisation is when a program rebuilds objects from bytes a visitor sent, and the rebuilding itself runs code the visitor chose. It can hand an attacker the whole server.
A shop keeps your basket in a cookie as a saved object, so it survives a restart. Someone edits the cookie. When the shop loads the basket back, it runs a command instead.
The one rule
Warning
This lab is a website 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 replace an unsafe deserialiser with a signed, data-only format.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsKey words
| Word | What it means | Example |
|---|---|---|
| Serialisation | turning an object into bytes to store or send | |
| Deserialisation | rebuilding the object from those bytes | |
| Gadget | existing code a crafted object makes run while loading | |
| Magic bytes | the first bytes that name a format | ac ed 00 05 |
| Base64 | a way to write bytes as plain letters | rO0AB |
| HMAC | a signature made with a secret key that shows data was not changed |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsLoading an object can run code
Formats such as Java serialisation, Python's pickle and PHP's serialize store which class an object is, and rebuild it by calling that class's code.
So the bytes choose the code. A crafted object can name classes already in the program, called gadgets, whose loading steps chain into running a command. Checking the object afterwards is too late: the code ran while it loaded.
A pickle that runs code as it loads
import pickle
class Note:
def __reduce__(self):
# Whatever this returns is called while the bytes are loaded.
return (print, ("this ran while loading, before any check",))
blob = pickle.dumps(Note())
print(blob[:2])
# Change the message above and press Run. Nothing below calls print.
pickle.loads(blob)
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsWorked example: spotting a format by its start
| Format | First bytes | In base64 it starts | Can run code on load? |
|---|---|---|---|
| Java serialisation | ac ed 00 05 | rO0AB | Yes, through gadgets |
| Python pickle (protocol 4) | 80 04 95 | gASV | Yes, by design |
| PHP serialize | O:4:"User" | Tzo0 | Yes, through magic methods |
| JSON | {" | eyJ | No, data only |
The cells students fill in are left blank in this preview.
Decode WebGoat's sample token
Your lab runs WebGoat. Its Insecure Deserialization lesson shows a sample token, a Java object written in base64. Start the lab, then make an account and sign in with the first two Runs. The third copies the token from the lesson page. The fourth decodes it and prints the first four bytes in hexadecimal. The fifth prints the rest as text.
Make an account in your copy
curl -s -c goat -d "username=leelab1&password=labpass1&matchingPassword=labpass1&agree=agree" -o /dev/null -w "%{http_code}\n" http://web/WebGoat/register.mvcShown here, not run. Press Start lab to type it into your own lab’s terminal.
Sign in and keep the session
curl -s -b goat -c goat -d "username=leelab1&password=labpass1" -o /dev/null -w "%{http_code} %{redirect_url}\n" http://web/WebGoat/loginShown here, not run. Press Start lab to type it into your own lab’s terminal.
The sample token on the lesson page
curl -s -b goat http://web/WebGoat/InsecureDeserialization.lesson | grep -o "rO0[A-Za-z0-9+/=]*"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Its first four bytes
curl -s -b goat http://web/WebGoat/InsecureDeserialization.lesson | grep -o "rO0[A-Za-z0-9+/=]*" | base64 -d | head -c 4 | od -A n -t x1Shown here, not run. Press Start lab to type it into your own lab’s terminal.
The rest, as text
curl -s -b goat http://web/WebGoat/InsecureDeserialization.lesson | grep -o "rO0[A-Za-z0-9+/=]*" | base64 -d | tail -c +8; echoShown here, not run. Press Start lab to type it into your own lab’s terminal.
What the answers tell you
The token starts rO0ABXQAVk, the base64 form of Java's magic bytes. The fourth Run prints ac ed 00 05: Java serialisation, version 5. The fifth prints a sentence: the object is a plain Java string.
This one is harmless. The point is that a token starting rO0 reaches a Java deserialiser on the server, and anyone can send a different one.
A common mistake
Warning
Many people think base64 or encryption makes a serialised cookie safe. Base64 is only spelling; anyone decodes it. Encryption without a signature can still be tampered with. The fix is to stop deserialising objects from visitors at all, and to sign whatever data you do send.
The fix: data only, and signed
Send data, not objects. JSON holds strings, numbers, lists and dictionaries and never names a class, so loading it runs nothing.
If the data must come back unchanged, sign it with an HMAC and a key only the server holds. Check the signature before reading anything. Where an old format cannot go yet, allow only a short list of classes in the deserialiser, as Java's serialisation filters do.
JSON with a signature
import hashlib
import hmac
import json
KEY = b"server-only-key"
body = json.dumps({"basket": ["pen", "ruler"]})
mac = hmac.new(KEY, body.encode(), hashlib.sha256).hexdigest()
# Change "ruler" to "laptop" in arrived, keep the old mac, and press Run.
arrived = '{"basket": ["pen", "ruler"]}'
good = hmac.new(KEY, arrived.encode(), hashlib.sha256).hexdigest()
if hmac.compare_digest(mac, good):
print("signature good:", json.loads(arrived))
else:
print("refused: the data was changed")
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsHow to detect deserialisation attacks
Search requests and cookies for the starts in the table: rO0AB, ac ed 00 05, gASV, O: followed by a number. Alert where an endpoint that expects JSON receives one.
On the server, log every class a deserialisation filter refuses. Watch for a web process starting a shell or making an unusual connection. Keep libraries patched, since gadgets live in them.
Assignment: signed tokens and format spotting
Write three functions. make_token(data, key) turns a dictionary into JSON with sorted keys, writes it in URL-safe base64, and adds "." and the HMAC-SHA256 of that base64 text in hexadecimal. read_token(token, key) returns the dictionary only if the token has exactly one dot and its HMAC matches, using hmac.compare_digest; otherwise it returns None. looks_serialised(text) returns "java" for text starting rO0, "pickle" for gASV, "php" for O: followed by a digit, and "" for anything else.
import base64
import hashlib
import hmac
import json
def make_token(data, key):
# JSON, then URL-safe base64, then "." and the HMAC-SHA256 of that text in hex.
return base64.urlsafe_b64encode(json.dumps(data, sort_keys=True).encode()).decode()
def read_token(token, key):
# Return the data only if the HMAC matches. Otherwise return None.
body = token.split(".")[0]
return json.loads(base64.urlsafe_b64decode(body.encode()))
def looks_serialised(text):
# Return "java", "pickle", "php" or "".
return ""
Make a free account to save your work and track your progress.
Exit quiz
Have a go