Search code examples
javapostgresqlsql-injectionmybatisamazon-redshift

Preventing Redshift SQL Injection


I have the unfortunate situation where I have to build up a SQL string by concatenating strings - the classic SQL injection scenario. I can't use prepared statements.

If I escape the ' character am I safe? Or are there other attack vectors?

I'm using MyBatis and it's ${} notation (vs #{} that generates prepared statements). I have no choice with this - it has to be ${}. I can't use prepared statements.

EDIT:

To add a little more clarity; it's an ASW Redshift UNLOAD command. The first parameter for UNLOAD is a SQL string.


Solution

  • (Given that you cannot do it the correct way because of restrictions in Redshift):

    On PostgreSQL with standard_conforming_strings set to on all you need to do is double quotes, making ' into ''. That's it.

    Backslashes aren't significant unless standard_conforming_strings is off or you use an E'' string. If either of those things are true then you have to do backslash escaping instead.

    As Redshift is based on a fork of an ancient PostgreSQL version I don't know for sure how this applies to it. Reading the documentation on its lexical structure and syntax would be wise, to verify that it is consistent with how PostgreSQL works.