HIGH crlf injectionrestifybearer tokens

Crlf Injection in Restify with Bearer Tokens

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

Crlf Injection occurs when user-controlled data is reflected in HTTP headers without sanitization, allowing an attacker to inject CRLF sequences (\r\n) to split headers and inject additional header lines or body content. In Restify, this risk is heightened when Bearer Tokens are handled naively in request processing, particularly when tokens are echoed in headers, logs, or error responses.

Consider a scenario where an API endpoint validates a Bearer Token but reflects it in a custom header or error message. If an attacker provides a token containing encoded line breaks, Restify may forward the token to downstream services or include it in logs without validation. For example, a token like abc123\r\nX-Injected: malicious can cause Restify to treat the injected sequence as a new header when the token is later used in header construction or logging, potentially enabling HTTP response splitting, cache poisoning, or sensitive information disclosure.

In the context of authentication, if Restify does not strictly validate or sanitize the Authorization header value before using it in any downstream operation, an attacker can leverage Crlf Injection to forge secondary headers. This can bypass intended authentication checks by injecting headers like Set-Cookie or Location, especially when combined with open redirects or insecure logging mechanisms. The unauthenticated scan capability of middleBrick specifically tests such injection points across 12 security checks, including Input Validation and Data Exposure, identifying whether reflected tokens enable header manipulation.

Moreover, when Bearer Tokens are passed through multiple services or logged for debugging, unsanitized newlines can alter the structure of HTTP messages, leading to response splitting or information leakage. middleBrick’s LLM/AI Security checks also verify whether token handling in AI-integrated endpoints risks exposing system prompts or sensitive data through manipulated headers. Because Crlf Injection exploits trust in header delimiters, defense requires strict validation of any user-derived content that reaches HTTP header construction logic.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

To mitigate Crlf Injection in Restify when handling Bearer Tokens, enforce strict validation and avoid reflecting raw token values in headers or logs. Always parse and sanitize the Authorization header server-side, and ensure no user input directly influences header formation.

Example of vulnerable code that echoes the token into a custom header:

const restify = require('restify');
const server = restify.createServer();

server.use((req, res, next) => {
  const auth = req.headers['authorization'] || '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : auth;
  // Vulnerable: reflecting token in a custom header
  res.setHeader('X-Token-Preview', token);
  return next();
});

server.get('/profile', (req, res, next) => {
  res.send({ message: 'ok' });
  return next();
});

server.listen(8080);

In this example, an attacker can supply Bearer abc123\r\nX-Injected: injected and cause X-Token-Preview to split the header, injecting X-Injected: injected into the response. This demonstrates how reflection of raw token segments enables Crlf Injection.

Secure remediation involves validating and sanitizing the token before any use, and never reflecting it in headers:

const restify = require('restify');
const server = restify.createServer();

function sanitizeHeaderValue(value) {
  if (typeof value !== 'string') return value;
  // Remove CR and LF characters to prevent header injection
  return value.replace(/[\r\n]+/g, '');
}

server.use((req, res, next) => {
  const auth = req.headers['authorization'] || '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : auth;
  const safeToken = sanitizeHeaderValue(token);
  // Safe: do not reflect token in headers
  req.context.tokenHash = require('crypto').createHash('sha256').update(safeToken).digest('hex');
  return next();
});

server.get('/profile', (req, res, next) => {
  res.send({ message: 'ok' });
  return next();
});

server.listen(8080);

This approach removes carriage return and line feed characters and avoids echoing the token in any header. For production use, store only a hashed representation of the token if needed for auditing, and rely on Restify’s built-in authentication handlers where possible. middleBrick’s CLI can be used to verify that such endpoints no longer reflect raw tokens by running middlebrick scan <url> and reviewing the Input Validation and Data Exposure findings.

Additionally, ensure that error messages do not include the raw Authorization header. Use consistent error formats that do not vary based on token content, and apply the same sanitization to any logged data involving tokens. The GitHub Action integration can enforce these checks in CI/CD, failing builds if unsafe patterns are detected.

Frequently Asked Questions

Can Crlf Injection with Bearer Tokens affect logged data in Restify?
Yes. If raw Bearer Tokens containing newline characters are written to logs, they can split log entries and enable log injection or sensitive data exposure. Always sanitize tokens before logging.
Does middleBrick detect Crlf Injection in Restify APIs that use Bearer Tokens?
Yes. middleBrick runs Input Validation and Data Exposure checks that test for Crlf Injection by injecting CRLF sequences into headers and observing whether they appear in responses, including when tokens are reflected.