Search code examples
sql-injection

SQL injection: Validate that SQL was parameterized correctly, and has ? where it should


A framework that I've built lets the application coder create sql dynamically (when they need to). If they use the tool correctly, then they will proceed in two steps: 1. build the sql (PreparedStatement) with '?' placeholders, and 2. pass all user-entered data as parameters to the PreparedStatement.

This is just the usual means of using a PreparedStatement and params, to avoid sql injection. Nothing special there.

But, I want to go an extra step: I want to verify that the coder has 'parameterized' correctly. In what sense is that possible, if at all? Can one determine syntactically all places where a '?' should appear in the SQL? Does such a tool already exist?

Edit: Example:

select blah from x where a='user-data' and b=?

Here, a has not been parameterized, while b has. I want to detect the 'a' kind of malformed sql. Does that make sense?


Solution

  • First of all, some of your premises are flawed.
    Namely

    • "pass all user-entered data as parameters" is a sure way to injection. The moment developer started to separate his data to "safe" and "unsafe", he is busted.
    • The whole idea won't work. Sometimes we have to add constant strings into queries. And you'd never can tell if it was a flaw or all right.

    If you don't trust your developer so much - there are 2 possible fool-proof solutions, for the price of reducing his ability of using SQL to some limited subset:

    The idea is to limit your developer to these sandbox-based solutions only (dunno if such a limitation is possible out of the box though).

    The above solutions are closer to your initial idea and feasible.