Issue
Im using Devexpress Grid to show my result for final users.
since im using remote mode , i should filter my own result on server based on grid fiter.
I made custom JS swtich\case to make SQL where condition based on filter result like this :
let whereClause = '';
if (loadOptions['filter']) {
const rawFilter = loadOptions['filter'];
let filters = null;
if (_.isArray(rawFilter[0])) {
filters = _.map(rawFilter, (item) => {
if (_.isArray(item)) {
if (!_.isNumber(item[2])) {
switch (item[1]) {
case 'contains':
return `(${item[0]} LIKE N'%${item[2]}%')`;
case 'notcontains':
return `(${item[0]} NOT LIKE N'%${item[2]}%')`;
case 'startswith':
return `(${item[0]} LIKE N'${item[2]}%')`;
case 'endswith':
return `(${item[0]} LIKE N'%${item[2]}')`;
default:
return `(${item[0]} ${item[1]} N'${item[2]}')`;
}
}
else {
return `(${item[0]} ${item[1]} ${item[2]})`;
}
}
else {
return item;
}
});
whereClause = _.join(filters, ' ');
}
}
And then passing the whereClause to controller , like : "( ColomnA like N'ABC')"
After that , using it in Store Procedure like this (passing it as SearchParam):
CREATE OR ALTER PROCEDURE GetTestResult
@Skip INT = 0,
@Take INT = 400000,
@SearchParam NVARCHAR(MAX) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sqlCommand NVARCHAR(MAX)
DECLARE @sqlCommandPagination NVARCHAR(MAX)
DECLARE @sqlCommandFinall NVARCHAR(MAX)
SET @sqlCommand = 'SELECT ColomnA,ColomnB,ColomnC FROM dbo.TestTable '
SET @sqlCommandPagination = ' ORDER BY ColomnA asc OFFSET ' + CAST(@Skip as varchar(500)) +
' ROWS FETCH NEXT ' + CAST(@Take as varchar(500)) + ' ROWS ONLY;'
If( @SearchParam <> '' AND @SearchParam IS NOT NULL )
Set @sqlCommandFinall = @sqlCommand + ' Where ' + @SearchParam + @sqlCommandPagination;
If( @SearchParam = '' OR @SearchParam IS NULL )
Set @sqlCommandFinall = @sqlCommand + @sqlCommandPagination;
Execute SP_ExecuteSQL @sqlCommandFinall;
END;
GO
Is there any way to make this method Sql Injection proof ?
Im Using Dapper\SqlMapper\Query Function For calling my sp from C#.
Solution
Not the way it's designed. Or at least not without carefully parsing the statement and then leveraging parameterized values and/or positively validating the components. And doing that is much more complex and prone to error than just passing the components.
In your current design, it's trivial to inject SQL into the where or order by. You should break this down into its components, pass those through and validate them at the backend. So, rather than passing ColomnA like N'ABC' (sic) you should pass ColomnA (sic) and ABC seperately, and use parameterized queries for the values (bind them).
In the second case, many databases will not allow parameterizing order by values, so you should be sure to use positive validation in that case.
Answered By - Egret Answer Checked By - Marilyn (sql.easybugfix Volunteer)
Post a Comment
Post a Comment