Skip to content

[NEW DATA EXTENSION] Rust: Diesel raw-SQL sinks for rust/sql-injection (CWE-89) - #141

Draft
felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/data-extension-createcwe-89-model
Draft

felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/data-extension-createcwe-89-model

Conversation

Copilot AI commented Oct 16, 2026 •

Copy link
Copy Markdown

📝 Data Extension Information

  • Language: rust
  • Extension Name(s): diesel.model.yml
  • Extension Types: sinkModel
  • Target Library/Framework: Diesel 2.2
  • Library Modules Covered: diesel::query_builder (sql_query, SqlQuery::sql), diesel::expression::sql_literal (dsl::sql), diesel::connection (SimpleConnection::batch_execute)

🎯 Description

What This Data Extension Models

An AI scan reported 3 CWE-89 findings that rust/sql-injection missed. I reproduced each one in a test database built from the real crates. Only one is a missing model:

Finding Root cause Outcome
Diesel sql_query with concatenated file content No Diesel models upstream Fixed by the new sinks
postgres::Client::query with file content Already modeled upstream (sink plus a file source on std::fs::read_to_string). Alerts only when local/file is enabled. Config only. Covered by the test.
Warp param().then(|p| async move { sqlx::query(..) }) Already modeled upstream (Warp source plus SQLx sink). Taint reaches the returned async move block as captured content, but nothing in user code awaits the block, so the taint never enters its body. A summary model that tried to force the call had no effect. Dataflow library limitation, marked MISSING:. The .map(|p| {..}) variant is detected.

There is also a separate standard-library false negative, marked MISSING:: format!("{}", s.trim()) drops taint. Formatting s directly, or concatenating s.trim() with +, is detected.

Supporting changes:

  • New model pack languages/rust/custom/models, with library: true and extensionTargets: codeql/rust-all.
  • New test pack languages/rust/custom/test. It depends on codeql/rust-queries plus the model pack, and enables the local threat model the same way upstream codeql/rust-tests does. Crates come from qltest_dependencies. Cargo.lock is committed; generated Cargo.toml, lib.rs and target/ are gitignored.
  • scripts/install-codeql-packs.sh now accepts rust as a language.

Threat Model

These are sinks, so they apply under any threat model. The Diesel test cases use local/file sources (as in the reported findings) and a remote Warp source. Under default setup (remote only), the file-based cases need local or file enabled.

Example Vulnerable Code

let db_key = fs::read_to_string("/var/tmp/tainted_file.txt").unwrap();
let q = "SELECT * FROM some_table WHERE key = '".to_owned() + db_key.trim() + "'";
let _ = diesel::sql_query(q).load::<DbItem>(&mut conn);

let route = warp::path::param().map(|p: String| {
    let _ = diesel::sql_query(format!("SELECT * FROM t WHERE key = '{}'", p)).load::<DbItem>(&mut conn);
    "ok"
});

Example Safe Code

let _ = diesel::sql_query("SELECT * FROM some_table WHERE key = ?")
    .bind::<diesel::sql_types::Text, _>(db_key.trim())
    .load::<DbItem>(&mut conn);
let _ = some_table::table.filter(some_table::key.eq(db_key.trim())).load::<DbItem>(&mut conn);
let _ = conn.batch_execute("DELETE FROM some_table WHERE id = 1");

📦 Extension Details

Extension YAML

extensions:
  - addsTo:
      pack: codeql/rust-all
      extensible: sinkModel
    data:
      - ["<diesel::connection::SimpleConnection>::batch_execute", "Argument[0]", "sql-injection", "manual"]
      - ["<diesel::query_builder::sql_query::SqlQuery>::sql", "Argument[0]", "sql-injection", "manual"]
      - ["diesel::expression::sql_literal::sql", "Argument[0]", "sql-injection", "manual"]
      - ["diesel::query_builder::functions::sql_query", "Argument[0]", "sql-injection", "manual"]

Access Path Explanation

Rust MaD rows key on the canonical path of the function where it is defined, not on the path used to call it. Both diesel::sql_query and diesel::dsl::sql_query resolve to diesel::query_builder::functions::sql_query. Trait methods use the <Trait>::method form, so batch_execute matches every SimpleConnection implementation (SqliteConnection, PgConnection, ...). Each row marks the raw SQL string, Argument[0], as the sink. I read the canonical paths off the static call targets in the extracted test database.

🧪 Testing

  • Extension YAML resolves without errors
  • Database created with sample code (codeql database create or codeql test extract)
  • Single query verified with extension applied (codeql query run --additional-packs=<model-pack-dir>)
  • Unit tests pass with extension applied (codeql test run --additional-packs=<model-pack-dir>)
  • Positive test cases (vulnerable code detected)
  • Negative test cases (safe code not flagged)

The model pack resolves through codeql-workspace.yml, so neither command needs --additional-packs.

📋 Checklist

  • Extension YAML is valid and properly formatted
  • Extension placed in correct location (languages/[language]/custom/src/). Placed in the dedicated model pack languages/rust/custom/models instead, because a query pack in custom/src cannot declare extensionTargets.
  • qlpack.yml includes dataExtensions configuration
  • Access paths verified via API graph queries. Not applicable: Rust uses canonical-path MaD rows rather than API graphs. The paths were checked against the static call targets in the test database instead.
  • No false positives in test cases
  • Documentation/comments included in YAML

🔗 References


Note: This data extension was developed following CodeQL Models as Data best practices.

…on tests

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Create data extension model for CWE-89 SQL NoSQL LDAP injection [NEW DATA EXTENSION] Rust: Diesel raw-SQL sinks for rust/sql-injection (CWE-89) Oct 16, 2026
Copilot AI requested a review from felickz October 16, 2026 16:12
@felickz

felickz commented Oct 16, 2026

Copy link
Copy Markdown

@copilot A rescan of the synthetic corpus found additional findings related to this issue. Please re-run your analysis against them, confirm whether the proposed change covers each scenario, and extend it where it does not. Rows marked (variant) differ from the originally linked pattern.

Repo Location CWE Severity Pattern Context
rust-vulnerable-apps sqli/sqli_bad_007_postgres/src/Sqli_bad_007.rs:12 CWE-89 high additional-instance-same-pattern In rust-vulnerable-apps at sqli/sqli_bad_007_postgres/src/Sqli_bad_007.rs:12: Same unsafe pattern as main.rs: untrusted input read from a file is interpolated into the SQL string passed to client.query, enabling SQL injection. CodeQL would need the model/query described as: SQL string built with format! from a Warp path parameter or file-read value and passed to postgres/sqlx query; needs the framework source and sqlx/postgres query sinks modeled.
rust-vulnerable-apps sqli/sqli_good_001_sqlx/src/main.rs:23 CWE-89 high additional-instance-same-pattern In rust-vulnerable-apps at sqli/sqli_good_001_sqlx/src/main.rs:23: The Warp path parameter is passed to vuln_func, interpolated into a query string, and executed without parameterization. CodeQL would need the model/query described as: SQL string built with format! from a Warp path parameter or file-read value and passed to postgres/sqlx query; needs the framework source and sqlx/postgres query sinks modeled.

Please continue on this pull request.

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>

Copilot AI commented Oct 16, 2026

Copy link
Copy Markdown
Author

@copilot A rescan of the synthetic corpus found additional findings related to this issue. Please re-run your analysis against them, confirm whether the proposed change covers each scenario, and exten...

I checked both rescan rows against the source. Neither needs a new model.

  • sqli_bad_007_postgres/src/Sqli_bad_007.rs:12: same file content and same postgres::Client::query call as the main.rs case the test already covers. CodeQL detects it once the local (or file) threat model is enabled, through the upstream postgres sink and std::fs::read_to_string source. That's a settings change, not a model gap.
  • sqli_good_001_sqlx/src/main.rs:23: this looks like a false positive. The file has no Warp code. The file content passed to vuln_func only reaches SQLx through .bind(tainted_key.trim()), and the query text is a fixed string (... WHERE key = $1). I added this as a negative test case in ded2608, and it produces no alert.

The test passes against the newer codeql/rust-all 0.2.23 and codeql/rust-queries 0.1.44. I haven't checked whether the newer pack versions fix the Warp then + async move gap from the original findings; the test result only shows its MISSING: annotation still holds.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The Diesel 2.2 test dependency resolves to 2.3.14, leaving the claimed 2.2 compatibility unverified until the dependency is constrained and the lockfile and expected results are regenerated.

1 open issue
What changed in this PR

Adds Diesel raw-SQL sink models for rust/sql-injection, addressing the missing-model portion of #138. Regression fixtures cover detected flows, safe parameter binding, and documented dataflow limitations.

Changes:

  • Introduces a Rust model pack with four Diesel SQL-injection sinks.
  • Adds real-crate test fixtures, expected results, and local threat-model configuration.
  • Enables Rust in the pack-installation script.
File Description
scripts/​install-codeql-packs.sh Accepts Rust as a language filter.
languages/​rust/​custom/​test/​SqlInjectionModels/​SqlInjection.qlref Selects the stock query and inline-expectation processor.
languages/​rust/​custom/​test/​SqlInjectionModels/​SqlInjection.expected Records expected alerts and dataflow paths.
languages/​rust/​custom/​test/​SqlInjectionModels/​options.yml Configures crate dependencies and Cargo checking.
languages/​rust/​custom/​test/​SqlInjectionModels/​main.rs Adds vulnerable and safe cases plus known-gap fixtures.
languages/​rust/​custom/​test/​SqlInjectionModels/​Cargo.lock Locks fixture dependency versions.
languages/​rust/​custom/​test/​qlpack.yml Defines test-pack dependencies and extensions.
languages/​rust/​custom/​test/​default-threat-models.model.yml Enables local sources for tests.
languages/​rust/​custom/​test/​.gitignore Excludes generated Rust test artifacts.
languages/​rust/​custom/​models/​qlpack.yml Defines the Rust model extension pack.
languages/​rust/​custom/​models/​diesel.model.yml Models four Diesel raw-SQL arguments as sinks.

Review effort: Balanced

@felickz

felickz commented Oct 31, 2026

Copy link
Copy Markdown

@copilot A rescan of the synthetic corpus found additional medium and low severity findings that fit this gap. Please re-run your analysis against each finding below, confirm whether the proposed change covers each scenario, and extend it where it does not. Keep each change minimal with a positive and a negative regression test, keep every existing test passing, and do not broaden scope. The same findings are listed in the matching comment on issue #138.

Linked findings

Repo CWE Severity AI scan alert Summary
rust-vulnerable-apps CWE-89 medium https://github.com/codeql-forks-felickz/rust-vulnerable-apps/security/code-scanning/30 The file-controlled value is first embedded directly into the SQL text; the subsequent .bind() does not undo that injection. An attacker can include SQL syntax plus one placeholder (for example, close the quote and add a tautological expression containing ?) so the added bind count remains va...

Handling

Add a data extension (model-as-data). An existing query should report these once the library is modeled; add the missing sources, sinks, summaries or barriers as extension rows.

Patterns

  • missing-source-or-sink-model (1 finding), for example rust-vulnerable-apps sqli/sqli_good_002_sqlx/src/main.rs

Finding details

1. rust-vulnerable-apps sqli/sqli_good_002_sqlx/src/main.rs:21 (CWE-89, medium)
  • AI Scan alert: https://github.com/codeql-forks-felickz/rust-vulnerable-apps/security/code-scanning/30
  • AI Scan message: The file-controlled value is first embedded directly into the SQL text; the subsequent .bind() does not undo that injection. An attacker can include SQL syntax plus one placeholder (for example, close the quote and add a tautological expression containing ?) so the added bind count remains valid while the altered query executes. Keep the SQL text constant (... WHERE key = ?) and bind the value only once.
  • Context for the agent: In rust-vulnerable-apps at sqli/sqli_good_002_sqlx/src/main.rs:21: The file-controlled value is first embedded directly into the SQL text; the subsequent .bind() does not undo that injection. CodeQL would need the model/query described as: SQL string built with format! from a Warp path parameter or file-read value and passed to postgres/sqlx query; needs the framework source and sqlx/postgres query sinks modeled.
  • Why CodeQL appears to miss it: missing-source-or-sink-model: SQL string built with format! from a Warp path parameter or file-read value and passed to postgres/sqlx query; needs the framework source and sqlx/postgres query sinks modeled.
  • Existing CodeQL queries considered: rust/sql-injection
  • Recommended action from the comparison: extend-existing-query (classification confidence: medium)

Please continue on this pull request.

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data Extension Create]: CWE-89 HIGH - Rust: data extension models for sql nosql ldap injection

3 participants