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?
If you have to deal in strings, then white-listing is your best bet. Firstly,
sortDirectionshould 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 expectedTypefor 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.But: strict white-list of known columns would be much better, as would an enum for the direction.