Swift SQL Injection

Swift SQL injection

Description

Interpolating user input into a Swift string used as SQL lets that input change the query conditions.

Potential impact

Depending on database privileges, this can bypass access checks, expose or change records, delete data or disrupt service.

Remediation

Pass values separately using SQLite bindings, prepared statements or an ORM query builder. Choose table and column names from an allow-list in code.

Examples

Before

swift
let query = "SELECT * FROM users WHERE name = '\(username)'"
try db.execute(query)

After

swift
import GRDB

func findUser(db: Database, username: String) throws -> Row? {
    return try Row.fetchOne(
        db,
        sql: "SELECT * FROM users WHERE name = ?",
        arguments: [username])
}

GRDB’s Row.fetchOne binds username to ? through arguments. It returns the first match, or nil when no row matches.

References