This rule aims to prevent the use of string concatenation or interpolation to build SQL queries in Kotlin. Combining user-provided data with SQL queries without proper sanitization can lead to SQL injection attacks. SQL injection is a common security vulnerability where an attacker can manipulate the query to execute arbitrary SQL commands, potentially leading to data theft, data corruption, or unauthorized access.
The best way to avoid this vulnerability is by using parameterized queries, also known as prepared statements, or a type-safe DSL (Domain-Specific Language) like Exposed in Kotlin. These methods ensure that user-provided input is properly escaped or handled, preventing it from being interpreted as part of the SQL command. This way, the user ID is not directly embedded into the query and is instead safely passed as a separate parameter, eliminating the risk of SQL injection.
Non-Compliant Code Examples
// Non-compliant: Direct string interpolation in SQL queries
fungetUserUnsafe(call:ApplicationCall){valuserId=call.parameters["id"]transaction{// WARNING: SQL injection vulnerability
valquery="SELECT * FROM users WHERE id = $userId"exec(query){rs->rs.next()rs.getString("name")}}}// Non-compliant: Using string concatenation for SQL queries
classUserRepository(privatevalcall:ApplicationCall){funsearchUsers(){valsearchName=call.request.queryParameters["name"]valsortOrder=call.request.queryParameters["sort"]?:"ASC"// WARNING: Multiple SQL injection vulnerabilities
valquery="SELECT * FROM users WHERE "+"name LIKE '%"+searchName+"%' "+"ORDER BY name "+sortOrdertransaction{// Dangerous: Using unvalidated user input directly in query
exec(query){rs->buildUserList(rs)// Some result processing
}}}// Also unsafe - concatenating in a separate function
privatefunbuildSearchQuery(name:String,sort:String):String{return"SELECT id, name, email FROM users "+"WHERE name LIKE '%"+name+"%' "+"OR email LIKE '%"+name+"%' "+"ORDER BY "+sort}}
Compliant Code Examples
// Compliant: Using Exposed DSL and prepared statements
fungetUserSafe(call:ApplicationCall){valuserId=call.parameters["id"]?.toIntOrNull()?:throwBadRequestException("Invalid ID")transaction{// Safe: Using type-safe DSL
Users.select{Users.idequserId}.map{it[Users.name]}.firstOrNull()}// Alternative: Using prepared statement if raw SQL is needed
transaction{exec("SELECT * FROM users WHERE id = ?"){stmt->stmt.setInt(1,userId)stmt.executeQuery()}}}// Compliant: Using Exposed table definitions
objectUsers:Table("users"){valid=integer("id").autoIncrement()valname=varchar("name",50)overridevalprimaryKey=PrimaryKey(id)}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines