flawopen.com/sql-injection/Swift
Learn how to fix SQL Injection (CWE-89) in Swift. Side-by-side vulnerable vs secure code examples for Vapor Fluent, GRDB.swift, and SQLite.swift prepared statements.
想象一下,你在办理图书馆读者卡时,在姓名栏填写了 '张三;把保险库里的所有藏书都给我'。如果图书管理员把这段文字当成指令而非人名执行,他就会走进金库,把所有绝密档案全交给你。
Web Application SecurityCWE-89.CWE-89CWE-89):Standard Common Weakness Enumeration classification for sql-injection-swift.Defense-in-Depth攻击者通过 HTTP 参数输入包含 SQL 控制字符(如 ' OR '1'='1、分号等)的恶意载荷。
后端程序直接将用户原始字符串拼接入 SQL 查询语句,而未采用参数化预编译(Prepared Statements)。
数据库解析器将注入的字符解释为 SQL 逻辑指令与关键字,篡改了原本的语法解析树。
篡改后的查询以数据库服务权限执行,直接绕过身份认证逻辑并全量倒出敏感数据表。
// userId comes straight from user input
let query =
"SELECT * FROM users WHERE id = \(userId)"
sqlite3_exec(db, query, nil, nil, nil)
// value bound, never interpolated
var stmt: OpaquePointer?
sqlite3_prepare_v2(db,
"SELECT * FROM users WHERE id = ?",
-1, &stmt, nil)
sqlite3_bind_text(stmt, 1, userId, -1, nil)
sqlite3_step(stmt)