Regex Dos in Adonisjs with Jwt Tokens
Regex Dos in Adonisjs with Jwt Tokens — how this specific combination creates or exposes the vulnerability
AdonisJS applications that use JSON Web Tokens (JWT) can be exposed to Regular Expression Denial of Service (ReDoS) when token validation or parsing relies on poorly constructed regular expressions. ReDoS occurs when a regular expression exhibits catastrophic backtracking on certain inputs, causing CPU usage to spike and blocking the event loop long enough to degrade or halt service. This becomes particularly relevant in JWT workflows where token strings are matched, extracted, or validated using regex patterns.
In AdonisJS, JWT handling is commonly implemented via the jwt provider in start/hooks.ts and route-level guards that verify tokens from headers (e.g., Authorization: Bearer <token>). If the application uses custom regex to parse or validate tokens—such as extracting the payload from a JWT string before passing it to the JWT library—these patterns may unintentionally introduce exponential time complexity. For example, a pattern like /^([a-zA-Z0-9_=\/]){50,2000}$/ applied to attacker-controlled input can cause significant backtracking due to the interplay between quantifiers and character classes.
Attackers can craft JWT strings that maximize backtracking by providing specially designed header or payload segments that match the regex’s ambiguous quantifiers. Since AdonisJS runs on Node.js, a single blocking regex evaluation can consume substantial CPU, affecting all concurrent requests. This issue is compounded when regex-based validation is layered on top of the standard JWT library flow, adding redundant checks that increase risk without improving security. The vulnerability is not in JWT itself but in how regex is used around token handling, especially when validating format or length constraints with open-ended ranges and overlapping groups.
middleBrick detects such risky patterns during scans by analyzing the unauthenticated attack surface and correlating runtime behavior with known ReDoS-prone regex structures. Findings include severity ratings and references to real-world patterns like CVE-classic ReDoS scenarios, mapped to OWASP API Top 10 and related categories. The scanner identifies endpoints and hooks where regex-based token processing occurs, providing remediation guidance that avoids reliance on vulnerable patterns.
Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes
To mitigate ReDoS risks in AdonisJS when working with JWT tokens, avoid using complex or open-ended regular expressions for token validation or extraction. Instead, rely on the JWT library’s built-in parsing and validation, and use simple, safe string operations where necessary. Below are concrete code examples demonstrating secure approaches.
First, configure JWT in start/hooks.ts using the official AdonisJS JWT provider without custom regex validation:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
import { Jwt } from '@ioc:Adonis/Addons/Jwt'
// Secure JWT validation hook example
export const handle = async (ctx: HttpContextContract) => {
const authHeader = ctx.request.header('authorization')
if (!authHeader || !authHeader.startsWith('Bearer ')) {
ctx.response.status(401).send({ error: 'Unauthorized' })
return
}
// Safe token extraction using string split instead of regex
const token = authHeader.split(' ')[1]
if (!token) {
ctx.response.status(401).send({ error: 'Invalid token format' })
return
}
try {
const payload = await Jwt.verify(token, 'your-secret-key', { algorithm: 'HS256' })
ctx.auth.user = payload as any
} catch (error) {
ctx.response.status(401).send({ error: 'Invalid token' })
}
}
This approach eliminates regex-based extraction and uses straightforward string operations, avoiding catastrophic backtracking. It also leverages the JWT library’s verified parsing, reducing redundant checks.
Second, if you must validate token format, use a bounded, non-backtracking pattern or simple length checks. For example, a JWT token has three dot-separated parts; you can validate structure without regex:
const isValidStructure = (token: string): boolean => {
const parts = token.split('.')
return parts.length === 3 && parts.every((part) => part.length > 0 && part.length <= 500)
}
Finally, ensure that any custom validation logic is tested with edge-case inputs to confirm it does not exhibit exponential behavior. middleBrick’s findings include prioritized remediation steps and references to compliance frameworks such as OWASP API Top 10 and SOC2, helping teams structure secure token handling in AdonisJS applications. Pro plan continuous monitoring can alert you if new risky patterns are detected during scans.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |