In our DB access layer we have some dynamic query creation. For instance, we have the following method for building a part of an ORDER BY
clause:
protected string BuildSortString(string sortColumn, string sortDirection, string defaultColumn)
{
if (String.IsNullOrEmpty(sortColumn))
{
return defaultColumn;
}
return String.Format("{0} {1}", sortColumn, sortDirection);
}
The problem is, sortColumn
and sortDirection
both come from outside as strings, so of course something should be done to prevent possible injection attacks. Does anybody have any idea how this can be done?
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
Character escaping is an effective way of preventing SQL injection. Special characters like “/ — ;” are interpreted by the SQL server as a syntax and can be treated as an SQL injection attack when added as part of the input.
As with regular SQL injection, blind SQL injection attacks can be prevented through the careful use of parameterized queries, which ensure that user input cannot interfere with the structure of the intended SQL query.
If you have to deal in strings, then white-listing is your best bet. Firstly, sortDirection
should be pretty trivial to white-list: a case-insensitive compare to "asc"
/ "desc"
and you should be set. For the others, my preference would be to white-list to known columns, perhaps by passing in the expected Type
for the data and validating. But at an absolute pinch, you could restrict with regex to (say) enforce they are all strictly alpha-numeric (in the a-z, A-Z, 0-9 range - maybe underscore if needed) - and then add []
, i.e.
return string.Format("[{0}] {1}", sortColumn, sortDirection);
But: strict white-list of known columns would be much better, as would an enum for the direction.
Another solution if you can change your method to accept int
instead of string
parameters.
protected string BuildSortString(int sortColumn, int sortDirection, string defaultColumn)
{
if (String.IsNullOrEmpty(sortColumn))
{
return defaultColumn;
}
//sortdirection 0-> "ASC" else "DESC"
//sorColumn 1 for your firstcolumn, 2 for your second column etc.
return String.Format("{0} {1}", sortColumn, sortDirection==0? " ASC " : " DESC ");
}
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With