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.
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.
# 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])
# 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