Wednesday, January 30, 2019

c# - SQL Injections with replace single-quotation and validate integers












I just want to know, If I replace every ' with '' in user inputs, for instance string.Replace("'","''"), and validate numbers (make sure that they are numbers, and do not contain any other character), is SQL Injection still possible? How?



I'm using dynamic SQL queries, using SqlCommand. Something like this:



cmd.CommandText = "SELECT * FROM myTable WHERE ID = " + theID.ToString();


or



cmd.CommandText = "UPDATE myTable SET title='" + title.Replace("'","''") + "' WHERE ID = " + theID.ToString();



Input integers are automatically validated (checked whether they are a real number) in ASP.NET MVC.


Answer



If this is a legacy project that is coded this way then, whilst not optimal, I'm not currently aware of any way that it can be susceptible to SQL injection as long as every string is treated in that manner and the queries are just simple ones as you have shown.



I cannot state any more certainty than that however. Without using parametrised queries there is always the possibility that there is some vulnerability that you have not yet considered.



Manually escaping the quotes yourself is error prone and can sometimes fail in ways that are difficult to anticipate in advance. For example with the following table




CREATE TABLE myTable(title VARCHAR(100))
INSERT INTO myTable VALUES('Foo')


And stored procedure using dynamic SQL built up with string concatenation



CREATE PROC UpdateMyTable
@newtitle NVARCHAR(100)
AS
/*

Double up any single quotes
*/
SET @newtitle = REPLACE(@newtitle, '''','''''')

DECLARE @UpdateStatement VARCHAR(MAX)

SET @UpdateStatement = 'UPDATE myTable SET title=''' + @newtitle + ''''

EXEC(@UpdateStatement)



You can try the following



Normal update



EXEC UpdateMyTable N'Foo'
SELECT * FROM myTable /*Returns "Foo"*/


SQL Injection attempt foiled




EXEC UpdateMyTable N''';DROP TABLE myTable--'
SELECT * FROM myTable /*Returns "';DROP TABLE myTable--"*/


SQL Injection attempt succeeds and drops the table



EXEC UpdateMyTable N'ΚΌ;DROP TABLE myTable--'
SELECT * FROM myTable /*Returns "Invalid object name 'myTable'."*/



The issue here is that the third query passes U+02BC instead of the standard apostrophe and then the string is assigned to a varchar(max) after the sanitation occurs which silently converts this to a regular apostrophe.



Until I read the answer here that issue would never have occurred to me.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...