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 in 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 take advantage of code injection vulnerabilities to embed malicious code into a source code, which the application interprets and executes. During the malicious injection, attackers leverage the fact that these systems construct part of a code segment using external data while lacking sufficient input validation. The malicious code is typically constructed to control the flow of data, 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 hard. Though this sounds alarming, with the right practices and timely detection, injection vulnerabilities are moderately hard to exploit.
Command Injection vs Code Injection Technique
While they are often confused, a Code Injection differs from Command Injection vulnerability. Code Injection is a collection of techniques that allow a malicious user to add his own 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 functionality of the application so it can execute arbitrary commands. With command injection, attackers supply unsafe input to the system shell, so they can execute OS commands on the vulnerable application.
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 includes 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, following which 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 take advantage of 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.
compute = input('\nYour expression? => ')
if not compute:
print ("No input")
print ("Result =", eval(compute))
Python Code injection
Applications that are built with Python, scripts that accept expressions from users and evaluate their input can be used to inject malicious code. Consider a simple calculator script that accepts and evaluates expressions at the user’s input:
A regular mathematical expression like 5*6 returns an expected result, 30. In the event the target process has access privileges, on malicious input such as _import__(‘os’).system(‘rm -rf /’) in the input form, all files and directories 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-user’s 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 https://codeinjection.crashtest-security.com/index.php?arg=1
$x = $_GET['arg'];
If the web application lacks sufficient input validation, hackers can gain information about the PHP version using the URL:
The attackers can then enumerate all services running in the server by requesting the URL:
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:
Ghost Shell, a cybersecurity activist group, was able to expose 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 on cybersecurity misconfiguration.
Turkish Government Debt Agency Breach
RedHack, a Turkish hacker group claimed to have penetrated the Istanbul Special Provincial Administration’s website (ios.gov.tr), clearing people’s debts to utility agencies. They utilized a simple SQL injection script to bypass the website’s login page, granting them access to both administrator and end-user accounts.
Injection attacks on Harvard-architecture devices
Cybersecurity researchers at Cornell University proved that buffer overflow techniques can 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 full 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 are accurate at finding 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, here are 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.
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 identification of vulnerabilities in real-time.
This article has already been published on https://crashtest-security.com/code-injection/ and has been authorized by Crashtest Security for a republish.