OS Command Injection

Verified by Precogs Threat Research
Security GuideA05:2025

What is OS Command Injection?

OS command injection occurs when an application passes unsafe user-supplied data to a system shell. Attackers can inject additional commands using shell metacharacters (;, |, &&, ||, backticks) to execute arbitrary operating system commands.

How Does it Work?

When applications use functions like system(), exec(), or os.popen() with user-controlled strings, attackers can append additional commands. For example, a ping utility that takes a hostname input can be exploited: input ";rm -rf /" after the hostname.

# VULNERABLE: User input passed directly to shell
import os
hostname = request.args.get('host')
os.system(f"ping -c 4 {hostname}")
# Attacker input: "8.8.8.8; cat /etc/passwd"
# Executes: ping -c 4 8.8.8.8; cat /etc/passwd

# SECURE: Use subprocess with argument list (no shell)
import subprocess
subprocess.run(["ping", "-c", "4", hostname], shell=False)
// VULNERABLE: Node.js command injection
const { exec } = require('child_process');
exec(`nslookup ${userInput}`, callback);
// Attacker: "google.com; rm -rf /"

// SECURE: Use execFile with arguments array
const { execFile } = require('child_process');
execFile('nslookup', [userInput], callback);

Real-World Examples

PHP CGI argument injection (CVE-2024-4577) enabled RCE through Unicode encoding tricks. Shellshock (CVE-2014-6271) affected 500M+ devices through environment variable processing. Command injection in IoT devices is extremely common.

Security Impact

Command injection gives attackers full operating system access: reading files, modifying configurations, installing backdoors, pivoting to other systems, and executing arbitrary programs with the privilege of the web application.

Prevention & Mitigation

Avoid OS command execution from application code. Use language-native libraries instead (e.g., net.ping in Java instead of shelling out to ping command). If shell interaction is unavoidable, use parameterized APIs and strict input validation.

How Precogs AI Stops OS Command Injection

Precogs AI detects command injection patterns in AI-generated code through pre-LLM filters and identifies OS command execution sinks in compiled binaries during Binary SAST analysis of firmware and applications.

Related CWE Entries