-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Rust: Add unsafe deserialization query (CWE-502) #22324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| extensions: | ||
| - addsTo: | ||
| pack: codeql/rust-all | ||
| extensible: sinkModel | ||
| data: | ||
| # serde_json deserialization functions | ||
| - ["crate::serde_json::from_str", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::serde_json::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::serde_json::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::serde_json::from_value", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # bincode deserialization functions | ||
| - ["crate::bincode::deserialize", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::bincode::deserialize_from", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # rmp_serde (MessagePack) deserialization functions | ||
| - ["crate::rmp_serde::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::rmp_serde::from_read", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # ciborium (CBOR) deserialization functions | ||
| - ["crate::ciborium::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # serde_yaml deserialization functions | ||
| - ["crate::serde_yaml::from_str", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::serde_yaml::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["crate::serde_yaml::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # toml deserialization | ||
| - ["crate::toml::from_str", "Argument[0]", "unsafe-deserialization", "manual"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /** | ||
| * Provides classes and predicates for reasoning about unsafe deserialization | ||
| * vulnerabilities (CWE-502). | ||
| */ | ||
|
|
||
| import rust | ||
| private import codeql.rust.dataflow.DataFlow | ||
| private import codeql.rust.dataflow.FlowSink | ||
| private import codeql.rust.dataflow.FlowBarrier | ||
| private import codeql.rust.Concepts | ||
| private import codeql.rust.security.Barriers as Barriers | ||
|
|
||
| /** | ||
| * Provides default sources, sinks and barriers for detecting unsafe deserialization | ||
| * vulnerabilities, as well as extension points for adding your own. | ||
| */ | ||
| module UnsafeDeserialization { | ||
| /** | ||
| * A data flow source for unsafe deserialization vulnerabilities. | ||
| */ | ||
| abstract class Source extends DataFlow::Node { } | ||
|
|
||
| /** | ||
| * A data flow sink for unsafe deserialization vulnerabilities. | ||
| */ | ||
| abstract class Sink extends QuerySink::Range { | ||
| override string getSinkType() { result = "UnsafeDeserialization" } | ||
| } | ||
|
|
||
| /** | ||
| * A barrier for unsafe deserialization vulnerabilities. | ||
| */ | ||
| abstract class Barrier extends DataFlow::Node { } | ||
|
|
||
| /** | ||
| * An active threat-model source, considered as a flow source. | ||
| */ | ||
| private class ActiveThreatModelSourceAsSource extends Source, ActiveThreatModelSource { } | ||
|
|
||
| /** | ||
| * A sink for unsafe deserialization from model data. | ||
| */ | ||
| private class ModelsAsDataSink extends Sink { | ||
| ModelsAsDataSink() { sinkNode(this, "unsafe-deserialization") } | ||
| } | ||
|
|
||
| /** | ||
| * A barrier for unsafe deserialization from model data. | ||
| */ | ||
| private class ModelsAsDataBarrier extends Barrier { | ||
| ModelsAsDataBarrier() { barrierNode(this, "unsafe-deserialization") } | ||
| } | ||
|
|
||
| /** | ||
| * A barrier for unsafe deserialization for nodes whose type is a numeric | ||
| * type, which is unlikely to expose any vulnerability. | ||
| */ | ||
| private class NumericTypeBarrier extends Barrier instanceof Barriers::NumericTypeBarrier { } | ||
|
|
||
| private class BooleanTypeBarrier extends Barrier instanceof Barriers::BooleanTypeBarrier { } | ||
|
|
||
| private class FieldlessEnumTypeBarrier extends Barrier instanceof Barriers::FieldlessEnumTypeBarrier | ||
| { } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| --- | ||
| category: newQuery | ||
| --- | ||
| * Added a new query, `rust/unsafe-deserialization`, to detect deserialization of user-controlled data. |
| Original file line number | Diff line number | Diff line change | ||
|---|---|---|---|---|
| @@ -0,0 +1,46 @@ | ||||
| <!DOCTYPE qhelp PUBLIC | ||||
| "-//Semmle//qhelp//EN" | ||||
| "qhelp.dtd"> | ||||
| <qhelp> | ||||
| <overview> | ||||
|
|
||||
| <p> | ||||
| Deserializing untrusted data without validation can allow an attacker to cause denial of service, consume excessive resources, or in some cases execute arbitrary code. In Rust, while memory safety mitigates some risks, deserializing untrusted data with libraries like <code>serde</code>, <code>bincode</code>, or <code>rmp-serde</code> can still lead to panics, excessive memory allocation, or logic bugs when trait objects or polymorphic types are involved. | ||||
| </p> | ||||
|
|
||||
| </overview> | ||||
| <recommendation> | ||||
|
|
||||
| <p> | ||||
| Avoid deserializing untrusted data with formats that allow unbounded allocation or polymorphic dispatch. Prefer formats with schema validation (like Protocol Buffers) when processing untrusted input. If using <code>serde</code>, consider: | ||||
| </p> | ||||
| <ul> | ||||
| <li>Validating input size before deserialization.</li> | ||||
| <li>Using <code>#[serde(deny_unknown_fields)]</code> to reject unexpected data.</li> | ||||
| <li>Avoiding <code>#[typetag]</code> or trait object deserialization with untrusted input.</li> | ||||
| <li>Using bounded containers (e.g., limiting <code>Vec</code> length via custom deserializers).</li> | ||||
| </ul> | ||||
|
|
||||
| </recommendation> | ||||
| <example> | ||||
|
|
||||
| <p> | ||||
| In the following example, data from an HTTP request is directly deserialized without any validation. An attacker could send a crafted payload that causes excessive memory allocation or other unintended behavior. | ||||
| </p> | ||||
|
|
||||
| <sample src="UnsafeDeserializationBad.rs" /> | ||||
|
|
||||
| <p> | ||||
| A safer approach validates the input size and uses strict deserialization settings: | ||||
| </p> | ||||
|
|
||||
| <sample src="UnsafeDeserializationGood.rs" /> | ||||
|
|
||||
| </example> | ||||
| <references> | ||||
|
|
||||
| <li>OWASP: <a href="https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/16-Testing_for_HTTP_Incoming_Requests">Deserialization of untrusted data</a>.</li> | ||||
| <li>CWE-502: <a href="https://cwe.mitre.org/data/definitions/502.html">Deserialization of Untrusted Data</a>.</li> | ||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
We don't need to include a reference to the CWE-502 page, this will be done automatically based on the |
||||
|
|
||||
| </references> | ||||
| </qhelp> | ||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| /** | ||
| * @name Deserialization of user-controlled data | ||
| * @description Deserializing user-controlled data may allow an attacker to trigger unexpected | ||
| * code execution, denial of service, or other harmful effects. | ||
| * @kind path-problem | ||
| * @problem.severity error | ||
| * @security-severity 9.8 | ||
| * @precision high | ||
| * @id rust/unsafe-deserialization | ||
| * @tags security | ||
| * external/cwe/cwe-502 | ||
| */ | ||
|
|
||
| import rust | ||
| import codeql.rust.dataflow.DataFlow | ||
| import codeql.rust.dataflow.TaintTracking | ||
| import codeql.rust.security.UnsafeDeserializationExtensions | ||
|
|
||
| /** | ||
| * A taint configuration for detecting unsafe deserialization vulnerabilities. | ||
| */ | ||
| module UnsafeDeserializationConfig implements DataFlow::ConfigSig { | ||
| import UnsafeDeserialization | ||
|
|
||
| predicate isSource(DataFlow::Node node) { node instanceof Source } | ||
|
|
||
| predicate isSink(DataFlow::Node node) { node instanceof Sink } | ||
|
|
||
| predicate isBarrier(DataFlow::Node barrier) { barrier instanceof Barrier } | ||
|
|
||
| predicate observeDiffInformedIncrementalMode() { any() } | ||
| } | ||
|
|
||
| module UnsafeDeserializationFlow = TaintTracking::Global<UnsafeDeserializationConfig>; | ||
|
|
||
| import UnsafeDeserializationFlow::PathGraph | ||
|
|
||
| from UnsafeDeserializationFlow::PathNode sourceNode, UnsafeDeserializationFlow::PathNode sinkNode | ||
| where UnsafeDeserializationFlow::flowPath(sourceNode, sinkNode) | ||
| select sinkNode.getNode(), sourceNode, sinkNode, | ||
| "This deserialization operation processes $@ without validation.", sourceNode.getNode(), | ||
| "user-provided data" | ||
|
Comment on lines
+38
to
+42
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Its right, though to be honest I slightly prefer your alert message. |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| use serde::Deserialize; | ||
|
|
||
| #[derive(Deserialize)] | ||
| struct UserData { | ||
| name: String, | ||
| items: Vec<String>, | ||
| } | ||
|
|
||
| fn handle_request(body: &[u8]) -> UserData { | ||
| // BAD: deserializing user-controlled data without size validation | ||
| serde_json::from_slice(body).unwrap() | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should include the bad and good example code in the test. (it's OK if the query doesn't give exactly the results we'd like on them, at this stage) |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| use serde::Deserialize; | ||
|
|
||
| const MAX_BODY_SIZE: usize = 1024 * 1024; // 1 MB limit | ||
|
|
||
| #[derive(Deserialize)] | ||
| #[serde(deny_unknown_fields)] | ||
| struct UserData { | ||
| name: String, | ||
| #[serde(deserialize_with = "bounded_vec")] | ||
| items: Vec<String>, | ||
| } | ||
|
|
||
| fn bounded_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> | ||
| where | ||
| D: serde::Deserializer<'de>, | ||
| { | ||
| let v = Vec::<String>::deserialize(deserializer)?; | ||
| if v.len() > 100 { | ||
| return Err(serde::de::Error::custom("too many items")); | ||
| } | ||
| Ok(v) | ||
| } | ||
|
|
||
| fn handle_request(body: &[u8]) -> Result<UserData, String> { | ||
| // GOOD: validate input size before deserialization, use bounded containers | ||
| if body.len() > MAX_BODY_SIZE { | ||
| return Err("payload too large".to_string()); | ||
| } | ||
| serde_json::from_slice(body).map_err(|e| e.to_string()) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| query: queries/security/CWE-502/UnsafeDeserialization.ql | ||
| postprocess: | ||
| - utils/test/PrettyPrintModels.ql | ||
| - utils/test/InlineExpectationsTestQuery.ql |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,66 @@ | ||||||
| use serde::Deserialize; | ||||||
|
|
||||||
| #[derive(Deserialize)] | ||||||
| struct UserData { | ||||||
| name: String, | ||||||
| items: Vec<String>, | ||||||
| } | ||||||
|
|
||||||
| #[derive(Deserialize)] | ||||||
| struct Config { | ||||||
| setting: String, | ||||||
| } | ||||||
|
|
||||||
| fn test_serde_json_deserialization() { | ||||||
| let remote_bytes = reqwest::blocking::get("http://example.com/") // $ Source=remote1 | ||||||
| .unwrap() | ||||||
| .bytes() | ||||||
| .unwrap(); | ||||||
| let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote2 | ||||||
| .unwrap() | ||||||
| .text() | ||||||
| .unwrap_or(String::from("{}")); | ||||||
| let const_string = String::from(r#"{"name": "test", "items": []}"#); | ||||||
|
|
||||||
| // --- safe cases --- | ||||||
|
|
||||||
| // Constant data deserialization | ||||||
| let _safe: UserData = serde_json::from_str(&const_string).unwrap(); // safe | ||||||
|
|
||||||
| // --- unsafe cases --- | ||||||
|
|
||||||
| // Remote bytes directly deserialized | ||||||
| let _unsafe1: UserData = serde_json::from_slice(&remote_bytes).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote1 | ||||||
|
|
||||||
| // Remote string directly deserialized | ||||||
| let _unsafe2: UserData = serde_json::from_str(&remote_string).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote2 | ||||||
| } | ||||||
|
|
||||||
| fn test_bincode_deserialization() { | ||||||
| let remote_bytes = reqwest::blocking::get("http://example.com/data") // $ Source=remote3 | ||||||
| .unwrap() | ||||||
| .bytes() | ||||||
| .unwrap(); | ||||||
|
|
||||||
| // Unsafe: remote data deserialized with bincode | ||||||
| let _unsafe: Config = bincode::deserialize(&remote_bytes).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote3 | ||||||
| } | ||||||
|
|
||||||
| fn test_safe_with_validation() { | ||||||
| let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote4 | ||||||
| .unwrap() | ||||||
| .text() | ||||||
| .unwrap_or(String::from("{}")); | ||||||
|
|
||||||
| // Safe: size check before deserialization (still flagged as the barrier | ||||||
| // is not modeled as a data flow barrier, but demonstrates the pattern) | ||||||
| if remote_string.len() < 1024 { | ||||||
| let _data: UserData = serde_json::from_str(&remote_string).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote4 | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use the
Suggested change
|
||||||
| } | ||||||
| } | ||||||
|
|
||||||
| fn main() { | ||||||
| test_serde_json_deserialization(); | ||||||
| test_bincode_deserialization(); | ||||||
| test_safe_with_validation(); | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| qltest_cargo_check: true | ||
| qltest_dependencies: | ||
| - reqwest = { version = "0.12.9", features = ["blocking"] } | ||
| - serde = { version = "1", features = ["derive"] } | ||
| - serde_json = { version = "1" } | ||
| - bincode = { version = "1" } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I get a 404 error for this link. Is this the page you want to reference?