Product Code Database
Example Keywords: hat -netbooks $68-143
   » » Wiki: Code Injection
Tag Wiki 'Code Injection'.
Tag

Code injection is a computer security exploit where a 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" into the program while it is running. Successful exploitation of a code injection vulnerability can result in , access to restricted or critical , and the spread of .

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 () databases, Extensible Markup Language () parsers, commands, Simple Mail Transfer Protocol () headers, and other program arguments. Injection flaws can be identified through examination, Static analysis, or dynamic testing methods such as .

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 through ; the impact of this can range from website defacement to serious compromise of . For more information, see Arbitrary code execution.
  • Installing or executing malevolent code on a server by injecting server scripting code (such as ).
  • Privilege escalation to either permissions on by exploiting shell injection vulnerabilities in a binary file or to privileges on Microsoft Windows by exploiting a service within Windows.
  • Attacking web users with Hyper Text Markup Language () or Cross-Site Scripting (XSS) injection.
Code injections that target the Internet of Things could also lead to severe consequences such as 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.
(2026). 9783642147050, Springer.
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 in .

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 by the developer to have special meaning (such as the 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 .


Prevention
To prevent code injection problems, the person could use secure input and output handling strategies, such as:
  • Using an application programming interface () 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 .
  • Validating or "sanitizing" input, such as 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 htmlspecialchars() function to escape special characters for safe output of text in HTML and the mysqli::real_escape_string() function to isolate data which will be included in an request can protect against SQL injection.
  • Encoding output, which can be used to prevent XSS attacks against website visitors.
  • Using the HttpOnly flag for . 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 , one can use parameterized queries, , 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 .

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 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.
  • : 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 attack takes advantage of 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 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 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 alice and the password hunter2, the server will generate and run this query:

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

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

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

While hunter2 might or might not be the correct password, the expression '1'='1' is always true and the database will return all rows in the UserList 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 hunter2'; DROP TABLE UserList; --, the resulting query would be:

SELECT UserList.Username FROM UserList WHERE UserList.Username = 'alice' AND UserList.Password = 'hunter2'; DROP TABLE UserList; --'

Because the ; symbol signifies the end of one statement, it is possible to begin a new statement — in this case, DROP TABLE. The symbol -- signifies the start of a comment, thus neutralizing the trailing ' 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 UserList 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 have a 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 enter a message such as: Nice site, I think I'll take it. 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.

(2009). 9780596514839, O'Reilly Media. .


Server-side template injection
Template engines are often used in modern to display dynamic data. However, trusting non-validated user data can frequently lead to critical vulnerabilities such as server-side Side Template Injections (SSTI). 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 <nowiki></nowiki> is replaced with data during the rendering process. Hello

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


Mitigation
Preventing SSTI, like all injection attacks, begins with sanitizing user inputs. Regex checks should ensure that only safe characters are allowed. Unsafe template engine functions should be disabled and auto-escaping should be used to distinguish between input data and code. Components should be kept up to date and vendor advisories monitored for any new vulnerabilities that may be published.


Dynamic evaluation vulnerabilities
An eval() injection vulnerability occurs when an attacker can control all or part of an input string that is fed into an eval() . $myvar = 'somevalue'; $x = $_GET'arg'; eval('$myvar = ' . $x . ';'); The argument of "[[eval]]" will be processed as , 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
PHP allows and 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 was found in 2013.


Remote file injection
Consider this program (which includes a file specified by request): $color = $_GET['color']; require($color . '.php');

The example expects a color to be provided, while attackers might provide <nowiki></nowiki> 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 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.
  1. include

char input100; int number; char password10 = "Password1";

printf("Enter an integer\n"); scanf("%d", &number); printf("Please enter a string\n"); fgets(input, sizeof(input), stdin);

printf(input); printf("\n"); 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 specifiers will access the address of password, which is on the stack, and print Password1 to the screen.

Instead, to safely print the input: printf("%s", input); This hard-codes the format behavior, preventing format specifier injection.


Shell injection
Shell injection (or command injection) is named after UNIX shells but applies to most systems that allow software to programmatically execute a . Here is an example vulnerable script:

  1. !/bin/tcsh
  2. check arg
  3. outputs "it matches" if the argument is 1
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 (hypothetical) shell command evil 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.Douglas W. Jones, CS:3620 Notes, Lecture 4—Shell Scripts. , Spring 2018.

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

The passthru 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 provided by the web browser, this allows the 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):

Sequential executionUSER_INPUT; malicious_commandExecutes /bin/funnytext ; malicious_command, then executes funnytext.
Pipelinesmalicious_command&#124; malicious_commandSends the output of /bin/funnytext &#124; malicious_command as input to funnytext.
Command substitutionmalicious_command`malicious_command`Sends the output of /bin/funnytext `malicious_command` as arguments to malicious_command.
Command substitutionfunnytext$(malicious_command)Sends the output of /bin/funnytext $(malicious_command) as arguments to malicious_command.
AND listfunnytext&& malicious_commandExecutes /bin/funnytext && malicious_command malicious_command returns an exit status of 0 (success).
OR listfunnytext&#124;&#124; malicious_commandExecutes /bin/funnytext &#124;&#124; malicious_command malicious_command returns a nonzero exit status (error).
Output redirectionfunnytext&gt; ~/.bashrcOverwrites the contents the /bin/funnytext &gt; ~/.bashrc file with the output of .bashrc.
Input redirectionfunnytext&lt; ~/.bashrcSends the contents of the /bin/funnytext &lt; ~/.bashrc file as input to .bashrc.

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

  • : funnytext and [http://www.php.net/manual/en/function.escapeshellarg.php escapeshellarg()]
  • Python: [http://www.php.net/manual/en/function.escapeshellcmd.php escapeshellcmd()]

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 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 functionality by invoking [https://docs.python.org/3/library/shlex.html#shlex.quote shlex.quote()] shell commands, it is better to use a Git API such as libgit2.


Cypher Injection
Cypher is a language similar to SQL languages, but for retrieving data from Neo4j’s . Cypher Injection occurs when an attacker uses Cypher to read, write, or delete data from a graph database. Concatenated user inputs can lead to execution, and depending on Neo4j’s configuration, an attacker may be able to access other services. All user inputs should be parameterized, however, Neo4j parameters are limited and may still be vulnerable to injection when concatenated. Node labels, relationship types, and parameters must be sanitized as they can include non-alphabetic characters. Backticks, single quotes, and double quotes are escape characters in cypher and must be sanitized.


See also

External links

Page 1 of 1
1
Page 1 of 1
1

Account

Social:
Pages:  ..   .. 
Items:  .. 

Navigation

General: Atom Feed Atom Feed  .. 
Help:  ..   .. 
Category:  ..   .. 
Media:  ..   .. 
Posts:  ..   ..   .. 

Statistics

Page:  .. 
Summary:  .. 
1 Tags
10/10 Page Rank
5 Page Refs
1s Time