HIGH command injectionhapicockroachdb

Command Injection in Hapi with Cockroachdb

Command Injection in Hapi with Cockroachdb — how this specific combination creates or exposes the vulnerability

Command Injection occurs when untrusted input is concatenated into a system command executed by the application. In a Hapi server that uses CockroachDB, this typically arises when SQL results or request parameters are improperly passed to operating system utilities via Node.js functions such as child_process.exec or child_process.spawn. For example, a route might build a shell command that includes a database value (e.g., a hostname or label from CockroachDB) without validation or escaping, creating a path for an attacker to inject additional shell commands.

Consider a scenario where a Hapi route retrieves a CockroachDB node name from the database and uses it in a diagnostic shell command. If the node name is user-influenced (perhaps via application configuration or an exported metric) and not sanitized, an attacker who can influence that database value may inject shell metacharacters such as ; or &&. A vulnerable implementation might look like this:

const NodeUtil = require('node:util');
const exec = NodeUtil.promisify(require('child_process').exec);

server.route({
  method: 'GET',
  path: '/debug/node-shell',
  handler: async (request, h) =>
  {
    const { rows } = await pool.query('SELECT node_name FROM crdb_internal.nodes LIMIT 1');
    const nodeName = rows[0]?.node_name || 'unknown';
    const { stdout, stderr } = await exec('echo node=' + nodeName);
    return { stdout, stderr };
  }
});

In this pattern, if node_name contains something like localhost; cat /etc/passwd, the shell will execute the injected command, leading to unintended system interaction. This is a classic Command Injection vector that exploits the boundary between database content and shell execution.

Another relevant pattern involves dynamic configuration or logging where CockroachDB metadata is forwarded to external tooling via shell commands. Because the database can be the source of truth for hostnames, ports, or labels, any unchecked propagation of these values into shell contexts increases risk. The key issue is not CockroachDB itself, but the way Hapi code combines database-derived data with shell execution without input validation, output encoding, or use of safer APIs.

Additionally, attackers who can influence SQL data indirectly—through other vulnerabilities such as IDOR or BFLA—may position themselves to alter values stored in CockroachDB that later appear in shell commands. This multi-step chain amplifies the impact of seemingly low-severity issues. Therefore, treating database values as untrusted input is essential, even when those values originate from within your own cluster.

Cockroachdb-Specific Remediation in Hapi — concrete code fixes

Remediation centers on avoiding shell execution entirely and treating all data from CockroachDB as untrusted. The most robust fix is to replace shell-based utilities with native Node.js libraries or CockroachDB-native operations. For diagnostics, prefer structured querying over shell commands.

If you must invoke external processes, use parameterized approaches or avoid concatenation. Below is a safe alternative that does not rely on shell injection-prone string building:

const { execFile } = require('child_process');

server.route({
  method: 'GET',
  path: '/debug/nodes-list',
  handler: (request, h) =>
  {
    return new Promise((resolve, reject) =>
    {
      // execFile uses argument array, avoiding shell parsing
      execFile('echo', ['node=placeholder'], (error, stdout, stderr) =>
      {
        if (error) { return reject(error); }
        resolve({ stdout, stderr });
      });
    });
  }
});

For CockroachDB-specific operations, rely on the SQL interface rather than external tooling. For example, instead of using a shell command to inspect node status, query system tables directly:

// Safe: pure SQL, no shell involvement
const { rows } = await pool.query(`
  SELECT node_id, address, locality, is_live
  FROM crdb_internal.nodes
  WHERE is_live = true
`);
return rows;

When input must reach the shell (rare), use strict allowlists and avoid interpolation. For instance, if you need to run a predefined script with a numeric identifier, validate and cast the identifier before use:

const identifier = parseInt(request.query.id, 10);
if (!Number.isInteger(identifier) || identifier < 1 || identifier > 1000) {
  return h.response('invalid').code(400);
}
// Safe: identifier is numeric, no shell injection risk
const { stdout } = await execFile('./script.sh', [String(identifier)]);

In CI/CD and development workflows, you can integrate middleBrick to detect such issues early. Using the CLI, run middlebrick scan <url> to identify Command Injection risks in your API routes. For automated checks, add the GitHub Action to your pipeline to fail builds if risky patterns are found, or use the MCP Server to scan APIs directly from your IDE during development.

Finally, always prefer structured logging and native database diagnostics. This eliminates the need for shell interaction and keeps your Hapi application secure when working with CockroachDB.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can CockroachDB user-defined functions cause Command Injection in Hapi?
If a UDF internally invokes shell commands and those commands incorporate unvalidated external input, Command Injection is possible. Avoid executing shell commands from within database functions and treat UDF behavior as part of the attack surface.
Does middleBrick fix Command Injection findings automatically?
middleBrick detects and reports Command Injection with remediation guidance. It does not automatically patch or modify code; developers must apply the recommended fixes.