Code injection is a class of attacks in which an attacker supplies input that an application mistakenly executes as program code.
How code injection works
The root cause is mixing data and code. If an application builds code from user input – for example passing it to eval() in PHP, JavaScript or Python, or inserting it into a template – an attacker can add their own instructions. The weakness is catalogued as CWE-94. Related variants include:
- OS command injection (CWE-78) – input reaches a system shell command.
- Server-side template injection – input is evaluated by template engines such as Jinja2 or Twig.
- Expression language injection – for example OGNL injection in Apache Struts, which led to the 2017 Equifax breach.
- SQL injection and cross-site scripting, where the injected code is a database query or browser script.
The 2014 Shellshock bug in Bash showed how widespread the problem can be: specially crafted environment variables made Bash execute commands on web servers, routers and other devices.
Why it matters
Successful code injection usually means remote code execution with the application’s privileges: data theft, web shells, cryptominers or a foothold for ransomware. Injection flaws have been in the OWASP Top 10 since its first edition, and they are a favourite target of automated scanners. Insecure deserialization is a close relative that also turns data into executed code.
How to prevent code injection
- Never pass user input to eval-like functions or shells; use safe APIs and parameterised queries.
- Validate input against strict allowlists and encode output for its context.
- Run applications with minimal privileges and sandbox template engines.
- Use static analysis and security testing to find injection points early.