diff --git a/compliance-agent/rules/cra_semgrep.yaml b/compliance-agent/rules/cra_semgrep.yaml index 6f0d6c1..56ed5fa 100644 --- a/compliance-agent/rules/cra_semgrep.yaml +++ b/compliance-agent/rules/cra_semgrep.yaml @@ -117,12 +117,13 @@ rules: - pattern: 'crypto.createCipher(...)' # --- C/C++ firmware ------------------------------------------------------------ + # C and C++ sources alike (`languages: [c, cpp]`), with the `std::` spellings. # Microcontroller code: unbounded string handling, non-literal format strings, # credentials compiled into every device, broken crypto and predictable # randomness. Memory-safety defects that need data flow (out-of-bounds # writes, uninitialised reads) come from cppcheck, not from these patterns. - id: cra-ai-20-c-unbounded-string-function - languages: [c] + languages: [c, cpp] severity: ERROR message: $FN() writes without a bound on the destination โ€” input longer than the buffer overflows it (CWE-120). Use a bounded call (snprintf, strncpy/strlcpy with the buffer size). metadata: @@ -132,10 +133,10 @@ rules: - pattern: $FN(...) - metavariable-regex: metavariable: $FN - regex: ^(gets|strcpy|strcat|sprintf|vsprintf|wcscpy|wcscat)$ + regex: ^(std::)?(gets|strcpy|strcat|sprintf|vsprintf|wcscpy|wcscat)$ - id: cra-ai-20-c-scanf-unbounded-string - languages: [c] + languages: [c, cpp] severity: ERROR message: A "%s" conversion without a field width reads unbounded input into a fixed buffer (CWE-120). Give the conversion a width, e.g. "%15s". metadata: @@ -151,7 +152,7 @@ rules: regex: ^".*%s.*"$ - id: cra-ai-20-c-non-literal-format-string - languages: [c] + languages: [c, cpp] severity: WARNING message: The format string is not a literal โ€” text an attacker controls can read or write memory through format specifiers (CWE-134). Print it with a literal format, e.g. printf("%s", text). metadata: @@ -165,12 +166,17 @@ rules: - pattern: sprintf($B, $FMT, ...) - pattern: snprintf($B, $N, $FMT, ...) - pattern: syslog($P, $FMT, ...) + # C++ reaches the same functions through std::. + - pattern: std::printf($FMT, ...) + - pattern: std::fprintf($F, $FMT, ...) + - pattern: std::sprintf($B, $FMT, ...) + - pattern: std::snprintf($B, $N, $FMT, ...) - metavariable-regex: metavariable: $FMT regex: ^[^"] - id: cra-ai-8-c-hardcoded-credential - languages: [c] + languages: [c, cpp] severity: ERROR message: A credential ($NAME) is written into the firmware source โ€” every device ships the same secret, and it can be read out of the image (CWE-798). Provision it per device at production or first boot. metadata: @@ -190,7 +196,7 @@ rules: regex: .{6,} - id: cra-ai-13-c-broken-hash-or-cipher - languages: [c] + languages: [c, cpp] severity: WARNING message: $FN uses a broken algorithm (MD5, SHA-1 or DES) that protects neither integrity nor confidentiality (CWE-327). Use SHA-256 or better, and AES-GCM or ChaCha20-Poly1305. metadata: @@ -203,7 +209,7 @@ rules: regex: ^(MD5|MD5_Init|MD5_Update|MD5_Final|SHA1|SHA1_Init|SHA1_Update|SHA1_Final|DES_\w+|mbedtls_md5\w*|mbedtls_sha1\w*|mbedtls_des_\w+|wc_Md5\w*|wc_InitSha|wc_ShaUpdate|wc_ShaFinal|wc_Des_\w+)$ - id: cra-ai-16-c-predictable-random - languages: [c] + languages: [c, cpp] severity: WARNING message: rand() is predictable, so $NAME can be guessed (CWE-338). Take keys, nonces and tokens from the MCU's hardware RNG or a DRBG. metadata: diff --git a/compliance-agent/src/pipeline/semgrep.rs b/compliance-agent/src/pipeline/semgrep.rs index 796f9b9..0a75b3e 100644 --- a/compliance-agent/src/pipeline/semgrep.rs +++ b/compliance-agent/src/pipeline/semgrep.rs @@ -195,6 +195,56 @@ fn extract_cwe(metadata: &serde_json::Value) -> Option { mod tests { use super::*; + /// The `languages:` of each rule in our pack, by id. The pack is flat + /// (`- id:` then `languages: [..]`), so lines are enough. + fn rule_languages() -> std::collections::HashMap> { + let mut out = std::collections::HashMap::new(); + let mut id = None; + for line in CRA_RULES.lines().map(str::trim) { + if let Some(rest) = line.strip_prefix("- id:") { + id = Some(rest.trim().to_string()); + } else if let (Some(rest), Some(rule)) = (line.strip_prefix("languages:"), id.take()) { + let langs = rest + .trim() + .trim_matches(|c| c == '[' || c == ']') + .split(',') + .map(|l| l.trim().to_string()) + .collect(); + out.insert(rule, langs); + } + } + out + } + + #[test] + fn the_control_map_claims_the_languages_our_rules_cover() { + // A binding that claims fewer languages undersells a rule; one whose + // rule does not run on a language it claims would make the CRA status + // say "no violation found" for code no rule read. + let rules = rule_languages(); + let map = control_map::ControlMap::cra().unwrap_or_else(|e| panic!("map: {e}")); + for control in &map.controls { + for binding in control.scans.iter().filter(|b| b.tool == "semgrep") { + for rule in &binding.rules { + let langs = rules + .get(rule) + .unwrap_or_else(|| panic!("{rule} is not in the rule pack")); + for lang in langs { + assert!( + binding.languages.contains(lang), + "{}: {rule} runs on {lang}, the binding does not say so", + control.control + ); + } + } + } + } + assert_eq!( + rules.get("cra-ai-20-c-unbounded-string-function"), + Some(&vec!["c".to_string(), "cpp".to_string()]) + ); + } + #[test] fn extract_cwe_handles_list_and_normalises() { let md = serde_json::json!({"cwe": ["CWE-798: Use of Hard-coded Credentials"]}); diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index 8bd4977..8144b92 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -123,7 +123,8 @@ "php", "csharp", "kotlin", - "c" + "c", + "cpp" ], "cwe": [ "CWE-798", @@ -263,7 +264,8 @@ "php", "csharp", "kotlin", - "c" + "c", + "cpp" ], "cwe": [ "CWE-327", @@ -351,7 +353,8 @@ "php", "csharp", "kotlin", - "c" + "c", + "cpp" ], "cwe": [ "CWE-798", @@ -403,7 +406,8 @@ "php", "csharp", "kotlin", - "c" + "c", + "cpp" ], "cwe": [ "CWE-89", diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 3b53fde..df4306a 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -223,8 +223,9 @@ mod tests { // Only Python/JS rules check secure defaults. assert!(!secure_defaults.checked_for(&c_only)); assert!(secure_defaults.checked_for(&python)); - // Our C rules and cppcheck check memory safety in C. + // Our C rules and cppcheck check memory safety in C, and in C++. assert!(memory_safety.checked_for(&c_only)); + assert!(memory_safety.checked_for(&["cpp".to_string()])); // gitleaks reads any file, so no language is needed. assert!(secrets.checked_for(&[])); } diff --git a/fixtures/nightly/baselines/fw-c-sensor-node.json b/fixtures/nightly/baselines/fw-c-sensor-node.json index c33809b..252acaa 100644 --- a/fixtures/nightly/baselines/fw-c-sensor-node.json +++ b/fixtures/nightly/baselines/fw-c-sensor-node.json @@ -12,9 +12,12 @@ "cppcheck:uninitvar sensors.c:19", "semgrep:cra-ai-13-c-broken-hash-or-cipher comms.c:36", "semgrep:cra-ai-16-c-predictable-random comms.c:35", + "semgrep:cra-ai-20-c-non-literal-format-string cli.cpp:15", "semgrep:cra-ai-20-c-non-literal-format-string comms.c:23", + "semgrep:cra-ai-20-c-unbounded-string-function cli.cpp:11", "semgrep:cra-ai-20-c-unbounded-string-function comms.c:20", "semgrep:cra-ai-20-c-unbounded-string-function comms.c:25", + "semgrep:cra-ai-8-c-hardcoded-credential cli.cpp:8", "semgrep:cra-ai-8-c-hardcoded-credential comms.c:10", "semgrep:cra-ai-8-c-hardcoded-credential comms.c:9" ], diff --git a/fixtures/nightly/firmware/c-sensor-node/Core/Src/cli.cpp b/fixtures/nightly/firmware/c-sensor-node/Core/Src/cli.cpp new file mode 100644 index 0000000..091f55c --- /dev/null +++ b/fixtures/nightly/firmware/c-sensor-node/Core/Src/cli.cpp @@ -0,0 +1,22 @@ +// Service console on UART2 (C++): prints a banner, logs lines and answers +// "status". Planted flaws for the nightly: the C rules run on C++ too. +#include +#include + +namespace cli { + +static const std::string service_password = "svc-Pr0be-2024"; + +void banner(char* out, const char* version) { + std::sprintf(out, "sensor-node %s", version); +} + +void log_line(const char* text) { + std::printf(text); +} + +void status(const char* state) { + std::printf("state: %s\n", state); +} + +} // namespace cli diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index c8ba428..d785834 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -221,7 +221,7 @@ "key": "fw-c-sensor-node", "name": "Firmware ยท C sensor node (SAST)", "target_type": "firmware_bare_metal", - "description": "STM32Cube-style C project with planted flaws: CRA C rules and cppcheck must fire in Core/, and the vendored HAL under Drivers/ must stay out of SAST.", + "description": "STM32Cube-style C project with a C++ module and planted flaws: CRA C rules (on C and C++) and cppcheck must fire in Core/, and the vendored HAL under Drivers/ must stay out of SAST.", "artifacts": [ { "kind": "source_archive",