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)}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다