User Tools

Site Tools


sql_injection:what_is_sql_injection

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
sql_injection:what_is_sql_injection [2016/10/14 09:48] petersql_injection:what_is_sql_injection [2020/04/16 20:53] (current) – removed peter
Line 1: Line 1:
-====== SQL Injection - What is SQL Injection ====== 
- 
-===== What is SQL Injection? ===== 
- 
-SQL Injection is an exploit of improperly formatted query. 
- 
-<code php> 
-$name  = "Bobby';DROP TABLE users; -- "; 
-$query = "SELECT * FROM users WHERE name='$name'"; 
-</code> 
- 
-which compiles into malicious sequence 
- 
-<code php> 
-SELECT * FROM users WHERE name='Bobby';DROP TABLE users; -- ' 
-</code> 
- 
- 
- 
-If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: 
- 
-<code php> 
-$unsafe_variable = $_POST['user_input'];  
- 
-mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); 
-</code> 
- 
-That's because the user can input something like: 
- 
-<code php> 
-value'); DROP TABLE table;-- 
-</code> 
- 
-and the query becomes: 
- 
-<code sql> 
-INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') 
-</code> 
- 
- 
-===== What can be done to prevent this from happening? ===== 
- 
-Use prepared statements and parameterized queries.  These are SQL statements that are sent to and parsed by the database server separately from any parameters.  This way it is impossible for an attacker to inject malicious SQL. 
- 
-You basically have two options to achieve this: 
- 
-Using [[http://php.net/manual/en/book.pdo.php|PDO]] (for any supported database driver): 
- 
-<code php> 
-$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); 
- 
-$stmt->execute(array('name' => $name)); 
- 
-foreach ($stmt as $row) { 
-    // do something with $row 
-} 
-</code> 
- 
- 
-Using [[http://php.net/manual/en/book.mysqli.php|MySQLi]] (for MySQL): 
- 
-<code mysql> 
-$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); 
-$stmt->bind_param('s', $name); 
- 
-$stmt->execute(); 
- 
-$result = $stmt->get_result(); 
-while ($row = $result->fetch_assoc()) { 
-    // do something with $row 
-} 
-</code> 
- 
-If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (e.g. **pg_prepare()** and **pg_execute()** for PostgreSQL).  PDO is the universal option. 
- 
- 
-===== Correctly setting up the connection ===== 
- 
-Note that when using **PDO** to access a MySQL database real prepared statements **are not used by default**.  To fix this you have to disable the emulation of prepared statements.  An example of creating a connection using PDO is: 
- 
-<code php> 
-$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass'); 
- 
-$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
-$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
-</code> 
- 
-In the above example the error mode isn't strictly necessary, **but it is advised to add it**.  This way the script will not stop with a Fatal Error when something goes wrong.  And it gives the developer the chance to catch any error(s) which are thrown as PDOExceptions. 
- 
-What is **mandatory** however is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements.  This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL). 
- 
-Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) [[http://php.net/manual/en/ref.pdo-mysql.connection.php|silently ignored the charset parameter]] in the DSN. 
- 
- 
-===== Explanation ===== 
- 
-What happens is that the SQL statement you pass to **prepare** is parsed and compiled by the database server.  By specifying parameters (either a **?** or a named parameter like **:name** in the example above) you tell the database engine where you want to filter on.  Then when you call execute, the prepared statement is combined with the parameter values you specify. 
- 
-The important thing here is that the parameter values are combined with the compiled statement, not an SQL string.  SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database.  So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.  Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course).  In the example above, if the $name variable contains **'Sarah'; DELETE FROM employees** the result would simply be a search for the string **"'Sarah'; DELETE FROM employees"**, and you will not end up with an empty table. 
- 
-Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains. 
- 
-Oh, and since you asked about how to do it for an insert, here's an example (using PDO): 
- 
-<code php> 
-$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); 
- 
-$preparedStatement->execute(array('column' => $unsafeValue)); 
-</code> 
- 
- 
-===== Can Prepared Statements Be Used For Dynamic Queries? ===== 
- 
-While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized. 
- 
-For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values. 
- 
-<code> 
-// Value whitelist 
-  // $dir can only be 'DESC' or 'ASC' 
-$dir = !empty($direction) ? 'DESC' : 'ASC';  
-</code> 
- 
- 
-===== Warnings ===== 
- 
-All escaping a string does is suitably apply slashes before a quotation mark, but it doesn't prevent keywords being used in the string that is applied to the SQL, for example having multiple quotes can confuse the real escape string (in combination with incorrect character encoding such as  
- 
-<code php> 
-'\\''' DELETE FROM table' 
-</code> 
- 
-now, the real escape strings might escape the quotes but the string will still contain the **DELETE** clause.  
- 
-Please read https://phpdelusions.net/sql_injection and http://stackoverflow.com/a/12118602/3536236. 
- 
-http://www.sqlserverlogexplorer.com/prevent-sql-injection-in-sql-server/ 
- 
- 
-===== References ===== 
- 
-https://phpdelusions.net/sql_injection 
  
sql_injection/what_is_sql_injection.1476438491.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki