SQL Injection is an injection attack wherein attacker is able to submit a database SQL command which is executed by a web application exposing back-end database. Attacker can add SQL query in web form input text box to gain access to resources and make changes in database. On a user authentication web form , user is allowed to enter username and password in the text boxes provided for them, those values are inserted into a SELECT query. If the entered username and password values are found as corrected, then user is allowed access otherwise access is denied. However in most of the web forms, there is no way to block input text boxes other than username and password so in this manner attacker can send his own request through input text boxes to database, which can allow them to gain whole access to entire database.
Lets see an example from the below table "users" :-
Lets say we have a authentication web form
Lets see the query and the server code to authenticate user.
WHERE `userName` = '" . $username . "' AND `password` = '" . $password . "';
Now see the query below, how an attacker can type anything in the username and password text box by simply inserting " or ""=" to expose the database table users. It means how he can gain access to all usernames and passwords.The above authenticate query can become like below :-
WHERE `userName` ="" or ""="" AND `password` ="" or ""="";
Above Query will return all the rows from users table. since WHERE ""="" is always TRUE.Similarly Attacker might enter 1=1 which is also always TRUE and return all the rows from the table.
Preventing SQL Injection
We can prevent SQL Injection by applying input validation technique in which user input is authenticated to enter alphabets, integer, alphanumeric, symbols, length etc.
We should make sure that users with the permission to access the database have the least privileges.