15 Feb, 2023

Code Injection

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

Code injection is a type of security vulnerability that occurs when an attacker injects malicious code into a program, which is then executed by the application. The attacker can exploit this vulnerability to execute arbitrary code and potentially take control of the application or the underlying system.

The code injection attack can take many forms, including SQL injection, cross-site scripting (XSS), and command injection. In SQL injection, an attacker injects malicious SQL statements into a web application, allowing them to view or modify sensitive data in the application’s database. In XSS, an attacker injects malicious scripts into a web page, allowing them to steal user credentials or perform other malicious activities. In command injection, an attacker injects malicious commands into an application, allowing them to execute arbitrary commands on the underlying system.

Example of vulnerable code on different programming languages:

in Python:

				
					import os

user_input = input("Enter a file name: ")
os.system("cat " + user_input)
				
			


In this Python code, the os.system() function is used to execute a command entered by the user without any validation or sanitization. An attacker could inject malicious code into the user input to execute arbitrary commands on the underlying system.

To prevent code injection in this code, you should validate the user input and use the subprocess module instead of os.system().

• in Java:

				
					String query = "SELECT * FROM users WHERE username = '" + userInput + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);

				
			


In this Java code, the user input is concatenated into a SQL query string without any validation or sanitization. An attacker could inject malicious SQL statements into the user input to view or modify sensitive data in the application’s database.

To prevent SQL injection in this code, you should use parameterized queries instead of concatenating user input into the SQL query string.

• in PHP:

				
					$user_input = $_GET['input'];
eval("echo $user_input;");

				
			


In this PHP code, the eval() function is used to execute arbitrary code entered by the user. An attacker could inject malicious code into the user input to execute arbitrary commands on the underlying system.

To prevent code injection in this code, you should avoid using the eval() function and validate the user input before executing it.

• in C#:

				
					string command = "ping " + userInput;
Process.Start("cmd.exe", "/c " + command);

				
			


In this C# code, the Process.Start() function is used to execute a command entered by the user without any validation or sanitization. An attacker could inject malicious code into the user input to execute arbitrary commands on the underlying system.

To prevent code injection in this code, you should validate the user input and use the ProcessStartInfo class instead of Process.Start().

Examples of exploitation Code Injection

• SQL Injection Suppose a web application uses a vulnerable SQL query that concatenates user input into the query string without any validation or sanitization, as in the following example:

				
					SELECT * FROM users WHERE username = '" + userInput + "'";
				
			


An attacker could exploit this vulnerability by entering a malicious input like:

				
					' OR '1'='1

				
			


This would modify the original query to:

				
					SELECT * FROM users WHERE username = '' OR '1'='1';

				
			


Which would return all records from the users table, including sensitive information such as usernames and passwords.

• Command Injection Suppose a web application uses a vulnerable function that executes a command entered by the user without any validation or sanitization, as in the following example:

				
					exec("ping " + userInput);

				
			


An attacker could exploit this vulnerability by entering a malicious input like:

				
					127.0.0.1; rm -rf /

				
			


This would execute the following command on the underlying system:

				
					ping 127.0.0.1; rm -rf /

				
			


which would delete all files on the root directory of the system.

• Cross-Site Scripting (XSS) Suppose a web application uses a vulnerable function that outputs user input without any validation or sanitization, as in the following example:

				
					echo "Hello, " + userInput + "!";

				
			


An attacker could exploit this vulnerability by entering a malicious input like:

				
					<script>alert('XSS')</script>

				
			


This would inject the malicious script into the web page and execute it in the context of the user’s browser, potentially stealing their session cookies or performing other malicious activities.

Privilege escalation techniques for Code Injection

Operating System Command Injection
In this type of attack, the attacker exploits a vulnerability in an application to execute arbitrary commands on the underlying operating system. Once the attacker has gained access to the system, they can use additional code injection techniques to escalate their privileges, such as modifying system files, creating new user accounts, or installing backdoors.

SQL Injection
In this type of attack, the attacker exploits a vulnerability in a web application to modify the SQL query used to retrieve data from the application’s database. By injecting a carefully crafted SQL query, the attacker can gain access to sensitive data or even administrative privileges in the application.

Cross-Site Scripting (XSS)
In this type of attack, the attacker injects malicious scripts into a web page to steal user credentials or perform other malicious activities. By stealing the user’s session cookies or login credentials, the attacker can gain access to the application with the user’s privileges, and then use additional code injection techniques to escalate their privileges.

Code Injection in Authentication
Mechanisms In some cases, authentication mechanisms themselves can be vulnerable to code injection attacks. For example, an attacker might be able to bypass authentication by injecting code that alters the value of a user session variable, or by injecting code that causes the application to skip the authentication process altogether.

General methodology and checklist for Code Injection

Methodology:

  1. Identify User Input Points
    The first step is to identify all the points in the application where user input is accepted. This includes web forms, search boxes, and other input fields.

  2. Test for SQL Injection
    To test for SQL injection vulnerabilities, try to inject SQL statements into user input fields to see if they are executed by the application. This can include using special characters, like quotes and semicolons, to alter the behavior of the SQL query.

  3. Test for Command Injection
    To test for command injection vulnerabilities, try to inject command-line commands into user input fields to see if they are executed by the application. This can include using special characters, like pipes and semicolons, to chain commands together.

  4. Test for Cross-Site Scripting (XSS)
    To test for cross-site scripting vulnerabilities, try to inject malicious scripts into user input fields to see if they are executed by the application. This can include using special characters, like angle brackets and quotes, to inject scripts that steal user credentials or perform other malicious activities.

  5. Test for Code Injectionin Other Languages
    If the application uses other languages, like PHP or Java, it is important to test for code injection vulnerabilities in those languages as well. This can include testing for eval() and similar functions that can be used to execute arbitrary code.

  6. Use Automated Testing Tools
    There are several automated testing tools available that can help identify code injection vulnerabilities in software. These tools can simulate various attack scenarios and identify vulnerabilities that may be difficult to find through manual testing.

  7. Regularly Test and Update
    It is important to regularly test the application for code injection vulnerabilities and to update the software as needed to fix any vulnerabilities that are identified. This can include implementing security patches and following secure coding practices.

Checklist:

  1. Identify all user input points in the application.

  2. Test for SQL injection vulnerabilities by injecting SQL statements into user input fields.

  3. Test for command injection vulnerabilities by injecting command-line commands into user input fields.

  4. Test for cross-site scripting vulnerabilities by injecting malicious scripts into user input fields.

  5. Test for code injection vulnerabilities in other languages used by the application.

  6. Use automated testing tools to help identify code injection vulnerabilities.

  7. Regularly test and update the application to fix any vulnerabilities that are identified.

  8. Check for the proper validation and sanitization of all user input.

  9. Check for the use of parameterized queries to prevent SQL injection vulnerabilities.

  10. Check for the proper encoding and escaping of user input to prevent cross-site scripting vulnerabilities.

  11. Check for the avoidance of dangerous functions like eval(), system(), and exec().

  12. Check for the proper implementation of least privilege to prevent privilege escalation vulnerabilities.

  13. Check for the use of security tools like firewalls and intrusion detection systems.

  14. Check for regular security audits to identify and fix vulnerabilities.

Tools set for exploiting Code Injection

Manual Tools:

  • Burp Suite: A popular intercepting proxy tool for web application security testing, which can be used to identify and exploit code injection vulnerabilities.

  • Sqlmap: A powerful open-source tool that automates the process of detecting and exploiting SQL injection vulnerabilities in web applications.

  • Metasploit: A widely used framework for developing, testing, and executing exploits, including those related to code injection vulnerabilities.

  • PowerShell: A command-line shell and scripting language used primarily on Windows systems, which can be used to execute arbitrary code and escalate privileges.

  • Netcat: A versatile networking utility that can be used to create and manipulate network connections, including for executing commands on remote systems.

  • Nmap: A popular network mapping tool that can be used to identify potential targets for code injection attacks.

  • Immunity Debugger: A powerful debugger that can be used to analyze and exploit software vulnerabilities, including those related to code injection.

  • IDA Pro: A popular disassembler and debugger that can be used to analyze binary code for vulnerabilities, including those related to code injection.

  • OllyDbg: A popular debugger for Windows systems that can be used to analyze and exploit software vulnerabilities, including those related to code injection.

  • GDB: A popular debugger for Unix and Unix-like systems, which can be used to analyze and exploit software vulnerabilities, including those related to code injection.

Automated Tools:

  • Nessus: A popular vulnerability scanner that can be used to identify code injection vulnerabilities, among other security issues.

  • Acunetix: A web application security scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • AppScan: A web application security scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • Zed Attack Proxy: An open-source web application security scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • Arachni: An open-source web application security scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • OpenVAS: An open-source vulnerability scanner that can be used to identify code injection vulnerabilities, among other issues.

  • Skipfish: An open-source web application security scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • Nikto: An open-source web server scanner that can be used to identify potential vulnerabilities, including code injection vulnerabilities.

  • Vega: An open-source web application vulnerability scanner that can be used to identify and exploit code injection vulnerabilities, among other issues.

  • SQLNinja: An open-source tool that automates the process of exploiting SQL injection vulnerabilities in web applications, including code injection vulnerabilities.

Average CVSS score of stack Code Injection

The Common Vulnerability Scoring System (CVSS) is a framework for assessing the severity of software vulnerabilities on a scale of 0 to 10, with 10 being the most severe. The CVSS score takes into account various factors, including the potential impact of the vulnerability and the ease of exploiting it.

Code injection vulnerabilities are a broad category of vulnerabilities that can exist in many different types of software and can range in severity from low to critical. The CVSS score for a code injection vulnerability depends on several factors, such as the type of code injection vulnerability, the potential impact of the vulnerability, and the likelihood of the vulnerability being exploited.

For example, a SQL injection vulnerability that allows an attacker to read sensitive information from a database might be given a CVSS score of 7 or 8, while a remote code execution vulnerability that allows an attacker to take control of a server might be given a CVSS score of 9 or 10.

Because the CVSS score of a code injection vulnerability can vary widely, it is difficult to provide an average score for all stack code injection vulnerabilities. However, it is important to note that code injection vulnerabilities can be extremely serious and can lead to data breaches, system compromises, and other security incidents. As such, it is important for software developers and security professionals to take code injection vulnerabilities seriously and to take steps to prevent and mitigate them.

The Common Weakness Enumeration (CWE)

CWE-78: Improper Neutralization of Special Elements used in an OS Command – This CWE refers to vulnerabilities where an application allows user input to be passed to an operating system command without proper validation or filtering. An attacker can use this to execute arbitrary commands on the affected system.

CWE-94: Improper Control of Generation of Code – This CWE refers to vulnerabilities where an application generates code dynamically based on user input or other data. If the code generation process is not properly controlled, an attacker may be able to inject malicious code into the generated code, leading to a variety of attacks.

CWE-98: Improper Control of Filename for Include/Require Statement in PHP Program – This CWE refers specifically to PHP programs that include or require external files. If the filename is not properly validated, an attacker can supply a malicious file that can execute arbitrary code on the server.

CWE-116: Improper Encoding or Escaping of Output – This CWE refers to vulnerabilities where an application fails to properly encode or escape output that contains user input. This can lead to a range of attacks, including cross-site scripting (XSS) and other injection attacks.

CWE-129: Improper Validation of Array Index – This CWE refers to vulnerabilities where an application fails to properly validate input that is used as an array index. If an attacker can supply an out-of-bounds index value, they may be able to manipulate program behavior or execute arbitrary code.

CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE refers to vulnerabilities where an application allows users to upload files without properly validating the file type or content. An attacker can upload a file that contains malicious code, which can then be executed on the server.

Top 10 CVES related to Code Injection

CVE-2023-25719 – ConnectWise Control before 22.9.10032 (formerly known as ScreenConnect) fails to validate user-supplied parameters such as the Bin/ConnectWiseControl.Client.exe h parameter. This results in reflected data and injection of malicious code into a downloaded executable. The executable can be used to execute malicious queries or as a denial-of-service vector.

CVE-2023-23619 – Modelina is a library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents. Versions prior to 1.0.0 are vulnerable to Code injection. This issue affects anyone who is using the default presets and/or does not handle the functionality themself. This issue has been partially mitigated in version 1.0.0, with the maintainer’s GitHub Security Advisory (GHSA) noting “It is impossible to fully guard against this, because users have access to the original raw information. However, as of version 1, if you only access the constrained models, you will not encounter this issue. Further similar situations are NOT seen as a security issue, but intended behavior.” The suggested workaround from the maintainers is “Fully custom presets that change the entire rendering process which can then escape the user input.”

CVE-2023-23551 – Control By Web X-600M devices run Lua scripts and are vulnerable to code injection, which could allow an attacker to remotely execute arbitrary code.

CVE-2023-23488 – The Paid Memberships Pro WordPress Plugin, version < 2.9.8, is affected by an unauthenticated SQL injection vulnerability in the ‘code’ parameter of the ‘/pmpro/v1/order’ REST route.

CVE-2023-22643 – An Improper Neutralization of Special Elements used in an OS Command (‘OS Command Injection’) vulnerability in libzypp-plugin-appdata of SUSE Linux Enterprise Server for SAP 15-SP3; openSUSE Leap 15.4 allows attackers that can trick users to use specially crafted REPO_ALIAS, REPO_TYPE or REPO_METADATA_PATH settings to execute code as root. This issue affects: SUSE Linux Enterprise Server for SAP 15-SP3 libzypp-plugin-appdata versions prior to 1.0.1+git.20180426. openSUSE Leap 15.4 libzypp-plugin-appdata versions prior to 1.0.1+git.20180426.

CVE-2023-22598 – InHand Networks InRouter 302, prior to version IR302 V3.5.56, and InRouter 615, prior to version InRouter6XX-S-V2.3.0.r5542, contain vulnerability CWE-78: Improper Neutralization of Special Elements used in an OS Command (‘OS Command Injection’). An unauthorized user with privileged access to the local web interface or the cloud account managing the affected devices could push a specially crafted configuration update file to gain root access. This could lead to remote code execution with root privileges.

CVE-2023-0792 – Code Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11.

CVE-2023-0788 – Code Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11.

CVE-2023-0774 – A vulnerability has been found in SourceCodester Medical Certificate Generator App 1.0 and classified as critical. This vulnerability affects unknown code of the file action.php. The manipulation of the argument lastname leads to sql injection. The attack can be initiated remotely. The exploit has been disclosed to the public and may be used. VDB-220558 is the identifier assigned to this vulnerability.

CVE-2023-0671 – Code Injection in GitHub repository froxlor/froxlor prior to 2.0.10.

Code Injection exploits

  • SQL injection attacks – This type of attack involves injecting SQL code into an application’s input fields, which can allow an attacker to execute unauthorized SQL queries and potentially access sensitive data or even take control of the affected system.

  • Command injection attacks – This type of attack involves injecting malicious code into an application’s command line input fields, which can allow an attacker to execute arbitrary commands on the affected system.

  • Cross-site scripting (XSS) attacks – This type of attack involves injecting malicious code into an application’s output fields, such as text boxes or URLs, which can allow an attacker to execute arbitrary code in a victim’s browser.

  • Remote code execution (RCE) attacks – This type of attack involves injecting malicious code into an application’s input fields, which can allow an attacker to execute arbitrary code on the affected system and potentially gain full control of it.

  • Code injection attacks in web application frameworks – Many web application frameworks have been found to be vulnerable to code injection attacks, such as the Java Struts 2 framework and the Ruby on Rails framework. In these cases, attackers can exploit vulnerabilities in the framework itself to inject malicious code into the application.

  • File inclusion attacks – This type of attack involves injecting malicious code into an application’s input fields, which can allow an attacker to include and execute arbitrary files on the affected system.

Practicing in test for Code Injection

  1. Set up a testing environment – Create a test environment that mimics your production environment. This can include web applications, APIs, and other software that your organization uses.

  2. Learn about common code injection vulnerabilities – Familiarize yourself with the different types of code injection vulnerabilities, including SQL injection, command injection, and cross-site scripting (XSS) attacks.

  3. Use automated testing tools – There are many automated tools available that can help you identify code injection vulnerabilities in your applications. These tools can help you find vulnerabilities more quickly and efficiently than manual testing.

  4. Practice manual testing – It’s important to also practice manual testing methods, as automated tools are not always able to detect all types of vulnerabilities. This can include manually testing input fields and other areas of your application for vulnerabilities.

  5. Participate in bug bounty programs – Many companies offer bug bounty programs, which reward individuals for finding vulnerabilities in their applications. Participating in these programs can give you the opportunity to practice testing for code injection vulnerabilities and receive feedback on your testing skills.

  6. Stay up-to-date with the latest threats – It’s important to stay informed about the latest threats and vulnerabilities related to code injection. This can include reading security blogs and attending industry events and conferences.

For study Code Injection

Online courses – Many online courses are available that cover code injection and related topics. These courses can provide a structured learning experience and may offer hands-on exercises and labs to help you practice.

Books – There are several books available that cover code injection and other application security topics. These books can provide in-depth information on code injection vulnerabilities and how to prevent and mitigate them.

Online resources – There are many online resources available that cover code injection, including blogs, articles, and tutorials. These resources can provide up-to-date information on the latest threats and vulnerabilities related to code injection.

Online communities – Joining online communities and forums related to application security can be a great way to connect with other professionals and learn from their experiences. These communities can also provide a platform for asking questions and receiving feedback on your own work.

Hands-on experience – Practicing testing for code injection vulnerabilities and participating in bug bounty programs can provide valuable hands-on experience and help you improve your skills.

Books with review of Code Injection

“The Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws” by Dafydd Stuttard and Marcus Pinto – This book covers a wide range of application security topics, including code injection.

“Black Hat Python: Python Programming for Hackers and Pentesters” by Justin Seitz – This book teaches readers how to use Python for hacking and penetration testing, including code injection attacks.

“Gray Hat Hacking: The Ethical Hacker’s Handbook” by Allen Harper, Daniel Regalado, and Ryan Linn – This book covers various hacking techniques, including code injection, and how to defend against them.

“The Tangled Web: A Guide to Securing Modern Web Applications” by Michal Zalewski – This book focuses on web application security, including code injection attacks and how to prevent them.

“Penetration Testing: A Hands-On Introduction to Hacking” by Georgia Weidman – This book provides a hands-on introduction to penetration testing and covers various types of attacks, including code injection.

“Hacking: The Art of Exploitation” by Jon Erickson – This book teaches readers how to find and exploit vulnerabilities in computer systems, including code injection attacks.

“Web Application Security: A Beginner’s Guide” by Bryan Sullivan and Vincent Liu – This book provides an introduction to web application security, including code injection vulnerabilities and how to prevent them.

“Secure Coding in C and C++” by Robert Seacord – This book provides guidance on how to write secure code in C and C++, including best practices for preventing code injection attacks.

“SQL Injection Attacks and Defense” by Justin Clarke – This book focuses on SQL injection attacks, a common type of code injection vulnerability.

“The Basics of Hacking and Penetration Testing: Ethical Hacking and Penetration Testing Made Easy” by Patrick Engebretson – This book provides an introduction to hacking and penetration testing, including code injection and other types of attacks.

List of payloads Code Injection

  1. Basic injection: ‘; DROP TABLE users; —

  2. Union based injection: ‘ UNION SELECT 1,2,3 —

  3. Error-based injection: ‘ AND 1=(SELECT COUNT(*) FROM tabname); —

  4. Time-based injection: ‘ AND SLEEP(10); —

  5. Boolean-based injection: ‘ OR 1=1; —

  6. Out-of-band injection: ‘); EXEC xp_cmdshell(‘ping 8.8.8.8’); —

  7. XML injection: ‘; SELECT * FROM OPENXML(@idoc, ‘/doc/@*’) —

  8. JSON injection: { “$ne”: “1” }

  9. LDAP injection: )(&(objectClass=person)(userPassword=))(|(uid=admin))

  10. XPath injection: ‘ or 1=1 or ”=’

How to be protected from Code Injection

  1. Input validation:
    Ensure that all user input is properly validated and sanitized. This can help prevent malicious code from being injected into your application.

  2. Parameterized queries:
    Use parameterized queries or prepared statements when querying a database. This can help prevent SQL injection attacks, a common type of code injection vulnerability.

  3. Encoding:
    Use encoding techniques, such as HTML entity encoding, to prevent script injection attacks and cross-site scripting (XSS) vulnerabilities.

  4. Access control:
    Implement access control mechanisms to restrict user access to certain parts of your application. This can help prevent unauthorized users from injecting malicious code.

  5. Regular updates:
    Keep your software up-to-date with the latest security patches and updates. This can help prevent known vulnerabilities, including code injection, from being exploited.

  6. Use a firewall:
    Implement a firewall to help detect and prevent malicious traffic, including attacks aimed at exploiting code injection vulnerabilities.

  7. Use a web application firewall:
    A WAF can help protect your application against a wide range of attacks, including code injection.

  8. Perform security testing:
    Regularly test your application for vulnerabilities, including code injection, using automated tools, manual testing, or both.

Conclusion

Code injection is a serious and common vulnerability that can allow attackers to execute malicious code on a system or application. It can be exploited in various ways, including SQL injection, cross-site scripting (XSS), and command injection. Code injection can result in data theft, damage to systems and applications, and other security threats.

To protect against code injection attacks, it’s important to follow best practices for secure software development, such as input validation, parameterized queries, encoding, access control, and regular updates. It’s also recommended to use firewalls, web application firewalls, and runtime application self-protection, and to perform regular security testing.

Other Services

Ready to secure?

Let's get in touch