Skip to main content
Insecure Deserialization & Race Conditions
Lesson 15 of 23

Insecure Deserialization & Race Conditions

Understand how untrusted object deserialization triggers lifecycle hooks and gadget chains before validation, how HTTP/2 single-packet bursts exploit TOCTOU race conditions, and how to enforce safe data formats and atomic database invariants.

Expert 36 min Web security
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain why native object deserializers execute attacker-controlled behaviour during object reconstruction before type checks run
  • Compare data-only serialization formats with object-graph formats across Python, PHP, and Java
  • Diagnose Time-of-Check to Time-of-Use (TOCTOU) race windows and explain how HTTP/2 single-packet delivery aligns concurrent requests
  • Remediate deserialization flaws with safe formats and HMAC integrity, and eliminate race conditions using atomic conditional updates and row locks

Recommended first: REST & GraphQL Security (OWASP API Security Top 10)Security Misconfiguration & OWASP Top 10 (2021/2025)

#Why this matters

Injection flaws corrupt a single query or template; insecure deserialization and race conditions subvert application state and execution flow. Insecure deserialization occurs when an application turns untrusted bytes back into live language objects, allowing lifecycle methods to run before any type check happens. Race conditions exploit sub-millisecond Time-of-Check to Time-of-Use (TOCTOU) windows between concurrent requests, letting an attacker redeem a one-time coupon multiple times or overdraw a balance.

Both classes often pass functional QA and basic vulnerability scanners because single sequential requests look completely normal.

#Insecure deserialization and gadget chains

Serialization converts an in-memory object into a storable byte stream; deserialization rebuilds it. Pure data formats such as JSON represent only primitive types (strings, numbers, booleans, arrays, maps). Native object serializers - including Python pickle, PHP serialize/unserialize, and Java ObjectInputStream - encode class names and reconstruct full object graphs.

Format or API Encodes arbitrary types Lifecycle hooks invoked on load Safe default for untrusted input
JSON (json.loads) No None Yes (with schema validation)
Python pickle.loads Yes __reduce__, __setstate__ No (unsafe by design)
PHP unserialize Yes __wakeup, __destruct, __toString No (unless allowed_classes => false)
Java ObjectInputStream Yes readObject, readResolve No (requires strict ObjectInputFilter)

The core misconception is believing an application can validate the object after deserializing it. In reality, hooks execute during reconstruction. Even if the caller immediately rejects the returned object with isinstance(), the hook has already run.

Attackers chain existing classes already present in the application or its dependencies - known as a gadget chain - so that deserializing a crafted stream triggers unintended calls across those classes. Below is a harmless Python lab demonstration showing how __reduce__ runs inside pickle.loads(), contrasted with safe JSON parsing:

python
import json
import pickle

class LabMarker:
    def __reduce__(self):
        # Harmless callable invoked immediately during pickle.loads()
        return (print, ("[LAB-MARKER] __reduce__ executed during deserialization",))

payload = pickle.dumps(LabMarker())
# Even without using the return value, pickle.loads() triggers print()
pickle.loads(payload)

# Safe alternative: data-only JSON with explicit field validation
raw = '{"theme": "dark", "page_size": 25}'
prefs = json.loads(raw)
if not isinstance(prefs.get("page_size"), int):
    raise ValueError("Invalid preference type")

Note that base64 encoding provides zero security - it only makes binary streams ASCII-safe for cookies or JSON fields.

#Race conditions and the single-packet attack

A TOCTOU race condition arises when a server checks a condition in one step and updates state in a separate step without locking or atomicity:

Double-spend TOCTOU window on a balance endpointDouble-spend TOCTOU window on a balance endpointRequest1DatabaseRequest2SELECT balance FROM wallets WHERE id = 7 (returns 100)SELECT balance FROM wallets WHERE id = 7 (returns 100)Both requests pass the balance >= 100 check before either updatesUPDATE wallets SET balance = 0 WHERE id = 7UPDATE wallets SET balance = 0 WHERE id = 7200 OK (order 1 shipped)200 OK (order 2 shipped)

Over HTTP/1.1, network jitter spreads consecutive requests across milliseconds, often missing tight server windows. With HTTP/2 multiplexing, tools like Burp Repeater implement the single-packet attack: they queue 10 to 20 complete requests (minus the final byte or frame), then transmit the final bytes together inside a single TCP segment. Because all requests arrive in the same network packet, the server dispatches them to worker threads within microseconds of one another.

When testing over local HTTP/1.1 in Python, asyncio with a pre-opened connection pool or barrier reduces client-side jitter:

python
import asyncio
import httpx

async def race_probe():
    url = "http://lab.local/api/redeem"
    payload = {"code": "LAB-ONCE-100"}
    async with httpx.AsyncClient(http2=True) as client:
        # Warm TLS/connection before bursting requests together
        await client.get("http://lab.local/health")
        tasks = [client.post(url, json=payload) for _ in range(10)]
        responses = await asyncio.gather(*tasks)
        print([r.status_code for r in responses])

#Defending and common mistakes

To eliminate insecure deserialization:

  • Use data-only formats: Standardize on JSON (or strictly typed Protobuf) and validate fields against an explicit schema (such as Pydantic or JSON Schema).
  • Keep state server-side: Store session objects in Redis or a database and send only an opaque random session ID to the client.
  • If serialized blobs must cross a trust boundary: Verify an HMAC-SHA256 tag over the exact payload using constant-time comparison before calling any parser.
  • Harden unavoidable native parsers: Configure yaml.safe_load instead of yaml.load, set allowed_classes => false in PHP unserialize(), and enforce strict ObjectInputFilter allow-lists in Java.

To eliminate web race conditions:

  1. Client requestsarrive concurrently via HTTP/2
  2. DB constraintUNIQUE key or idempotency token rejects duplicates
  3. Atomic UPDATEWHERE balance >= amount checks and mutates in one statement
  4. Row lockSELECT ... FOR UPDATE serializes multi-table workflows

Common implementation mistakes include:

  • Using in-process locks (threading.Lock) in web apps: Multi-worker servers (Gunicorn, Kubernetes replicas) do not share process memory, so locks must live in the database or a distributed lock manager.
  • Checking types after deserializing: Calling isinstance() after pickle.loads() or ObjectInputStream.readObject() is too late because lifecycle hooks run during parsing.
  • Ignoring affected_rows after an atomic UPDATE: An atomic UPDATE ... WHERE used = 0 only stops a race if the application checks that rowcount == 1 before issuing the reward.

#Summary

  • Native object deserializers (pickle, ObjectInputStream, unrestricted unserialize) execute lifecycle hooks during parsing, making them unsafe for untrusted data regardless of post-load type checks.
  • Replace native object serialization with schema-validated JSON, server-side session storage, or HMAC-authenticated payloads verified before parsing.
  • TOCTOU race conditions occur when precondition checks and state updates are separated; HTTP/2 single-packet bursts reliably trigger sub-millisecond windows.
  • Enforce concurrency invariants inside the database using atomic conditional updates, SELECT ... FOR UPDATE row locks, and UNIQUE idempotency constraints.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge