Is it possible to detect 100% of SQLi with a simple regex?

Keyword filtering for SQLi is not a good technique. There are too many ways to bypass it.

Crazy things like sel/**/ect might work, for instance. Or playing games with substr(). And then there's EXEC('SEL' + 'ECT 1').

There are many guides on how to bypass common filtering techniques.

But then you might ask if there is a superset of things to filter for (like select and /**/ and substr and EXEC), but then the list gets very, very long, and you still might not get a comprehensive list.

The better approach is to understand the range of acceptable inputs and protect those or to make it ineffective to use SQLi through proper design.


NO

Since every SQL injection is (by definition) valid SQL and since SQL is a context-free language (source), there is (again, by definition) no regex capable of matching an SQL injection, and trying to do so would probably give result similar to this.

As said by pretty much every comment, use the right tool for the job. In this case it's a prepared statement.


Technically, this is completely possible (though doing so also renders the database useless):

  • .+ Will indeed detect any possible SQLi.

However, it will also detect any attempt to do normal queries(or any text at all), rendering the database completely useless.

You could equally say that turning the database off protects from SQLi. It's true, but it also renders the database useless for it's intended purpose.

Use prepared statements or parameterized queries. They exist to solve this issue.