I am taking in a string from user input, and splitting it on whitespace (using \w) into an array of strings. I then loop through the array, and append a part of the where clause like this:
query += ' AND ( ' + 'field1 LIKE '%' + searchStrings[i] +'%' ' + ' OR field2 LIKE '%' + searchStrings[i] +'%' ' + ' OR field3 LIKE '%' + searchStrings[i] +'%' ' + ') ';
I feel like this is dangerous, since I am appending user input to my query. However, I know that there isn’t any whitespace in any of the search strings, since I split the initial input on whitespace.
Is it possible to attack this via a SQL injection? Giving Robert');DROP TABLE students;-- wouldn’t actually drop anything, since there needs to be whitespace in there. In that example, it would not behave properly, but no damage would be done.
Can anyone with more experience fighting SQL injections help me either fix this, or put my mind at ease?
Thanks!
EDIT:
Wow, that is a lot of great input. Thank you everyone who responded. I will investigate full-text search and, at a minimum, parameterize my query.
Just so I can better understand the problem, would it be possible to inject if all whitespace AND single quotes were escaped?
Any time you allow a user to enter data into a query string like this you are vulnerable to SQL injection and it should be avoided like the plague!
You should be very careful how you allow your searchStrings[] array to be populated. You should always append variable data to your query using parameter objects:
And if you’re using SQL Server for example
Be very wary how you build a query string that you’re going to run against a production server, especially if it has any data of consequence in it!
In your example you mentioned Little Bobby Tables
Robert’);DROP TABLE students;–
And cited that because it needs white space, you couldn’t do it – but if the malicious user encoded it using something like this:
I would say – better to be safe and do it the right way. There’s no simple way to make sure you catch every scenario otherwise…