Code Injection

Cybersecurity Glossary APIs & Server-Side Security

Code Injection

A vulnerability that allows attackers to inject and execute arbitrary code within an application's runtime environment through functions like eval().

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.

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()

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