diff --git a/rust/ql/lib/codeql/rust/frameworks/serde.model.yml b/rust/ql/lib/codeql/rust/frameworks/serde.model.yml new file mode 100644 index 000000000000..3d3c8d63ef85 --- /dev/null +++ b/rust/ql/lib/codeql/rust/frameworks/serde.model.yml @@ -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"] diff --git a/rust/ql/lib/codeql/rust/frameworks/stdlib/process.model.yml b/rust/ql/lib/codeql/rust/frameworks/stdlib/process.model.yml new file mode 100644 index 000000000000..0187f073d679 --- /dev/null +++ b/rust/ql/lib/codeql/rust/frameworks/stdlib/process.model.yml @@ -0,0 +1,15 @@ +extensions: + - addsTo: + pack: codeql/rust-all + extensible: sinkModel + data: + # std::process::Command - the command name itself + - ["::new", "Argument[0]", "command-injection", "manual"] + # std::process::Command - arguments passed to the command + - ["::arg", "Argument[0]", "command-injection", "manual"] + - ["::args", "Argument[0]", "command-injection", "manual"] + # tokio::process::Command - the command name itself + - ["::new", "Argument[0]", "command-injection", "manual"] + # tokio::process::Command - arguments passed to the command + - ["::arg", "Argument[0]", "command-injection", "manual"] + - ["::args", "Argument[0]", "command-injection", "manual"] diff --git a/rust/ql/lib/codeql/rust/security/CommandInjectionExtensions.qll b/rust/ql/lib/codeql/rust/security/CommandInjectionExtensions.qll new file mode 100644 index 000000000000..7e0150d53f66 --- /dev/null +++ b/rust/ql/lib/codeql/rust/security/CommandInjectionExtensions.qll @@ -0,0 +1,64 @@ +/** + * Provides classes and predicates for reasoning about command injection + * vulnerabilities (CWE-078). + */ + +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 command injection + * vulnerabilities, as well as extension points for adding your own. + */ +module CommandInjection { + /** + * A data flow source for command injection vulnerabilities. + */ + abstract class Source extends DataFlow::Node { } + + /** + * A data flow sink for command injection vulnerabilities. + */ + abstract class Sink extends QuerySink::Range { + override string getSinkType() { result = "CommandInjection" } + } + + /** + * A barrier for command injection 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 command injection from model data. + */ + private class ModelsAsDataSink extends Sink { + ModelsAsDataSink() { sinkNode(this, "command-injection") } + } + + /** + * A barrier for command injection from model data. + */ + private class ModelsAsDataBarrier extends Barrier { + ModelsAsDataBarrier() { barrierNode(this, "command-injection") } + } + + /** + * A barrier for command injection vulnerabilities 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 + { } +} diff --git a/rust/ql/lib/codeql/rust/security/UnsafeDeserializationExtensions.qll b/rust/ql/lib/codeql/rust/security/UnsafeDeserializationExtensions.qll new file mode 100644 index 000000000000..70b0c55184c0 --- /dev/null +++ b/rust/ql/lib/codeql/rust/security/UnsafeDeserializationExtensions.qll @@ -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 + { } +} diff --git a/rust/ql/src/queries/security/CWE-078/CommandInjection.qhelp b/rust/ql/src/queries/security/CWE-078/CommandInjection.qhelp new file mode 100644 index 000000000000..3e7b336090b4 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-078/CommandInjection.qhelp @@ -0,0 +1,40 @@ + + + + +

+If a system command is built from user-provided data without sufficient sanitization, a user may be able to run malicious commands. An attacker can craft input to change the meaning of the command, potentially gaining control of the system. +

+ +
+ + +

+If possible, use hard-coded string literals for commands. If the command must be built from user-provided data, do not pass user input directly to shell commands. Instead, use APIs that accept command arguments as separate parameters (such as std::process::Command with individual .arg() calls for each argument), which avoids shell interpretation of special characters. If shell execution is necessary, validate and sanitize user input against an allowlist of permitted values. +

+ +
+ + +

+In the following example, a command is constructed directly from user-controlled input obtained via an HTTP request. An attacker could supply a malicious value to execute arbitrary commands. +

+ + + +

+A safer approach uses a fixed command with validated arguments, or avoids shell interpretation entirely: +

+ + + +
+ + +
  • OWASP: Command Injection.
  • +
  • Wikipedia: Shell injection.
  • + +
    +
    diff --git a/rust/ql/src/queries/security/CWE-078/CommandInjection.ql b/rust/ql/src/queries/security/CWE-078/CommandInjection.ql new file mode 100644 index 000000000000..b6e93a8d88a1 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-078/CommandInjection.ql @@ -0,0 +1,42 @@ +/** + * @name Uncontrolled command line + * @description Using externally controlled strings in a command line may allow a malicious + * user to change the meaning of the command. + * @kind path-problem + * @problem.severity error + * @security-severity 9.8 + * @precision high + * @id rust/command-line-injection + * @tags security + * external/cwe/cwe-078 + * external/cwe/cwe-088 + */ + +import rust +import codeql.rust.dataflow.DataFlow +import codeql.rust.dataflow.TaintTracking +import codeql.rust.security.CommandInjectionExtensions + +/** + * A taint configuration for detecting command injection vulnerabilities. + */ +module CommandInjectionConfig implements DataFlow::ConfigSig { + import CommandInjection + + 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 CommandInjectionFlow = TaintTracking::Global; + +import CommandInjectionFlow::PathGraph + +from CommandInjectionFlow::PathNode sourceNode, CommandInjectionFlow::PathNode sinkNode +where CommandInjectionFlow::flowPath(sourceNode, sinkNode) +select sinkNode.getNode(), sourceNode, sinkNode, "This command line depends on a $@.", + sourceNode.getNode(), "user-provided value" diff --git a/rust/ql/src/queries/security/CWE-078/CommandInjectionBad.rs b/rust/ql/src/queries/security/CWE-078/CommandInjectionBad.rs new file mode 100644 index 000000000000..fa81cef9fe15 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-078/CommandInjectionBad.rs @@ -0,0 +1,10 @@ +use std::process::Command; + +fn handle_request(user_input: &str) { + // BAD: user input is passed directly to a shell command + Command::new("sh") + .arg("-c") + .arg(user_input) + .output() + .expect("failed to execute"); +} diff --git a/rust/ql/src/queries/security/CWE-078/CommandInjectionGood.rs b/rust/ql/src/queries/security/CWE-078/CommandInjectionGood.rs new file mode 100644 index 000000000000..bb720d39d03e --- /dev/null +++ b/rust/ql/src/queries/security/CWE-078/CommandInjectionGood.rs @@ -0,0 +1,13 @@ +use std::process::Command; + +fn handle_request(filename: &str) { + // GOOD: use a fixed command with the user input as a separate argument, + // avoiding shell interpretation + let allowed_names = ["report.pdf", "summary.txt", "data.csv"]; + if allowed_names.contains(&filename) { + Command::new("cat") + .arg(filename) + .output() + .expect("failed to execute"); + } +} diff --git a/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.qhelp b/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.qhelp new file mode 100644 index 000000000000..daa155b51fa9 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.qhelp @@ -0,0 +1,46 @@ + + + + +

    +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 serde, bincode, or rmp-serde can still lead to panics, excessive memory allocation, or logic bugs when trait objects or polymorphic types are involved. +

    + +
    + + +

    +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 serde, consider: +

    +
      +
    • Validating input size before deserialization.
    • +
    • Using #[serde(deny_unknown_fields)] to reject unexpected data.
    • +
    • Avoiding #[typetag] or trait object deserialization with untrusted input.
    • +
    • Using bounded containers (e.g., limiting Vec length via custom deserializers).
    • +
    + +
    + + +

    +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. +

    + + + +

    +A safer approach validates the input size and uses strict deserialization settings: +

    + + + +
    + + +
  • OWASP: Deserialization of untrusted data.
  • +
  • CWE-502: Deserialization of Untrusted Data.
  • + +
    +
    diff --git a/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.ql b/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.ql new file mode 100644 index 000000000000..ec6490fabee4 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-502/UnsafeDeserialization.ql @@ -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; + +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" diff --git a/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationBad.rs b/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationBad.rs new file mode 100644 index 000000000000..8e4f2c6b2c0a --- /dev/null +++ b/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationBad.rs @@ -0,0 +1,12 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +struct UserData { + name: String, + items: Vec, +} + +fn handle_request(body: &[u8]) -> UserData { + // BAD: deserializing user-controlled data without size validation + serde_json::from_slice(body).unwrap() +} diff --git a/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationGood.rs b/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationGood.rs new file mode 100644 index 000000000000..a7d69fb48a56 --- /dev/null +++ b/rust/ql/src/queries/security/CWE-502/UnsafeDeserializationGood.rs @@ -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, +} + +fn bounded_vec<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let v = Vec::::deserialize(deserializer)?; + if v.len() > 100 { + return Err(serde::de::Error::custom("too many items")); + } + Ok(v) +} + +fn handle_request(body: &[u8]) -> Result { + // 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()) +} diff --git a/rust/ql/test/query-tests/security/CWE-078/CommandInjection.qlref b/rust/ql/test/query-tests/security/CWE-078/CommandInjection.qlref new file mode 100644 index 000000000000..3b14f15fafe6 --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-078/CommandInjection.qlref @@ -0,0 +1,4 @@ +query: queries/security/CWE-078/CommandInjection.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/rust/ql/test/query-tests/security/CWE-078/main.rs b/rust/ql/test/query-tests/security/CWE-078/main.rs new file mode 100644 index 000000000000..eecf95cec33d --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-078/main.rs @@ -0,0 +1,75 @@ +use std::process::Command; + +fn test_std_command_injection() { + let arg_string = std::env::args().nth(1).unwrap_or(String::from("ls")); // $ Source=args1 + let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote1 + .unwrap() + .text() + .unwrap_or(String::from("ls")); + let const_string = String::from("echo hello"); + + // --- safe cases --- + + // Constant command and argument + Command::new("ls") + .arg("-la") + .output() + .expect("failed"); // safe + + // Constant constructed command + Command::new(const_string.as_str()) + .output() + .expect("failed"); // safe + + // --- unsafe cases --- + + // User input as the command itself + Command::new(arg_string.as_str()) // $ Alert[rust/command-line-injection]=args1 + .output() + .expect("failed"); + + // User input as an argument to sh -c + Command::new("sh") + .arg("-c") + .arg(remote_string.as_str()) // $ Alert[rust/command-line-injection]=remote1 + .output() + .expect("failed"); + + // User input as an argument + Command::new("grep") + .arg(arg_string.as_str()) // $ Alert[rust/command-line-injection]=args1 + .arg("file.txt") + .output() + .expect("failed"); + + // Remote input via args() + Command::new("bash") + .args(&["-c", remote_string.as_str()]) // $ Alert[rust/command-line-injection]=remote1 + .output() + .expect("failed"); +} + +async fn test_tokio_command_injection() { + let remote_string = reqwest::blocking::get("http://example.com/") // $ Source=remote2 + .unwrap() + .text() + .unwrap_or(String::from("ls")); + + // Unsafe: remote input as tokio command + let _output = tokio::process::Command::new(remote_string.as_str()) // $ Alert[rust/command-line-injection]=remote2 + .output() + .await + .expect("failed"); + + // Unsafe: remote input as tokio command argument + tokio::process::Command::new("sh") + .arg("-c") + .arg(remote_string.as_str()) // $ Alert[rust/command-line-injection]=remote2 + .output() + .await + .expect("failed"); +} + +fn main() { + test_std_command_injection(); +} diff --git a/rust/ql/test/query-tests/security/CWE-078/options.yml b/rust/ql/test/query-tests/security/CWE-078/options.yml new file mode 100644 index 000000000000..78cb2f883af1 --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-078/options.yml @@ -0,0 +1,4 @@ +qltest_cargo_check: true +qltest_dependencies: + - reqwest = { version = "0.12.9", features = ["blocking"] } + - tokio = { version = "1", features = ["full"] } diff --git a/rust/ql/test/query-tests/security/CWE-502/UnsafeDeserialization.qlref b/rust/ql/test/query-tests/security/CWE-502/UnsafeDeserialization.qlref new file mode 100644 index 000000000000..26ecd83ac0b3 --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-502/UnsafeDeserialization.qlref @@ -0,0 +1,4 @@ +query: queries/security/CWE-502/UnsafeDeserialization.ql +postprocess: + - utils/test/PrettyPrintModels.ql + - utils/test/InlineExpectationsTestQuery.ql diff --git a/rust/ql/test/query-tests/security/CWE-502/main.rs b/rust/ql/test/query-tests/security/CWE-502/main.rs new file mode 100644 index 000000000000..5c607982c36b --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-502/main.rs @@ -0,0 +1,66 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +struct UserData { + name: String, + items: Vec, +} + +#[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 + } +} + +fn main() { + test_serde_json_deserialization(); + test_bincode_deserialization(); + test_safe_with_validation(); +} diff --git a/rust/ql/test/query-tests/security/CWE-502/options.yml b/rust/ql/test/query-tests/security/CWE-502/options.yml new file mode 100644 index 000000000000..f3664c3c1ba7 --- /dev/null +++ b/rust/ql/test/query-tests/security/CWE-502/options.yml @@ -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" }