What Are Race Condition Vulnerabilities?
Race conditions occur when the behavior of software depends on the timing or sequence of uncontrollable events. In web applications, this happens when multiple requests manipulate shared state concurrently, leading to outcomes the developer never intended.
The classic example: a user with $100 sends two simultaneous $100 withdrawal requests. Without proper concurrency controls, both requests read the balance as $100, both approve, and the user extracts $200.
Types of Web Race Conditions
Time-of-Check to Time-of-Use (TOCTOU)
The most common pattern. A condition is checked at one moment, but the state changes before the result is used:
Thread 1: Check balance ($100) -> Balance >= $100? Yes
Thread 2: Check balance ($100) -> Balance >= $100? Yes
Thread 1: Deduct $100 -> Balance = $0
Thread 2: Deduct $100 -> Balance = -$100 (should have been blocked)
Limit Bypass
Attackers exceed rate limits, coupon usage limits, or vote counts:
# Vulnerable coupon redemption
def redeem_coupon(user_id, code):
coupon = db.find(code=code)
if coupon.uses < coupon.max_uses: # Check
apply_discount(user_id)
coupon.uses += 1 # Use (gap between check and use)
coupon.save()
Double-Spend
Financial transactions processed twice due to concurrent requests:
- Cryptocurrency exchanges
- Payment processing
- Loyalty point redemptions
- Gift card balance transfers
Exploitation Techniques
Single-Packet Attack
Send multiple HTTP requests in a single TCP packet to ensure they arrive simultaneously:
import socket
# Craft multiple HTTP requests
requests = [build_request() for _ in range(20)]
payload = b"".join(requests)
# Send as single TCP segment
sock = socket.create_connection(("target.com", 443))
sock.sendall(payload)
HTTP/2 Single-Connection
HTTP/2 multiplexing enables true parallel requests over one connection:
# Using h2 library for HTTP/2 multiplexing
for i in range(20):
conn.send_headers(stream_id=i*2+1, headers=headers)
conn.send_data(stream_id=i*2+1, data=body)
# All requests sent simultaneously on one connection
Last-Byte Synchronization
For HTTP/1.1, send all requests except the last byte, then complete them simultaneously to synchronize arrival at the server.
Real-World Impact
- E-commerce: Apply a single-use discount code multiple times
- Banking: Overdraw account balances
- Voting: Submit multiple votes in polls
- File uploads: Overwrite files during concurrent access
- User registration: Create duplicate accounts bypassing uniqueness checks
Prevention Strategies
1. Database-Level Locking
-- Pessimistic locking
SELECT * FROM accounts WHERE id = 123 FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 123;
2. Atomic Operations
# Instead of read-modify-write:
result = db.accounts.update_one(
{"_id": user_id, "balance": {"$gte": 100}},
{"$inc": {"balance": -100}}
)
if result.modified_count == 0:
raise InsufficientFunds()
3. Idempotency Keys
@app.post("/api/transfer")
def transfer(request):
idempotency_key = request.headers.get("Idempotency-Key")
if db.processed_keys.find_one({"key": idempotency_key}):
return existing_response # Already processed
# Process and store key atomically
4. Distributed Locks
For microservice architectures, use Redis-based distributed locks:
lock = redis.lock(f"transfer:{user_id}", timeout=10)
if lock.acquire():
try:
process_transfer()
finally:
lock.release()
Testing with SuperClue
SuperClue's race condition module sends concurrent requests to state-changing endpoints and flags cases where every request succeeds, a common sign of double-spend or duplicate-resource bugs.