Skip to content

Commit 2fd4b57

Browse files
committed
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.
1 parent 9f6a5d9 commit 2fd4b57

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

swift/ql/src/queries/Security/CWE-089/SqlInjection.qhelp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Most database connector libraries offer a way to safely embed untrusted data int
1818
</recommendation>
1919
<example>
2020

21-
<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.
21+
<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.
2222
</p>
2323

2424
<sample src="SqlInjectionBad.swift" />
@@ -35,4 +35,4 @@ Most database connector libraries offer a way to safely embed untrusted data int
3535
<li>OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html">SQL Injection Prevention Cheat Sheet</a>.</li>
3636

3737
</references>
38-
</qhelp>
38+
</qhelp>
Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1-
let unsafeQuery = "SELECT * FROM users WHERE username='\(userControlledString)'" // BAD
1+
// with SQLite.swift
22

3-
try db.execute(unsafeQuery)
3+
let unsafeQuery = "SELECT * FROM users WHERE username='\(userControlledString)'"
4+
5+
try db.execute(unsafeQuery) // BAD
6+
7+
let stmt = try db.prepare(unsafeQuery) // also BAD
8+
try stmt.run()
9+
10+
// with SQLite3 C API
11+
12+
let result = sqlite3_exec(db, unsafeQuery, nil, nil, nil) // BAD
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,19 @@
1+
// with SQLite.swift
2+
13
let safeQuery = "SELECT * FROM users WHERE username=?"
24

35
let stmt = try db.prepare(safeQuery, userControlledString) // GOOD
46
try stmt.run()
7+
8+
// with sqlite3 C API
9+
10+
var stmt2: OpaquePointer?
11+
12+
if (sqlite3_prepare_v2(db, safeQuery, -1, &stmt2, nil) == SQLITE_OK) {
13+
if (sqlite3_bind_text(stmt2, 1, userControlledString, -1, SQLITE_TRANSIENT) == SQLITE_OK) { // GOOD
14+
let result = sqlite3_step(stmt2)
15+
16+
// ...
17+
}
18+
sqlite3_finalize(stmt2)
19+
}

0 commit comments

Comments
 (0)