Link Search Menu Expand Document

SQL Injection in Scala


Vulnerable example

The following snippet performs a SQL query using the facilities provided by Slick:

val db = Database.forURL("...")"""SELECT * FROM Objects WHERE some_field = '#$some_variable'""").as[SomeObject]

In particular, the above code employs string interpolation to build the executable query, but it uses the #$ notation, which performs literal string interpolation. In fact, notice how single quotes are used here to delimit the value of some_variable.

The above snippet is vulnerable to SQL injection. Suppose, for example, that some_variable is set to ' OR some_field = 'some_other_value; in this case, the code is equivalent to:"SELECT * FROM Objects WHERE some_field = '' OR some_field = 'some_other_value'").as[SomeObject]

If some_variable is controlled by a malicious user, he / she could then be able to, among other things, alter the semantics of the query and return arbitrary values.


Instead of using the #$ notation, the solution is to simply use $, which inserts the value as a bind variable. This also takes care of quoting, hence the final query becomes:"""SELECT * FROM Objects WHERE some_field = $some_variable""").as[SomeObject]


CWE - CWE-89: Improper Neutralization of Special Elements used in an SQL Command

OWASP - SQL Injection

OWASP - SQL Injection Prevention Cheat Sheet

Scala Slick - Plain SQL Queries