Wednesday, April 10, 2013

Sql Injection

Sql Injection just like a solving the puzzle for this we need little bit understanding of sql.

Basically when we use Select Clause to retrieve record from database or while insert record sql injection applied.

Example For Login Query

Select * from Empdetail where  EmailID='perfect.chourasia@gmail.com' and pwd='1a2s3d'

Above query return the result where email id and password match by result set.

By Few User can access without any Emailid and Pwd
Use 'OR''=' ,'OR''='--, 'OR''=', 'OR'1'='1 in place of Perfect.chourasia@gmail.com.

Query will break -


Select * from Empdetail where  EmailID=''OR''='--' and pwd='1a2s3d'


Say you have a stored procedure that executes dynamic SQL from a user input. A very simple example:
CREATE PROCEDURE dbo.sp_testproc
    @query    varchar(1000)
AS

DECLARE @sql varchar(1000);
SET @sql='SELECT * FROM dbo.Employees WHERE '+@query;
EXEC(@sql);
Needless to say, it is really dangerous to allow people to insert ad-hoc SQL code. Here’s what could happen:
EXECUTE dbo.sp_testproc
    @query='currentlyEmployed=1; DELETE FROM dbo.Employees';
In the example above, the user can wipe the dbo.Employees table because he uses a semicolon to separate a statement into two. Actually, a line break would do just as well.

Replacing semicolons, etc

As a step in validating user-input, you can use the REPLACE() function to eliminate characters or strings in the user input variable.
SET @query=REPLACE(@query, ';', '');
SET @query=REPLACE(@query, CHAR(10), '');
SET @query=REPLACE(@query, CHAR(13), '');

Escaping apostrophes

Apostrophees can be used for a similar purpose when generating SQL injections. You can provide apostrophes in regular text strings in T-SQL, but they are escaped with another apostrophe.
SET @query=REPLACE(@query, '''', '''''');
This may look tricky at first, but remember that an escaped apostrophe is actually two apostrophes when in a string. So to set a variable to the value “Life’s good”, you’d use the following T-SQL
SET @status='Life''s good';


Due to or condition query check the condition ''='' it return true. So hacker succeeded in there aim.

No comments:

Post a Comment