HIGH crlf injectionkoabearer tokens

Crlf Injection in Koa with Bearer Tokens

Crlf Injection in Koa with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Crlf Injection occurs when an attacker can inject CRLF sequences (\r\n) into HTTP headers, causing header splitting and potentially injecting additional headers or response splitting. In Koa, this risk arises when untrusted input is reflected into headers such as Location during redirects or custom headers added via ctx.set(). When a Bearer Token is handled naively— for example, parsed from an Authorization header and then used to build other headers or redirect URLs— unsanitized input containing \r\n can corrupt the header structure.

Consider a Koa route that takes a token value from a request and uses it to construct a Location header for redirects or to set a custom header. If the token or a parameter derived from it is not strictly validated, an attacker can supply a token like abc\r\nX-Injected: malicious. Because Koa does not inherently sanitize header values, the injected CRLF splits the header line, causing the server to interpret X-Injected: malicious as a separate header. This can lead to response splitting, cache poisoning, or open redirects. In the context of Bearer Tokens, an attacker might embed CRLF to forge secondary headers related to authorization or to manipulate downstream processing that relies on header integrity.

The interaction with Bearer Tokens is notable when tokens are logged, echoed, or used to build dynamic headers. For example, a logging or tracing mechanism might place the Authorization header value into a custom header or response field without sanitization. An attacker who can influence the token (e.g., via a compromised client or a parameter that is incorrectly mapped to the token) can exploit this to inject malicious headers. Because Bearer Tokens often appear in Authorization headers, developers might inadvertently trust them and reflect them without validation, turning an otherwise safe authentication mechanism into an injection vector.

Real-world impact includes response splitting (OWASP API Top 10:2023 — Injection), open redirects, and bypass of security controls that rely on header integrity. In extreme cases, CRLF Injection can facilitate cross-site scripting in browsers if the injected headers lead to script execution in the response body. The vulnerability is not in the Bearer Token specification itself, but in how Koa applications handle and reflect token values into headers without proper input validation and canonicalization.

Bearer Tokens-Specific Remediation in Koa — concrete code fixes

Remediation focuses on strict input validation, avoiding reflection of untrusted data into headers, and using safe abstractions. Never directly set HTTP headers with values derived from user-controlled input, including Bearer Tokens extracted from Authorization headers. If you must include token-derived values in headers or redirects, canonicalize and validate them rigorously.

Below are concrete Koa code examples demonstrating vulnerable patterns and their fixes.

Vulnerable pattern: reflecting a Bearer Token into a Location header

// BAD: directly using token from Authorization header in redirect
const token = ctx.request.header.authorization?.replace('Bearer ', '');
if (token) {
  ctx.redirect(`/callback?token=${token}`); // also URL unsafe
}

Issues: Token may contain CRLF, enabling header splitting if later reflected; URL is not encoded. An attacker-controlled token like abc\r\nSet-Cookie: foo=bar can split headers.

Fixed pattern: strict validation and safe redirects

// GOOD: validate token format, avoid reflection into headers/URLs
const auth = ctx.request.header.authorization || '';
const tokenMatch = auth.match(/^Bearer ([A-Za-z0-9\-._~+\/=]+)$/);
if (!tokenMatch) {
  ctx.throw(401, 'Invalid authorization token format');
}
const token = tokenMatch[1];
// Use token only for intended server-side validation or storage; do not echo into headers
// If you must redirect, use a server-side opaque mapping, not the raw token
ctx.redirect(302, '/callback');

The fix ensures the token conforms to a strict regex for Bearer Tokens, rejecting any CRLF or control characters. It avoids echoing the token into headers or URLs. For flows requiring token propagation, use server-side session identifiers or opaque mappings rather than reflecting the raw token.

Vulnerable pattern: setting custom headers with token-derived values

// BAD: setting a header with token value
const token = ctx.request.header.authorization?.replace('Bearer ', '');
if (token) {
  ctx.set('X-Token-Hint', token); // dangerous if token contains CRLF
}

Fixed pattern: sanitize or avoid custom headers with untrusted data

// GOOD: either omit the header or set a safe, non-user-derived value
// Option 1: do not set header based on token
// Option 2: set a constant, sanitized value
ctx.set('X-Request-Id', generateSafeRequestId()); // generateSafeRequestId returns a sanitized UUID

Additional measures: enforce strict Content Security Policy where relevant, use urlencode for any URL parameters, and apply framework-level validation (e.g., Joi or Zod) for all inputs. Regularly audit header-setting code paths to ensure no unchecked user input reaches response headers.

Frequently Asked Questions

Can CRLF Injection affect authenticated sessions even when Bearer Tokens are used?
Yes. If an attacker can inject CRLF into values that are reflected into headers—such as tokens placed in custom headers or redirects—it can split responses, inject cookies, or manipulate session-related headers, undermining authentication controls.
Does validating Bearer Token format fully prevent CRLF Injection in Koa?
It significantly reduces risk when the validation rejects CRLF and control characters and avoids reflecting the token into headers. However, comprehensive prevention also requires sanitizing any other user-influenced data that reaches headers, logging, and redirects, not just the token itself.