FAQ - Help and questions

What is a parameterised query, and how does it stop SQL injection in Rust?

#security#sql#injection#rusqlitepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A parameterised query sends the SQL text and the values separately, so the database treats a value as data even if it contains quotes or SQL words. Never build SQL with format! or string concatenation; use placeholders such as ?1 with rusqlite, or bind with sqlx, and keep the SQL text constant.

Checked with rustc 1.93.0, rusqlite 0.32.1 (bundled SQLite), Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

SQL injection happens when user input becomes part of the SQL text. A quote in the input ends the string literal early, and what follows is read as SQL. The fix is not escaping; it is to keep input out of the SQL text completely. With a placeholder, the statement is prepared first and the value is attached afterwards, so it can never change the shape of the statement.

The demonstration uses an in-memory database with two harmless rows and an input that is shaped like the classic trick. It shows the bug class and its fix; nothing here is aimed at any real system.

src/main.rsrust
use rusqlite::{params, Connection};

fn main() -> rusqlite::Result<()> {
    let db = Connection::open_in_memory()?;
    db.execute("CREATE TABLE notes (owner TEXT, body TEXT)", [])?;
    db.execute("INSERT INTO notes VALUES ('ada', 'ada note'), ('bob', 'bob note')", [])?;

    // Hostile-looking input. It is only text; the query must keep treating it as text.
    let owner = "nobody' OR '1'='1";

    // WRONG: the input becomes part of the SQL, and its quote closes the string early.
    let sql = format!("SELECT body FROM notes WHERE owner = '{owner}'");
    let mut stmt = db.prepare(&sql)?;
    let leaked: Vec<String> = stmt.query_map([], |r| r.get(0))?.collect::<Result<_, _>>()?;
    println!("string formatting returned {} rows: {:?}", leaked.len(), leaked);

    // RIGHT: the SQL text is fixed; the value travels separately as a parameter.
    let mut stmt = db.prepare("SELECT body FROM notes WHERE owner = ?1")?;
    let safe: Vec<String> = stmt.query_map(params![owner], |r| r.get(0))?.collect::<Result<_, _>>()?;
    println!("bound parameter returned {} rows: {:?}", safe.len(), safe);
    Ok(())
}
text
string formatting returned 2 rows: ["ada note", "bob note"]
bound parameter returned 0 rows: []

The format! version returned both owners' rows for an owner name that matches nobody. The bound version treated the whole input as one name and found nothing.

The same idea applies to every database library. With sqlx the equivalent is sqlx::query("... WHERE owner = $1").bind(owner); placeholders are ? or $1 depending on the database.

How to do it#

  1. Write the SQL as a constant string with placeholders.
  2. Pass every value as a parameter.
  3. Use a database account that can do only what the application needs, so a flaw does less damage (see the thread on least privilege).
  4. Where the SQL structure itself has to vary (column names, sort order), see the next thread.

Common mistakes#

  • Escaping quotes by hand. It is easy to get wrong for one database dialect or character set.
  • Using a parameter for a table or column name. Placeholders carry values only.
  • Believing that an ORM or query builder makes injection impossible. Check where raw SQL fragments are allowed.
  • Concatenating with + or format! "only for numbers". Parse the number first and still bind it.

Does Rust's type system stop SQL injection?#

No. A query is a String; the compiler cannot tell input from constants. Some libraries (for example sqlx with compile-time checked macros) check the SQL against a database at build time, which finds mistakes but does not replace parameters.

What about stored procedures?#

They help only when they use parameters inside. A procedure that builds SQL from strings is as open to injection as application code.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet