SQL injection

SQL injection in C/C++

Description

Combining untrusted values into a SQL command string can make them SQL syntax rather than data. Attackers can insert quotes, operators, comments, or statement separators to change conditions and statements. This applies both to immediate execution functions such as sqlite3_exec() and PQexec() and to passing SQL assembled from external input to sqlite3_prepare_v2(), PQprepare(), mysql_stmt_prepare(), or SQLPrepare(). A prepared statement API name does not make a query safe: keep the SQL template fixed and bind values separately.

String replacement and parameter binding provide different protections. Binding separates SQL code from values at the protocol or driver level. Manually replacing quotes or calling a function named sanitize_sql() does not establish correct handling of the database, connection encoding, value or identifier position, and surrounding quote context.

Potential impact

  • Authentication or access-control conditions may be bypassed, exposing other users' data.
  • Data may be created, changed, or deleted, and database schemas or settings altered.
  • Depending on the database account's permissions and server features, file access, operating-system command execution, or service disruption may be possible.
  • Errors and differences in responses may reveal database structure or sensitive information.

Remediation

Keep the SQL text fixed and bind every external value with the parameter API for your database.

  • SQLite supports ?, ?NNN, :name, @name, and $name. Prepare the query with sqlite3_prepare_v2() or sqlite3_prepare_v3() and bind each value with sqlite3_bind_*().
  • PostgreSQL libpq provides PQexecParams() for a single execution. For a prepared query, use PQprepare() and pass the values to PQexecPrepared(). Use the corresponding parameter APIs for asynchronous queries.
  • MySQL 8.4 C API uses mysql_stmt_prepare(), mysql_stmt_bind_named_param(), then mysql_stmt_execute(). With an older compatible client, use mysql_stmt_bind_param() to bind each value to its ? marker.
  • ODBC uses SQLPrepare(), SQLBindParameter(), then SQLExecute(). For a single call to SQLExecDirect(), bind the values first and keep the SQL text fixed.

If users can select a table, column, sort direction, operator, or SQL keyword, map each allowed choice to a fixed SQL fragment. Check every prepare, bind, and execute result. Release statements and results with their matching APIs and give the database account only the permissions it needs.

OWASP recommends parameterized queries. When dynamic SQL is unavoidable, use escaping specific to the database and SQL position. SQLite %q doubles single quotes without adding outer quotes, while %Q also adds the outer quotes for a string literal. In libpq, use PQescapeLiteral() for literals and PQescapeIdentifier() for identifiers. Place each result only where that function expects it. Moving it to another position or putting it inside already-open quotes can undo the protection.

Examples

C

Before

c
#include <stddef.h>
#include <sqlite3.h>

int find_user_unsafe(sqlite3 *database, const char *name) {
    char *sql = sqlite3_mprintf(
        "SELECT id FROM users WHERE name = '%s'", name);
    if (sql == NULL) {
        return SQLITE_NOMEM;
    }

    int result = sqlite3_exec(database, sql, NULL, NULL, NULL);
    sqlite3_free(sql);
    return result;
}

After

c
#include <stddef.h>
#include <sqlite3.h>

int find_user(sqlite3 *database, const char *name) {
    static const char query[] =
        "SELECT id FROM users WHERE name = ?";
    sqlite3_stmt *statement = NULL;

    int result = sqlite3_prepare_v3(
        database, query, -1, 0, &statement, NULL);
    if (result != SQLITE_OK) {
        return result;
    }

    result = sqlite3_bind_text(
        statement, 1, name, -1, SQLITE_TRANSIENT);
    if (result != SQLITE_OK) {
        sqlite3_finalize(statement);
        return result;
    }

    result = sqlite3_step(statement);
    int finalize_result = sqlite3_finalize(statement);
    if (result != SQLITE_ROW && result != SQLITE_DONE) {
        return result;
    }
    return finalize_result;
}

sqlite3_prepare_v3() prepares a fixed query containing ?. sqlite3_bind_text() supplies name as the value for that parameter.

C++

Before

cpp
#include <sqlite3.h>
#include <string>

int find_user_unsafe(sqlite3 *database, const std::string &name) {
    const std::string sql =
        "SELECT id FROM users WHERE name = '" + name + "'";
    return sqlite3_exec(
        database, sql.c_str(), nullptr, nullptr, nullptr);
}

After

cpp
#include <memory>
#include <sqlite3.h>
#include <string>

struct StatementDeleter {
    void operator()(sqlite3_stmt *statement) const noexcept {
        sqlite3_finalize(statement);
    }
};

int find_user(sqlite3 *database, const std::string &name) {
    constexpr char query[] =
        "SELECT id FROM users WHERE name = ?";
    sqlite3_stmt *raw_statement = nullptr;

    int result = sqlite3_prepare_v3(
        database, query, -1, 0, &raw_statement, nullptr);
    if (result != SQLITE_OK) {
        return result;
    }

    const std::unique_ptr<sqlite3_stmt, StatementDeleter>
        statement{raw_statement};
    result = sqlite3_bind_text(
        statement.get(), 1, name.c_str(), -1, SQLITE_TRANSIENT);
    if (result != SQLITE_OK) {
        return result;
    }

    result = sqlite3_step(statement.get());
    if (result == SQLITE_ROW || result == SQLITE_DONE) {
        return SQLITE_OK;
    }
    return result;
}

The C++ example also binds name to a fixed query. The std::unique_ptr deleter calls sqlite3_finalize() on every return path after preparation succeeds.

A sort column cannot be bound as a value. Here, each allowed sort key selects a fixed query.

c
#include <sqlite3.h>
#include <string.h>

int list_users(sqlite3 *database, const char *sort_key) {
    const char *query = NULL;
    if (strcmp(sort_key, "name") == 0) {
        query = "SELECT id, name FROM users ORDER BY name";
    } else if (strcmp(sort_key, "created") == 0) {
        query = "SELECT id, name FROM users ORDER BY created_at";
    } else {
        return SQLITE_MISUSE;
    }

    return sqlite3_exec(database, query, NULL, NULL, NULL);
}

References