Regex Dos in Adonisjs with Mutual Tls
Regex Dos in Adonisjs with Mutual Tls — how this specific combination creates or exposes the vulnerability
AdonisJS applications that terminate TLS at the framework level and also use route parameter validation via regex can enter a state where the overlap between transport-layer security expectations and pattern-based input handling creates exploitable conditions. Mutual TLS (mTLS) enforces client certificate verification before requests reach application logic, which typically reduces attack surface by ensuring only authorized clients can connect. However, when developers combine mTLS with strict regex-based validation of path or query parameters, two classes of issues emerge: bypass patterns and ReDoS amplification.
First, bypass patterns occur when the regex used for validation is not anchored and allows overlapping or ambiguous matches. For example, a route defined as GET /api/resource/:id(\d+) intends to accept only numeric IDs. If the application also relies on mTLS to identify tenants or roles, an attacker with a valid client certificate can still supply crafted input like 123?ignore=evil if the regex unintentionally permits trailing characters after the intended match. Because AdonisJS matches the parameter against the pattern before routing to the controller, the partial match may route to a handler that operates under the privileges implied by the mTLS identity, effectively bypassing tighter authorization checks that developers assumed were enforced by the pattern alone.
Second, ReDoS amplification becomes critical when mTLS reduces overall request volume (due to handshake overhead) while complex or non-anchored regular expressions remain in place. A regex such as ^(a+)+$ applied to user input in a route parameter can exhibit catastrophic backtracking on long strings of a characters. Under normal HTTPS conditions, rate limiting and infrastructure protections may mitigate this. With mTLS, the handshake adds latency, but the application layer remains vulnerable: a single malicious but authenticated request with a pathological payload can consume significant event-loop time, degrading responsiveness for other authenticated clients. This combination therefore does not introduce a new vulnerability class, but it tightens the impact window and increases severity when regex flaws intersect with mTLS identity-based routing and authorization logic.
Real-world relevance includes scenarios where APIs use mTLS for partner onboarding and then apply regex to enforce ID formats, scopes encoded in CN, or tenant identifiers extracted from certificate fields. If the regex is permissive or not normalized, an attacker with valid credentials can probe for these subtle match ambiguities. Because middleBrick scans test unauthenticated attack surfaces and also include checks aligned with OWASP API Top 10 and compliance mappings, such regex-related misconfigurations under mTLS would be surfaced as findings with severity tied to potential privilege or routing bypass.
Mutual Tls-Specific Remediation in Adonisjs — concrete code fixes
Remediation focuses on tightening regex definitions and ensuring identity derived from mTLS is not implicitly trusted for input validation. Below are concrete, syntactically correct examples for AdonisJS using the built-in route definitions and middleware patterns.
1. Anchor and normalize regex patterns
Always anchor patterns and avoid nested quantifiers. Prefer strict character class definitions and explicit length constraints.
// routes.ts
import Route from '@ioc:Adonis/Core/Route'
// Good: anchored, no ambiguous repetition
Route.get('/api/resource/:id(\d{1,10})', 'ResourceController.show')
// Good: explicit alphanumeric with fixed prefix, anchored
Route.get('/api/tenant/:slug([a-z0-9_-]{3,32})', 'TenantController.lookup')
2. Validate certificate-derived fields explicitly
Do not assume certificate fields match expected patterns. Extract and sanitize before use.
// start/kernel.ts or a dedicated mTLS middleware
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
export default class MtlsAuthMiddleware {
public async handle(ctx: HttpContextContract, next: () => Promise) {
const cert = ctx.request.sslCredentials()
const subject = cert.subject
// Example: extract CN and validate before assigning tenant
const cn = subject.commonName
const cnSchema = schema.create({
cn: schema.string({}, [rules.alpha({ allow: ['.', '-'] }), rules.minLength(3), rules.maxLength(64)])
})
const payload = await cnSchema.validate(cn)
ctx.auth.user = { cn: payload.cn }
await next()
}
}
3. Combine mTLS identity with explicit authorization checks
Do not rely on regex or route parameters alone for access control. Use policy checks that reference the authenticated identity from the certificate.
// policies/ResourcePolicy.ts
import { schema } from '@ioc:Adonis/Core/Validator'
import { Exception } from '@poppinss/utils'
export default class ResourcePolicy {
public async view(ctx, id: string) {
const idSchema = schema.create({
id: schema.string({}, [rules.regex(/^\d{1,10}$/)]) // re-validate even when mTLS is used
})
const validated = await idSchema.validate({ id })
const resource = await Resource.findOrFail(validated.id)
if (resource.tenantId !== ctx.auth.user.tenantId) {
throw new Exception('Forbidden', 403, 'E_MISMATCH_TENANT')
}
return true
}
}
4. Infrastructure-level tuning
While middleBrick does not describe internal engines, operators should ensure that TLS termination and client certificate verification are configured to reject incomplete chains and enforce strong cipher suites. This reduces the likelihood of malformed or malicious certificates reaching application code where regex validation may be bypassed.
5. Monitoring and scanning
Use middleBrick’s dashboard and CLI to continuously scan endpoints and track security scores. The scanner includes checks aligned with OWASP API Top 10 and compliance frameworks, surfacing regex-related issues in authenticated contexts where mTLS is present. For CI/CD integration, the GitHub Action can enforce a minimum score before deployment, and the MCP server enables scanning directly from AI coding assistants as you develop routes and validation logic.
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 |