Code Injection

Enes Yilmaz
17 min readOct 22, 2022

--

  1. What is Code Injection?

Exploitation of computer error resulting from processing invalid data. Injection is used by an attacker to inject code into a vulnerable computer program and change the course of execution.

Code injection refers to attacks that involve injecting malicious code into an application. The application then interprets or executes code that affects the application’s performance and functionality.

Code injection attacks often take advantage of existing data vulnerabilities, such as insecure processing of data from untrusted sources.

2.How Code Injection Attacks Work?

Code Injection, also known as Remote Code Execution or Code Evaluation, involves replacing an executable or script that contains malicious code. Hackers first probe the application for attack surfaces that can accept untrusted data and use it while executing program code. These include direct input such as file uploads, form fields, or other data sources such as cookies and query string parameters.

A successful exploit gives attackers access to the application’s server-side interpreter. Attackers can use system calls to run commands on the server and further penetrate for deeper exploitation.

3.Types of Code Injection Attacks

3.1. XSS Attack

3.2. LDAP Injection

3.3. SQL Injection

3.4. Command Injection

3.1. XSS (Cross-Site Scripting) Attack

3.1.1. What is XSS?

A cross-site scripting attack (XSS) occurs when a hacker injects malicious code, usually in the form of client-side scripting, into the content of a web page that is seen as benign and trustworthy. Malicious scripting is usually written in client-side programming languages, which are JavaScript and HTML.

In general, web applications prone to XSS attacks do not validate or encode users’ input. A cyber criminal could exploit this flaw and send a dangerous script to an unsuspecting end user. Unfortunately, the user’s browser treats the script as if it comes from a trusted source and executes it; this potentially harms the unsuspecting user.

3.1.2. How Does an XSS Attack Work?

  • Cyber criminals discover that a web page that accepts users’ input is vulnerable to XSS attacks. It may be accepting users’ input via comment boxes, login forms, or search boxes.
  • Attackers create a malicious script (payload) and send it to an unsuspecting user. It can attach the payload to a phishing link and persuade the targeted person to click it
  • When the targeted person clicks on the malicious link, they are taken to the vulnerable web page they trusted until now.
  • Payload is injected into the vulnerable web page and the targeted person’s web browser treats it as legitimate source code.
  • When the unsuspecting user enters some entries and submits them, the payload is carried out according to the instructions of the cyber criminals.

3.1.3. XSS Attack Types

There are three main attack strategies for XSS. These are DOM XSS, reflected XSS, and stored XSS.

3.1.3.1. DOM XSS

In a DOM-based XSS attack strategy, the hacker injects payload by changing the document object model (DOM) in the victim’s browser, where the original client script is running. The page doesn’t change, but the client-side code found on the page works with malicious code changes.

3.1.3.2. Reflected XSS

In a reflected XSS cyber attack, also known as non-persistent XSS, hackers inject malicious script directly into an HTTP request. It then mirrors it to the user’s browser where it was executed from the web server. The hacker often sends the targeted people customized links that bring them to a vulnerable page.

Reflected XSS attacks are not permanent. When a user clicks on a malicious link, is tricked into submitting a specially crafted form or browsing a malicious site, the injected code goes to the vulnerable website. The web server, in turn, returns or mirrors the injected script to the user’s browser. This deception can be in an error message, search result, or any other type of response that includes data sent to the server as part of the request. The browser executes the code as it assumes the response comes from a “trusted” server that the user is already interacting with.

3.1.3.3 Stored XSS

Attacks occur when hackers store their payloads on a compromised server. It is a generally damaging XSS attack method. The attacker uses this approach to inject their payload into the target application. If the application does not have login validation, the malicious code is permanently stored or persisted by the application in a location such as a database. In practice, this allows an attacker to insert a malicious script into user input fields, such as comment sections on a blog or forum post.

The payload of the attacker is presented to the user’s browser when they open the infected page, in the same way that a legitimate comment would appear in their browser. The targeted people accidentally execute the malicious script when they view the page in their browser.

3.1.4 Common Cross-Site Scripting Vulnerability Vectors

  • script tags
  • i-frame tags
  • image attributes
  • input tags
  • link tags
  • the background attribute of table tags and <td> tags
  • div tags
  • object tags

3.1.5 How to prevent XSS attacks?

  • Filter input on arrival

At the point where user input is received, filter as strictly as possible based on what is expected or valid input.

  • Encode data on output

At the point where user-controllable data is output in HTTP responses, encode the output to prevent it from being interpreted as active content. Depending on the output context, this might require applying combinations of HTML, URL, JavaScript, and CSS encoding.

  • Use appropriate response headers

To prevent XSS in HTTP responses that aren’t intended to contain any HTML or JavaScript, you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend.

  • Content Security Policy

As a last line of defense, you can use Content Security Policy (CSP) to reduce the severity of any XSS vulnerabilities that still occur.

3.2 LDAP ( Lightweight Directory Access Protocol) Injection

3.2.1 What is LDAP injection?

LDAP injection is a vulnerability in which queries are constructed from un trusted input without prior validation or sanitization. LDAP uses queries constructed from predicates that involve the use of special characters (e.g., brackets, asterisks, ampersands, or quotes). Meta characters such as these control the meaning of the query; thereby, affecting the type and number of objects retrieved from the underlying directory. If an attacker can submit input containing these control characters, they can alter the query and change the intended behavior.

3.2.2 How do LDAP injections work?

An LDAP injection attack exploits security loopholes caused by un sanitized user input data. In other words, LDAP injections create malformed queries to gain access in order to potentially change data in a directory. LDAP queries contain special characters such as asterisks, brackets, ampersands and quotes. These characters control the meaning of LDAP queries and dictate the type and number of objects returned by a query. Attackers can alter the query and its intended behavior by modifying these control characters within the query.

For example, in a login query that uses LDAP, an attacker can enter the username plus several meta characters that manipulate the protocol into ignoring the password field.

Using LDAP injection, an attacker can enter the directory to gain access to unauthorized information or modify LDAP statements and content inside the LDAP tree. They can also exploit web applications that create LDAP statements based on user input. Tools that use LDAP include Red Hat Directory Server and Microsoft Active Directory.

3.2.3 LDAP Attack Types

3.2.3.1. Authentication bypass

3.2.3.2. Elevation of access privileges

3.2.3.3. Resource disclosure

3.2.3.4. Blind attack

3.2.3.1 Authentication bypass

Authentication bypass on a login page, there are generally two text box fields for a username and password. LDAP normally validates username and password pairs using LDAP filters. To bypass the password validation portion of the process, the attacker can enter a meta character — specifically an ampersand.

3.2.3.2. Elevation of access privileges

Elevation of access privileges an attacker uses un sanitized user input to gain unauthorized access to information that is reserved for privileged users in the system.

3.2.3.3. Resource disclosure

Resource disclosure the attacker takes advantage of the fact that some objects in the LDAP system are searchable by any user. The attacker searches for a certain object, and under normal circumstances, the directory would return all publicly available results. With the insertion of malicious code, the attacker could manipulate this query to return all objects of that type, both private and public.

3.2.3.4. Blind attack

Blind attack Blind LDAP injections work on binary They elicit a true or false response from the server, enabling the attacker to gain information about the contents of the directory. These attacks are slower to implement but are simpler because they just rely on a true or false response. Attackers can test if a certain resource exists or is available — a user object or a printer, for example. A skilled hacker could use this technique to return more complex values using a mechanism called Booleanization. For example, a hacker could query each value in a string as a true or false question, until the entire string is revealed.

3.2.4 How to prevent LDAP injection attacks?

  • Input validation (allow listing)

Allow listing involves only accepting input that is known to be good; for example, setting an expected length or numeric range for a given input field.

  • Escaping all variables

This tells the computer to ignore the special functions of meta characters — like ampersands — that hackers can use to manipulate LDAP input fields. Some querying frameworks escape automatically when building queries — like LINQ to LDAP, for example.

  • Indexing fields that contain sensitive information

This increases the number of filters an attacker has to bypass or manipulate to access sensitive information.

  • Static source code analysis tools

These enable developers to debug an LDAP application before it is running.

  • Dynamic checks

These enable developers to test and debug an application while it is running.

3.3 SQL (Structured Query Language) Injection

3.3.1 What is SQL Injection?

SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve. This might include data belonging to other users, or any other data that the application itself is able to access. In many cases, an attacker can modify or delete this data, causing persistent changes to the application’s content or behavior.

In some situations, an attacker can escalate an SQL injection attack to compromise the underlying server or other back-end infrastructure, or perform a denial-of-service attack.

3.3.2 How Does a SQL Injection Attack Work?

A SQL injection attack targets vulnerabilities in dynamic SQL statements. Think of a dynamic SQL statement like a multivariate function in mathematics, of which the parameters are fixed, while the values substituted in the independent variables determine the result.

Similarly, a dynamic SQL statement also consists of a predetermined set of parameters (such as a web form), of which the complete statement is only generated when a user fills in their inputs. See the following example of a SQL statement of a login form:

SELECT * FROM users WHERE username = ‘$username’ AND password = bcrypt (‘$password’)

<?php
$query = "SELECT * FROM users WHERE kullanıcı adı = '" . $_POST['kullanıcı adı'] . "'";
$sorgu .=" VE şifre = '" . $_POST['şifre'] . "'";
?>

After the user enters their username and password, the statement would be completed, after which a query would be sent to the server to retrieve the user’s information from the database.

When a vulnerability exists in a dynamic SQL statement, the attacker would be able to enter complex scripts into the forms to interfere with the preexisting parameters to alter the meaning of the complete statement.

3.3.3 SQL Injection Attack Types

3.3.3.1. In-band SQLi (Classic SQLi)

3.3.3.2. Inferential SQLi (Blind SQLi)

3.3.3.3. Out-of-band SQLi

3.3.3.1. In-band SQLi (Classic SQLi)

In-band SQL Injection is the most common and easy-to-exploit of SQL Injection attacks. In-band SQL Injection occurs when an attacker is able to use the same communication channel to both launch the attack and gather results.

Error-based SQLi is an in-band SQL Injection technique that relies on error messages thrown by the database server to obtain information about the structure of the database. In some cases, error-based SQL injection alone is enough for an attacker to enumerate an entire database. While errors are very useful during the development phase of a web application, they should be disabled on a live site, or logged to a file with restricted access instead.

Union-based SQLi is an in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result which is then returned as part of the HTTP response.

3.3.3.2. Inferential SQLi (Blind SQLi)

Inferential SQL Injection, unlike in-band SQLi, may take longer for an attacker to exploit, however, it is just as dangerous as any other form of SQL Injection. In an inferential SQLi attack, no data is actually transferred via the web application and the attacker would not be able to see the result of an attack in-band (which is why such attacks are commonly referred to as blind SQL Injection attacks. Instead, an attacker is able to reconstruct the database structure by sending payloads, observing the web application’s response and the resulting behavior of the database server.

Boolean-based SQL Injection is an inferential SQL Injection technique that relies on sending an SQL query to the database which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result.Depending on the result, the content within the HTTP response will change, or remain the same. This allows an attacker to infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically slow (especially on large databases) since an attacker would need to enumerate a database, character by character.

Time-based SQL Injection is an inferential SQL Injection technique that relies on sending an SQL query to the database which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE.Depending on the result, an HTTP response will be returned with a delay, or returned immediately. This allows an attacker to infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically slow (especially on large databases) since an attacker would need to enumerate a database character by character.

3.3.3.3. Out-of-band SQLi

Out-of-band SQL Injection is not very common, mostly because it depends on features being enabled on the database server being used by the web application. Out-of-band SQL Injection occurs when an attacker is unable to use the same channel to launch the attack and gather results.

Out-of-band techniques, offer an attacker an alternative to inferential time-based techniques, especially if the server responses are not very stable (making an inferential time-based attack unreliable).

Out-of-band SQLi techniques would rely on the database server’s ability to make DNS or HTTP requests to deliver data to an attacker. Such is the case with Microsoft SQL Server’s xp_dirtree command, which can be used to make DNS requests to a server an attacker controls; as well as Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL and PL/SQL to a server an attacker controls.

3.3.4 How to Prevent a SQL Injection Attack?

Preventing or mitigating SQL injection attacks is a lot about ensuring that none of the fields are vulnerable to invalid inputs and application execution. yours is manually impossible to actually to check every page and every application on the website, especially when updates are frequent and user-friendliness is the top priority.Nonetheless, security analysts and seasoned developers recommend a number of the subsequent points guarantee your database square measure well protected inside the confinement of the server.

1)Continuous Scanning and Penetration Testing

The automated web application scanner has been the best choice to point out vulnerabilities within the web applications for quite some time now. Now, with SQL injections getting smarter in exploiting logical flaws, website security professionals should explore manual testing with the help of a security vendor.

They can authenticate user inputs against a set of rules for syntax, type, and length. It helps to audit application vulnerabilities discreetly so that you can patch the code before hackers exploit it to their advantage.

2)Restrict Privileges

It is more of a database management function, but enforcing specific privileges to specific accounts helps prevent blind SQL injection attacks. Begin with no privileges account and move on to ‘read-only’, ‘edit’, ‘delete’ and similar privilege levels.

Minimizing privileges to the application will ensure that the attacker, who gets into the database through the application, cannot make unauthorized use of specific data.

3)Use Query Parameters

Dynamic queries create a lot of troubles for security professionals. They have to deal with variable vulnerabilities in each application, which only gets graver with updates and changes. It is recommended that you prepare parameterized queries.

These queries are simple, easy to write, and only pass when each parameter in SQL code is clearly defined. This way, your info is supplied with weapons to differentiate between code and information inputs.

4)Instant Protection

A majority of organizations fail the problems like outdated code, scarcity of resources to test and make changes, no knowledge of application security, and frequent updates in the application. For these, web application protection is the best solution.

A managed web application firewall can be deployed for immediate mitigation of such attacks. It contains custom policies to block any suspicious input and deny information breach instantly. This way, you do not have to manually look for loopholes and mend problems afterward.

3.4. Command Injection

3.4.1. What is Command Injection?

Accomplished by sending incidental and corrupted commands towards the host server’s OS, this attack aspires to gain admin-like control of the targeted site or app and its associated elements. Depending upon the intensity, the OWASP command injection attack can influence other application components such as hosting infrastructure, trust between the client and the server, and overall application performance.

3.4.2 How Does Command Injection Work?

  • Its success is more probably when risky elements like HTTP header fields, form components, and session cookies are linked with the user-delivered data
  • For complete execution, attackers take the help of any third-party vulnerable resource/application
  • The lack of valid inputs supports the existence of this attack
  • This attack doesn’t necessitate the insertion of code. Instead, it deals with expanding the default app capabilities to deploy command injection payloads successfully on the tempered system.

Examples

  1. Let’s say, there is a program that allows users to view file contents but the commands including “;rm -rf /” work for it. An intruder can erase data from the current partition’s contents easily through it.
  2. Let’s consider a command injection PHP scenario now. If a corrupted HTTP GET request is accepted in your system, it can manipulate your files, putting them at risk for sure. See this:

http ://127.0.0.1/delete.php?filename=inject_demo.txt;id

The above command will delete a file named “inject_demo.txt” from your website/app and can be run by anyone.

3.4.3. Command Injection Attack Types

3.4.3.1. Random command injection

3.4.3.2. Arbitrary file uploading or usage

3.4.3.3. Vulnerable serialization

3.4.3.4. Server-side Template Injection

3..4.3.5. XML External Entity Injection or XXE

3.4.3.1. Random command injection

There are various applications that allow clients to execute random commands. These apps are more prone to injection through commands as commands can be sent automatically to the host.

3.4.3.2. Arbitrary file uploading or usage

Applications permitting clients to upload any random file is problematic because attacks can make use of it to carry out command injection attacks. It’s easy to introduce any malicious command using an arbitrary file.

Mostly, threat actors place such files in the web root and execute the attack.

3.4.3.3. Vulnerable serialization

When server-side deserialization is completed without adequate user input verification, it’s easy to perform this attack.

3.4.3.4. Server-side Template Injection

It permits a website to create dynamic HTML responses, which is an opportunity for attackers. The presence of such HTML responses makes malicious command insertion on the server-side templates possible.

3.4.3.5. XML External Entity Injection or XXE

Applications featuring an ill-configured XML parser won’t be able to parse the user-controlled XML inputs properly and create a vulnerability space for the command injection. Taking the advantage, attackers can introduce an exploited command in the XML parser resulting in DDoS and SSRF attacks. Additionally, it will lead to data theft.

3.4.4. How to prevent command injection?

Depending on the affected application and the data it inherits, the result of a command injection can be very harmful. Therefore, along with early detection, some of the most appropriate command injection prevention tactics should be aware of

Safeguard ‘exec’ First

Try to avoid “exec” out to the OS as much as possible as it will keep the risks on the lower side. Ensure that most of the application work is done inside the application.

Strict Validation Checks

Make sure that the un trusted inputs are validated from beginning to end. Introducing non-validated inputs encourages vulnerability in the application. Along with the validation, one must also ensure that the inputs meet the application’s expectations.

One of the most widely acceptable validation processes is “whitelist validation” which involves accepting only application-compatible input and rejecting others. While performing validation, input components like character set, date bounds, minimum & maximum length, date & numeric bounds, Regular Expression Pattern match value, and many more.

Neutralize meta-characters

There are many meta-characters that hold some importance in the OS command line. So, by neutralizing them, you can prevent their misuse by hackers. It should be done in Windows, Linux, and Unix OS.

Window users can make this happen by preceding every character with a ‘^’. To neutralize its special meaning, ( ) <>& * ‘ | = ? ; [ ] ^ ~ ! . ” % @ / \ : + , ` needs to be done.

The procedure is used for Linux and Unix OS. In this case, antecedent of the subsequent characters should be done with an ‘\’ and meaning neutralization can be one with { } ( ) <>& * ‘ | = ? ; [ ] $ — # ~ ! . ” % / \ : + , `. In each case, meaning neutralization will be done to the command-line interpreter.

Give Fewer Privileges

Implementing least privilege is not direct prevention. But, as it limits the permissions related to the account used for OS command execution, it keeps the risks and incurred harm on the lower side.

Use Safe APIs

Command execution should be done with the help of secured APIs. Such APIs reduce the command injection risks as they permit the command execution first as a parameter and then as a command-line arguments array. This way, it warrants extensive command validation and takes the form of a valid program, free from risky elements.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Enes Yilmaz
Enes Yilmaz

Written by Enes Yilmaz

Fırat University Software Engineer

No responses yet

Write a response