SQL Injection› Blind SQL Injection Vulnerable Code Exploit› Classic Login Page Vulnerability› Error Based Injection(SQL Server)› Union Based Injection› Injection SQL Command› Running CMD Command› Blind Injection Attack
How to Prevent› Parameterized Query› Use of Stored Procedure› Escaping All User Supplied Input› Additional Defenses(Configuration) Latest Privilege Isolate the Web Server Turning off Error Reporting PHP Configuration
A SQL injection attack consists of insertionor "injection" of a SQL query via the inputdata from the client to the application. A successful SQL injection exploit canread sensitive data from thedatabase, modify database data (Insert/Update/ Delete), execute administrationoperations on the database (such asshutdown the DBMS).
SQL Injection recover the content of a givenfile present on the DBMS file system and insome cases issue commands to the operatingsystem. SQL injection is a code injectiontechnique that exploits a securityvulnerability occurring in the databaselayer of an application. SQL injection is one of the oldest attacksagainst web applications.
Blind SQL injection is identical to normal SQLInjection except that when an attackerattempts to exploit an application rather thengetting a useful error message they get ageneric page specified by the developerinstead. This makes exploiting a potential SQLInjection attack more difficult but notimpossible. An attacker can still steal data by asking a seriesof True and False questions through SQLstatements.
SQL Injection happens when a developer acceptsuser input that is directly placed into a SQLstatement and doesnt properly filter out dangerouscharacters. This can allow an attacker to not only steal datafrom your database, but also modify and deleteit. Attackers commonly insert single quotes into aURLs query string, or into a forms input field totest for SQL Injection. Every code that uses user inputs to generate SQLqueries without sanitization is vulnerable to SQLinjections.
SQL Injection is very common with PHPand ASP applications due to theprevalence of older functional interfaces. Due to the nature of programmatic interfacesavailable, Java EE and ASP.NET applicationsare less likely to have easily exploited SQLinjections. SQL injection bugs is very various so it isvery difficult to identify the actual procedureof preventing SQL injection.
The attacker attempts to elicit exceptionconditions and anomalous behavior fromthe Web application by manipulating theidentified inputs.› Special Characters› White Space› SQL Keywords› Oversized request
Any unexpected reaction from the Webapplication is noted and investigated by theattackers.› Scripting Error Message possibly with snippets of code› Server Errors Error 500/ Error 513› Half Loader Page› Timed out Server Request
Attackers often try following inputs todetermine if web application has sql injectionbug or not.› › or 1=1› or 1=1—› " or 1=1—› or 1=1--› or a=a› " or "a"="a› ) or (a=a
Here is a login SQL query-› var sql = "select * from users whereusername = " + username + " andpassword = " + password + ""; In a normal login when user inputs arefollowings:› Username: John› Password: 1234 The query string is:› select * from users where username =John and password = 1234
But if user manipulates input like thefollowings:› Username: John› Password: i_dont_know or x=x Then the query becomes:› select * from users where username =John and password = i_dont_know orx=x‘ So where clause is true for every row of tableand user can login without knowing password!
If the user specifies the following:› Username: ; drop table users-- The users table will be deleted, denying accessto the application for all users.› The -- character sequence is the single linecomment sequence in Transact-SQL.› The ; character denotes the end of one query andthe beginning of another.› The -- at the end of the username field is required inorder for this particular query to terminate withouterror.
The attacker could log on as any user, giventhat they know the users name, using thefollowing input:› Username: admin‘-- The attacker could log in as the first user in theusers table, with the following input:› Username: or 1=1-- the attacker can log in as an entirely fictionaluser with the following input:› Username: union select1, fictional_user, some_password, 1--
This is the most common attack on MicrosoftSQL Server. This kind of attack is based on errormessage received from server. Error messages that are returned from theapplication, the attackers can determine thedetermine the entire structure of thedatabase or can get any value that can beread only by a user of that application.
The UNION operator is used to combine theresult-set of two or more SELECT statements. In this kind of injection attacker tries to inject aunion operator to the query to change the resultto read information. Union based attacks look like this:› Username: junk union select1,2,3,4,... -- Notice that each SELECT statement within theUNION must have the same number ofcolumns.
Attacker can inject sql commands if the database supports stacked queries. In most of data bases it is possible toexecuting more than one query in onetransaction by using semicolon ( ;). Following example show how to create atable named foo which has a single columnline by injecting stacked query:› Username: create table foo (linevarchar(1000))--
This can only work on Microsoft SQL Server. Attacker can use stored procedures to dothings like executing commands. xp_cmdshell is a built-in extended storedprocedure that allows the execution ofarbitrary command lines. For example:› Username: ; execmaster..xp_cmdshell dir‘--
Some of MS-SQL Extended storedprocedures are listed below:› xp_cmdshell - execute shell commands› xp_enumgroups - enumerate NT user groups› xp_logininfo - current login info› xp_grantlogin - grant login rights› xp_getnetname - returns WINS server name› xp_regdeletekey - registry manipulation› xp_msver - SQL server version info
An attacker may verify whether a sent requestreturned True or False in a few ways:› (in)visible content: Having a simple page, whichdisplays article with given ID as theparameter, the attacker may perform a couple ofsimple tests if a page is vulnerable to SQL Injectionattack.› Example URL: http://newspaper.com/items.php?id=2› Sends the following query to the database: SELECT title, description, body FROMitems WHERE ID = 2
› Timing Attack: A Timing Attack depends uponinjecting the following MySQL query: SELECT IF(expression, true, false)› Using some time-taking operation e.g.BENCHMARK(), will delay server responses ifthe expression is True. BENCHMARK(5000000,ENCODE(MSG,by 5seconds))› This will execute 5000000 times the ENCODEfunction.
Parameterized queries force the developerto first define all the SQL code, and thenpass in each parameter to the query later. This coding style allows the database todistinguish between code anddata, regardless of what user input issupplied. Prepared statements ensure that an attackeris not able to change the intent of aquery, even if SQL commands are insertedby an attacker.
Language specific recommendations:› Java EE – use PreparedStatement() with bindvariables› .NET – use parameterized queries likeSqlCommand() or OleDbCommand() with bindvariables› PHP – use PDO with strongly typedparameterized queries (using bindParam())› Hibernate - use createQuery() with bindvariables (called named parameters inHibernate)
Stored procedures have the same effect asthe use of prepared statements whenimplemented safely. They require the developer to define the SQLcode first, and then pass in the parametersafter. The difference between prepared statementsand stored procedures is that the SQL code for astored procedure is defined and stored in thedatabase itself, and then called from theapplication.
This is a technique to escape user inputbefore putting it in a query. This is a very useful method because this canbe applied with almost no effect on thestructure of the code. This actually removes some specialcharacters from the input data that arehighly vulnerable to the DBMS such as- * , `( ) - -- ;
Least Privilege› Web applications should not use one connectionfor all transactions to the database. Because if aSQL Injection bug has been exploited, it cangrant most access to the attacker. Isolate the Webserver› Design the network infrastructure to assumethat attackers will have full administrator accessto the machine, and then attempt to limit howthat can be leveraged to compromise otherthings.
Turning off error reporting› The default error reporting for someframeworks includes developer debugginginformation, and this cannot be shown tooutside users. PHP Configuration› PHP Configuration has a direct bearing on theseverity of attacks.› many “security” options in PHP are setincorrectly by default and give a false sense ofsecurity.