What is SQL Injection & How to Prevent SQL Injection

What is SQL Injection?

SQL injection is a technique used by attackers to gain unauthorized access to a database in a web application by inserting a string of malicious code into a database query. SQL injection (SQLi) is the manipulation of SQL code to gain access to protected resources, such as sensitive data, or to execute malicious SQL statements.

SQL in Web Pages

SQL injection typically occurs when you request input from a user, such as their UserName/UserId, and instead of a Name/Id, the user provides you with a SQL statement that you unknowingly run on your database.

Consider the following example, which adds a variable (txtUserId) to a select string to generate a SELECT statement. The variable is retrieved from the user (getCredential).

txtUserId = getCredential("UserId");
txtResult = "SELECT * FROM Users WHERE UserId = " + txtUserId;

SQL Injection Using 1=1 is Always Correct

Examine the preceding example once more. The code’s original purpose was to generate a SQL statement to select a user with a given user id.

If nothing prevents a user from entering “wrong” input, the user can enter some “smart” input, such as this:

UserId

The SQL statement will look like this:

SELECT * FROM Users WHERE UserId = 104 OR 1=1;

As OR 1=1 is always TRUE, the SQL above is correct and will return ALL rows from the “Users” table.

By entering 104 OR 1=1 into the input field, a hacker could gain access to all of the user names and passwords in a database.

SQL Injection Using “=” is Always Correct

Let’s see the example of User Login

UserName  
Password   

UserName = getCredential("username");
UserPass = getCredential("userpassword");

sql = 'SELECT * FROM Users WHERE Name ="' + UserName + '" AND Pass ="' + UserPass + '"'

Result

SELECT * FROM Users WHERE Name ="Riya T" AND Pass ="myPass"

A hacker might get access to user names and passwords in a database by inserting ” OR “”=” into the user name or password text box as shown in below:

UserName
Password  

Result

SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

Because OR “”=”” is always TRUE, the SQL above is correct and will return all rows from the “Users” table.

How to Prevent SQL injection

  1. Validate Input
  2. Create a Prepared Statement
  3. Prepared Query

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories