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

Free lesson

Insecure deserialisation and safe data formats

After this lesson: I can replace an unsafe deserialiser with a signed, data-only format.

55 min lesson5 commandsWebGoat lab: guided web security lessons with WebWolf 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 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 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
Serialisationturning an object into bytes to store or send
Deserialisationrebuilding the object from those bytes
Gadgetexisting code a crafted object makes run while loading
Magic bytesthe first bytes that name a formatac ed 00 05
Base64a way to write bytes as plain lettersrO0AB
HMACa 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 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

Loading 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

Code: python
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 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

Worked example: spotting a format by its start

FormatFirst bytesIn base64 it startsCan run code on load?
Java serialisationac ed 00 05rO0ABYes, through gadgets
Python pickle (protocol 4)80 04 95gASVYes, by design
PHP serializeO:4:"User"Tzo0Yes, through magic methods
JSON{"eyJNo, 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

Command
curl -s -c goat -d "username=leelab1&password=labpass1&matchingPassword=labpass1&agree=agree" -o /dev/null -w "%{http_code}\n" http://web/WebGoat/register.mvc

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

Sign in and keep the session

Command
curl -s -b goat -c goat -d "username=leelab1&password=labpass1" -o /dev/null -w "%{http_code} %{redirect_url}\n" http://web/WebGoat/login

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

The sample token on the lesson page

Command
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

Command
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 x1

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

The rest, as text

Command
curl -s -b goat http://web/WebGoat/InsecureDeserialization.lesson | grep -o "rO0[A-Za-z0-9+/=]*" | base64 -d | tail -c +8; echo

Shown 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

Code: python
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 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 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.

Code: python
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

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.