SQL Injection: Prof. Kirtankumar Rathod Dept. of Computer Science ISHLS, Indus University
SQL Injection: Prof. Kirtankumar Rathod Dept. of Computer Science ISHLS, Indus University
Example
• txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
SQL Injection Based on 1=1 is Always True
• Look at the example above again. The original purpose of the code
was to create an SQL statement to select a user, with a given user id.
• If there is nothing to prevent a user from entering "wrong" input, the
user can enter some "smart" input like this:
• UserId: 105 or 1=1
• Then, the SQL statement will look like this:
• SELECT * FROM Users WHERE UserId = 105 OR 1=1;
SQL Injection Based on 1=1 is Always True
• The SQL above is valid and will return ALL rows from the "Users" table, since
OR 1=1 is always TRUE.
• Does the example above look dangerous? What if the "Users" table contains
names and passwords?
• The SQL statement above is much the same as this:
• SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
• A hacker might get access to all the user names and passwords in a database, by
simply inserting 105 OR 1=1 into the input field.
SQL Injection Based on ""="" is Always
True
• Here is an example of a user login on a web site:
• Example
• uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND
Pass ="' + uPass + '"'
• Result
• SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
• A hacker might get access to user names and passwords in a database by simply
inserting " OR ""=" into the user name or password text box:
• Result
• SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
• The SQL above is valid and will return all rows from the "Users" table, since
OR ""="" is always TRUE.
Here, in this example the query will return all the
values of student name based on the SQL injection
“1=1” which is always TRUE..
How to Prevent an SQL Injection
• The only sure way to prevent SQL Injection attacks is input validation and
parametrized queries including prepared statements.
• The application code should never use the input directly. The developer must
sanitize all input, not only web form inputs such as login forms.
• They must remove potential malicious code elements such as single quotes.
• It is also a good idea to turn off the visibility of database errors on your
production sites. Database errors can be used with SQL Injection to gain
information about your database.
How to Prevent SQL Injections (SQLi) –
Generic Tips
Step 1: Train and maintain awareness
• To keep your web application safe, everyone involved in building the web application
must be aware of the risks associated with SQL Injections. You should provide suitable
security training to all your developers, QA staff, DevOps, and SysAdmins.