Skip to content

Commit 3a3bea5

Browse files
committed
Rust: Add unsafe deserialization query (CWE-502)
Detects user-controlled data flowing into deserialization functions (serde_json, bincode, rmp_serde, ciborium, serde_yaml, toml). - Extension library with sources, sinks, and barriers - Models-as-data sink definitions - Query help (.qhelp) with examples - Test cases with inline expectations Query ID: rust/unsafe-deserialization
1 parent 08547cb commit 3a3bea5

9 files changed

Lines changed: 294 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
extensions:
2+
- addsTo:
3+
pack: codeql/rust-all
4+
extensible: sinkModel
5+
data:
6+
# serde_json deserialization functions
7+
- ["crate::serde_json::from_str", "Argument[0]", "unsafe-deserialization", "manual"]
8+
- ["crate::serde_json::from_slice", "Argument[0]", "unsafe-deserialization", "manual"]
9+
- ["crate::serde_json::from_reader", "Argument[0]", "unsafe-deserialization", "manual"]
10+
- ["crate::serde_json::from_value", "Argument[0]", "unsafe-deserialization", "manual"]
11+
# bincode deserialization functions
12+
- ["crate::bincode::deserialize", "Argument[0]", "unsafe-deserialization", "manual"]
13+
- ["crate::bincode::deserialize_from", "Argument[0]", "unsafe-deserialization", "manual"]
14+
# rmp_serde (MessagePack) deserialization functions
15+
- ["crate::rmp_serde::from_slice", "Argument[0]", "unsafe-deserialization", "manual"]
16+
- ["crate::rmp_serde::from_read", "Argument[0]", "unsafe-deserialization", "manual"]
17+
# ciborium (CBOR) deserialization functions
18+
- ["crate::ciborium::from_reader", "Argument[0]", "unsafe-deserialization", "manual"]
19+
# serde_yaml deserialization functions
20+
- ["crate::serde_yaml::from_str", "Argument[0]", "unsafe-deserialization", "manual"]
21+
- ["crate::serde_yaml::from_slice", "Argument[0]", "unsafe-deserialization", "manual"]
22+
- ["crate::serde_yaml::from_reader", "Argument[0]", "unsafe-deserialization", "manual"]
23+
# toml deserialization
24+
- ["crate::toml::from_str", "Argument[0]", "unsafe-deserialization", "manual"]
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Provides classes and predicates for reasoning about unsafe deserialization
3+
* vulnerabilities (CWE-502).
4+
*/
5+
6+
import rust
7+
private import codeql.rust.dataflow.DataFlow
8+
private import codeql.rust.dataflow.FlowSink
9+
private import codeql.rust.dataflow.FlowBarrier
10+
private import codeql.rust.Concepts
11+
private import codeql.rust.security.Barriers as Barriers
12+
13+
/**
14+
* Provides default sources, sinks and barriers for detecting unsafe deserialization
15+
* vulnerabilities, as well as extension points for adding your own.
16+
*/
17+
module UnsafeDeserialization {
18+
/**
19+
* A data flow source for unsafe deserialization vulnerabilities.
20+
*/
21+
abstract class Source extends DataFlow::Node { }
22+
23+
/**
24+
* A data flow sink for unsafe deserialization vulnerabilities.
25+
*/
26+
abstract class Sink extends QuerySink::Range {
27+
override string getSinkType() { result = "UnsafeDeserialization" }
28+
}
29+
30+
/**
31+
* A barrier for unsafe deserialization vulnerabilities.
32+
*/
33+
abstract class Barrier extends DataFlow::Node { }
34+
35+
/**
36+
* An active threat-model source, considered as a flow source.
37+
*/
38+
private class ActiveThreatModelSourceAsSource extends Source, ActiveThreatModelSource { }
39+
40+
/**
41+
* A sink for unsafe deserialization from model data.
42+
*/
43+
private class ModelsAsDataSink extends Sink {
44+
ModelsAsDataSink() { sinkNode(this, "unsafe-deserialization") }
45+
}
46+
47+
/**
48+
* A barrier for unsafe deserialization from model data.
49+
*/
50+
private class ModelsAsDataBarrier extends Barrier {
51+
ModelsAsDataBarrier() { barrierNode(this, "unsafe-deserialization") }
52+
}
53+
54+
/**
55+
* A barrier for unsafe deserialization for nodes whose type is a numeric
56+
* type, which is unlikely to expose any vulnerability.
57+
*/
58+
private class NumericTypeBarrier extends Barrier instanceof Barriers::NumericTypeBarrier { }
59+
60+
private class BooleanTypeBarrier extends Barrier instanceof Barriers::BooleanTypeBarrier { }
61+
62+
private class FieldlessEnumTypeBarrier extends Barrier instanceof Barriers::FieldlessEnumTypeBarrier
63+
{ }
64+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
<overview>
6+
7+
<p>
8+
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.
9+
</p>
10+
11+
</overview>
12+
<recommendation>
13+
14+
<p>
15+
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:
16+
</p>
17+
<ul>
18+
<li>Validating input size before deserialization.</li>
19+
<li>Using <code>#[serde(deny_unknown_fields)]</code> to reject unexpected data.</li>
20+
<li>Avoiding <code>#[typetag]</code> or trait object deserialization with untrusted input.</li>
21+
<li>Using bounded containers (e.g., limiting <code>Vec</code> length via custom deserializers).</li>
22+
</ul>
23+
24+
</recommendation>
25+
<example>
26+
27+
<p>
28+
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.
29+
</p>
30+
31+
<sample src="UnsafeDeserializationBad.rs" />
32+
33+
<p>
34+
A safer approach validates the input size and uses strict deserialization settings:
35+
</p>
36+
37+
<sample src="UnsafeDeserializationGood.rs" />
38+
39+
</example>
40+
<references>
41+
42+
<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>
43+
<li>CWE-502: <a href="https://cwe.mitre.org/data/definitions/502.html">Deserialization of Untrusted Data</a>.</li>
44+
45+
</references>
46+
</qhelp>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @name Deserialization of user-controlled data
3+
* @description Deserializing user-controlled data may allow an attacker to trigger unexpected
4+
* code execution, denial of service, or other harmful effects.
5+
* @kind path-problem
6+
* @problem.severity error
7+
* @security-severity 9.8
8+
* @precision high
9+
* @id rust/unsafe-deserialization
10+
* @tags security
11+
* external/cwe/cwe-502
12+
*/
13+
14+
import rust
15+
import codeql.rust.dataflow.DataFlow
16+
import codeql.rust.dataflow.TaintTracking
17+
import codeql.rust.security.UnsafeDeserializationExtensions
18+
19+
/**
20+
* A taint configuration for detecting unsafe deserialization vulnerabilities.
21+
*/
22+
module UnsafeDeserializationConfig implements DataFlow::ConfigSig {
23+
import UnsafeDeserialization
24+
25+
predicate isSource(DataFlow::Node node) { node instanceof Source }
26+
27+
predicate isSink(DataFlow::Node node) { node instanceof Sink }
28+
29+
predicate isBarrier(DataFlow::Node barrier) { barrier instanceof Barrier }
30+
31+
predicate observeDiffInformedIncrementalMode() { any() }
32+
}
33+
34+
module UnsafeDeserializationFlow = TaintTracking::Global<UnsafeDeserializationConfig>;
35+
36+
import UnsafeDeserializationFlow::PathGraph
37+
38+
from UnsafeDeserializationFlow::PathNode sourceNode, UnsafeDeserializationFlow::PathNode sinkNode
39+
where UnsafeDeserializationFlow::flowPath(sourceNode, sinkNode)
40+
select sinkNode.getNode(), sourceNode, sinkNode,
41+
"This deserialization operation processes $@ without validation.", sourceNode.getNode(),
42+
"user-provided data"
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use serde::Deserialize;
2+
3+
#[derive(Deserialize)]
4+
struct UserData {
5+
name: String,
6+
items: Vec<String>,
7+
}
8+
9+
fn handle_request(body: &[u8]) -> UserData {
10+
// BAD: deserializing user-controlled data without size validation
11+
serde_json::from_slice(body).unwrap()
12+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use serde::Deserialize;
2+
3+
const MAX_BODY_SIZE: usize = 1024 * 1024; // 1 MB limit
4+
5+
#[derive(Deserialize)]
6+
#[serde(deny_unknown_fields)]
7+
struct UserData {
8+
name: String,
9+
#[serde(deserialize_with = "bounded_vec")]
10+
items: Vec<String>,
11+
}
12+
13+
fn bounded_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
14+
where
15+
D: serde::Deserializer<'de>,
16+
{
17+
let v = Vec::<String>::deserialize(deserializer)?;
18+
if v.len() > 100 {
19+
return Err(serde::de::Error::custom("too many items"));
20+
}
21+
Ok(v)
22+
}
23+
24+
fn handle_request(body: &[u8]) -> Result<UserData, String> {
25+
// GOOD: validate input size before deserialization, use bounded containers
26+
if body.len() > MAX_BODY_SIZE {
27+
return Err("payload too large".to_string());
28+
}
29+
serde_json::from_slice(body).map_err(|e| e.to_string())
30+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
query: queries/security/CWE-502/UnsafeDeserialization.ql
2+
postprocess:
3+
- utils/test/PrettyPrintModels.ql
4+
- utils/test/InlineExpectationsTestQuery.ql
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use serde::Deserialize;
2+
3+
#[derive(Deserialize)]
4+
struct UserData {
5+
name: String,
6+
items: Vec<String>,
7+
}
8+
9+
#[derive(Deserialize)]
10+
struct Config {
11+
setting: String,
12+
}
13+
14+
fn test_serde_json_deserialization() {
15+
let remote_bytes = reqwest::blocking::get("http://example.com/") // $ Source=remote1
16+
.unwrap()
17+
.bytes()
18+
.unwrap();
19+
let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote2
20+
.unwrap()
21+
.text()
22+
.unwrap_or(String::from("{}"));
23+
let const_string = String::from(r#"{"name": "test", "items": []}"#);
24+
25+
// --- safe cases ---
26+
27+
// Constant data deserialization
28+
let _safe: UserData = serde_json::from_str(&const_string).unwrap(); // safe
29+
30+
// --- unsafe cases ---
31+
32+
// Remote bytes directly deserialized
33+
let _unsafe1: UserData = serde_json::from_slice(&remote_bytes).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote1
34+
35+
// Remote string directly deserialized
36+
let _unsafe2: UserData = serde_json::from_str(&remote_string).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote2
37+
}
38+
39+
fn test_bincode_deserialization() {
40+
let remote_bytes = reqwest::blocking::get("http://example.com/data") // $ Source=remote3
41+
.unwrap()
42+
.bytes()
43+
.unwrap();
44+
45+
// Unsafe: remote data deserialized with bincode
46+
let _unsafe: Config = bincode::deserialize(&remote_bytes).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote3
47+
}
48+
49+
fn test_safe_with_validation() {
50+
let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote4
51+
.unwrap()
52+
.text()
53+
.unwrap_or(String::from("{}"));
54+
55+
// Safe: size check before deserialization (still flagged as the barrier
56+
// is not modeled as a data flow barrier, but demonstrates the pattern)
57+
if remote_string.len() < 1024 {
58+
let _data: UserData = serde_json::from_str(&remote_string).unwrap(); // $ Alert[rust/unsafe-deserialization]=remote4
59+
}
60+
}
61+
62+
fn main() {
63+
test_serde_json_deserialization();
64+
test_bincode_deserialization();
65+
test_safe_with_validation();
66+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
qltest_cargo_check: true
2+
qltest_dependencies:
3+
- reqwest = { version = "0.12.9", features = ["blocking"] }
4+
- serde = { version = "1", features = ["derive"] }
5+
- serde_json = { version = "1" }
6+
- bincode = { version = "1" }

0 commit comments

Comments
 (0)