--- name: sh-kb-secrets description: "Knowledge base for finding hardcoded secrets and sensitive-data exposure - API keys, passwords, tokens, private keys, and connection strings embedded in source/config/CI/IaC/client bundles/git history, or secrets leaked to logs/errors/URLs. Use when hunting secret exposure. CWE-798/259/312/532, OWASP A05/A02:2021." --- # Hardcoded Secrets & Sensitive Exposure - Hunter Knowledge Base Credentials embedded in code/config or leaked through logs, errors, or client-visible responses. High value: a single leaked key can defeat every other control. In this KB never reproduce a real credential: mask values in notes and reports (`AKIA****`, ``). ## What to hunt - **Hardcoded credentials** (CWE-798/259): API keys, passwords, tokens, private keys, DB connection strings, cloud keys committed in source, config, Dockerfiles, CI files, IaC, or client bundles. - **Secrets in client-shipped code**: keys in frontend JS/mobile apps (extractable by anyone). Server secrets placed in client-exposed env prefixes (`NEXT_PUBLIC_*`, `VITE_*`, `REACT_APP_*`), secrets in source maps, server props serialized into the page (Next `getServerSideProps` returning a whole config). - **CI and build config**: `.github/workflows/*.yml`, `.gitlab-ci.yml`, `Jenkinsfile`, `.circleci/`, with literal tokens in `env:`/`variables:`; Dockerfile `ENV`/`ARG` (persist in image layers and history). - **IaC and deployment**: Terraform `*.tfvars` and committed `terraform.tfstate` (state holds plaintext secrets), Helm `values.yaml`, `docker-compose.yml`, Ansible vars without vault, Kubernetes `Secret` manifests (base64 is encoding, not protection), `kubeconfig` files. - **Tool credential files**: `.env` committed, `.npmrc` (`_authToken`), `.pypirc`, `.netrc`, `.git-credentials`, `.aws/credentials`, `.docker/config.json`, service-account JSON (`"type": "service_account"`, `"private_key"`), Rails `config/master.key`, Laravel `APP_KEY`, .NET `appsettings*.json`/`web.config` `machineKey`, Spring `application*.properties`, Django `SECRET_KEY`, Flask `secret_key`, JWT signing literals (`jwt.sign(x, 'secret')`). - **Secrets to logs/errors** (CWE-532): logging tokens, passwords, PII, `Authorization`/`Cookie` headers, full request bodies; verbose stack traces returned to users; debug endpoints (`phpinfo`, Spring actuator `/env` or `/heapdump`, Django `DEBUG=True` pages); `console.log(process.env)`; secrets in URLs (query strings get logged/cached/Referer-leaked); error trackers capturing request payloads. - **Weak storage** (CWE-312): sensitive data stored plaintext at rest; constant encryption keys/IVs in code. - **Default or shared credentials**: `admin/admin`, seeded accounts, one key reused across environments. ## Detection patterns (grep targets) - Assignment patterns: `password\s*[:=]`, `passwd`, `api[_-]?key`, `secret`, `token`, `access[_-]?key`, `client_secret`, `Authorization: Bearer `, `-----BEGIN (RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----`. - High-entropy string literals assigned to those names (not `os.environ[...]`/`process.env.*`/vault calls). - Provider prefixes: `AKIA`/`ASIA` (AWS), `AIza` (Google), `ghp_`/`gho_`/`ghs_`/`github_pat_` (GitHub), `glpat-` (GitLab), `sk_live_`/`rk_live_` (Stripe), `sk-` (OpenAI-style), `xox[baprs]-` (Slack), `SG.` (SendGrid), `npm_` (npm), `pypi-` (PyPI), `eyJ` (JWTs and base64 JSON), `-----BEGIN`. - Connection strings: `mongodb(\+srv)?://user:pass@`, `postgres://user:pass@`, `redis://:pass@`, `Data Source=...Password=`, `amqp://user:pass@`, URLs of the form `https://user:token@host`. - Log/error sinks with secrets: `logger.*(... token/password ...)`, `print(headers)`, returning exception detail to clients. ## Detection recipe 1. `graft grep "(api|secret|access|private)[_-]?(key|token)|password|BEGIN [A-Z ]*PRIVATE KEY|AKIA|ASIA|sk_live|xox[bp]-|ghp_|glpat-|github_pat_" --json` (and native Grep across config/CI/Docker/IaC/`.env` committed files, with ignore rules off so build and hidden directories are included). 2. Confirm the value is a real literal, not a placeholder (`changeme`, `xxx`, `example`) or an env lookup. 3. For client bundles, check what ships to the browser/app (built output, source maps, public env prefixes). 4. For logs/errors, trace whether secret/PII values reach log or client-facing error sinks. 5. Git history: `git log -p -S'' --all`, search deleted files (`--diff-filter=D`) and other branches; a value removed from HEAD is still exposed and must be rotated. 6. Check where else the same value is consumed (deploy config, CI, other services) to size the blast radius. ## PoC / evidence - The literal at `file:line` (mask the value in the report: `AKIA****`). For a live key, the "PoC" is demonstrating it authenticates - describe rather than actually using third-party creds without authorization. - For log leak: show the code path where the secret enters the log/response. - Real vs fake: correct provider prefix, length and charset; used by live config (referenced from a deploy or CI file, not only a test); not the vendor's documented example value (e.g. `AKIAIOSFODNN7EXAMPLE`). ## Variant hunting - Same secret copied elsewhere: Dockerfile, compose, CI, Helm, docs, notebooks (`.ipynb` outputs), Postman collections, `.vscode/launch.json`, backups (`.bak`, `.orig`), mobile `strings.xml`/`Info.plist`. - Sibling environments (staging/prod configs), other branches and tags, vendored or third-party directories. - One leaked key implies its siblings: other keys of the same provider in the same file, and the same secret-loading helper being bypassed by a hardcoded fallback (`os.getenv("KEY", "literal")`, `process.env.K || "literal"`). - Other log statements that dump the same object (`request`, `headers`, `config`, `user`). ## False-positive filters - Placeholders/examples/test fixtures/`*.example`; obviously fake values; documented vendor sample keys. - Values loaded from env/secret managers/vault (`os.environ`, `process.env`, AWS Secrets Manager, Vault, KMS). A **default literal fallback** on that lookup is still a finding if it looks real. - Public/publishable keys meant to be client-side (Stripe publishable `pk_`, OAuth client_id, public certs, Firebase web `apiKey`, Maps browser keys restricted by referrer) - note, but do not rate as secrets. - Non-secret high-entropy strings (UUIDs, checksums, hashes of public data, lockfile integrity values) - confirm meaning before flagging. Encrypted values (Ansible vault, sops, sealed secrets) are not plaintext leaks. ## CWE / OWASP / severity CWE-798/259 (hardcoded creds), CWE-312 (cleartext storage), CWE-532 (log exposure), CWE-522. OWASP A05:2021 (Misconfiguration) / A02:2021 (Cryptographic Failures). Live production credential -> **critical**; test/limited-scope or client publishable-by-design -> low/info. ## Chaining hints A leaked key is often the *first* link: DB creds -> full data access; cloud key -> infra takeover; JWT secret -> forge tokens (`auth`); CI token -> supply-chain write access; pairs with `path-traversal`/`sqli`/ `xxe` reads that surface config files. ## Detection signals (for defenders) - **Cloud audit logs** (AWS CloudTrail, Azure sign-in/activity logs, GCP Cloud Audit Logs; need principal or access key id, source IP, user agent, API name): a long-lived key used from an IP/ASN or user agent never seen for it; first calls being identity and enumeration APIs (`GetCallerIdentity`, `List*`/`Describe*` sweeps across many services); activity on a key right after a repo was made public or a leak was posted. - **Source-control and CI audit logs**: push events adding files matching secret patterns, repository visibility changes, secret-scanning alerts, CI jobs printing environment or fetching secrets then making outbound calls to unfamiliar hosts. - **Web/proxy logs**: probes for `/.env`, `/.git/config`, `/actuator/env`, `/config.json`, `*.map`, `phpinfo`; a 200 with a body of secret-like content is exposure. Credentials in URLs appear in access logs. - **Behavior-based ideas**: (1) per-credential baseline of source network and API set, alert on a new source combined with enumeration calls; (2) alert on any use of a credential that a scanner or rotation ticket flagged as exposed (honeytoken style: a decoy key that should never authenticate). - ATT&CK: T1552 Unsecured Credentials; T1552.001 Credentials In Files; T1552.004 Private Keys; T1078.004 Valid Accounts: Cloud Accounts (use of the leaked key); T1190 Exploit Public-Facing Application (exposed config endpoints). ## Mitigation Remove secrets from code; load from env/secret manager/vault; rotate any exposed secret (and purge from git history, but treat it as compromised regardless); never log secrets/PII (redact headers and bodies); return generic errors to clients; keep keys server-side and prefix-scoped env vars out of client builds; use short-lived credentials (OIDC federation in CI, instance roles); add pre-commit and CI secret scanning (gitleaks/trufflehog) and push protection to prevent recurrence.