开发者

Is this method of building dynamic SQL vulnerable to SQL injection or bad for performance?

I would like to build a safe dynamic select statement that can handle multiple WHERE clauses.

For example the base SQL would look like:

SELECT * FROM Books Where Type='Novel'

I would pass the function something like:

SafeDynamicSQL("author,=,Herman Melville","pages,>,1000");

Which would sanitize inputs and concatenate like:

SELECT * FROM Books Where Type='Novel' AND author=@author AND pages>@pages

The function would sanitize the column name by checking against an array of predefined column names. The operator would only be allowed to be >,<,=. The value would be added as a normal paramater.

Would this still be vulnerable to SQL injection?

There will be some string manipulation and small loops which will affect performance but my thoughts are that this will only take a few milliseconds compared to the request which on average take 200ms. Would this tax the server more than I am thinking if these requests are made about once a second?

I know this isn't best practice by any开发者_Python百科 means, but it will greatly speed up development. Please give me any other reasons why this could be a bad idea.


It looks like you're reinventing any number of existing ORM solutions which offer a similar API for creating WHERE clauses.

The answer to your question hinges on what you mean by "The value would be added as a normal paramater." If by that you mean performing string concatenation to produce the string you showed then yes, that would still be subject to SQL injection attack. If you mean using an actual parameterized query then you would be safe. In the later case, you would produce something like

 SELECT * FROM Books Where Type='Novel' AND author=? AND pages > ?

and then bind that to a list of values like ['Herman Melville', 1000]. Exactly what it would look like depends on what programming language you're using.

Finally, if you pursue this path I would strongly recommend changing from comma-delimited arguments to three separate arguments, you'd save yourself a lot of programming time.


Pretty much any code that appends together (or interpolates) strings to create SQL is bad form from a security point of view, and is probably subject to some SQLi attack vector. Just use bound parameters and avoid the entire problem; avoiding SQL injection is super-easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜