Code Injection – Examples and Prevention

In this article:

Detect Code Injection Vulnerabilities in Your Web Apps and APIs
Scan now for free

The Online Web Application Security Project (OWASP) helps organizations improve their security posture by offering guidelines based on real-world scenarios and community-led open-source projects. Out of the various threats, OWASP considers Code Injection to be a commonly known threat mechanism in which attackers exploit input validation flaws to introduce malicious code into an application.

This article explores how a code injection attack is performed, the types of attacks, and how software teams can protect their web applications from injection flaws.

What is Code Injection?

Threat actors use code injection vulnerabilities to embed malicious code into a source code, which the application interprets and executes. During the malicious injection, attackers leverage that these systems construct part of a code segment using external data while lacking sufficient input validation. The malicious code is typically built to control data flow, leading to loss of confidentiality and reduced application availability.

Attackers identify user input validation flaws such as — data format, allowed characters, and the amount of expected data — and use them as the basis for developing malicious code. OWASP ranks Injection vulnerabilities as number one, with their detectability ranging from easy to complex. Though this sounds alarming, injection vulnerabilities are moderately hard to exploit with the right practices and timely detection. 

Command Injection vs Code Injection Technique

While they are often confused, a Code Injection differs from a Command Injection vulnerability. Code Injection is a collection of techniques that allow a malicious user to add his arbitrary code to be executed by the application. Code Injection is limited to target systems and applications since the code’s effectiveness is confined to a particular programming language. 

On the other hand, Command Injection involves taking advantage of application vulnerabilities to extend the application’s functionality so it can execute arbitrary commands. With command injection, attackers supply unsafe input to the system shell to execute OS commands on the vulnerable application. 

Injection Attacks visual

How Code Injection Works

Code Injection, also known as Remote Code Execution or Code Evaluation, involves modifying an executable or script containing malicious code. Hackers first probe the application for attack surfaces that can accept untrusted data and use it when executing program code. These include direct input such as file uploads, form fields, or other data sources such as cookies and query string parameters. The introduction of code typically consists of a direct concatenation of character string, the PHP eval() function, or its equivalent in another language. A successful exploit grants attackers access to the application’s server-side interpreter. The attackers can use system calls to run commands on the server and penetrate further for deeper exploitation.

Code Injection – Type of Attack Exploits

Types of code injection attacks differ depending on the programming language used to develop the application’s source code and the attacker’s malicious code. This section explores some common categories of code injection vulnerabilities/attacks.

Client-Side Code Injection

In Client-side injection, hackers exploit flaws in applications where input validation is performed at the browser before the data is sent to the server. Such attacks include:

SQL Code Injection (SQLi)

SQL is widely used in modern applications to build data structures and query data sets. Attackers target vulnerable configuration details in relational database management systems to control a web application’s database server with malicious SQL statements. These statements modify SQL queries, granting hackers access to crucial data, such as login credentials and the application’s configuration information. 

Python Code injection

Applications built with Python, scripts that accept expressions from users and evaluate their input can be used to inject malicious code. For example, consider a simple calculator script that accepts and evaluates expressions at the user’s input:

compute = input('\nYour expression? => ') 
if not compute: 
    print ("No input") 
    print ("Result =", eval(compute))

A regular mathematical expression like 5*6 returns an expected result, 30. Suppose the target process has access privileges, on malicious input such as _import__(‘os’).system(‘rm -rf /’) in the input-form. In that case, all files and directories are located in the script’s folder are deleted. 

HTML Code Injection/Cross-Site Scripting

Attackers commonly use HTML code injection vulnerabilities to compromise how users interact with a web application. While doing so, the hacker injects malicious HTML into a trusted website, which then executes untrusted scripts on the end-users browser. Since the browser cannot detect the malicious script, the attacker can access session tokens, cookies, and other crucial data that the browser retains. 

Server-Side Code Injection

Server-side code injection involves exploiting flaws in applications that validate user input at the server end. These include:

PHP Code Injection

Some web applications built in PHP may include an unsafe function that allows attackers to control part or all of the software. These flaws enable hackers to change the course of code execution by modifying parts of an input string. The code below processes user input using the php eval() function:

//The URL to access this
        $x = $_GET['arg'];

If the web application lacks sufficient input validation, hackers can gain information about the PHP version using the URL:; phpinfo()

The attackers can then enumerate all services running on the server by requesting the URL:; system('id')

Server-Side Javascript Injection

It is relatively easy to insert and use one’s own Javascript code on a website either by finding a cross-site scripting vulnerability or by including code in the address bar. While it is often used in the developer’s console as a debugging mechanism, attackers can utilize Javascript injection vulnerabilities to orchestrate attacks, hijack registration forms, gain access credentials, and compromise system availability.

Examples of Code Injection Attacks

While code injection attacks are common and every organization is known to be affected by such vulnerabilities, here are some famous code injection attacks that occurred in the recent past:

The Ghostshell Attack

Ghost Shell, a cybersecurity activist group, exposed over 30 Million account details by taking advantage of SQL injection and poorly configured PHP scripts. The hacks, which target government and educational institutions, involved downloading numerous databases from different servers with broken authentication mechanisms. Using port-scanning tools, the hackers were able to locate servers hosting crucial databases, then uploaded breached data to raise awareness of cybersecurity misconfiguration.

Turkish Government Debt Agency Breach

RedHack, a Turkish hacker group, claimed to have penetrated the Istanbul Special Provincial Administration’s website (, clearing people’s debts to utility agencies. They utilized a simple SQL injection script to bypass the website’s login page, granting access to administrator and end-user accounts.

Injection attacks on Harvard-architecture devices

Cybersecurity researchers at Cornell University proved that buffer overflow techniques could be used to inject code into embedded devices that rely on Harvard architecture CPU design. These devices have limited memory, so they can only process small packets. Using various program vulnerabilities, the researchers proved that it is possible to inject permanent code into sensors so they can gain complete control of the host process. 

How to Detect and Prevent Code Injection Attacks

As long as attackers can exploit server-side interpreter settings by sending malicious data, almost any data input interface can be a vector for code injection attacks. These attacks are common since attackers have access to fuzzers and scanners that find code injection flaws. The business impact of such attacks can range from mild to severe depending on the data exposed and business functions implemented by the software. As a result, it is of utmost importance to fix incorrect server configurations, avoid untrusted data sources, and eliminate other injection vectors. 

Best Practices to Prevent Code Injection Attacks

While use-cases differ for different organizations, some best practices to eliminate code injection flaws in modern web applications.

  1. Utilize Whitelisting for input validation – Whitelisting is simpler to set up and gives security teams stricter control over what data or types of input the application can process, thereby helping to reduce the risk of an attacker executing malicious code.
  2. Encode HTML outputs – Security teams should leverage contextual output encoding to convert malicious input into safer representatives, where user data can be displayed but not executed as code.
  3. Use a static type system to enforce language separation – With static type systems, teams can develop declarative control checks without the additional run-time overhead. 
  4. Leverage Parameterized Queries and Criteria-Based APIs to interpret user data strings – This is done to ensure that APIs do not accept any string values other than those specified. Additionally, parameterized queries consider inputs of malicious commands as a string instead of being an SQL command.  
  5. Avoid using unsafe functions in source code – It’s important to avoid all vulnerable code evaluation constructs when developing source code. Developers should instead use secure, dedicated, language-specific features to process user-supplied inputs.
  6. Use the HttpOnly flag for cookies to disable client-side script interaction – If the server sets the HttpOnly flag on every cookie it creates, it indicates that the cookie should not be accessible from the client-side. The cookies cannot, therefore, be revealed to third parties even in the presence of HTML injection flaws.
  7. Use SCA Tools to find and fix issues – Teams should set up automatic static code checking tools to find and eliminate injection vectors in source code
  8. Avoid Javascript code serialization – Developers use code serialization to rearrange input data into a set of regular functions and expressions. Some versions of Javascript serialization packages cannot properly sanitize against untrusted characters in regular expressions. It is recommended as a best practice to avoid serialization unless absolutely necessary.


Injection attacks are number one on the OWASP Top 10 vulnerabilities and sixth on the Common Weakness Enumeration list.  Unsurprisingly, such vulnerabilities are highly prevalent, especially in legacy applications that weren’t built with code security best practices.

Code injection flaws are one of the most common exploits in malware attacks, as they can be used to access protected data, gain unauthorized access, or escalate privileges. The impacts and severity of the attacks require security teams to ensure adequate user input validation to avoid the injection of malicious code. Along with following the best practices to avoid such vulnerabilities, it is also recommended to leverage SCA tools that help with comprehensive scanning and identifying vulnerabilities in real-time.

Try Crashtest Security today to discover how it integrates into your development stack for efficient, automated vulnerability scanning.