Link Search Menu Expand Document

SQL Injection in Scala

Play SecureFlag Play Scala Labs on this vulnerability with SecureFlag!

Slick

Vulnerable example

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

val db = Database.forURL("...")
db.run(sql"""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:

db.run("SELECT * FROM Objects WHERE some_field = '' OR some_field = 'some_other_value'").as[SomeObject]

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

Prevention

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:

db.run(sql"""SELECT * FROM Objects WHERE some_field = $some_variable""").as[SomeObject]

References

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