<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>SQL Injection</title> </head> <body><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="security.database.storage.html">Encrypted Storage Model</a></div> <div class="next" style="text-align: right; float: right;"><a href="security.errors.html">Error Reporting</a></div> <div class="up"><a href="security.database.html">Database Security</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div><hr /><div id="security.database.sql-injection" class="sect1"> <h2 class="title">SQL Injection</h2> <p class="simpara"> Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands. </p> <p class="simpara"> Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately. </p> <p class="para"> Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database. <div class="example" id="example-334"> <p><strong>Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL) </strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$offset </span><span style="color: #007700">= </span><span style="color: #0000BB">$argv</span><span style="color: #007700">[</span><span style="color: #0000BB">0</span><span style="color: #007700">]; </span><span style="color: #FF8000">// beware, no input validation!<br /></span><span style="color: #0000BB">$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET </span><span style="color: #0000BB">$offset</span><span style="color: #DD0000">;"</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$result </span><span style="color: #007700">= </span><span style="color: #0000BB">pg_query</span><span style="color: #007700">(</span><span style="color: #0000BB">$conn</span><span style="color: #007700">, </span><span style="color: #0000BB">$query</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> Normal users click on the 'next', 'prev' links where the <var class="varname"><var class="varname">$offset</var></var> is encoded into the <acronym title="Uniform Resource Locator">URL</acronym>. The script expects that the incoming <var class="varname"><var class="varname">$offset</var></var> is a decimal number. However, what if someone tries to break in by appending a <span class="function"><a href="function.urlencode.html" class="function">urlencode()</a></span>'d form of the following to the <acronym title="Uniform Resource Locator">URL</acronym> <div class="informalexample"> <div class="example-contents"> <div class="sqlcode"><pre class="sqlcode">0; insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd) select 'crack', usesysid, 't','t','crack' from pg_shadow where usename='postgres'; --</pre> </div> </div> </div> If it happened, then the script would present a superuser access to him. Note that <em>0;</em> is to supply a valid offset to the original query and to terminate it. </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> It is common technique to force the SQL parser to ignore the rest of the query written by the developer with <em>--</em> which is the comment sign in SQL. </p> </p></blockquote> <p class="para"> A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize <em>WHERE, ORDER BY, LIMIT</em> and <em>OFFSET</em> clauses in <em>SELECT</em> statements. If your database supports the <em>UNION</em> construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged. <div class="example" id="example-335"> <p><strong>Example #2 Listing out articles ... and some passwords (any database server) </strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"SELECT id, name, inserted, size FROM products<br /> WHERE size = '</span><span style="color: #0000BB">$size</span><span style="color: #DD0000">'"</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$result </span><span style="color: #007700">= </span><span style="color: #0000BB">odbc_exec</span><span style="color: #007700">(</span><span style="color: #0000BB">$conn</span><span style="color: #007700">, </span><span style="color: #0000BB">$query</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> The static part of the query can be combined with another <em>SELECT</em> statement which reveals all passwords: <div class="informalexample"> <div class="example-contents"> <div class="sqlcode"><pre class="sqlcode">' union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable; --</pre> </div> </div> </div> If this query (playing with the <em>'</em> and <em>--</em>) were assigned to one of the variables used in <var class="varname"><var class="varname">$query</var></var>, the query beast awakened. </p> <p class="para"> SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the <em>SET</em> clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames. <div class="example" id="example-336"> <p><strong>Example #3 From resetting a password ... to gaining more privileges (any database server) </strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br />$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"UPDATE usertable SET pwd='</span><span style="color: #0000BB">$pwd</span><span style="color: #DD0000">' WHERE uid='</span><span style="color: #0000BB">$uid</span><span style="color: #DD0000">';"</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> But a malicious user sumbits the value <em>' or uid like'%admin%</em> to <var class="varname"><var class="varname">$uid</var></var> to change the admin's password, or simply sets <var class="varname"><var class="varname">$pwd</var></var> to <em>hehehe', trusted=100, admin='yes</em> to gain more privileges. Then, the query will be twisted: <div class="informalexample"> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br /></span><span style="color: #FF8000">// $uid: ' or uid like '%admin%<br /></span><span style="color: #0000BB">$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';"</span><span style="color: #007700">;<br /><br /></span><span style="color: #FF8000">// $pwd: hehehe', trusted=100, admin='yes<br /></span><span style="color: #0000BB">$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE<br />...;"</span><span style="color: #007700">;<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> </p> <p class="para"> A frightening example how operating system level commands can be accessed on some database hosts. <div class="example" id="example-337"> <p><strong>Example #4 Attacking the database hosts operating system (MSSQL Server)</strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"SELECT * FROM products WHERE id LIKE '%</span><span style="color: #0000BB">$prod</span><span style="color: #DD0000">%'"</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$result </span><span style="color: #007700">= </span><span style="color: #0000BB">mssql_query</span><span style="color: #007700">(</span><span style="color: #0000BB">$query</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> If attacker submits the value <em>a%' exec master..xp_cmdshell 'net user test testpass /ADD' --</em> to <var class="varname"><var class="varname">$prod</var></var>, then the <var class="varname"><var class="varname">$query</var></var> will be: <div class="informalexample"> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"SELECT * FROM products<br /> WHERE id LIKE '%a%'<br /> exec master..xp_cmdshell 'net user test testpass /ADD' --%'"</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$result </span><span style="color: #007700">= </span><span style="color: #0000BB">mssql_query</span><span style="color: #007700">(</span><span style="color: #0000BB">$query</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as <em>sa</em> and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine. </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner. </p> </p></blockquote> <p class="para"> <div class="mediaobject"> <div class="imageobject"> <img src="images/fa7c5b5f326e3c4a6cc9db19e7edbaf0-xkcd-bobby-tables.png" alt="A worked example of the issues regarding SQL Injection" width="666" height="205" /> </div> </div> Image courtesy of <a href="http://xkcd.com/327" class="link external">» xkcd</a> </p> <div class="sect2" id="security.database.avoiding"> <h3 class="title">Avoidance Techniques</h3> <p class="simpara"> While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'. </p> <p class="simpara"> These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters. </p> <ul class="itemizedlist"> <li class="listitem"> <span class="simpara"> Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges. </span> </li> <li class="listitem"> <span class="simpara"> Use prepared statements with bound variables. They are provided <a href="pdo.prepared-statements.html" class="link">by PDO</a>, <a href="mysqli.quickstart.prepared-statements.html" class="link">by MySQLi</a> and by other libraries. </span> </li> <li class="listitem"> <span class="simpara"> Check if the given input has the expected data type. <acronym title="PHP: Hypertext Preprocessor">PHP</acronym> has a wide range of input validating functions, from the simplest ones found in <a href="ref.var.html" class="link">Variable Functions</a> and in <a href="ref.ctype.html" class="link">Character Type Functions</a> (e.g. <span class="function"><a href="function.is-numeric.html" class="function">is_numeric()</a></span>, <span class="function"><a href="function.ctype-digit.html" class="function">ctype_digit()</a></span> respectively) and onwards to the <a href="ref.pcre.html" class="link">Perl compatible Regular Expressions</a> support. </span> </li> <li class="listitem"> <p class="para"> If the application waits for numerical input, consider verifying data with <span class="function"><a href="function.ctype-digit.html" class="function">ctype_digit()</a></span>, or silently change its type using <span class="function"><a href="function.settype.html" class="function">settype()</a></span>, or use its numeric representation by <span class="function"><a href="function.sprintf.html" class="function">sprintf()</a></span>. <div class="example" id="example-338"> <p><strong>Example #5 A more secure way to compose a query for paging</strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />settype</span><span style="color: #007700">(</span><span style="color: #0000BB">$offset</span><span style="color: #007700">, </span><span style="color: #DD0000">'integer'</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">$query </span><span style="color: #007700">= </span><span style="color: #DD0000">"SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET </span><span style="color: #0000BB">$offset</span><span style="color: #DD0000">;"</span><span style="color: #007700">;<br /><br /></span><span style="color: #FF8000">// please note %d in the format string, using %s would be meaningless<br /></span><span style="color: #0000BB">$query </span><span style="color: #007700">= </span><span style="color: #0000BB">sprintf</span><span style="color: #007700">(</span><span style="color: #DD0000">"SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;"</span><span style="color: #007700">,<br /> </span><span style="color: #0000BB">$offset</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> </p> </li> <li class="listitem"> <span class="simpara"> If the database layer doesn't support binding variables then quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. <span class="function"><a href="function.mysql-real-escape-string.html" class="function">mysql_real_escape_string()</a></span>, <span class="function"><a href="function.sqlite-escape-string.html" class="function">sqlite_escape_string()</a></span>, etc.). Generic functions like <span class="function"><a href="function.addslashes.html" class="function">addslashes()</a></span> are useful only in a very specific environment (e.g. MySQL in a single-byte character set with disabled <var class="varname"><var class="varname">NO_BACKSLASH_ESCAPES</var></var>) so it is better to avoid them. </span> </li> <li class="listitem"> <span class="simpara"> Do not print out any database specific information, especially about the schema, by fair means or foul. See also <a href="security.errors.html" class="link">Error Reporting</a> and <a href="ref.errorfunc.html" class="link">Error Handling and Logging Functions</a>. </span> </li> <li class="listitem"> <span class="simpara"> You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts. </span> </li> </ul> <p class="simpara"> Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less. </p> </div> </div><hr /><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="security.database.storage.html">Encrypted Storage Model</a></div> <div class="next" style="text-align: right; float: right;"><a href="security.errors.html">Error Reporting</a></div> <div class="up"><a href="security.database.html">Database Security</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div></body></html>