feat(sast): C/C++ SAST for microcontroller firmware (#334) (#339)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m55s

This commit was merged in pull request #339.
This commit is contained in:
sharang committed 2026-09-23 13:07:50 +00:00
1 parent c6d2d07999
commit fbf3a7cf29
19 files changed
+1036 -24

No files matched your search

+3 -3
View File
@@ -47,7 +47,7 @@ ARG RUFF_VERSION
# toolchain, which nothing at runtime needs.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates libssl3 git curl python3 python3-pip npm \
ca-certificates libssl3 git curl python3 python3-pip npm cppcheck \
&& rm -rf /var/lib/apt/lists/*
# Cargo resolves Rust lockfiles and metadata for the SBOM stage. Installed
@@ -75,9 +75,9 @@ RUN pip3 install --break-system-packages --no-cache-dir \
"semgrep==${SEMGREP_VERSION}" "ruff==${RUFF_VERSION}"
RUN mkdir -p /opt/pruefwerk \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s"}\n' \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s"}\n' \
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \
"${SEMGREP_VERSION}" "${RUFF_VERSION}" \
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
> /opt/pruefwerk/tool-versions.json
# The agent runs unprivileged. It writes only to its home (tool caches), the
+104
View File
@@ -115,3 +115,107 @@ rules:
- pattern: 'crypto.createCipheriv("des-ecb", ...)'
- pattern: 'crypto.createCipheriv("des", ...)'
- pattern: 'crypto.createCipher(...)'
# --- C/C++ firmware ------------------------------------------------------------
# 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]
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:
cwe: ["CWE-120: Buffer Copy without Checking Size of Input"]
control: cra-ai-20
patterns:
- pattern: $FN(...)
- metavariable-regex:
metavariable: $FN
regex: ^(gets|strcpy|strcat|sprintf|vsprintf|wcscpy|wcscat)$
- id: cra-ai-20-c-scanf-unbounded-string
languages: [c]
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:
cwe: ["CWE-120: Buffer Copy without Checking Size of Input"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: scanf($FMT, ...)
- pattern: sscanf($SRC, $FMT, ...)
- pattern: fscanf($FILE, $FMT, ...)
- metavariable-regex:
metavariable: $FMT
regex: ^".*%s.*"$
- id: cra-ai-20-c-non-literal-format-string
languages: [c]
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:
cwe: ["CWE-134: Use of Externally-Controlled Format String"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: printf($FMT, ...)
- pattern: vprintf($FMT, ...)
- pattern: fprintf($F, $FMT, ...)
- pattern: sprintf($B, $FMT, ...)
- pattern: snprintf($B, $N, $FMT, ...)
- pattern: syslog($P, $FMT, ...)
- metavariable-regex:
metavariable: $FMT
regex: ^[^"]
- id: cra-ai-8-c-hardcoded-credential
languages: [c]
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:
cwe: ["CWE-798: Use of Hard-coded Credentials"]
control: cra-ai-8
patterns:
- pattern-either:
- pattern: $TYPE $NAME = "$VALUE";
- pattern: $TYPE *$NAME = "$VALUE";
- pattern: $TYPE $NAME[] = "$VALUE";
- pattern: $TYPE $NAME[$N] = "$VALUE";
- metavariable-regex:
metavariable: $NAME
regex: (?i).*(passw|passwd|pwd|secret|api_?key|token|psk|credential).*
- metavariable-regex:
metavariable: $VALUE
regex: .{6,}
- id: cra-ai-13-c-broken-hash-or-cipher
languages: [c]
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:
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
control: cra-ai-13
patterns:
- pattern: $FN(...)
- metavariable-regex:
metavariable: $FN
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]
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:
cwe: ["CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)"]
control: cra-ai-16
patterns:
- pattern-either:
- pattern: $NAME = rand();
- pattern: $NAME = rand() % $M;
- pattern: $NAME = ($T) rand();
- pattern: $TYPE $NAME = rand();
- pattern: $TYPE $NAME = rand() % $M;
- metavariable-regex:
metavariable: $NAME
regex: (?i).*(key|nonce|iv|token|salt|secret|challenge|session).*
+372
View File
@@ -0,0 +1,372 @@
//! C and C++ static analysis with cppcheck.
//!
//! semgrep matches patterns; cppcheck follows values through the code, which is
//! what finds the defects that matter in firmware: out-of-bounds writes,
//! uninitialised reads, null dereferences, leaks. It parses and never runs the
//! code, so it is safe on a tenant's tree.
use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use crate::pipeline::dedup;
use crate::pipeline::source_text::{read_lines, relative_path};
/// Compilation units cppcheck analyses; headers are read through them.
const SOURCE_EXTENSIONS: &[&str] = &["c", "cc", "cpp", "cxx"];
/// Include directories passed as `-I`, at most. They only help cppcheck
/// resolve macros such as array sizes; beyond this the parse gets slow.
const MAX_INCLUDE_DIRS: usize = 64;
/// Checks that report on the analysis itself, not on the code.
const ANALYSIS_NOTES: &[&str] = &[
"missingInclude",
"missingIncludeSystem",
"toomanyconfigs",
"checkersReport",
"unmatchedSuppression",
"normalCheckLevelMaxBranches",
"noValidConfiguration",
"syntaxError",
"internalAstError",
"unknownMacro",
"preprocessorErrorDirective",
];
/// cppcheck over the C/C++ sources of a tree, skipping vendor directories.
///
/// The files are listed explicitly rather than excluded with `-i`: cppcheck
/// matches `-i Drivers` against any path component, which would also skip a
/// customer's own `app/Drivers/`.
#[derive(Debug, Default)]
pub struct CppcheckScanner {
/// Compilation units to analyse, relative to the tree.
sources: Vec<String>,
/// Include directories (relative to the tree), for macro resolution.
include: Vec<String>,
}
impl CppcheckScanner {
/// Prepare a scan of `root` that skips the `excluded` directories (see
/// [`crate::pipeline::vendor`]). `None` when the tree has no C or C++
/// outside them. Walks the tree, so call it off the async runtime.
pub fn for_tree(root: &Path, excluded: &[String]) -> Option<Self> {
let mut sources: Vec<String> = walk_outside(root, excluded)
.filter(|e| e.file_type().is_file() && is_compilation_unit(e.path()))
.filter_map(|e| {
e.path()
.strip_prefix(root)
.ok()
.map(|p| p.to_string_lossy().replace('\\', "/"))
})
.collect();
sources.sort();
(!sources.is_empty()).then(|| Self {
include: include_dirs(root),
sources,
})
}
}
impl Scanner for CppcheckScanner {
fn name(&self) -> &str {
"cppcheck"
}
fn scan_type(&self) -> ScanType {
ScanType::Sast
}
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let mut cmd = crate::pipeline::tool_cmd::tool("cppcheck", &[]);
cmd.args([
"--xml",
"--xml-version=2",
"--enable=warning,portability",
"--inconclusive",
"--max-configs=1",
"-j2",
"--quiet",
]);
for check in [
"missingInclude",
"missingIncludeSystem",
"unmatchedSuppression",
] {
cmd.arg(format!("--suppress={check}"));
}
for dir in &self.include {
cmd.arg(format!("-I{dir}"));
}
let list = FileList::write(&self.sources).map_err(|e| CoreError::Scanner {
scanner: "cppcheck".to_string(),
source: Box::new(e),
})?;
// Relative to the tree, so reported paths are too.
cmd.arg(format!("--file-list={}", list.path().display()))
.current_dir(repo_path);
let output = tokio::time::timeout(std::time::Duration::from_secs(900), cmd.output())
.await
.map_err(|_| CoreError::Scanner {
scanner: "cppcheck".to_string(),
source: "timed out after 15 minutes".into(),
})?
.map_err(|e| CoreError::Scanner {
scanner: "cppcheck".to_string(),
source: Box::new(e),
})?;
// The XML report goes to stderr.
let report = String::from_utf8_lossy(&output.stderr);
let issues = parse_report(&report).map_err(|e| CoreError::Scanner {
scanner: "cppcheck".to_string(),
source: format!("unreadable report (exit {}): {e}", output.status).into(),
})?;
let findings = issues
.into_iter()
.map(|issue| issue.into_finding(repo_path, repo_id))
.collect();
Ok(ScanOutput {
findings,
sbom_entries: Vec::new(),
})
}
}
/// One defect cppcheck reported.
#[derive(Debug, Clone, PartialEq)]
struct Issue {
id: String,
severity: String,
msg: String,
verbose: String,
cwe: Option<u32>,
file: String,
line: u32,
}
impl Issue {
fn into_finding(self, root: &Path, repo_id: &str) -> Finding {
let file = relative_path(root, &self.file);
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
"cppcheck",
&self.id,
&file,
&self.line.to_string(),
]);
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
"cppcheck".to_string(),
ScanType::Sast,
self.msg,
self.verbose,
map_severity(&self.severity),
);
finding.code_snippet = read_lines(root, &file, self.line, self.line);
finding.rule_id = Some(self.id);
finding.cwe = self.cwe.map(|n| format!("CWE-{n}"));
finding.line_number = Some(self.line);
finding.file_path = Some(file);
finding
}
}
/// cppcheck's severity levels, as ours.
fn map_severity(level: &str) -> Severity {
match level {
"error" => Severity::High,
"warning" => Severity::Medium,
"portability" | "performance" | "style" => Severity::Low,
_ => Severity::Info,
}
}
/// The defects in a cppcheck XML v2 report. Analysis notes (missing includes,
/// configuration limits, parse failures) and entries without a location are
/// left out: they say nothing about the customer's code.
fn parse_report(xml: &str) -> Result<Vec<Issue>, roxmltree::Error> {
let start = xml.find("<?xml").unwrap_or(0);
let doc = roxmltree::Document::parse(&xml[start..])?;
let issues = doc
.descendants()
.filter(|n| n.has_tag_name("error"))
.filter_map(|n| {
let id = n.attribute("id")?;
let severity = n.attribute("severity").unwrap_or_default();
if ANALYSIS_NOTES.contains(&id) || matches!(severity, "information" | "debug") {
return None;
}
let location = n.children().find(|c| c.has_tag_name("location"))?;
Some(Issue {
id: id.to_string(),
severity: severity.to_string(),
msg: n.attribute("msg").unwrap_or(id).to_string(),
verbose: n
.attribute("verbose")
.or(n.attribute("msg"))
.unwrap_or(id)
.to_string(),
cwe: n
.attribute("cwe")
.and_then(|c| c.parse().ok())
.filter(|c| *c > 0),
file: location.attribute("file")?.to_string(),
line: location.attribute("line")?.parse().ok()?,
})
})
.collect();
Ok(issues)
}
/// Directories named `inc` or `include` (any case), vendor ones included:
/// their headers define the macros the customer's code uses.
fn include_dirs(root: &Path) -> Vec<String> {
let mut dirs: Vec<String> = walk_outside(root, &[])
.filter(|e| e.file_type().is_dir())
.filter(|e| {
let name = e.file_name().to_string_lossy();
name.eq_ignore_ascii_case("inc") || name.eq_ignore_ascii_case("include")
})
.filter_map(|e| {
e.path()
.strip_prefix(root)
.ok()
.map(|p| p.to_string_lossy().replace('\\', "/"))
})
.collect();
dirs.sort();
dirs.truncate(MAX_INCLUDE_DIRS);
dirs
}
/// Every entry under `root` outside `.git` and the `excluded` directories.
fn walk_outside<'a>(
root: &'a Path,
excluded: &'a [String],
) -> impl Iterator<Item = walkdir::DirEntry> + 'a {
walkdir::WalkDir::new(root)
.min_depth(1)
.into_iter()
.filter_entry(move |e| {
if e.file_name() == ".git" {
return false;
}
let rel = e
.path()
.strip_prefix(root)
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_default();
!excluded.contains(&rel)
})
.filter_map(Result::ok)
}
fn is_compilation_unit(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| SOURCE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
}
/// The list of files handed to cppcheck, in a temporary file removed on drop.
struct FileList(std::path::PathBuf);
impl FileList {
fn write(sources: &[String]) -> std::io::Result<Self> {
let path = std::env::temp_dir().join(format!("cs-cppcheck-{}.lst", uuid::Uuid::new_v4()));
std::fs::write(&path, sources.join("\n"))?;
Ok(Self(path))
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for FileList {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
const REPORT: &str = r#"Checking ...
<?xml version="1.0" encoding="UTF-8"?>
<results version="2">
<cppcheck version="2.10"/>
<errors>
<error id="arrayIndexOutOfBounds" severity="error" msg="Array 'readings[8]' accessed at index 8, which is out of bounds." verbose="Array 'readings[8]' accessed at index 8, which is out of bounds." cwe="788" file0="Core/Src/sensors.c">
<location file="Core/Src/sensors.c" line="15" column="17" info="Array index out of bounds"/>
<location file="Core/Src/sensors.c" line="14" column="23" info="Assuming that condition 'i&lt;=8' is not redundant"/>
</error>
<error id="uninitvar" severity="error" msg="Uninitialized variable: limit" verbose="Uninitialized variable: limit" cwe="457" file0="Core/Src/sensors.c">
<location file="Core/Src/sensors.c" line="19" column="15"/>
</error>
<error id="missingIncludeSystem" severity="information" msg="Include file not found"/>
<error id="checkersReport" severity="information" msg="Active checkers: 106/592"/>
</errors>
</results>"#;
#[test]
fn a_report_yields_defects_not_analysis_notes() {
let issues = parse_report(REPORT).expect("parse");
let ids: Vec<_> = issues.iter().map(|i| i.id.as_str()).collect();
assert_eq!(ids, ["arrayIndexOutOfBounds", "uninitvar"]);
// The first location is where the defect is.
assert_eq!(issues[0].line, 15);
assert_eq!(issues[0].cwe, Some(788));
}
#[test]
fn a_defect_becomes_a_finding_with_cwe_and_a_relative_location() {
let issue = parse_report(REPORT).expect("parse").remove(1);
let finding = issue.into_finding(Path::new("/work/t/a"), "target-1");
assert_eq!(finding.scanner, "cppcheck");
assert_eq!(finding.rule_id.as_deref(), Some("uninitvar"));
assert_eq!(finding.cwe.as_deref(), Some("CWE-457"));
assert_eq!(finding.file_path.as_deref(), Some("Core/Src/sensors.c"));
assert_eq!(finding.line_number, Some(19));
assert_eq!(finding.severity, Severity::High);
}
#[test]
fn an_empty_or_garbled_report_is_an_error_or_empty() {
assert!(parse_report("<results version=\"2\"><errors/></results>")
.expect("parse")
.is_empty());
assert!(parse_report("not xml at all").is_err());
}
#[test]
fn vendor_directories_are_left_out() {
let root = std::env::temp_dir().join(format!("cs-cppcheck-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(root.join("Drivers/HAL/Src")).expect("mkdir");
std::fs::create_dir_all(root.join("Core/Inc")).expect("mkdir");
std::fs::write(root.join("Drivers/HAL/Src/hal.c"), "int x;").expect("write");
let vendor = vec!["Drivers".to_string()];
assert!(
CppcheckScanner::for_tree(&root, &vendor).is_none(),
"only vendor C code: nothing to check"
);
std::fs::write(root.join("Core/main.c"), "int main(void){return 0;}").expect("write");
// A customer's own directory that happens to be called Drivers stays in.
std::fs::create_dir_all(root.join("app/Drivers")).expect("mkdir");
std::fs::write(root.join("app/Drivers/uart.c"), "int y;").expect("write");
let scanner = CppcheckScanner::for_tree(&root, &vendor).expect("customer C code");
assert_eq!(scanner.sources, ["Core/main.c", "app/Drivers/uart.c"]);
assert_eq!(scanner.include, ["Core/Inc"]);
std::fs::remove_dir_all(&root).ok();
}
}
+3
View File
@@ -1,4 +1,5 @@
pub mod code_review;
pub mod cppcheck;
pub mod cve;
pub mod dedup;
pub mod firmware_sbom;
@@ -15,5 +16,7 @@ mod pr_review;
pub mod repo_view;
pub mod sbom;
pub mod semgrep;
pub mod source_text;
pub mod tool_cmd;
mod tracker_dispatch;
pub mod vendor;
+58 -8
View File
@@ -10,6 +10,7 @@ use compliance_core::{AgentConfig, NetGuard};
use crate::database::Database;
use crate::error::AgentError;
use crate::llm::LlmClient;
use crate::pipeline::cppcheck::CppcheckScanner;
use crate::pipeline::cve::CveScanner;
use crate::pipeline::git::GitOps;
use crate::pipeline::gitleaks::GitleaksScanner;
@@ -106,18 +107,67 @@ impl PipelineOrchestrator {
let mut all_findings: Vec<Finding> = Vec::new();
// Stage 1: Semgrep SAST
tracing::info!("[{repo_id}] Stage 1: Semgrep SAST");
// Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is
// not the customer's to fix, so both analysers skip it and the run says
// so; the SBOM still covers it.
tracing::info!("[{repo_id}] Stage 1: SAST");
self.update_phase(scan_run_id, ScanPhase::Sast).await;
match async {
let semgrep = SemgrepScanner;
semgrep.scan(&repo_path, &repo_id).await
}
.instrument(tracing::info_span!("stage_sast"))
let tree = repo_path.clone();
let (vendor, cppcheck) = tokio::task::spawn_blocking(move || {
let vendor = crate::pipeline::vendor::vendor_dirs(&tree);
let cppcheck = CppcheckScanner::for_tree(&tree, &vendor);
(vendor, cppcheck)
})
.await
.unwrap_or_default();
if !vendor.is_empty() {
self.skip_stage(
scan_run_id,
"sast_vendor_code",
&format!(
"vendor and third-party code is not analysed for SAST findings: {}; \
it is still covered by the SBOM",
vendor.join(", ")
),
)
.await;
}
match SemgrepScanner::new(vendor)
.scan(&repo_path, &repo_id)
.instrument(tracing::info_span!("stage_sast"))
.await
{
Ok(output) => all_findings.extend(output.findings),
Err(e) => tracing::warn!("[{repo_id}] Semgrep failed: {e}"),
Err(e) => {
tracing::warn!("[{repo_id}] Semgrep failed: {e}");
// A failed analysis must not read as clean code.
self.skip_stage(
scan_run_id,
"sast",
&format!("semgrep did not complete: {e}"),
)
.await;
}
}
// C and C++: cppcheck follows values through the code (out-of-bounds
// writes, uninitialised reads, null dereferences), which patterns miss.
if let Some(cppcheck) = cppcheck {
match cppcheck
.scan(&repo_path, &repo_id)
.instrument(tracing::info_span!("stage_sast_cpp"))
.await
{
Ok(output) => all_findings.extend(output.findings),
Err(e) => {
tracing::warn!("[{repo_id}] cppcheck failed: {e}");
self.skip_stage(
scan_run_id,
"sast_c_cpp",
&format!("cppcheck did not complete: {e}"),
)
.await;
}
}
}
// Stage 2: SBOM Generation
+1 -1
View File
@@ -59,7 +59,7 @@ impl PipelineOrchestrator {
let mut pr_findings: Vec<Finding> = Vec::new();
// SAST scan (semgrep)
match SemgrepScanner.scan(&repo_path, repo_id).await {
match SemgrepScanner::default().scan(&repo_path, repo_id).await {
Ok(output) => {
for f in output.findings {
if let Some(fp) = &f.file_path {
+43 -9
View File
@@ -5,6 +5,10 @@ use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use crate::pipeline::dedup;
use crate::pipeline::source_text::{read_lines, relative_path};
/// What open-source semgrep writes in place of the matched code.
const REDACTED_LINES: &str = "requires login";
/// Custom CRA-control detectors bundled into the binary and staged to a temp file
/// at scan time so semgrep can `--config` them alongside the auto ruleset. These
@@ -30,7 +34,19 @@ async fn stage_cra_rules() -> Option<PathBuf> {
Some(path)
}
pub struct SemgrepScanner;
/// semgrep over a tree, skipping vendor directories.
#[derive(Debug, Default)]
pub struct SemgrepScanner {
/// Directories (relative to the tree) left out of the analysis.
pub excluded: Vec<String>,
}
impl SemgrepScanner {
/// A scanner that skips `excluded` (see [`crate::pipeline::vendor`]).
pub fn new(excluded: Vec<String>) -> Self {
Self { excluded }
}
}
impl Scanner for SemgrepScanner {
fn name(&self) -> &str {
@@ -51,9 +67,13 @@ impl Scanner for SemgrepScanner {
if let Some(path) = &cra_rules {
command.arg(format!("--config={}", path.display()));
}
command
.args(["--json", "--quiet", "--max-memory", "500", "--jobs", "1"])
.arg(repo_path);
command.args(["--json", "--quiet", "--max-memory", "500", "--jobs", "2"]);
// Anchored at the tree root: a bare `Drivers` would also skip a
// customer's own `app/Drivers/`.
for dir in &self.excluded {
command.arg("--exclude").arg(format!("/{dir}"));
}
command.arg(repo_path);
let output = tokio::time::timeout(std::time::Duration::from_secs(600), command.output())
.await
@@ -66,10 +86,15 @@ impl Scanner for SemgrepScanner {
source: Box::new(e),
})?;
// No report at all is a failed run, not a clean one: returning no
// findings here would read as "nothing wrong with this code".
if !output.status.success() && output.stdout.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!("Semgrep exited with {}: {stderr}", output.status);
return Ok(ScanOutput::default());
let tail: String = stderr.lines().rev().take(3).collect::<Vec<_>>().join(" / ");
return Err(CoreError::Scanner {
scanner: "semgrep".to_string(),
source: format!("exited with {}: {tail}", output.status).into(),
});
}
let result: SemgrepOutput = serde_json::from_slice(&output.stdout)?;
@@ -84,12 +109,19 @@ impl Scanner for SemgrepScanner {
_ => Severity::Info,
};
// Relative to the tree: the absolute path is our work directory,
// which means nothing to a customer and changes when an archive
// is uploaded again.
let path = relative_path(repo_path, &r.path);
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
&r.check_id,
&r.path,
&path,
&r.start.line.to_string(),
]);
let end_line = r.end.as_ref().map_or(r.start.line, |e| e.line);
let snippet = read_lines(repo_path, &path, r.start.line, end_line)
.or_else(|| (r.extra.lines != REDACTED_LINES).then(|| r.extra.lines.clone()));
let mut finding = Finding::new(
repo_id.to_string(),
@@ -101,9 +133,9 @@ impl Scanner for SemgrepScanner {
severity,
);
finding.rule_id = Some(r.check_id);
finding.file_path = Some(r.path);
finding.file_path = Some(path);
finding.line_number = Some(r.start.line);
finding.code_snippet = Some(r.extra.lines);
finding.code_snippet = snippet;
finding.cwe = r.extra.metadata.as_ref().and_then(extract_cwe);
finding
})
@@ -126,6 +158,8 @@ struct SemgrepResult {
check_id: String,
path: String,
start: SemgrepPosition,
#[serde(default)]
end: Option<SemgrepPosition>,
extra: SemgrepExtra,
}
@@ -0,0 +1,81 @@
//! Where a finding points in the scanned tree, as the customer should see it.
//!
//! Scanners report paths into our work directory (`/tmp/compliance-scanner/…`),
//! and open-source semgrep replaces the matched code with the text
//! `requires login`. Both are ours to fix before a finding is stored: paths
//! become relative to the tree, and the snippet is read from the file itself.
use std::path::{Component, Path};
/// At most this many lines of a finding's code are kept as its snippet.
const MAX_SNIPPET_LINES: u32 = 12;
/// `path` relative to the scanned `root`, with `/` separators. A path already
/// relative is returned as it is.
pub fn relative_path(root: &Path, path: &str) -> String {
let p = Path::new(path);
let rel = p.strip_prefix(root).unwrap_or(p);
let rel = rel.strip_prefix("./").unwrap_or(rel);
rel.to_string_lossy().replace('\\', "/")
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
/// [`MAX_SNIPPET_LINES`]. `None` when the file is unreadable or the path would
/// leave `root`.
pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option<String> {
let rel_path = Path::new(rel);
// Scanner output is not trusted to stay inside the tree.
if rel_path.is_absolute()
|| rel_path
.components()
.any(|c| matches!(c, Component::ParentDir))
{
return None;
}
let start = start.max(1);
let end = end.max(start).min(start + MAX_SNIPPET_LINES - 1);
let text = std::fs::read_to_string(root.join(rel_path)).ok()?;
let lines: Vec<&str> = text
.lines()
.skip(start as usize - 1)
.take((end - start + 1) as usize)
.collect();
(!lines.is_empty()).then(|| lines.join("\n"))
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn paths_become_relative_to_the_tree() {
let root = Path::new("/tmp/compliance-scanner/work/t1/a1");
assert_eq!(
relative_path(root, "/tmp/compliance-scanner/work/t1/a1/Core/Src/comms.c"),
"Core/Src/comms.c"
);
assert_eq!(relative_path(root, "./Core/Src/main.c"), "Core/Src/main.c");
assert_eq!(relative_path(root, "Core/Src/main.c"), "Core/Src/main.c");
}
#[test]
fn a_snippet_is_read_from_the_file_and_capped() {
let root = std::env::temp_dir().join(format!("cs-snippet-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(root.join("src")).expect("mkdir");
let body: String = (1..=40).map(|n| format!("line {n}\n")).collect();
std::fs::write(root.join("src/a.c"), body).expect("write");
assert_eq!(
read_lines(&root, "src/a.c", 3, 4).as_deref(),
Some("line 3\nline 4")
);
let long = read_lines(&root, "src/a.c", 1, 40).expect("snippet");
assert_eq!(long.lines().count(), MAX_SNIPPET_LINES as usize);
// Nothing outside the tree, and nothing that does not exist.
assert_eq!(read_lines(&root, "../etc/passwd", 1, 1), None);
assert_eq!(read_lines(&root, "/etc/passwd", 1, 1), None);
assert_eq!(read_lines(&root, "src/missing.c", 1, 1), None);
std::fs::remove_dir_all(&root).ok();
}
}
+157
View File
@@ -0,0 +1,157 @@
//! Third-party SDK code inside a customer's source tree.
//!
//! Firmware projects carry their silicon vendor's SDK (HAL, CMSIS, board
//! support) and third-party middleware next to their own code. SAST findings in
//! that code are not the customer's to fix, and they drown out the ones that
//! are, so the SAST scanners skip it. The SBOM and CVE matching still cover it.
//!
//! Matching is deliberately narrow: a customer's own `src/drivers/` must never
//! be skipped. Only names that are vendor SDK conventions count, plus the
//! STM32Cube layout, where `Drivers/` sits next to the generated `Core/`.
use std::path::Path;
/// Directory names that hold vendor or third-party code, compared
/// case-insensitively.
const VENDOR_DIR_NAMES: &[&str] = &[
"cmsis",
"third_party",
"thirdparty",
"third-party",
"vendor",
"vendors",
];
/// Suffixes of vendor peripheral-library directories, e.g.
/// `STM32F4xx_HAL_Driver` or `STM32F10x_StdPeriph_Driver`.
const VENDOR_DIR_SUFFIXES: &[&str] = &["_hal_driver", "_stdperiph_driver"];
/// The top-most vendor directories under `root`, relative to it with `/`
/// separators, sorted. A directory inside one that already matched is not
/// listed again.
pub fn vendor_dirs(root: &Path) -> Vec<String> {
let mut found = Vec::new();
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
if !entry.file_type().is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name == ".git" {
walker.skip_current_dir();
continue;
}
if is_vendor_dir(&name, entry.path()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
found.push(rel.to_string_lossy().replace('\\', "/"));
}
walker.skip_current_dir();
}
}
found.sort();
found
}
/// Whether the directory `name` (lower-cased) at `path` holds vendor code.
fn is_vendor_dir(name: &str, path: &Path) -> bool {
if VENDOR_DIR_SUFFIXES.iter().any(|s| name.ends_with(s)) {
return true;
}
if VENDOR_DIR_NAMES.contains(&name) {
// Zephyr keeps the project's own boards at `boards/<vendor>/<board>`,
// and its template names that folder literally `vendor`.
return !parent_is(path, "boards");
}
// STM32Cube generates `Core/` for the application and `Drivers/` for the
// HAL, CMSIS and BSP. Only in that layout is `Drivers/` the vendor's.
name == "drivers"
&& path
.parent()
.is_some_and(|parent| has_child_dir(parent, "core"))
}
/// Whether the parent of `path` is named `name`, case-insensitively.
fn parent_is(path: &Path, name: &str) -> bool {
path.parent()
.and_then(Path::file_name)
.is_some_and(|n| n.to_string_lossy().eq_ignore_ascii_case(name))
}
/// Whether `dir` has a sub-directory named `name`, case-insensitively.
fn has_child_dir(dir: &Path, name: &str) -> bool {
std::fs::read_dir(dir).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
e.file_type().is_ok_and(|t| t.is_dir())
&& e.file_name().to_string_lossy().eq_ignore_ascii_case(name)
})
})
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
/// A scratch tree with the given directories, removed on drop.
struct Tree(std::path::PathBuf);
impl Tree {
fn new(dirs: &[&str]) -> Self {
let root = std::env::temp_dir().join(format!("cs-vendor-{}", uuid::Uuid::new_v4()));
for d in dirs {
std::fs::create_dir_all(root.join(d)).expect("mkdir");
}
std::fs::create_dir_all(&root).expect("mkdir root");
Tree(root)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn the_stm32cube_layout_marks_drivers_as_vendor() {
let t = Tree::new(&[
"Core/Src",
"Drivers/STM32F4xx_HAL_Driver/Src",
"Drivers/CMSIS/Include",
"Middlewares/Third_Party/FreeRTOS",
]);
assert_eq!(vendor_dirs(&t.0), ["Drivers", "Middlewares/Third_Party"]);
}
#[test]
fn a_customers_own_drivers_folder_is_kept() {
// No generated Core/ beside it: these are the customer's drivers.
let t = Tree::new(&["src/drivers/uart", "src/app"]);
assert!(vendor_dirs(&t.0).is_empty());
}
#[test]
fn zephyr_board_vendor_folders_are_the_projects_own() {
let t = Tree::new(&["boards/vendor/custom_plank", "drivers/blink", "app/src"]);
assert!(vendor_dirs(&t.0).is_empty());
}
#[test]
fn vendor_names_match_at_any_depth() {
let t = Tree::new(&[
"firmware/lib/CMSIS/Core",
"firmware/STM32F10x_StdPeriph_Driver/src",
"firmware/app",
"tools/vendor/json",
]);
assert_eq!(
vendor_dirs(&t.0),
[
"firmware/STM32F10x_StdPeriph_Driver",
"firmware/lib/CMSIS",
"tools/vendor"
]
);
}
}
+38 -3
View File
@@ -96,7 +96,9 @@
"CWE-798",
"CWE-259"
],
"rules": []
"rules": [
"cra-ai-8-c-hardcoded-credential"
]
}
],
"note": null,
@@ -181,7 +183,9 @@
"CWE-327",
"CWE-326"
],
"rules": []
"rules": [
"cra-ai-13-c-broken-hash-or-cipher"
]
}
],
"note": null,
@@ -238,7 +242,9 @@
"CWE-798",
"CWE-321"
],
"rules": []
"rules": [
"cra-ai-16-c-predictable-random"
]
}
],
"note": null,
@@ -278,6 +284,35 @@
"CWE-79",
"CWE-22"
],
"rules": [
"cra-ai-20-c-unbounded-string-function",
"cra-ai-20-c-scanf-unbounded-string",
"cra-ai-20-c-non-literal-format-string"
]
},
{
"tool": "cppcheck",
"scan_type": "sast",
"cwe": [
"CWE-119",
"CWE-120",
"CWE-121",
"CWE-122",
"CWE-125",
"CWE-131",
"CWE-190",
"CWE-369",
"CWE-401",
"CWE-415",
"CWE-416",
"CWE-457",
"CWE-476",
"CWE-562",
"CWE-758",
"CWE-786",
"CWE-787",
"CWE-788"
],
"rules": []
}
],
@@ -0,0 +1,23 @@
{
"scan_status": "completed",
"skipped_stages": [
"sast_vendor_code"
],
"sbom": [
"toolchain:arm-none-eabi-gcc@"
],
"findings": [
"cppcheck:arrayIndexOutOfBounds sensors.c:15",
"cppcheck:memleak sensors.c:32",
"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 comms.c:23",
"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 comms.c:10",
"semgrep:cra-ai-8-c-hardcoded-credential comms.c:9"
],
"cves": [],
"registry_rules": []
}
+1
View File
@@ -17,6 +17,7 @@ SBOM reads as declared dependencies (#317):
| `zephyr-pinned` | `zephyr-pinned` | Zephyr (`west.yml`, pinned revision, + module imports) |
| `freertos-cmake` | (ours) | CMake pulling the FreeRTOS kernel with `FetchContent` at a pinned tag |
| `freertos-lostbuild` | `lostbuild` | source archaeology: no build system, FreeRTOS found from its headers |
| `c-sensor-node` | (ours) | Make; C/C++ SAST (#334): planted flaws in `Core/`, a vendored HAL in `Drivers/` that must not be reported |
| `yocto-layer` | (ours) | none: Yocto is not analysed yet, so the scan must record it |
When Firmwerk's detection changes on purpose, refresh the copy and re-bless.
@@ -0,0 +1,13 @@
#ifndef APP_H
#define APP_H
#include <stdint.h>
#define RX_BUFFER_SIZE 64
#define SENSOR_CHANNELS 8
void comms_handle_command(const char *rx_buffer);
int sensors_read_all(void);
uint32_t comms_new_session(void);
#endif
@@ -0,0 +1,40 @@
/* UART command handling and cloud session setup. Planted for the scan regression. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "app.h"
/* Hard-coded credentials: every device ships the same secrets. */
static const char *wifi_password = "SensorNode-2024!";
static const char api_token[] = "sk_node_4f9a1c2e8b7d6a5f3e2d1c0b9a8f7e6d";
extern int MD5(const unsigned char *data, unsigned long len, unsigned char *out);
void comms_handle_command(const char *rx_buffer)
{
char command[16];
char reply[32];
/* The command is copied without a length check: a long line overflows it. */
strcpy(command, rx_buffer);
/* Received text used as the format string. */
printf(rx_buffer);
sprintf(reply, "ack:%s", command);
(void)reply;
}
uint32_t comms_new_session(void)
{
unsigned char digest[16];
uint32_t session_nonce;
/* A predictable nonce, and a broken hash protecting the handshake. */
session_nonce = rand();
MD5((const unsigned char *)api_token, sizeof(api_token), digest);
(void)wifi_password;
return session_nonce ^ digest[0];
}
@@ -0,0 +1,14 @@
/* Sensor node: reads eight temperature channels, reports over UART. */
#include <stdlib.h>
#include "app.h"
static char rx_buffer[RX_BUFFER_SIZE];
int main(void)
{
for (;;) {
sensors_read_all();
comms_handle_command(rx_buffer);
}
return 0;
}
@@ -0,0 +1,37 @@
/* Sensor sampling. Planted memory-safety defects for the scan regression. */
#include <stdlib.h>
#include "app.h"
static int readings[SENSOR_CHANNELS];
int sensors_read_all(void)
{
int limit;
int sum = 0;
char *scratch = malloc(64);
/* Off by one: writes readings[8], past the end of the array. */
for (int i = 0; i <= SENSOR_CHANNELS; i++) {
readings[i] = i * 10;
}
/* `limit` is read before it is ever assigned. */
if (sum > limit) {
return -1; /* and `scratch` leaks on this path */
}
free(scratch);
return sum;
}
int sensors_calibrate(int channel)
{
int *table = malloc(SENSOR_CHANNELS * sizeof(int));
if (channel < 0) {
return -1; /* `table` leaks here */
}
table[0] = channel;
free(table);
return 0;
}
@@ -0,0 +1,9 @@
/* Vendor HAL (shipped with the SDK). Excluded from SAST by default: the
* customer did not write it, and the SBOM covers it. The strcpy below must
* NOT be reported as a finding. */
#include <string.h>
void HAL_UART_CopyName(char *dst, const char *src)
{
strcpy(dst, src);
}
@@ -0,0 +1,10 @@
# Sensor node firmware: STM32F407, bare metal, GNU Arm toolchain.
TARGET = sensor-node
CC = arm-none-eabi-gcc
CFLAGS = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard -O2 -Wall \
-ICore/Inc -IDrivers/STM32F4xx_HAL_Driver/Inc -DSTM32F407xx
SRCS = Core/Src/main.c Core/Src/comms.c Core/Src/sensors.c \
Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c
$(TARGET).elf: $(SRCS)
$(CC) $(CFLAGS) $(SRCS) -o $@
+29
View File
@@ -202,6 +202,35 @@
}
]
},
{
"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.",
"artifacts": [
{
"kind": "source_archive",
"upload": "fixtures/nightly/firmware/c-sensor-node"
}
],
"expect": {
"sast_rule_ids": [
"cra-ai-20-c-unbounded-string-function",
"cra-ai-20-c-non-literal-format-string",
"cra-ai-8-c-hardcoded-credential",
"cra-ai-13-c-broken-hash-or-cipher",
"cra-ai-16-c-predictable-random",
"arrayIndexOutOfBounds",
"uninitvar"
],
"cwes": [
"CWE-120",
"CWE-134",
"CWE-798",
"CWE-788"
]
}
},
{
"key": "fw-yocto-layer",
"name": "Firmware · Yocto layer (unsupported)",