Code Injection

Code Injection is a vulnerability that allows attackers to inject and execute arbitrary code within an application's runtime environment. Unlike command injection which targets the OS shell, code injection targets the application's programming language interpreter.

How It Works

When user input is passed to functions that evaluate or execute code dynamically (like eval()), attackers can inject malicious code that runs with the application's privileges.

Vulnerable Code Examples

# Python - eval injection
result = eval(user_input)  # Input: __import__('os').system('whoami')

# PHP - eval injection
eval('$result = ' . $_GET['expr'] . ';');

# JavaScript - eval injection
eval(userInput);  // Input: require('child_process').exec('id')

# Ruby - eval injection
eval(params[:code])

Common Vulnerable Functions

  • Python: eval(), exec(), compile()
  • PHP: eval(), assert(), preg_replace() with /e modifier
  • JavaScript: eval(), Function(), setTimeout() with strings
  • Ruby: eval(), instance_eval(), class_eval()

Exploitation Techniques

  • Direct code execution via eval-like functions
  • Object instantiation to access dangerous classes
  • Sandbox escape using language internals
  • Chaining with file operations for persistence

Prevention

  • Never use eval(): Almost always avoidable with proper design
  • Use safe alternatives: JSON.parse() instead of eval() for data, AST parsers for expressions
  • Strict input validation: If dynamic code is unavoidable, use strict allowlists
  • Sandboxing: Isolate code execution environments (containers, VMs, restricted interpreters)
  • Static analysis: Flag dangerous functions in code reviews

Safe Alternatives

# Instead of eval() for JSON
# UNSAFE
data = eval(user_input)
# SAFE
data = json.loads(user_input)

# Instead of eval() for math expressions
# UNSAFE
result = eval(expression)
# SAFE - use a safe expression parser
import ast
result = ast.literal_eval(expression)  # Only literals
# Or use a math expression library

See Also