Swift: Expand the swift/sql-injection qhelp examples by labelling the API that's used, adding SQLite3 C API examples, and adding an example of using a prepared statement incorrectly.

This commit is contained in:
Geoffrey White
2024-07-30 22:39:14 +01:00
parent 9f6a5d9e13
commit 2fd4b57d74
3 changed files with 28 additions and 4 deletions

View File

@@ -18,7 +18,7 @@ Most database connector libraries offer a way to safely embed untrusted data int
</recommendation>
<example>
<p>In the following example, a SQL query is prepared using string interpolation to directly include a user-controlled value <code>userControlledString</code> in the query. An attacker could craft <code>userControlledString</code> to change the overall meaning of the SQL query.
<p>In the following examples, an SQL query is prepared using string interpolation to directly include a user-controlled value <code>userControlledString</code> in the query. An attacker could craft <code>userControlledString</code> to change the overall meaning of the SQL query.
</p>
<sample src="SqlInjectionBad.swift" />
@@ -35,4 +35,4 @@ Most database connector libraries offer a way to safely embed untrusted data int
<li>OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html">SQL Injection Prevention Cheat Sheet</a>.</li>
</references>
</qhelp>
</qhelp>

View File

@@ -1,3 +1,12 @@
let unsafeQuery = "SELECT * FROM users WHERE username='\(userControlledString)'" // BAD
// with SQLite.swift
try db.execute(unsafeQuery)
let unsafeQuery = "SELECT * FROM users WHERE username='\(userControlledString)'"
try db.execute(unsafeQuery) // BAD
let stmt = try db.prepare(unsafeQuery) // also BAD
try stmt.run()
// with SQLite3 C API
let result = sqlite3_exec(db, unsafeQuery, nil, nil, nil) // BAD

View File

@@ -1,4 +1,19 @@
// with SQLite.swift
let safeQuery = "SELECT * FROM users WHERE username=?"
let stmt = try db.prepare(safeQuery, userControlledString) // GOOD
try stmt.run()
// with sqlite3 C API
var stmt2: OpaquePointer?
if (sqlite3_prepare_v2(db, safeQuery, -1, &stmt2, nil) == SQLITE_OK) {
if (sqlite3_bind_text(stmt2, 1, userControlledString, -1, SQLITE_TRANSIENT) == SQLITE_OK) { // GOOD
let result = sqlite3_step(stmt2)
// ...
}
sqlite3_finalize(stmt2)
}