Categories
security sql sql-injection

What is SQL injection? [duplicate]

106

Can someone explain SQL injection? How does it cause vulnerabilities? Where exactly is the point where SQL is injected?

12

28

SQL Injection occurs when the user of an application is able to affect the meaning of database query. This often occurs when arbitary strings from user input are concatenated to create SQL which is fed to the database. For example lets say we had the following code (in PHP, but the same holds true for any language), which might be used to handle a user login.

$sql = "SELECT  FROM users WHERE username="".$_GET["username']."' AND password='".$_GET['password']."'";

The harm is done when the user enters something like

administrator'; --

… for the username. Without proper encoding the query becomes:

SELECT * FROM users WHERE username="administrator"; -- AND password=''

The issue here is that the ‘ in the username closes out the username field then the — starts a SQL comment causing the database server to ignore the rest of the string. The net result is the user can now log in as the administrator without having to know the password. SQL Inection can also be used to execute UPDATE, DELETE or DROP queries and really damage the database.

SQL Injection can be prevented by using parameterised queries, or applying your language/toolkit’s escaping functions (such as mysql_real_escape_string() in PHP).

Once you understand SQL Injection you’ll get the joke behind this cartoon.

0

    14

    This question has been answered many times on StackOverflow, but it’s an important topic for everyone to know about, so I’m not going to vote to close this question.

    Here are links to some of my past answers on this topic:

    I also gave a presentation at the MySQL Conference this month, and my slides are online: