Repository navigation
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
Open
lcmangalagiri
wants to merge
4
commits into
github:main
Choose a base branch
from
lcmangalagiri:rust-cwe-502-unsafe-deserialization
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3a3bea5
Rust: Add unsafe deserialization query (CWE-502)
lcmangalagiri 1c65c98
Add change note for rust/unsafe-deserialization query
lcmangalagiri d231f83
Merge branch 'main' into rust-cwe-502-unsafe-deserialization
geoffw0 bccfc94
Rust: Address unsafe deserialization review feedback
lcmangalagiri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| extensions: | ||
| - addsTo: | ||
| pack: codeql/rust-all | ||
| extensible: sinkModel | ||
| data: | ||
| # serde_json deserialization functions | ||
| - ["serde_json::de::from_str", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_json::de::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_json::de::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_json::value::from_value", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_json::value::from_value", "Argument[0].Field[serde_json::value::Value::String(0)]", "unsafe-deserialization", "manual"] | ||
| # bincode deserialization functions | ||
| - ["bincode::deserialize", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["bincode::deserialize_from", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # rmp_serde (MessagePack) deserialization functions | ||
| - ["rmp_serde::decode::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["rmp_serde::decode::from_read", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # ciborium (CBOR) deserialization functions | ||
| - ["ciborium::de::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # serde_yaml deserialization functions | ||
| - ["serde_yaml::de::from_str", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_yaml::de::from_slice", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| - ["serde_yaml::de::from_reader", "Argument[0]", "unsafe-deserialization", "manual"] | ||
| # toml deserialization | ||
| - ["toml::de::from_str", "Argument[0]", "unsafe-deserialization", "manual"] |
64 changes: 64 additions & 0 deletions
64
rust/ql/lib/codeql/rust/security/UnsafeDeserializationExtensions.qll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| { } | ||
| } |
4 changes: 4 additions & 0 deletions
4
rust/ql/src/change-notes/2026-08-11-unsafe-deserialization.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
45 changes: 45 additions & 0 deletions
45
rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.qhelp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| <!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://community.owasp.org/vulnerabilities/Deserialization_of_untrusted_data">Deserialization of untrusted data</a>.</li> | ||
|
|
||
| </references> | ||
| </qhelp> |
42 changes: 42 additions & 0 deletions
42
rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
12 changes: 12 additions & 0 deletions
12
rust/ql/src/queries/security/CWE-502/UnsafeDeserializationBad.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
||
30 changes: 30 additions & 0 deletions
30
rust/ql/src/queries/security/CWE-502/UnsafeDeserializationGood.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Its right, though to be honest I slightly prefer your alert message.