HIGH command injectionbearer tokens

Command Injection with Bearer Tokens

How Command Injection Manifests in Bearer Tokens

Command injection in Bearer Tokens occurs when user-controlled input is incorporated into command execution without proper sanitization. This vulnerability allows attackers to execute arbitrary system commands on the server, potentially leading to complete system compromise.

The most common attack vector involves API endpoints that accept Bearer Tokens and then use the token or associated metadata to construct system commands. For example, a logging endpoint might execute a command like:

curl -X POST https://api.example.com/logs -H "Authorization: Bearer $TOKEN"

If an attacker can control part of the token value, they might inject malicious commands:

Authorization: Bearer xyz$(rm -rf /)abc

This would execute the rm -rf / command when the server processes the token.

Another common pattern involves using Bearer Tokens to reference files or execute scripts:

const execSync = require('child_process').execSync;
const token = req.headers.authorization.split(' ')[1];
execSync(`echo ${token} >> logs/${token}.log`);

If an attacker provides a token like abc; rm -rf /, the shell will execute both commands sequentially.

Command injection can also occur through less obvious paths:

  • Token validation that calls external processes
  • Database queries constructed with token data that get executed as commands
  • Configuration files written with token data that are later parsed as executable code
  • API endpoints that use tokens to determine which system commands to execute

The severity of command injection in Bearer Tokens contexts is particularly high because tokens often have elevated privileges and are used in sensitive operations.

Bearer Tokens-Specific Detection

Detecting command injection in Bearer Tokens requires both static analysis and dynamic testing. middleBrick's scanner specifically looks for these patterns in API endpoints that accept Bearer Tokens.

Static detection involves scanning code for dangerous patterns:

const dangerousPatterns = [
  /exec\s*\(/,
  /system\s*\(/,
  /eval\s*\(/,
  /shell_exec\s*\(/,
  /Process\s*\(/,
  /Runtime\.getRuntime\s*\(\)\.exec\s*\(/,
  /os\.Exec\s*\(/,
  /Command::new\s*\(/
];

middleBrick analyzes your API endpoints to identify where Bearer Tokens are used in conjunction with these dangerous functions.

Dynamic testing involves sending specially crafted tokens to detect command injection vulnerabilities:

const testPayloads = [
  'abc$(id)',           // Unix command injection
  'abc%26%26id',         // URL-encoded injection
  'abc%7Cid',            // Pipe injection
  'abc%7C%7Cid',         // OR injection
  'abc%26%26dir',         // Windows injection
  'abc%26%26whoami'       // Unix user check
];

The scanner looks for differences in response times, error messages, or output that indicate command execution. For example, if a response includes process IDs or system information, this strongly suggests command injection.

middleBrick also checks for:

  • Environment variable leakage through error messages
  • Process IDs or system paths in responses
  • Unusual response times that suggest command execution
  • Changes in application state that indicate system-level modifications
  • Access to files or directories that shouldn't be accessible

The scanner provides a severity score and specific remediation guidance for each finding, mapping vulnerabilities to OWASP API Top 10 categories.

Bearer Tokens-Specific Remediation

Remediating command injection in Bearer Tokens contexts requires a defense-in-depth approach. The primary strategies include input validation, proper escaping, and architectural changes to avoid command execution entirely.

First, validate and sanitize all token inputs:

function validateBearerToken(token) {
  // Allow only alphanumeric characters and specific symbols
  const tokenRegex = /^[a-zA-Z0-9\-\._~\+\/]+$/;
  
  if (!tokenRegex.test(token)) {
    throw new Error('Invalid token format');
  }
  
  // Additional validation based on token structure
  const parts = token.split('.');
  if (parts.length !== 3) {
    throw new Error('Malformed token');
  }
  
  return true;
}

Second, use safe APIs that don't invoke shells:

// Dangerous - invokes shell
const execSync = require('child_process').execSync;
execSync(`echo ${token} >> logs/${token}.log`);

// Safe - no shell invocation
const { spawn } = require('child_process');
const echo = spawn('echo', [token]);
echo.stdout.pipe(fs.createWriteStream(`logs/${token}.log`));

Third, implement proper escaping for any unavoidable command execution:

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

function safeCommandExecution(token, filename) {
  // Use execFile instead of exec to avoid shell interpretation
  const args = [token, filename];
  execFile('process-file', args, (error, stdout, stderr) => {
    if (error) {
      console.error('Command execution failed:', error);
      return;
    }
    console.log('Command output:', stdout);
  });
}

Fourth, implement comprehensive logging and monitoring:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'security.log' })
  ]
});

function logSecurityEvent(eventType, details) {
  logger.warn({
    eventType,
    timestamp: new Date().toISOString(),
    ip: req.ip,
    userAgent: req.get('User-Agent'),
    details
  });
}

Finally, use middleBrick's continuous monitoring to ensure these fixes remain effective over time. The Pro plan can scan your APIs on a configurable schedule and alert you if new command injection vulnerabilities are detected.

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 if my Bearer Token implementation is vulnerable to command injection?
Use middleBrick's CLI tool to scan your API endpoints: middlebrick scan https://api.example.com --header "Authorization: Bearer test$(id)". The scanner will attempt various injection payloads and report any successful command execution. You can also manually test by sending tokens with special characters like $(id), &&id, or |id and monitoring for system information in responses.
What's the difference between command injection and SQL injection in Bearer Token contexts?
Command injection executes system-level commands on the server (like rm -rf / or whoami), potentially giving attackers full control of the system. SQL injection targets database queries. While both involve untrusted input, command injection is typically more severe because it can lead to complete system compromise. middleBrick scans for both types of injection but uses different payloads and detection methods for each.