Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Database query built from user-controlled sources

ID: rust/sql-injectionKind: path-problemSecurity severity: 8.8Severity: errorPrecision: highTags:   - security   - external/cwe/cwe-089Query suites:   - rust-code-scanning.qls   - rust-security-extended.qls   - rust-security-and-quality.qls

Click to see the query in the CodeQL repository

If a database query (such as an SQL query) is built from user-provided data without sufficient sanitization, a user may be able to run malicious database queries. An attacker can craft the part of the query they control to change the overall meaning of the query.

Recommendation

Most database connector libraries offer a way to safely embed untrusted data into a query using query parameters or prepared statements. You should use these features to build queries, rather than string concatenation or similar methods. You can also escape (sanitize) user-controlled strings so that they can be included directly in an SQL command. A library function should be used for escaping, because this approach is only safe if the escaping function is robust against all possible inputs.

Example

In the following examples, an SQL query is prepared using string formatting to directly include a user-controlled valueremote_controlled_string. An attacker could craftremote_controlled_string to change the overall meaning of the SQL query.

// with SQLxletunsafe_query=format!("SELECT * FROM people WHERE firstname='{remote_controlled_string}'");let_=conn.execute(unsafe_query.as_str()).await?;// BAD (arbitrary SQL injection is possible)let_=sqlx::query(unsafe_query.as_str()).fetch_all(&mutconn).await?;// BAD (arbitrary SQL injection is possible)

A better way to do this is with a prepared statement, bindingremote_controlled_string to a parameter of that statement. An attacker who controlsremote_controlled_string now cannot change the overall meaning of the query.

// with SQLxletprepared_query="SELECT * FROM people WHERE firstname=?";let_=sqlx::query(prepared_query_1).bind(&remote_controlled_string).fetch_all(&mutconn).await?;// GOOD (prepared statement with bound parameter)

References


[8]ページ先頭

©2009-2025 Movatter.jp