--- name: hunt-apikey-leak description: API key/secret detection — JS bundles, source code, config files, error messages, backup files. Must demonstrate sensitive capability impact. --- # API KEY LEAK HUNTING — 3 BULLETS MAX **Core:** Exposed keys are only vulnerabilities if they provide sensitive capability. ## DETECTION ```bash # JS bundles katana -u target.com -d 3 -jc | grep "\.js$" | xargs -I{} curl -s {} | grep -oiE "(api[_-]?key|secret|token|password|authorization|bearer|oauth|jwt|private[_-]?key)['\"]?\s*[:=]\s*['\"][^'\"]+['\"]" # Config files for f in .env config.yml config.json docker-compose.yml .git/config .htaccess web.config; do curl -s "https://target.com/$f" | head -5 done # Source code leaks curl -s "https://target.com/.git/HEAD" # Git repo exposed curl -s "https://target.com/.env" | grep -iE "key|secret|token|password" # Error messages curl -s "https://target.com/api/error" | grep -iE "key|token|secret|password" # Backup files for f in backup.zip source.zip db.sql database.sql dump.sql; do code=$(curl -s -o /dev/null -w "%{http_code}" "https://target.com/$f") [ "$code" != "404" ] && echo "[+] $f → $code" done ``` ## IMPACT ASSESSMENT ``` AWS key → test: aws sts get-caller-identity → Critical if admin Stripe key → test: create $0.10 charge → Critical if production SendGrid key → test: send email → High GitHub token → test: list repos → High if private repos Database URL → connect to DB → Critical JWT secret → forge tokens → Critical OAuth client_secret → impersonate app → High ``` ## CHAINS ``` API key → cloud access → infrastructure compromise → Critical OAuth secret → impersonate app → ATO → Critical JWT secret → forge admin tokens → Critical Database URL → mass data exfil → Critical ``` ## WHERE KEYS HIDE - **JS bundles and source maps**: grep shipped assets for key-shaped strings (`AKIA`, `sk_live`, `ghp_`, `xox`, `AIza`, JWT-shaped blobs); source maps hand you the original source the key was pasted into. - **Mobile apps**: APK/IPA strings, `google-services.json`, `GoogleService-Info.plist`, embedded config plists — decompile only the operator's copy of a public app, within program rules. - **Git history**: the key was "removed" in a later commit — history still serves it. TruffleHog/gitleaks over full history, not HEAD. - **Error surfaces**: stack traces and debug pages echoing env, CI logs linked from public repos, Postman collections, public gists, support attachments, Wayback copies of config files (`.env`, `config.json`) that are 404 today. - **Referer leakage**: keys in URLs (analytics, map tiles, signed links) leak to every third-party origin the page loads. ## IDENTIFY BEFORE YOU TOUCH Classify the key before any validation call: provider (AWS, Stripe, GitHub, Slack, SendGrid, cloud service accounts), type (publishable vs secret — Stripe `pk_` is public by design; `sk_` is not), and likely scope. **Public-by-design keys are not findings**: Firebase API keys, Google Maps keys, and publishable keys ship in clients intentionally. They become findings only when the *restrictions* are missing — a Maps key with no referer/API restriction usable for paid APIs from your own test page, a Firebase key whose database rules allow unauthenticated read/write (prove with your own canary document, delete it after). ## VALIDATION DISCIPLINE One minimum-privilege proof call, nothing more: - Read-only identity endpoints only (`sts:GetCallerIdentity`, `/v1/me`, token info/introspection). Never list real resources, never read data, never make a write, never test "what else it can do" against the live account. - For cloud keys, the identity call *is* the impact proof: account id + principal name in the report, redacted in screenshots beyond the last few characters. - If no safe validation endpoint exists, report the exposure with the key's location and type and say validation was deliberately not attempted — triagers accept this; they do not accept exploration. - Never use a leaked key from a *different* program's scope, and never retain keys after the report: delete local copies, say so in the report. ## IMPACT FRAMING AND REMEDIATION NOTES Impact scales with scope: a read-only analytics key is low; a cloud root or CI token is critical because it mints everything else. Strong reports add the remediation the maintainer actually needs: revoke/rotate (history means the key is burned even if deleted from HEAD), move to a secrets manager / short-lived OIDC credentials, add server-side restrictions, and add secret-scanning to CI so the class dies permanently. ## FALSE-POSITIVE TRAPS - Example/placeholder keys from docs and tutorials (`AKIAIOSFODNN7EXAMPLE` is AWS's own documentation example). - Test/sandbox keys (`sk_test`, staging projects) — check the environment the key authenticates to before claiming production impact. - Keys belonging to the *user's own browser extensions* in captured traffic, not the target's assets. ## REPORTING CHECKLIST - [ ] Exact location (URL/file/commit) and how the key was found - [ ] Provider, type, and environment (prod vs test) established - [ ] At most one read-only identity validation call, request/response kept - [ ] Public-by-design keys claimed only via missing restrictions, proven safely - [ ] Key redacted in the report except trailing characters needed to identify it - [ ] Rotation + history-purge remediation included; local copies deleted --- ## METHOD — SWEEP SYSTEMATICALLY, VALIDATE MINIMALLY Leak hunting is a coverage problem, not a luck problem. Work the surfaces in a fixed order and log a negative for each, so the report (and your own notes) show what was actually swept: 1. **Shipped client code:** JS bundles + source maps, mobile binaries, desktop app resources. Pattern-scan first, entropy-scan second. 2. **Exposed files on the origin:** config, backup, and VCS paths (table below), including per-subdomain — staging and admin hosts leak what production hides. 3. **History:** git history of public repos, Wayback snapshots of config paths, old app versions (last year's APK predates the rotation). 4. **Third-party surfaces:** public Postman workspaces, gists, CI artifacts, npm/PyPI packages published by the org, Docker image layers (`docker history` / layer tarballs carry build-time env). 5. **Live error/debug surface:** debug pages, verbose error handlers, GraphQL error extensions, health/config endpoints that echo env. Tooling: `gitleaks`/`trufflehog` for repos and history (trufflehog's verified mode makes live calls — read the validation discipline below before enabling it), `grep -E` with the prefix table for bundles, and source-map rebuilders (`source-map-explorer`, `shuji`) to recover the original tree a key was pasted into. ## KEY TAXONOMY — RECOGNIZE THE SHAPE, KNOW THE BLAST RADIUS | Shape | Owner | Default blast radius | | --- | --- | --- | | `AKIA…` / `ASIA…` | AWS access key / session key | Whatever the IAM principal holds — identity call first | | Service-account JSON (`"type":"service_account"`, PEM inside) | GCP | Project-level API access; often broad by default | | `ghp_` / `gho_` / `github_pat_` | GitHub PAT (classic / OAuth / fine-grained) | Classic: broad scopes; fine-grained: per-repo — read the scope, don't assume | | `xoxb-` / `xoxp-` / `xapp-` | Slack bot / user / app token | Workspace messages/files within the token's channels | | `sk_live_` / `rk_live_` | Stripe secret / *restricted* key | `sk_`: full API incl. payouts path; `rk_`: only its granted endpoints — enumerate by the key info endpoint, not by trying charges | | `SG.` | SendGrid | Mail send + often stats/lists | | `SK…` + account SID | Twilio | Messaging/voice spend, number inventory | | PEM block (`BEGIN … PRIVATE KEY`) | SSH/TLS/JWT signing | Whatever it signs/opens — JWT signing keys forge sessions; SSH keys are host access | | `postgres://` `mysql://` `mongodb+srv://` with password | Database URL | Direct data access if network-reachable; test reachability, never dump | | Long base64/hex beside `secret`, `hmac`, `signing` | Webhook/JWT shared secret | Forgery of webhooks or tokens for that one integration | Entropy alone is a weak signal (minified bundles are full of random- looking strings). A prefix match *plus* a plausible assignment context (`apiKey:`, env name, provider SDK import in the same file) is what makes a candidate worth the single validation call. ## EXPOSED-FILE TABLE — THE PATHS THAT ACTUALLY PAY ``` .git/HEAD .git/config .git/logs/HEAD → full repo recovery (git-dumper) — history included .env .env.local .env.production .env.bak .env~ .env.save .env.old config.json config.yml application.yml appsettings.json web.config .svn/entries .DS_Store → directory listing oracle backup.zip app.zip www.zip .zip db.sql dump.sql .sql.gz docker-compose.yml .gitlab-ci.yml → env values inline, or the secret names to hunt elsewhere ``` Rules: a 200 on a *backup of source* is a source disclosure finding on its own; the keys inside it are separate findings only if validated. Soft-404s (200 with the SPA shell) are the top false positive here — compare body hashes against a known-missing path before claiming any of these. ## WORKED EXAMPLE — SOURCE MAP TO KEY TO IDENTITY ``` 1. app.js references //# sourceMappingURL=app.js.map (200, 4 MB) 2. Rebuild sources → src/config.ts contains: export const analytics = { key: "SG.k7…" } (SendGrid-shaped, assigned, in source) 3. Classification: SendGrid API key, production context (file also holds the prod API base URL) 4. ONE validation call: GET https://api.sendgrid.com/v3/scopes with the key → 200, scopes include mail.send 5. Report: location (bundle URL + source path), provider, scopes observed, key redacted to last 4. No email sent. Key deleted locally. ``` The scopes endpoint is the proof — sending a test email "to confirm" is a write against a production system and turns a clean report into an incident. ## WORKED EXAMPLE — PUBLIC-BY-DESIGN KEY, REAL FINDING (FIREBASE) A Firebase config in a web app is expected. The finding is the rules: ``` GET https://.firebaseio.com/.json → 200 with data = world-readable DB (stop; screenshot the shape, read nothing personal) PUT a canary document {canary: "hunter-test-2026"} to your own test path → 200 = world-writable DELETE the canary → cleanup confirmed ``` Prove with a canary you created, delete it, and report the rules posture — never browse the existing data to "show impact". ## SCOPED AND RESTRICTED KEYS — DON'T OVER- OR UNDER-CLAIM - **Restricted keys (Stripe `rk_`, fine-grained PATs, scoped cloud tokens):** the scope *is* the severity. Use the provider's own metadata/introspection to state the granted scope; a restricted key that can only read charges is not "full Stripe access". - **Publishable vs secret pairs shipped together:** finding the `pk_` is noise; finding its `sk_` sibling in the same bundle is the report. Check pairs, not singles. - **Short-lived tokens in URLs/logs:** CI job tokens, signed URLs, and session tokens in analytics payloads expire — record the TTL you observed; an expired token is a hygiene note, not a leak finding. - **Revocation check:** if the program responds "rotated", a re-test of the identity endpoint returning 401 closes the loop and is worth reporting back — it converts your finding into a verified fix. ## FALSE-POSITIVE TRAPS — ADDITIONS - Keys in *your own* request captures that belong to browser extensions or the proxy tool itself. - High-entropy strings that are asset hashes, integrity digests (`integrity="sha384-…"`), or encrypted blobs with no key in scope. - A `.env` that returns the SPA index page (soft 404) — hash-compare before claiming, every time. - Dead keys: identity call returns 401. Report as "exposed, already revoked" informational only if the program wants hygiene reports; otherwise drop it and keep hunting. ## REPORTING CHECKLIST — ADDITIONS - [ ] Surfaces swept listed, with negatives (bundles, files, history, third-party) - [ ] Key shape matched to the taxonomy table; assignment context quoted - [ ] Scope stated from the provider's metadata endpoint, not from attempted operations - [ ] Soft-404 check done for every exposed-file claim (body hash vs known-missing path) - [ ] Canary-only proof for open databases/storage; canary deleted, deletion confirmed - [ ] Fix verification offered: post-rotation 401 re-test result included when available