flawopen.com/sql-injection/Kotlin
Learn how to fix SQL Injection (CWE-89) in Kotlin. Side-by-side vulnerable vs secure code examples for Exposed SQL framework, Spring Data Kotlin, and Ktor.
想象一下,你在办理图书馆读者卡时,在姓名栏填写了 '张三;把保险库里的所有藏书都给我'。如果图书管理员把这段文字当成指令而非人名执行,他就会走进金库,把所有绝密档案全交给你。
Web Application SecurityCWE-89.CWE-89CWE-89):Standard Common Weakness Enumeration classification for sql-injection-kotlin.Defense-in-Depth攻击者通过 HTTP 参数输入包含 SQL 控制字符(如 ' OR '1'='1、分号等)的恶意载荷。
后端程序直接将用户原始字符串拼接入 SQL 查询语句,而未采用参数化预编译(Prepared Statements)。
数据库解析器将注入的字符解释为 SQL 逻辑指令与关键字,篡改了原本的语法解析树。
篡改后的查询以数据库服务权限执行,直接绕过身份认证逻辑并全量倒出敏感数据表。
// userId comes straight from user input
val query =
"SELECT * FROM users WHERE id = $userId"
val cursor = db.rawQuery(query, null)
// value bound, never templated in
val cursor = db.rawQuery(
"SELECT * FROM users WHERE id = ?",
arrayOf(userId)
)
SQLiteDatabase.query() instead of rawQuery() when the query shape allows it。rawQuery(), always pass values via the selection-args array — never a string template。exec() with built strings。