Basically SQL Injection is used for hacking purposes since it is mostly used by Hackers. SQL Injection can destroy your whole database.
When SQL is used to display the data on the web page, it is common to let the web users to input their own search values to perform some hacking or to perform his/her own action accordingly.
Since SQL statements are text only, so it is easy (with a little piece of computer code) to dynamically change the SQL statements to provide the user with selected data.
Let's look at the following code:
txtUserId = getRequestString("UserId"); txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The above example creates a SELECT statement by adding a variable (i.e., txtUserId here) to a select the string. The variable is fetched from the user input (request) to the page.
Now let us describe the potential dangers of using the user inputs in SQL statements.
SQL injection is a technique where a malicious user can inject the SQL commands into the SQL statement, via the web page inputs.
Injected SQL commands can alter the SQL statement and compromise the security of a web application.
Let us look at the example above, one more time.
Let us say that the original purpose of the code was to create an SQL statement to select a user with the given user id.
If there is nothing to prevent a user from entering the "wrong" input, the user can enter some "smart" input like this:UserId:
SELECT * FROM Users WHERE UserId = 105 or 1=1
Here, the SQL statement above is valid. So, it will return all the rows from the table named Users, since WHERE 1=1 is always true.
The above example may cause some dangers if the table Users contains names and passwords or other useful information.
The SQL statement above is same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1
Using SQL Injection, a smart hacker might get access to all the user names and passwords present in the database by simply inserting 105 or 1=1 into the input box.
Following is a common construction, that is used to verify the user login to a web site:User Name:
Let's look at the following server code:
uName = getRequestString("UserName"); uPass = getRequestString("UserPass"); sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
A smart hacker might get access to all the user names and passwords present in the database by simply inserting " or ""=" into the user name or password field of the input box.
The code at the server will create a valid SQL statement like this :
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
This result in SQL is valid and it will return all the rows present in the table Users, since WHERE ""="" is always true.