HIGH crlf injectionrestifycockroachdb

Crlf Injection in Restify with Cockroachdb

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

Crlf Injection occurs when user-controlled data is reflected into HTTP headers without sanitization, enabling an attacker to inject CRLF sequences (\r\n) and inject additional headers or split the response. In a Restify service that interacts with Cockroachdb, this typically happens when a request parameter (such as a user ID, sort field, or tag) is read from the query string or headers and then used to construct a response header, a log entry, or a dynamically generated value that later reaches an HTTP header.

Consider a Restify endpoint that retrieves a user record from Cockroachdb and sets a custom header x-user-role based on a request query parameter:

const restify = require('restify');
const server = restify.createServer();
const { Client } = require('pg');

server.get('/user', async (req, res, next) => {
  const client = new Client({
    connectionString: 'postgresql://user:pass@cockroachdb-host:26257/mydb?sslmode=require'
  });
  await client.connect();
  const { roleParam } = req.query;
  // Unsafe: roleParam used directly in header
  res.set('x-user-role', roleParam || 'guest');
  const result = await client.query('SELECT username, email FROM users WHERE role = $1', [roleParam || 'guest']);
  res.send(result.rows);
  await client.end();
  return next();
});
server.listen(8080);

If roleParam contains admin\r\nSet-Cookie: session=hijacked, the response will include an injected Set-Cookie header, potentially enabling session fixation or cookie poisoning. Even when the value is used strictly for application logic (e.g., selecting a role for the SQL query), reflected values in custom headers or logs can provide an injection vector.

Another scenario involves logging or error handling. Restify may include request parameters in access logs or error messages. If those logs are later viewed in a web UI or exported to a monitoring system that renders the content without proper escaping, the injected CRLF could manipulate log parsing or trigger header injection in downstream systems. Cockroachdb itself does not introduce the injection; the risk arises from how Restify handles input before using it in HTTP headers or logging contexts.

The presence of Cockroachdb can also affect exploit observability. For example, an attacker might attempt data exfiltration via an injected header that causes the server to make an external HTTP request (SSRF), targeting internal Cockroachdb administrative endpoints or other internal services. While Restify does not follow redirects or make requests automatically, injected headers like Location or Refresh could be used in combination with other vulnerabilities to probe the Cockroachdb admin UI on localhost if SSRF is also present.

Because middleBrick scans the unauthenticated attack surface and tests header injection points, it can identify whether user-controlled inputs reach HTTP headers in a Restify service. The LLM/AI Security checks do not apply here, but the standard injection detection will highlight the presence of CRLF sequences in reflected headers and provide guidance on input validation and output encoding.

Cockroachdb-Specific Remediation in Restify — concrete code fixes

Remediation focuses on strict input validation, avoiding direct reflection of untrusted data into HTTP headers, and safe usage of database parameters. The SQL query itself is safe when using parameterized queries, but the surrounding HTTP handling must be hardened.

First, avoid setting response headers with user-controlled values. If you must communicate role or status to the client, include it in the response body (e.g., within the JSON payload) rather than in headers:

const restify = require('restify');
const server = restify.createServer();
const { Client } = require('pg');

server.get('/user', async (req, res, next) => {
  const client = new Client({
    connectionString: 'postgresql://user:pass@cockroachdb-host:26257/mydb?sslmode=require'
  });
  await client.connect();
  const { roleParam } = req.query;
  // Validate against an allowlist
  const allowedRoles = ['admin', 'user', 'guest'];
  const role = allowedRoles.includes(roleParam) ? roleParam : 'guest';
  const result = await client.query('SELECT username, email FROM users WHERE role = $1', [role]);
  // Safe: include data in body, not in headers
  res.set('Content-Type', 'application/json');
  res.send({ role, users: result.rows });
  await client.end();
  return next();
});
server.listen(8080);

If you need to set a header derived from database values (not user input), ensure the value is strictly controlled and sanitized. For example, mapping roles to numeric priorities should be done server-side with no direct echo:

const rolePriority = {
  'guest': 1,
  'user': 2,
  'admin': 3
};

server.get('/profile', async (req, res, next) => {
  const client = new Client({
    connectionString: 'postgresql://user:pass@cockroachdb-host:26257/mydb?sslmode=require'
  });
  await client.connect();
  const { roleParam } = req.query;
  const role = rolePriority[roleParam] ? roleParam : 'guest';
  const result = await client.query('SELECT username FROM users WHERE role = $1', [role]);
  // Safe: derived value is not user-controlled
  res.set('X-Role-Level', String(rolePriority[role]));
  res.send(result.rows);
  await client.end();
  return next();
});

Additionally, sanitize any values that might be used in logging or error formatting. If you log request parameters, ensure they are escaped or omitted to prevent log injection:

server.on('after', (req, res, route, err) => {
  // Avoid directly concatenating req.query values into logs
  console.log(`Request to ${route.path} with role ${req.query.roleParam ? 'provided' : 'omitted'}`);
});

For continuous monitoring, the Pro plan can be integrated via the GitHub Action to fail builds if a CRLF-related finding appears in the scan results, while the CLI allows you to test endpoints locally with middlebrick scan <url>. The Dashboard helps track how remediation reduces the risk score over time.

Frequently Asked Questions

Can parameterized SQL queries fully prevent CRLF Injection in Restify?
No. Parameterized queries protect the database but do not affect how Restify handles request data when constructing HTTP headers, logs, or other outputs. Input validation and avoiding header reflection are still required to prevent CRLF Injection.
Does middleBrick fix CRLF Injection findings automatically?
middleBrick detects and reports findings with remediation guidance; it does not fix, patch, block, or remediate. Developers must apply the suggested input validation and header handling changes in the application code.