SQL injection
SQL injection is when untrusted text is copied into a SQL string and parsed as SQL. The attacker changes the statement's meaning. The fix in C++ is the same as everywhere: prepared statements and bound parameters, never sql += user.
Detailed Explanation
std::string sql = "select * from users where name = '" + name + "'"; looks like a filter. If name is x' OR '1'='1, the filter is gone. If name is x'; drop table users; --, you hope SQLite's exec of multiple statements is off (it is not always). The database did what you told it. You told it the attacker's SQL.
C++ does not make this harder or easier than Python. std::string addition is the hole. Logging the constructed SQL in production is how you discover it after the fact.
Defence:
- Bind values.
?,$1,:name. See prepared statements. - Allow-list identifiers. Table and column names cannot be bound as values on most engines. Map a user-facing key (
"email") to a constant"email"in your code. - Least privilege. The app role cannot
DROP TABLE. Injection still reads or writes data; it should not own the schema. - No
execof concatenated batches.
ORMs and SOCI do not save you if you pass a raw string you built. sql << userSuppliedSql is the same bug.
Integer interpolation (... + std::to_string(id)) is not injection if id is actually an int. The habit is still wrong: the next field will be a string. Bind everything.
Blind injection and second-order injection (store the payload, execute it later in a different query) still happen if any query concatenates a stored field. Bind when you read the field into SQL too.
Error messages: do not send sqlite3_errmsg or Postgres detail to the client. Log them. The client gets 400/500.
Tests: a name ' OR '1'='1 should return zero rows, not the whole table. Put that in the suite.
Code Examples
#include <sqlite3.h>
#include <string>
// Safe: value is bound, not spliced.
int countUser(sqlite3* db, const std::string& name) {
sqlite3_stmt* st = nullptr;
sqlite3_prepare_v2(db, "select count(*) from users where name = ?", -1, &st, nullptr);
sqlite3_bind_text(st, 1, name.c_str(), -1, SQLITE_TRANSIENT);
int n = 0;
if (sqlite3_step(st) == SQLITE_ROW) n = sqlite3_column_int(st, 0);
sqlite3_finalize(st);
return n;
}
// Unsafe illustration (do not use):
// std::string sql = "select count(*) from users where name = '" + name + "'";#include <pqxx/pqxx>
#include <string>
int countUser(pqxx::work& txn, const std::string& name) {
auto r = txn.exec_params("select count(*) from users where name=$1", name);
return r[0][0].as<int>();
}Common Gotchas
Escaping by hand
replacing `'` with `''` misses encodings, identifiers, and LIKE metacharacters. Bind.
Identifier interpolation
`order by ` + column is injection if `column` is a query param. Allow-list.
ORM `raw`/`execute`
still SQL you built. Treat it as dangerous.
Logging secrets in SQL text
bound parameters should not appear in client errors.