--- name: sh-kb-auth description: "Knowledge base for finding authentication and session-management failures - weak login, broken JWT/session handling, password/reset flaws, MFA bypass, credential storage issues. Use when hunting authentication (not authorization - see sh-kb-access-control). CWE-287/384/613/620/640, OWASP A07:2021-Identification and Authentication Failures." --- # Authentication & Session - Hunter Knowledge Base Failures in proving *who* the user is (vs `access-control`, which is *what* they may do). Covers login, sessions, tokens, password handling, and account recovery. ## What to hunt - **JWT flaws**: `alg:none` accepted; algorithm confusion (RS256 verified with the public key as an HMAC secret); signature not verified (`decode` without verify); secret hardcoded/weak (offline-brute-forceable); no `exp` check; trusting unverified claims for authz. **Header-parameter injection**: `kid` used to look up the verification key via a path (traversal to a predictable low-entropy file, e.g. `/dev/null` -> empty-string HMAC key) or a DB query (SQLi); `jwk` header lets the server verify against an attacker-embedded public key (attacker signs with the matching private key); `jku`/`x5u` header points to an attacker-hosted key set/certificate with no host allowlist. - **Session management**: session id not rotated after login (fixation, CWE-384); no server-side invalidation on logout; predictable/low-entropy tokens; missing `HttpOnly`/`Secure`/`SameSite`; overly long/absent expiry (CWE-613); session token in URL. - **Password handling**: plaintext or fast-hash storage (`md5`/`sha1`/unsalted) instead of bcrypt/scrypt/ argon2 (CWE-256/916); no rate limiting / lockout (credential stuffing, CWE-307); timing-unsafe comparison of secrets (`==` on tokens); lockout counter keyed by source IP instead of the account (trivially bypassed with distributed attempts) or a lockout with no path to self-recovery (usable as a DoS against a victim). - **Account recovery**: guessable/predictable reset tokens, reset token that doesn't expire or isn't single-use, host-header poisoning in reset links, user enumeration via differing responses (CWE-640). - **MFA**: verification step skippable, OTP not rate-limited/reusable, backup-code weaknesses. - **Broken "remember me"** / trust tokens; OAuth `state` missing (CSRF on login); redirect_uri not validated. - **OAuth/OIDC/SSO client side**: ID token accepted without checking `iss`, `aud`, `exp`, `nonce`; account linking or login by email claim without `email_verified`; matching users by email across providers (pre-account takeover); SAML assertion signature checked on the wrong element or not required; PKCE absent on public clients. - **API keys / service tokens**: long-lived, not hashed at rest, not scoped, compared with `==`, accepted in query strings (end up in logs), or an "internal" header (`X-Forwarded-User`, `X-Internal`) trusted from the client. - **Missing-check bugs (no sink to grep)**: a route or method never wrapped by the auth middleware; a second login path (mobile, legacy, `/api/v1`, SSO callback, magic link, impersonation/"login as") that skips MFA or lockout; password change or email change that does not require the current password or re-auth; reset flow that returns the token or a session in the response; sessions not revoked on password change/reset/MFA change. - **Stored/second-order**: attacker-registered username or email that later collides with a privileged identity (case, Unicode normalization, trailing space, `+` alias); invite/verification tokens reused across accounts. ## Sinks / patterns (grep targets) `jwt.decode(`/`verify(`, `algorithms=`, `verify=False`, `verify_signature`, `md5(`/`sha1(` near "password", `==` comparing tokens/HMACs (vs `hmac.compare_digest`/`crypto.timingSafeEqual`), `session[`, `set_cookie`, `SECRET_KEY`, `random`/`Math.random` for tokens, `password_reset`, `otp`, `login`, `authenticate`, JWT header parsing that reads `kid`/`jwk`/`jku`/`x5u` before signature verification. Guard APIs and their unsafe forms, by stack: - **Python**: PyJWT `jwt.decode(t, options={"verify_signature": False})` or missing `algorithms=[...]`; Django `check_password` fine but `User.objects.filter(password=...)`, `MD5PasswordHasher`/`UnsaltedSHA1` in `PASSWORD_HASHERS`; Flask `session` with a weak/default `SECRET_KEY`; `itsdangerous` tokens without `max_age`. - **JS/TS**: `jsonwebtoken` `jwt.decode()` used for authz (no verify), `verify` without `algorithms`, `ignoreExpiration: true`; `express-session` missing `regenerate()` on login, `cookie.secure` false; passport `done(null, user)` before checking the password; NextAuth `callbacks.signIn` returning true unconditionally. - **Java/Spring**: `NoOpPasswordEncoder`, `Jwts.parser().parse(` (unsigned accepted) vs `parseClaimsJws`; `sessionFixation().none()`; `permitAll` on `/actuator/**`; `==` on `String` secrets. - **Go**: `jwt.Parse` keyfunc that does not check `token.Method`; `bytes.Equal`/`==` on MACs vs `subtle.ConstantTimeCompare`. - **PHP/Laravel**: `md5(`/`sha1(` for passwords, `==` loose comparison on tokens/hashes (type juggling, `0e...` strings), missing `session()->regenerate()` after login, `Auth::loginUsingId` fed from request data. - **Ruby/Rails**: Devise `config.stretches` very low, `reset_password_within` very long, `secret_key_base` committed; `==` on tokens vs `ActiveSupport::SecurityUtils.secure_compare`. - **C#/ASP.NET**: `ValidateIssuer/Audience/Lifetime/IssuerSigningKey = false`, `RequireSignedTokens = false`, `SignatureValidator` that returns the token unvalidated; cookie `ExpireTimeSpan` huge with `SlidingExpiration`. ## Detection recipe 1. Find the login, logout, session-issue, password-store, and reset flows from `codebase-map.json`. 2. For JWT: check the verify call actually verifies signature + `exp` + expected `alg`, and the secret's source. 3. For sessions: is the id regenerated on privilege change/login? cookie flags set? entropy adequate? 4. For passwords: which hash + salt? is comparison constant-time? is there lockout/rate limiting? 5. For reset: token entropy, expiry, single-use, and whether the reset link host comes from a request header. 6. For every login-like path (SSO callback, magic link, mobile/legacy API, impersonation, token exchange), confirm it ends in the same session-issue code and the same MFA/lockout checks as the main login. 7. For every state-changing account action (password, email, MFA, API key), check re-authentication and that other sessions/tokens are revoked afterwards. 8. Verify the secret's origin: grep `SECRET_KEY|JWT_SECRET|secret\s*[:=]` in source, `.env.example`, config and Docker/compose files for a real-looking default that ships to production. ## Variant hunting Once one weak spot is found, grep the same helper across the code base: every caller of the unsafe `decode`, every other place `==` compares a secret, every other token generator using the same RNG, every other cookie set without the flags. Check sibling flows for the same flaw (password reset vs email-change vs invite vs magic link vs API-key rotation), the same flaw in a second service or language that shares the token format, and old API versions or mobile endpoints that kept the pre-fix logic. ## Payloads / PoC - JWT none: set header `{"alg":"none"}`, drop signature, change `sub`/`role`. Confusion: sign with RS256 public key as HMAC secret. Expired token still accepted -> no `exp` check. - JWT header injection: `kid` -> `../../../../dev/null` (then sign with empty-string HMAC key) or a SQLi string if `kid` feeds a key-lookup query; `jwk` -> attacker's own public key embedded in the header, token signed with the matching private key; `jku`/`x5u` -> attacker-controlled URL serving a malicious key set/certificate. - Fixation: set a session id pre-login, authenticate, check it's unchanged. - Reset poisoning: `POST /forgot` with `Host: attacker.com` -> link points to attacker. - Enumeration: compare responses/timing for known vs unknown usernames. ## False-positive filters - Vetted library with defaults (Django auth, Devise, Spring Security, NextAuth, Passport) used correctly. - JWT verified with the right algorithm+secret and `exp`/`nbf` enforced; secret from env/secret manager. - `kid` resolves only against a fixed in-memory/config map of known key ids (no path/DB use); `jwk` header ignored in favor of a pinned server-side key; `jku`/`x5u` restricted to a strict host allowlist. - Passwords via bcrypt/argon2/scrypt with per-user salt; constant-time compares for secrets. - Session id from a CSPRNG; cookie flags set; rotation on login present in middleware. - A "missing" lockout or MFA step that a gateway, WAF, or identity provider enforces upstream (confirm in config, not by assumption). `jwt.decode` without verify is fine only if the result never feeds an authz decision. - Real evidence of a finding: the verify/compare/regenerate call is absent or misconfigured on a path an anonymous request can reach, and you can state what forged or replayed input is accepted. Missing flags or enumeration alone are low-to-medium; do not inflate. - Lockout counter keyed by account (not just source IP) with a bounded exponential delay, and a working self-recovery path so lockout can't be used to lock out a victim. ## Detection signals (for defenders) - **Logs needed**: identity provider / auth service logs (username, outcome, reason, source IP, user agent, MFA result), web/proxy logs for login/reset/token routes, app session logs, cloud audit logs for console/API sign-ins. - **Credential attacks**: many failed logins across many usernames from one source or ASN, or many sources against one account; high failure rate followed by a success from the same source; success from a new device/geo right after a burst of failures; password-reset requests for many accounts; reset requests with a `Host` or `X-Forwarded-Host` that is not an allowed hostname. - **Token forgery**: valid-looking sessions or JWTs with an `alg` of `none` or unexpected, `kid`/`jku`/`jwk` values that are paths or external URLs, tokens whose subject or role never appears in a prior login event, tokens used after expiry, one token used from many IPs. - **Post-compromise**: password/email/MFA change followed by new sessions from a different source, MFA method added then immediate sensitive action, session created with no preceding authentication event. - **Behaviour detection ideas**: (1) login events grouped by source IP with distinct-username count over a window, joined to later success; (2) authenticated requests whose session/token id has no matching login event in the auth log (forged or replayed token). - **ATT&CK**: T1110 (Brute Force; sub-techniques .003 password spraying, .004 credential stuffing), T1078 (Valid Accounts), T1190 (Exploit Public-Facing Application) for auth-bypass flaws, T1550 (Use Alternate Authentication Material) for forged or stolen tokens, T1556 (Modify Authentication Process) for MFA/auth-flow tampering. ## CWE / OWASP / severity CWE-287/384/613/620/640/307/916. OWASP A07:2021. Auth bypass / token forgery -> **critical**; weak hashing or missing lockout -> high; missing cookie flags / enumeration -> medium. ## Chaining hints Weak session/JWT + `xss` or `open-redirect`/Referer leak -> token theft -> takeover; user enumeration + no lockout -> credential stuffing; reset-token flaw -> account takeover; `access-control` IDOR that leaks tokens feeds this. Auth bypass unlocks every authenticated finding. ## Mitigation Use a maintained auth framework; verify JWT signature+alg+exp (never `none`); pin/allowlist the verification key rather than trusting `kid`/`jwk`/`jku`/`x5u` from the token itself; store passwords with argon2/bcrypt+salt; constant-time secret comparison; rotate session id on login and invalidate on logout; set `HttpOnly`/`Secure`/`SameSite`; CSPRNG single-use expiring reset tokens; rate-limit + lockout keyed by account with exponential backoff and a DoS-safe recovery path; enforce MFA.