HIGH command injectionchi

Command Injection in Chi

How Command Injection Manifests in Chi

Command injection in Chi occurs when user-controlled data flows into system commands without proper sanitization. Chi's flexible templating and dynamic execution model creates multiple attack surfaces where malicious input can escape intended boundaries.

The most common Chi vulnerability arises in template rendering contexts where user input is interpolated into shell commands. Consider this vulnerable Chi pattern:

const chi = require('chi');

app.get('/process', async (req, res) => {
  const command = `echo "${req.query.message}"`;
  const { exec } = require('child_process');
  exec(command, (error, stdout, stderr) => {
    res.send(stdout);
  });
});

An attacker can exploit this with: /process?message=%22;cat%20/etc/passwd%20;%20echo%20%22, causing the command to execute:

echo "";cat /etc/passwd ; echo ""

Chi's middleware execution chain creates additional injection opportunities. When user input passes through multiple middleware layers before reaching command execution, each layer may introduce new injection vectors:

app.use(async (ctx, next) => {
  ctx.command = `process --input "${ctx.query.data}"`;
  await next();
});

app.get('/execute', async (ctx) => {
  const { exec } = require('child_process');
  exec(ctx.command, (error, stdout) => {
    ctx.body = stdout;
  });
});

Chi's dynamic import capabilities introduce another injection vector. When user input determines which modules to load:

const chi = require('chi');

app.get('/load', async (req, res) => {
  const module = req.query.name;
  const loaded = await import(`./modules/${module}`);
  res.send(loaded.default());
});

An attacker could request /load?name=../malicious to execute arbitrary code. Chi's path resolution makes this particularly dangerous as it may traverse directories beyond intended boundaries.

Template injection within Chi's rendering engine creates a third attack class. When user input reaches template engines that can execute arbitrary code:

app.get('/render', async (req, res) => {
  const template = `Hello ${req.query.name}`;
  const html = chi.render(template, { name: req.query.name });
  res.send(html);
});

If the template engine supports code execution, an attacker could inject template logic that executes system commands.

Chi-Specific Detection

Detecting command injection in Chi applications requires both static analysis and runtime scanning. middleBrick's black-box scanner identifies these vulnerabilities by testing unauthenticated endpoints for command injection patterns.

For Chi applications, middleBrick tests command injection by sending payloads designed to trigger system responses. The scanner attempts payloads like:

echo "${injection}";id;echo "${injection}"
echo '$(id)'
echo "%0aid%0a"
echo "%0a%09id%0a"

These payloads help identify if user input reaches system commands. middleBrick's Chi-specific detection includes:

  • Testing template rendering paths for code execution
  • Checking dynamic import statements for path traversal
  • Analyzing middleware chains for command construction
  • Scanning for dangerous function calls like exec, spawn, eval, import()

middleBrick's scanner also examines OpenAPI specs for Chi applications, mapping endpoint parameters to potential injection points. When scanning a Chi API, middleBrick:

  1. Identifies endpoints accepting user input
  2. Tests each parameter with command injection payloads
  3. Analyzes responses for command execution indicators
  4. Maps findings to OWASP API Top 10 categories

For Chi applications using middleware, middleBrick traces data flow through the middleware chain to identify where user input becomes dangerous. The scanner can detect if input passes through:

app.use(authMiddleware);
app.use(inputSanitization);
app.use(commandBuilder);

If sanitization is missing or insufficient, middleBrick flags the vulnerability with severity and remediation guidance.

Chi-Specific Remediation

Remediating command injection in Chi requires eliminating unsafe command construction and implementing proper input validation. The most effective approach is avoiding shell command execution entirely when possible.

For file operations that might tempt developers to use shell commands, use Node.js native APIs:

// Vulnerable - command injection possible
const { exec } = require('child_process');
exec(`cat ${req.query.filename}`, callback);

// Secure - use native fs module
const fs = require('fs');
const path = require('path');

app.get('/read', async (req, res) => {
  const filename = path.basename(req.query.filename);
  const filepath = path.join(__dirname, 'files', filename);
  
  try {
    const content = await fs.promises.readFile(filepath, 'utf8');
    res.send(content);
  } catch (error) {
    res.status(400).send('Invalid file');
  }
});

When shell commands are unavoidable, use argument arrays instead of shell strings:

// Vulnerable - shell string interpolation
const command = `echo "${userInput}"`;
exec(command, callback);

// Secure - argument array
const { execFile } = require('child_process');
execFile('echo', [userInput], callback);

Chi applications should implement strict input validation using allowlists:

const allowedCommands = ['list', 'status', 'info'];

app.get('/command', async (req, res) => {
  const command = req.query.cmd;
  
  if (!allowedCommands.includes(command)) {
    return res.status(400).send('Invalid command');
  }
  
  // Safe to execute - input is validated
  const { execFile } = require('child_process');
  execFile('myapp', [command], (error, stdout) => {
    res.send(stdout);
  });
});

For Chi template rendering, use secure templating practices:

// Vulnerable - direct interpolation
const template = `Hello ${userInput}`;

// Secure - use template engine with auto-escaping
const ejs = require('ejs');
const html = ejs.render('<h1>Hello <%= name %></h1>', { name: userInput });

middleBrick's GitHub Action can automatically scan Chi applications in CI/CD pipelines:

- name: Scan Chi API
  uses: middlebrick/middlebrick-action@v1
  with:
    url: ${{ secrets.API_URL }}
    fail-on-severity: high
    token: ${{ secrets.MIDDLEBRICK_TOKEN }}

This integration ensures command injection vulnerabilities are caught before deployment. middleBrick's continuous monitoring (Pro plan) can also scan Chi APIs on a schedule, alerting developers when new vulnerabilities are discovered.

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

How can I test my Chi application for command injection vulnerabilities?
Use middleBrick's free scanner by submitting your Chi API endpoint URL. The scanner tests for command injection by sending payloads designed to trigger system responses, then analyzes the results to identify vulnerabilities. For continuous security, middleBrick's Pro plan offers scheduled scanning with alerts when new vulnerabilities are discovered.
Does middleBrick scan Chi applications for LLM-specific vulnerabilities?
Yes, middleBrick uniquely scans Chi applications for LLM/AI security issues including system prompt leakage, prompt injection, and excessive agency detection. The scanner tests for 27 regex patterns covering common LLM formats and performs active prompt injection testing with five sequential probes to identify AI-specific vulnerabilities.