diff --git a/Dockerfile.agent b/Dockerfile.agent index d2b06ab..1e9ffaf 100644 --- a/Dockerfile.agent +++ b/Dockerfile.agent @@ -16,6 +16,8 @@ ARG RUFF_VERSION=0.16.8 # mobsfscan pins an older semgrep; it is installed without its dependencies so # it runs on the semgrep above, and its other dependencies are pinned here. ARG MOBSFSCAN_VERSION=1.0.1 +# Yocto recipe lint (BSD-2-Clause): only its security rules run. +ARG OELINT_ADV_VERSION=9.11.2 # DevSkim (MIT) is published as a .NET tool on nuget.org, not as a release # binary: the package is pinned by checksum and run on the .NET runtime (MIT). ARG DEVSKIM_VERSION=1.0.100 @@ -63,6 +65,7 @@ ARG SBOMQS_SHA256 ARG SEMGREP_VERSION ARG RUFF_VERSION ARG MOBSFSCAN_VERSION +ARG OELINT_ADV_VERSION ARG DEVSKIM_VERSION ARG DEVSKIM_SHA256 ARG DOTNET_RUNTIME_VERSION @@ -117,6 +120,14 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \ "tabulate==0.10.0" "xmltodict==1.0.4" COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py +# Yocto recipe lint; see compliance-agent/src/pipeline/recipe_lint/oelint.rs. +# Its dependencies are pinned with it (oelint-parser reads the recipes; +# deprecated's wrapt is the 1.x semgrep's OpenTelemetry already installed). +RUN pip3 install --break-system-packages --no-cache-dir \ + "oelint-adv==${OELINT_ADV_VERSION}" "oelint-parser==8.13.2" "oelint-data==1.5.23" \ + "anytree==2.13.0" "argcomplete==3.7.2" "urllib3==2.8.0" "regex==2026.9.29" \ + "deprecated==1.3.1" + # .NET SAST without a build (#494): DevSkim on C#, VB.NET and .config files. # The .NET runtime only (no SDK), with invariant globalisation so it needs no # ICU; of DevSkim's bundled native libraries only the linux-x64 ones are kept. @@ -139,10 +150,11 @@ RUN curl -sSfL -o /tmp/dotnet.tar.gz \ COPY --chmod=0755 docker/devskim.sh /usr/local/bin/devskim RUN mkdir -p /opt/pruefwerk \ - && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \ + && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","oelint-adv":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \ "${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${BETTERLEAKS_VERSION}" \ "${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \ - "${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" "${DOTNET_RUNTIME_VERSION}" \ + "${MOBSFSCAN_VERSION}" "${OELINT_ADV_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" \ + "${DOTNET_RUNTIME_VERSION}" \ > /opt/pruefwerk/tool-versions.json # The agent runs unprivileged. It writes only to its home (tool caches), the diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index d895004..6682edc 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -72,6 +72,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> { "sast_c_cpp" => Some("cppcheck"), "sast_mobile" => Some("mobsfscan"), "sast_dotnet" => Some("devskim"), + "recipe_lint" => Some("oelint-adv"), "cve_lookup" => Some("osv"), "sbom" => Some("syft"), _ => None, @@ -456,6 +457,7 @@ mod tests { assert_eq!(tool_of_stage("cve_lookup"), Some("osv")); assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan")); assert_eq!(tool_of_stage("sast_dotnet"), Some("devskim")); + assert_eq!(tool_of_stage("recipe_lint"), Some("oelint-adv")); assert_eq!(tool_of_stage("sast_vendor_code"), None); } diff --git a/compliance-agent/src/pipeline/languages.rs b/compliance-agent/src/pipeline/languages.rs index 435e4c0..20f5d76 100644 --- a/compliance-agent/src/pipeline/languages.rs +++ b/compliance-agent/src/pipeline/languages.rs @@ -30,6 +30,8 @@ fn language_of(extension: &str) -> Option<&'static str> { // Objective-C; `.m` is also MATLAB's extension, which only means // mobsfscan looks at a tree it finds nothing in. "m" | "mm" => "objc", + // Yocto / OpenEmbedded recipes, appends and classes. + "bb" | "bbappend" | "bbclass" => "bitbake", _ => return None, }) } @@ -64,6 +66,10 @@ mod tests { ("tools/flash.py", "print('flash')"), ("Middlewares/Third_Party/lib/x.cpp", "int x;"), ("README.md", "# readme"), + ( + "meta-pump/recipes-app/pump/pump_1.0.bb", + "LICENSE = \"CLOSED\"", + ), ] { let file = root.join(path); std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); @@ -72,8 +78,11 @@ mod tests { let vendor = vec!["Middlewares/Third_Party".to_string()]; - assert_eq!(source_languages(root, &vendor), ["c", "python"]); - assert_eq!(source_languages(root, &[]), ["c", "cpp", "python"]); + assert_eq!(source_languages(root, &vendor), ["bitbake", "c", "python"]); + assert_eq!( + source_languages(root, &[]), + ["bitbake", "c", "cpp", "python"] + ); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 7362532..95af293 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -36,6 +36,7 @@ pub mod plan; pub mod plc; mod pr_review; mod public_http; +pub mod recipe_lint; pub mod repo_view; pub mod sbom; pub mod sbom_quality; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 25398fb..c910edd 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -379,6 +379,16 @@ impl PipelineOrchestrator { } } } + // Yocto layers: oelint-adv's security rules and our own over the + // recipes and the image configuration. + let (findings, completed) = self + .lint_recipes(&repo_path, &repo_id, scan_run_id, &languages, &vendor) + .instrument(tracing::info_span!("stage_recipe_lint")) + .await; + for scanner in completed { + run_findings.completed(scanner); + } + all_findings.extend(findings); run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; @@ -2179,6 +2189,69 @@ impl PipelineOrchestrator { .await; } + /// The recipe lint of a tree whose `languages` include BitBake, outside + /// the `vendor` directories: the findings, and the scanners that + /// completed. Upstream layers left out and an oelint-adv run that did not + /// complete are recorded as skipped stages. + async fn lint_recipes( + &self, + tree: &std::path::Path, + repo_id: &str, + scan_run_id: &str, + languages: &[String], + vendor: &[String], + ) -> (Vec, Vec<&'static str>) { + use crate::pipeline::recipe_lint::{self, oelint, rules, RecipeLint}; + let (root, id) = (tree.to_path_buf(), repo_id.to_string()); + let (languages, vendor) = (languages.to_vec(), vendor.to_vec()); + let prepared = tokio::task::spawn_blocking(move || { + RecipeLint::for_tree(&root, &languages, &vendor).map(|lint| { + let findings = lint.config_findings(&root, &id); + (lint, findings) + }) + }) + .await + .ok() + .flatten(); + let Some((lint, mut findings)) = prepared else { + return (Vec::new(), Vec::new()); + }; + let mut completed = vec![rules::SCANNER]; + let upstream = lint.upstream_layers().join(", "); + if !upstream.is_empty() { + self.skip_stage( + scan_run_id, + SkippedStage::new( + recipe_lint::UPSTREAM_STAGE, + SkipCode::VendorCode, + format!("upstream Yocto layers are left out of the recipe lint: {upstream}"), + ) + .about(upstream), + ) + .await; + } + match lint.oelint_findings(tree, repo_id).await { + Ok(found) => { + completed.push(oelint::SCANNER); + findings.extend(found); + } + Err(e) => { + tracing::warn!("[{repo_id}] oelint-adv failed: {e}"); + self.skip_stage( + scan_run_id, + SkippedStage::new( + recipe_lint::STAGE, + SkipCode::ToolFailed, + "oelint-adv did not complete", + ) + .about(oelint::SCANNER), + ) + .await; + } + } + (findings, completed) + } + /// Record that `phase` started. Typed, so a phase the model cannot read /// back cannot be written: an unknown one made the whole run fail to /// deserialize and drop out of `GET /scan-runs`. diff --git a/compliance-agent/src/pipeline/plan.rs b/compliance-agent/src/pipeline/plan.rs index 6b2de91..a544513 100644 --- a/compliance-agent/src/pipeline/plan.rs +++ b/compliance-agent/src/pipeline/plan.rs @@ -176,19 +176,24 @@ mod tests { } #[test] - fn a_yocto_layer_tree_runs_its_source_scans_and_records_the_planned_recipe_stages() { + fn a_yocto_layer_tree_runs_its_source_scans_and_recipe_lint() { let t = target( TargetType::EmbeddedLinuxYocto, vec![Artifact::source_archive("meta-pump.zip")], ); let plan = build_scan_plan(&t); assert!(plan.has(ScanType::Sast) && plan.has(ScanType::Sbom)); + assert!(plan.has(ScanType::RecipeLint)); + assert_eq!( + step_for(&plan, ScanType::RecipeLint).map(|s| &s.phase), + Some(&ScanPhase::Sast) + ); assert!(!plan.has(ScanType::Dast)); let recorded: Vec = plan.unavailable.iter().map(|u| u.scan_type).collect(); assert_eq!( recorded, - [ScanType::RecipeInventory, ScanType::RecipeLint], - "only the recipe stages: no image is attached" + [ScanType::RecipeInventory], + "only the planned inventory: no image is attached" ); } diff --git a/compliance-agent/src/pipeline/recipe_lint/mod.rs b/compliance-agent/src/pipeline/recipe_lint/mod.rs new file mode 100644 index 0000000..d395fd0 --- /dev/null +++ b/compliance-agent/src/pipeline/recipe_lint/mod.rs @@ -0,0 +1,535 @@ +//! Recipe lint of a Yocto / OpenEmbedded layer tree (tier 1, no build). +//! +//! Two scanners read the layers' recipes and configuration: +//! +//! - **oelint-adv** (BSD-2-Clause, [`oelint`]) with only its security rules: +//! debug and empty-password image features, missing checksums, `AUTOREV`, +//! `tag=` fetches, network access in tasks and skipped QA checks; +//! - **our own rules** (`yocto-config`, [`rules`]): password hashes in +//! `EXTRA_USERS_PARAMS`, `http://` fetches, a shipped `sshd_config` that +//! allows root or password logins, certificates shipped with a recipe, and a +//! distro without `security_flags.inc`. +//! +//! Upstream layers (Poky, OpenEmbedded, the BSP vendors' layers) are not the +//! customer's to fix, so neither scanner reads them; the run names them, as it +//! names vendor code. + +pub mod oelint; +pub mod rules; + +use std::collections::BTreeMap; +use std::path::Path; + +use compliance_core::models::{Finding, ScanType, Severity}; + +use crate::pipeline::dedup; +use crate::pipeline::source_text::{read_lines, read_text}; + +/// The stage id a failed oelint-adv run is recorded under. +pub const STAGE: &str = "recipe_lint"; +/// The stage id the upstream layers left out are recorded under. +pub const UPSTREAM_STAGE: &str = "recipe_lint_upstream"; + +/// Directories never walked: version control and a build directory's output. +const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache"]; + +/// `BBFILE_COLLECTIONS` of upstream layers: OpenEmbedded-Core and Poky, the +/// meta-openembedded layers, and widely used security, virtualisation and +/// BSP layers. Their findings are upstream's, like vendor SDK code. +const UPSTREAM_COLLECTIONS: &[&str] = &[ + "core", + "yocto", + "yoctobsp", + "selftest", + "skeleton", + "openembedded-layer", + "meta-python", + "networking-layer", + "multimedia-layer", + "filesystems-layer", + "webserver", + "gnome-layer", + "xfce-layer", + "perl-layer", + "meta-initramfs", + "security", + "virtualization-layer", + "arm", + "arm-bsp", + "arm-toolchain", + "intel", + "freescale-layer", + "raspberrypi", + "clang-layer", + "qt6-layer", +]; + +/// The Yocto releases oelint-adv 9.11 knows, oldest first (its `--release` +/// choices, without `latest`). +const RELEASES: &[&str] = &[ + "inky", + "clyde", + "blinky", + "pinky", + "purple", + "green", + "laverne", + "bernard", + "edison", + "denzil", + "danny", + "dylan", + "dora", + "daisy", + "dizzy", + "fido", + "jethro", + "krogoth", + "morty", + "pyro", + "rocko", + "sumo", + "thud", + "warrior", + "zeus", + "dunfell", + "gatesgarth", + "hardknott", + "honister", + "kirkstone", + "langdale", + "mickledore", + "nanbield", + "scarthgap", + "styhead", + "walnascar", + "whinlatter", + "wrynose", + "blacksail", +]; + +/// The CRA Annex I requirement a rule's finding is about. The control it is +/// evidence for comes from the control map, by rule id. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cra { + /// Part I (2)(b): made available with a secure by default configuration. + SecureByDefault, + /// Part I (2)(j): designed to limit attack surfaces. + AttackSurface, + /// Part I (2)(f): the integrity of the software, here of what the image + /// is built from. + Integrity, + /// Informational, not a requirement on its own. + None, +} + +impl Cra { + /// The requirement in words, for the finding's description. + fn text(self) -> Option<&'static str> { + match self { + Self::SecureByDefault => Some( + "CRA Annex I Part I (2)(b): products are made available with a secure by \ + default configuration.", + ), + Self::AttackSurface => { + Some("CRA Annex I Part I (2)(j): products are designed to limit attack surfaces.") + } + Self::Integrity => Some( + "CRA Annex I Part I (2)(f): the integrity of the software is protected; an \ + image built from unverified or moving sources cannot be traced to them.", + ), + Self::None => None, + } + } +} + +/// What a rule reports: its scanner and id, title, severity, CWE, the CRA +/// requirement and the fix. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RuleInfo { + /// The scanner name findings carry. + pub scanner: &'static str, + /// The rule id findings carry. + pub id: &'static str, + /// The finding's title. + pub title: &'static str, + /// The finding's severity. + pub severity: Severity, + /// The weakness, as `CWE-`. + pub cwe: Option<&'static str>, + /// The CRA requirement. + pub cra: Cra, + /// How to fix it. + pub remediation: &'static str, +} + +/// A rule matching at a place, before it becomes a [`Finding`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Hit { + pub rule: &'static RuleInfo, + /// The file, relative to the tree. + pub path: String, + /// The line, 1-based. + pub line: u32, + /// What the rule saw there, for the description; may be empty. + pub detail: String, + /// The snippet to show instead of the line (with a secret hidden). + pub snippet: Option, +} + +impl Hit { + fn new(rule: &'static RuleInfo, path: &str, line: u32, detail: String) -> Self { + Self { + rule, + path: path.to_string(), + line, + detail, + snippet: None, + } + } + + /// The finding of `repo_id` for this hit in the tree under `root`. + fn into_finding(self, root: &Path, repo_id: &str) -> Finding { + let rule = self.rule; + let line = self.line.to_string(); + let fingerprint = + dedup::compute_fingerprint(&[repo_id, rule.scanner, rule.id, &self.path, &line]); + let description = [Some(self.detail.as_str()), rule.cra.text()] + .into_iter() + .flatten() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n\n"); + let mut finding = Finding::new( + repo_id.to_string(), + fingerprint, + rule.scanner.to_string(), + ScanType::RecipeLint, + rule.title.to_string(), + description, + rule.severity.clone(), + ); + finding.rule_id = Some(rule.id.to_string()); + finding.cwe = rule.cwe.map(str::to_string); + finding.remediation = Some(rule.remediation.to_string()); + finding.code_snippet = self + .snippet + .or_else(|| read_lines(root, &self.path, self.line, self.line)); + finding.line_number = Some(self.line); + finding.file_path = Some(self.path); + finding + } +} + +/// One layer of the tree and the files the recipe lint reads in it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Layer { + /// The layer's directory relative to the tree, `.` for the root. + pub dir: String, + /// The oldest release its `LAYERSERIES_COMPAT` names: the recipes are + /// read with that release's syntax and rules. + pub release: Option<&'static str>, + /// An upstream layer, which is not linted. + pub upstream: bool, + /// Its files relative to the tree; a nested layer's files are its own. + pub files: Vec, +} + +impl Layer { + /// `file` (relative to the tree) relative to the layer. + fn inner<'a>(&self, file: &'a str) -> &'a str { + if self.dir == "." { + file + } else { + file.get(self.dir.len() + 1..).unwrap_or(file) + } + } +} + +/// The recipe lint of one tree. +#[derive(Debug, Clone)] +pub struct RecipeLint { + layers: Vec, +} + +impl RecipeLint { + /// The recipe lint for a tree whose source `languages` include BitBake, + /// skipping the `excluded` vendor directories; `None` otherwise. + /// + /// # Arguments + /// + /// * `root` - the tree + /// * `languages` - the source languages found outside vendor code + /// * `excluded` - vendor directories relative to the tree + pub fn for_tree(root: &Path, languages: &[String], excluded: &[String]) -> Option { + languages.iter().any(|l| l == "bitbake").then(|| Self { + layers: layers(root, excluded), + }) + } + + /// The upstream layers left out, relative to the tree. + pub fn upstream_layers(&self) -> Vec<&str> { + self.layers + .iter() + .filter(|l| l.upstream) + .map(|l| l.dir.as_str()) + .collect() + } + + /// What our own rules ([`rules`]) find in the customer's layers under + /// `root`. They read files only, so they always complete. + pub fn config_findings(&self, root: &Path, repo_id: &str) -> Vec { + self.config_hits(root) + .into_iter() + .map(|hit| hit.into_finding(root, repo_id)) + .collect() + } + + /// The customer's layers: those the lint reads. + fn own_layers(&self) -> impl Iterator { + self.layers.iter().filter(|l| !l.upstream) + } +} + +/// Whether the recipe lint reads `inner` (a path relative to its layer): +/// recipes, appends, includes, classes, the layer's configuration, and what +/// recipes ship in their `files/` (sshd configurations, certificates). +fn is_read(inner: &str) -> bool { + let name = inner.rsplit('/').next().unwrap_or(inner); + let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext); + match ext { + "bb" | "bbappend" | "bbclass" | "inc" => true, + "conf" => inner.starts_with("conf/"), + "sample" => name == "local.conf.sample", + _ => rules::is_shipped_file(inner, name), + } +} + +/// The layers of the tree under `root`, outside the `excluded` directories: +/// each directory holding a `conf/layer.conf`. A tree without one (loose +/// recipes) is read as a single layer. +fn layers(root: &Path, excluded: &[String]) -> Vec { + let files: Vec = walkdir::WalkDir::new(root) + .min_depth(1) + .into_iter() + .filter_entry(|e| { + let rel = rel_path(root, e.path()); + !(e.file_type().is_dir() + && (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()) + || excluded.contains(&rel))) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()) + .map(|e| rel_path(root, e.path())) + .collect(); + let mut dirs: Vec = files + .iter() + .filter_map(|f| match f.strip_suffix("conf/layer.conf") { + Some("") => Some(".".to_string()), + Some(dir) => dir.strip_suffix('/').map(str::to_string), + None => None, + }) + .collect(); + if dirs.is_empty() { + dirs.push(".".to_string()); + } + // Deepest first, so a file belongs to the innermost layer holding it. + dirs.sort_by_key(|d| std::cmp::Reverse(d.len())); + let mut by_dir: BTreeMap> = BTreeMap::new(); + for file in files { + let owner = dirs + .iter() + .find(|d| d.as_str() == "." || file.starts_with(&format!("{d}/"))); + if let Some(owner) = owner { + by_dir.entry(owner.clone()).or_default().push(file); + } + } + dirs.sort(); + dirs.into_iter() + .map(|dir| { + let conf = if dir == "." { + "conf/layer.conf".to_string() + } else { + format!("{dir}/conf/layer.conf") + }; + let (collections, compat) = read_text(root, &conf) + .map(|text| layer_conf(&text)) + .unwrap_or_default(); + let mut layer = Layer { + upstream: collections + .iter() + .any(|c| UPSTREAM_COLLECTIONS.contains(&c.as_str())), + release: oldest_release(&compat), + files: Vec::new(), + dir, + }; + let mut files = by_dir.remove(&layer.dir).unwrap_or_default(); + files.retain(|f| is_read(layer.inner(f))); + files.sort(); + layer.files = files; + layer + }) + .collect() +} + +/// `path` relative to `root`, `/`-separated. +fn rel_path(root: &Path, path: &Path) -> String { + path.strip_prefix(root) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/") +} + +/// The collections a `layer.conf` declares and the releases it is compatible +/// with (`BBFILE_COLLECTIONS`, `LAYERSERIES_COMPAT_*`). +fn layer_conf(text: &str) -> (Vec, Vec) { + let mut collections = Vec::new(); + let mut compat = Vec::new(); + for assignment in rules::assignments(text) { + let words = assignment + .value + .split_whitespace() + .map(str::to_string) + .collect::>(); + if assignment.var == "BBFILE_COLLECTIONS" { + collections.extend(words); + } else if assignment.var.starts_with("LAYERSERIES_COMPAT_") { + compat.extend(words); + } + } + (collections, compat) +} + +/// The oldest of `releases` oelint-adv knows. +fn oldest_release(releases: &[String]) -> Option<&'static str> { + RELEASES + .iter() + .find(|known| releases.iter().any(|r| r == *known)) + .copied() +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +pub(crate) mod tests { + use super::*; + use std::path::PathBuf; + + /// A scratch tree holding `files`, removed on drop. + pub(crate) struct Tree(pub PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + pub(crate) fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-recipe-lint-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).expect("mkdir"); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + const POKY_META: &str = + "BBFILE_COLLECTIONS += \"core\"\nLAYERSERIES_COMPAT_core = \"scarthgap\"\n"; + const OWN: &str = + "BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap kirkstone\"\n"; + + #[test] + fn layers_are_found_with_their_release_and_upstream_ones_marked() { + let t = tree(&[ + ("poky/meta/conf/layer.conf", POKY_META), + ("poky/meta/recipes-core/busybox/busybox_1.36.bb", ""), + ("meta-pump/conf/layer.conf", OWN), + ("meta-pump/conf/distro/pump.conf", ""), + ("meta-pump/recipes-app/pump/pump_1.0.bb", ""), + ("meta-pump/recipes-app/pump/files/pump.c", ""), + ("meta-pump/recipes-app/pump/files/server.pem", ""), + ("meta-pump/README.md", ""), + ("build/conf/local.conf", ""), + ]); + let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake"); + assert_eq!(lint.upstream_layers(), ["poky/meta"]); + let own: Vec<&Layer> = lint.own_layers().collect(); + assert_eq!(own.len(), 1); + assert_eq!(own[0].dir, "meta-pump"); + // The oldest compatible release. + assert_eq!(own[0].release, Some("kirkstone")); + assert_eq!( + own[0].files, + [ + "meta-pump/conf/distro/pump.conf", + "meta-pump/conf/layer.conf", + "meta-pump/recipes-app/pump/files/server.pem", + "meta-pump/recipes-app/pump/pump_1.0.bb", + ] + ); + } + + #[test] + fn loose_recipes_are_one_layer_and_other_trees_are_not_linted() { + let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]); + let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake"); + let own: Vec<&Layer> = lint.own_layers().collect(); + assert_eq!(own[0].dir, "."); + assert_eq!(own[0].release, None); + assert!(RecipeLint::for_tree(&t.0, &["c".to_string()], &[]).is_none()); + } + + #[test] + fn vendor_directories_are_not_read() { + let t = tree(&[ + ("conf/layer.conf", OWN), + ("vendor/recipes-x/x/x_1.0.bb", ""), + ("recipes-app/pump/pump_1.0.bb", ""), + ]); + let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &["vendor".to_string()]) + .expect("bitbake"); + assert_eq!( + lint.layers[0].files, + ["conf/layer.conf", "recipes-app/pump/pump_1.0.bb"] + ); + } + + #[test] + fn every_rule_with_a_cra_requirement_is_bound_in_the_control_map() { + let map = control_map::ControlMap::cra().expect("map"); + let all = oelint::RULES.iter().chain(rules::RULES.iter().copied()); + for rule in all { + let bound = !map + .controls_for_finding(rule.scanner, None, Some(rule.id)) + .is_empty(); + assert_eq!(bound, rule.cra != Cra::None, "{}", rule.id); + } + } + + #[test] + fn a_hit_becomes_a_recipe_lint_finding_with_its_cra_requirement() { + let t = tree(&[("recipes-app/x/x.bb", "SRC_URI = \"http://x/y.tgz\"\n")]); + let rule = &rules::RULES[1]; + let finding = Hit::new(rule, "recipes-app/x/x.bb", 1, "Fetched without TLS".into()) + .into_finding(&t.0, "t"); + assert_eq!(finding.scanner, "yocto-config"); + assert_eq!(finding.scan_type, ScanType::RecipeLint); + assert_eq!(finding.rule_id.as_deref(), Some("yocto-src-uri-http")); + assert!(finding + .description + .starts_with("Fetched without TLS\n\nCRA Annex I")); + assert_eq!( + finding.code_snippet.as_deref(), + Some("SRC_URI = \"http://x/y.tgz\"") + ); + } + + #[test] + fn unknown_releases_are_ignored() { + assert_eq!(oldest_release(&["future".to_string()]), None); + assert_eq!( + oldest_release(&["wrynose".to_string(), "dunfell".to_string()]), + Some("dunfell") + ); + } +} diff --git a/compliance-agent/src/pipeline/recipe_lint/oelint.rs b/compliance-agent/src/pipeline/recipe_lint/oelint.rs new file mode 100644 index 0000000..5e314b6 --- /dev/null +++ b/compliance-agent/src/pipeline/recipe_lint/oelint.rs @@ -0,0 +1,458 @@ +//! oelint-adv (BSD-2-Clause, used unchanged) with only its security rules. +//! +//! oelint-adv is mostly a style linter for the OpenEmbedded style guide; the +//! rule file passed with `--rulefile` loads only the rules in [`RULES`], so +//! none of the style rules run. Two of its defaults are not safe for a +//! customer's tree: +//! +//! - it reads a `.oelint.cfg` from the working directory, which would let the +//! repository switch rules off: `OELINT_SKIP_CONFIG` turns that off; +//! - it caches results under the home directory only with `--cached`, which +//! is never passed. +//! +//! Each layer is read with the oldest release its `LAYERSERIES_COMPAT` names +//! (`--release`): the syntax (`_append` before Kirkstone) and which rules +//! apply depend on it. `oelint.vars.srcurigittag`, for one, only applies up +//! to Walnascar; later BitBake checks the tag itself. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use compliance_core::models::{Finding, Severity}; +use compliance_core::CoreError; + +use super::{Cra, Hit, RecipeLint, RuleInfo}; + +/// The scanner name of oelint-adv's findings. +pub const SCANNER: &str = "oelint-adv"; + +/// How long one run may take before it is stopped and recorded as failed. +const TIMEOUT: Duration = Duration::from_secs(600); + +/// Files per run, so a tree with many recipes stays under the argument +/// limit. A recipe and its appends are in the same layer, and a layer's files +/// are sorted, so they mostly stay in one run. +const FILES_PER_RUN: usize = 1000; + +/// A security rule of oelint-adv and what it means. +const fn rule( + id: &'static str, + title: &'static str, + severity: Severity, + cwe: Option<&'static str>, + cra: Cra, + remediation: &'static str, +) -> RuleInfo { + RuleInfo { + scanner: SCANNER, + id, + title, + severity, + cwe, + cra, + remediation, + } +} + +/// Removing a debug or development image feature. +const DROP_FEATURE: &str = "Remove the feature from IMAGE_FEATURES / EXTRA_IMAGE_FEATURES of \ + the product image; keep it in a separate development image."; + +/// The rules that run, by their id in oelint-adv 9.11. +pub static RULES: [RuleInfo; 13] = [ + rule( + "oelint.var.badimagefeature.debug-tweaks", + "Image feature debug-tweaks (empty root password, root login)", + Severity::High, + Some("CWE-258"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.allow-empty-password", + "Image feature allow-empty-password", + Severity::High, + Some("CWE-258"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.empty-root-password", + "Image feature empty-root-password", + Severity::High, + Some("CWE-258"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.serial-autologin-root", + "Image feature serial-autologin-root", + Severity::High, + Some("CWE-306"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.allow-root-login", + "Image feature allow-root-login", + Severity::Medium, + Some("CWE-1188"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.tools-debug", + "Image feature tools-debug (debugging tools on the device)", + Severity::Low, + Some("CWE-489"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.dbg-pkgs", + "Image feature dbg-pkgs (debug symbols on the device)", + Severity::Low, + Some("CWE-489"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.var.badimagefeature.dev-pkgs", + "Image feature dev-pkgs (development files on the device)", + Severity::Low, + Some("CWE-489"), + Cra::SecureByDefault, + DROP_FEATURE, + ), + rule( + "oelint.vars.srcurichecksum", + "Fetched source without a checksum", + Severity::Medium, + Some("CWE-494"), + Cra::Integrity, + "Add SRC_URI[sha256sum] for every downloaded file, so a changed or swapped download \ + fails the build.", + ), + rule( + "oelint.vars.autorev", + "SRCREV follows the branch head (AUTOREV)", + Severity::Medium, + Some("CWE-494"), + Cra::Integrity, + "Pin SRCREV to a commit: with AUTOREV every build takes whatever the branch holds, \ + and the image cannot be rebuilt or traced to its sources.", + ), + rule( + "oelint.vars.srcurigittag", + "Git source pinned by a tag instead of a commit", + Severity::Low, + Some("CWE-494"), + Cra::Integrity, + "Pin SRCREV to a commit: a tag can be moved.", + ), + rule( + "oelint.task.network", + "Task with network access", + Severity::Medium, + Some("CWE-494"), + Cra::AttackSurface, + "Fetch in do_fetch through SRC_URI, with checksums, instead of giving a build task \ + network access.", + ), + rule( + "oelint.vars.insaneskip", + "QA checks skipped (INSANE_SKIP)", + Severity::Low, + None, + Cra::None, + "Fix what the QA check reports instead of skipping it; some (ldflags, \ + already-stripped, textrel) guard the binaries' hardening.", + ), +]; + +/// The rule file passed with `--rulefile`: only [`RULES`] are loaded. An +/// empty severity keeps oelint-adv's own; ours come from [`RULES`]. +fn rulefile() -> String { + let entries: serde_json::Map = RULES + .iter() + .map(|r| (r.id.to_string(), serde_json::Value::String(String::new()))) + .collect(); + serde_json::Value::Object(entries).to_string() +} + +/// One issue of oelint-adv's `gitlab-codequality` report. +#[derive(Debug, serde::Deserialize)] +struct Issue { + check_name: String, + description: String, + location: Location, +} + +#[derive(Debug, serde::Deserialize)] +struct Location { + path: String, + lines: Lines, +} + +#[derive(Debug, serde::Deserialize)] +struct Lines { + begin: u32, +} + +/// The hits in a `gitlab-codequality` `report`. An issue is reported once per +/// place, though oelint-adv repeats it for each configuration it tries; a +/// rule we did not ask for is dropped. +/// +/// # Errors +/// +/// Returns the parse error when `report` is not that format. +fn parse_report(report: &str) -> Result, serde_json::Error> { + let issues: Vec = serde_json::from_str(report)?; + let mut seen = BTreeSet::new(); + Ok(issues + .into_iter() + .filter_map(|issue| { + let rule = RULES.iter().find(|r| r.id == issue.check_name)?; + let path = issue + .location + .path + .strip_prefix("./") + .unwrap_or(&issue.location.path) + .to_string(); + let line = issue.location.lines.begin.max(1); + if !seen.insert((rule.id, path.clone(), line)) { + return None; + } + // `[branch:true]` names the configuration oelint-adv tried. + let detail = match issue.description.rsplit_once(" [") { + Some((text, matrix)) if matrix.ends_with(']') => text, + _ => issue.description.as_str(), + }; + Some(Hit::new(rule, &path, line, detail.to_string())) + }) + .collect()) +} + +/// A scanner error with `source` as its cause. +fn failed(source: Box) -> CoreError { + CoreError::Scanner { + scanner: SCANNER.to_string(), + source, + } +} + +impl RecipeLint { + /// oelint-adv's findings in the customer's layers under `root`. + /// + /// # Errors + /// + /// Returns `CoreError::Scanner` when oelint-adv cannot start, times out, + /// exits with an error, or writes a report that cannot be read. + pub async fn oelint_findings( + &self, + root: &Path, + repo_id: &str, + ) -> Result, CoreError> { + let work = WorkDir::new().map_err(|e| failed(Box::new(e)))?; + let mut hits = Vec::new(); + for layer in self.own_layers() { + let files: Vec<&String> = layer + .files + .iter() + .filter(|f| is_bitbake(layer.inner(f))) + .collect(); + for chunk in files.chunks(FILES_PER_RUN) { + let report = run(root, layer.release, chunk, &work).await?; + hits.extend(parse_report(&report)?); + } + } + Ok(hits + .into_iter() + .map(|hit| hit.into_finding(root, repo_id)) + .collect()) + } +} + +/// Whether oelint-adv reads `inner` (relative to its layer): recipes, +/// appends, classes and the layer's configuration. Includes are read through +/// the recipes that require them. +fn is_bitbake(inner: &str) -> bool { + let ext = inner.rsplit_once('.').map_or("", |(_, ext)| ext); + matches!(ext, "bb" | "bbappend" | "bbclass") || (ext == "conf" && inner.starts_with("conf/")) +} + +/// One oelint-adv run over `files` (relative to `root`) read as `release`. +async fn run( + root: &Path, + release: Option<&str>, + files: &[&String], + work: &WorkDir, +) -> Result { + let mut cmd = crate::pipeline::tool_cmd::tool_in(SCANNER, root, &[]); + cmd.env("OELINT_SKIP_CONFIG", "1") + .args(["--quiet", "--exit-zero", "--relpaths", "--jobs", "2"]) + .args([ + "--outputformat", + "gitlab-codequality", + "--messageformat", + "{msg}", + ]) + .arg("--rulefile") + .arg(work.rulefile()) + .arg("--output") + .arg(work.report()); + if let Some(release) = release { + cmd.args(["--release", release]); + } + cmd.args(files.iter().map(|f| f.as_str())); + let output = crate::pipeline::tool_cmd::run_bounded_for(&mut cmd, SCANNER, TIMEOUT) + .await + .map_err(|e| failed(Box::new(e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let tail: String = stderr.lines().rev().take(3).collect::>().join(" / "); + return Err(failed( + format!("exited with {}: {tail}", output.status).into(), + )); + } + let report = std::fs::read_to_string(work.report()).map_err(|e| failed(Box::new(e)))?; + // The report is rewritten by every run. + let _ = std::fs::remove_file(work.report()); + Ok(report) +} + +/// The rule file and report of the runs, in a temporary directory removed on +/// drop. +struct WorkDir(PathBuf); + +impl WorkDir { + fn new() -> std::io::Result { + let dir = std::env::temp_dir().join(format!("cs-oelint-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + let work = Self(dir); + std::fs::write(work.rulefile(), rulefile())?; + Ok(work) + } + + fn rulefile(&self) -> PathBuf { + self.0.join("rules.json") + } + + fn report(&self) -> PathBuf { + self.0.join("report.json") + } +} + +impl Drop for WorkDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + const REPORT: &str = r#"[ + {"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:true]", + "check_name": "oelint.var.badimagefeature.debug-tweaks", + "fingerprint": "a", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}}, + "severity": "minor"}, + {"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:false]", + "check_name": "oelint.var.badimagefeature.debug-tweaks", + "fingerprint": "b", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}}, + "severity": "minor"}, + {"description": "Variable 'HOMEPAGE' should be set [branch:true]", + "check_name": "oelint.var.mandatoryvar.HOMEPAGE", + "fingerprint": "c", "location": {"path": "recipes-app/x/x.bb", "lines": {"begin": 1}}, + "severity": "critical"}, + {"description": "SRC_URI[sha256sum] is needed", + "check_name": "oelint.vars.srcurichecksum", + "fingerprint": "d", "location": {"path": "./recipes-app/web/web_2.1.bb", "lines": {"begin": 0}}, + "severity": "critical"} +]"#; + + #[test] + fn the_report_becomes_one_hit_per_rule_and_place() { + let hits = parse_report(REPORT).expect("report"); + let got: Vec<(&str, &str, u32, Severity)> = hits + .iter() + .map(|h| (h.rule.id, h.path.as_str(), h.line, h.rule.severity.clone())) + .collect(); + assert_eq!( + got, + [ + ( + "oelint.var.badimagefeature.debug-tweaks", + "recipes-core/images/pump-image.bb", + 8, + Severity::High + ), + ( + "oelint.vars.srcurichecksum", + "recipes-app/web/web_2.1.bb", + 1, + Severity::Medium + ), + ] + ); + assert_eq!( + hits[0].detail, + "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows \ + limitless access without authentication" + ); + assert!(parse_report("not json").is_err()); + assert!(parse_report("[]").expect("empty").is_empty()); + } + + #[test] + fn the_rule_file_lists_only_the_security_rules() { + let file: serde_json::Map = + serde_json::from_str(&rulefile()).expect("json"); + assert_eq!(file.len(), RULES.len()); + assert!(file.keys().all(|id| id.starts_with("oelint."))); + assert!(!file.contains_key("oelint.var.badimagefeature")); + } + + /// Runs the real oelint-adv over the nightly fixture when it is on the + /// PATH (the agent image has it); passes without it. + #[tokio::test] + async fn the_fixture_layer_yields_the_security_findings() { + let found = std::process::Command::new(SCANNER) + .arg("--version") + .output() + .is_ok_and(|o| o.status.success()); + if !found { + eprintln!("oelint-adv is not installed; skipping"); + return; + } + let root = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer"); + let lint = RecipeLint::for_tree(&root, &["bitbake".to_string()], &[]).expect("lint"); + let findings = lint.oelint_findings(&root, "t").await.expect("oelint-adv"); + let mut got: Vec = findings + .iter() + .map(|f| { + format!( + "{} {}:{}", + f.rule_id.as_deref().unwrap_or_default(), + f.file_path.as_deref().unwrap_or_default(), + f.line_number.unwrap_or(0) + ) + }) + .collect(); + got.sort(); + assert_eq!( + got, + [ + "oelint.task.network recipes-app/pump-web/pump-web_2.1.bb:8", + "oelint.var.badimagefeature.allow-empty-password recipes-core/images/pump-image.bb:7", + "oelint.var.badimagefeature.debug-tweaks recipes-core/images/pump-image.bb:8", + "oelint.vars.autorev recipes-app/pump-fw/pump-fw_git.bb:6", + "oelint.vars.srcurichecksum recipes-app/pump-web/pump-web_2.1.bb:6", + ] + ); + } +} diff --git a/compliance-agent/src/pipeline/recipe_lint/rules.rs b/compliance-agent/src/pipeline/recipe_lint/rules.rs new file mode 100644 index 0000000..e1f134f --- /dev/null +++ b/compliance-agent/src/pipeline/recipe_lint/rules.rs @@ -0,0 +1,607 @@ +//! Our own secure-by-default rules for Yocto layers (`yocto-config`). +//! +//! What oelint-adv does not check, read from the layer files without running +//! BitBake: +//! +//! - a password (hash or clear text) in `EXTRA_USERS_PARAMS`: every device +//! gets the same one; +//! - an `http://` fetch in `SRC_URI`; +//! - a shipped `sshd_config` with `PermitRootLogin yes` or +//! `PasswordAuthentication yes`; +//! - a certificate shipped with a recipe (informational: which trust anchors +//! the image carries). Private keys are the secret scanner's (gitleaks +//! reports PEM keys anywhere in the tree), so they are not reported twice; +//! - a distro configuration, or a `local.conf.sample` without a distro, that +//! does not pull in `security_flags.inc` (stack protector, FORTIFY_SOURCE, +//! PIE, RELRO). + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::sync::LazyLock; + +use compliance_core::models::Severity; +use regex::Regex; + +use super::{Cra, Hit, Layer, RecipeLint, RuleInfo}; +use crate::pipeline::source_text::read_text; + +/// The scanner name of these rules' findings. +pub const SCANNER: &str = "yocto-config"; + +/// Extensions of certificate files a recipe may ship. +const CERTIFICATE_EXTENSIONS: &[&str] = &["pem", "crt", "cer", "cert"]; + +/// Values of `-p` that lock an account instead of setting a password. +const LOCKED: &[&str] = &["*", "!", "!!", "!*", "x"]; + +const EXTRAUSERS_PASSWORD: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-extrausers-password", + title: "Password set in EXTRA_USERS_PARAMS", + severity: Severity::High, + cwe: Some("CWE-798"), + cra: Cra::SecureByDefault, + remediation: "Do not bake a password or password hash into the image: every device \ + ships with the same credential. Lock the account (usermod -p '*'), use key \ + authentication, or set a per-device password at provisioning.", +}; + +const SRC_URI_HTTP: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-src-uri-http", + title: "Source fetched over unencrypted http", + severity: Severity::Medium, + cwe: Some("CWE-319"), + cra: Cra::AttackSurface, + remediation: "Fetch over https (or git with protocol=https) and keep the checksum or \ + SRCREV pinned.", +}; + +const SSHD_ROOT_LOGIN: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-sshd-root-login", + title: "Shipped sshd_config allows root login", + severity: Severity::High, + cwe: Some("CWE-1188"), + cra: Cra::SecureByDefault, + remediation: "Set PermitRootLogin no (or prohibit-password with key authentication) in \ + the sshd_config the image ships.", +}; + +const SSHD_PASSWORD_AUTH: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-sshd-password-auth", + title: "Shipped sshd_config allows password logins", + severity: Severity::Medium, + cwe: Some("CWE-1188"), + cra: Cra::SecureByDefault, + remediation: "Set PasswordAuthentication no and use key authentication.", +}; + +const SHIPPED_CERTIFICATE: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-files-certificate", + title: "Certificate shipped with a recipe", + severity: Severity::Info, + cwe: None, + cra: Cra::None, + remediation: "Check that the certificate is meant to be on every device (a trust anchor, \ + not a device identity) and that it is renewed before it expires.", +}; + +const DISTRO_NO_SECURITY_FLAGS: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-distro-no-security-flags", + title: "Distro does not include security_flags.inc", + severity: Severity::Medium, + cwe: Some("CWE-693"), + cra: Cra::SecureByDefault, + remediation: "Add require conf/distro/include/security_flags.inc to the distro \ + configuration, so every package is built with the stack protector, \ + FORTIFY_SOURCE, PIE and full RELRO.", +}; + +const LOCAL_CONF_NO_SECURITY_FLAGS: RuleInfo = RuleInfo { + scanner: SCANNER, + id: "yocto-local-conf-no-security-flags", + title: "local.conf.sample builds without a distro or security_flags.inc", + severity: Severity::Info, + cwe: Some("CWE-693"), + cra: Cra::SecureByDefault, + remediation: "Set DISTRO to a distro that includes security_flags.inc, or require it in \ + the template.", +}; + +/// Every rule of this scanner. +pub const RULES: [&RuleInfo; 7] = [ + &EXTRAUSERS_PASSWORD, + &SRC_URI_HTTP, + &SSHD_ROOT_LOGIN, + &SSHD_PASSWORD_AUTH, + &SHIPPED_CERTIFICATE, + &DISTRO_NO_SECURITY_FLAGS, + &LOCAL_CONF_NO_SECURITY_FLAGS, +]; + +/// The start of a BitBake assignment: the variable (with its overrides), the +/// operator and the opening quote. +static ASSIGNMENT: LazyLock> = LazyLock::new(|| { + Regex::new( + r#"^\s*(?:export\s+)?([A-Za-z0-9_${}.+/-]+(?::[A-Za-z0-9_${}.+/-]+)*)\s*(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)\s*(["'])"#, + ) + .ok() +}); + +/// A password option of `useradd` / `usermod` and its value. +static PASSWORD_OPTION: LazyLock> = LazyLock::new(|| { + Regex::new( + r#"\b(?:useradd|usermod)\b[^;]*?\s(?:-p|-P|--password)\s+('[^']*'|\\?"[^"]*\\?"|[^\s;]+)"#, + ) + .ok() +}); + +/// A `require` or `include` and the file it names. +static INCLUDE: LazyLock> = + LazyLock::new(|| Regex::new(r"^\s*(?:require|include)\s+(\S+)").ok()); + +/// One assignment in a BitBake file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Assignment { + /// The variable without its overrides (`SRC_URI` for `SRC_URI:append`). + pub var: String, + /// The value between the quotes; continued lines are joined by `\n`. + pub value: String, + /// The line the assignment starts on, 1-based. + pub line: u32, +} + +impl Assignment { + /// The line of byte `offset` in the value. + fn line_at(&self, offset: usize) -> u32 { + let newlines = self.value.get(..offset).unwrap_or("").matches('\n').count(); + self.line + u32::try_from(newlines).unwrap_or(0) + } +} + +/// The assignments in BitBake `text`, in order. Flags (`SRC_URI[sha256sum]`) +/// and comments are not assignments. +pub(crate) fn assignments(text: &str) -> Vec { + let Some(start) = ASSIGNMENT.as_ref() else { + return Vec::new(); + }; + let mut out = Vec::new(); + let mut lines = text.lines().enumerate(); + while let Some((index, line)) = lines.next() { + let Some(caps) = start.captures(line) else { + continue; + }; + let (Some(name), Some(quote), Some(all)) = (caps.get(1), caps.get(2), caps.get(0)) else { + continue; + }; + let quote = quote.as_str(); + let mut value = String::new(); + let mut rest = &line[all.end()..]; + loop { + if let Some(end) = rest.find(quote) { + value.push_str(&rest[..end]); + break; + } + match rest.trim_end().strip_suffix('\\') { + Some(continued) => { + value.push_str(continued); + value.push('\n'); + match lines.next() { + Some((_, next)) => rest = next, + None => break, + } + } + None => { + value.push_str(rest); + break; + } + } + } + out.push(Assignment { + var: name + .as_str() + .split(':') + .next() + .unwrap_or_default() + .to_string(), + value, + line: u32::try_from(index + 1).unwrap_or(u32::MAX), + }); + } + out +} + +/// Whether `inner` (relative to its layer, file `name`) is a file a recipe +/// ships that these rules read: an sshd configuration or a certificate in a +/// `recipes-*` directory. +pub(crate) fn is_shipped_file(inner: &str, name: &str) -> bool { + if !inner.starts_with("recipes-") { + return false; + } + let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext); + name.starts_with("sshd_config") || CERTIFICATE_EXTENSIONS.contains(&ext) +} + +impl RecipeLint { + /// What our own rules find in the customer's layers under `root`. + pub(crate) fn config_hits(&self, root: &Path) -> Vec { + let index = ConfIndex::new(root, &self.layers); + let mut hits = Vec::new(); + for layer in self.own_layers() { + for file in &layer.files { + let Some(text) = read_text(root, file) else { + continue; + }; + let inner = layer.inner(file); + let name = inner.rsplit('/').next().unwrap_or(inner); + if name.starts_with("sshd_config") { + hits.extend(sshd_hits(file, &text)); + } else if is_shipped_file(inner, name) { + hits.extend(certificate_hit(file, &text)); + } else { + let found = assignments(&text); + hits.extend(extrausers_hits(file, &found)); + hits.extend(http_hits(file, &found)); + if is_distro_conf(inner) && !index.hardened(file, &text) { + hits.push(Hit::new(&DISTRO_NO_SECURITY_FLAGS, file, 1, String::new())); + } else if name == "local.conf.sample" + && without_distro(&found) + && !index.hardened(file, &text) + { + hits.push(Hit::new( + &LOCAL_CONF_NO_SECURITY_FLAGS, + file, + 1, + String::new(), + )); + } + } + } + } + hits + } +} + +/// Passwords set by `useradd` / `usermod` in `EXTRA_USERS_PARAMS`. The +/// snippet hides the value. +fn extrausers_hits(file: &str, found: &[Assignment]) -> Vec { + let Some(option) = PASSWORD_OPTION.as_ref() else { + return Vec::new(); + }; + found + .iter() + .filter(|a| a.var == "EXTRA_USERS_PARAMS") + .flat_map(|a| { + option.captures_iter(&a.value).filter_map(|caps| { + let value = caps.get(1)?; + let bare = value + .as_str() + .trim_matches(|c| matches!(c, '\'' | '"' | '\\')); + let reference = bare.starts_with("${") && bare.ends_with('}'); + if LOCKED.contains(&bare) || reference { + return None; + } + let whole = caps.get(0)?; + let command = a + .value + .get(whole.start()..value.start()) + .unwrap_or_default(); + let shown = format!("{}", command.trim_start()); + let mut hit = Hit::new( + &EXTRAUSERS_PASSWORD, + file, + a.line_at(value.start()), + if bare.is_empty() { + "The account is given an empty password.".to_string() + } else { + "The image sets a fixed password for the account.".to_string() + }, + ); + hit.snippet = Some(shown); + Some(hit) + }) + }) + .collect() +} + +/// `http://` fetches and `protocol=http` in `SRC_URI`. +fn http_hits(file: &str, found: &[Assignment]) -> Vec { + found + .iter() + .filter(|a| a.var == "SRC_URI") + .flat_map(|a| { + a.value + .split_whitespace() + .filter(|uri| { + uri.starts_with("http://") + || uri.split(';').skip(1).any(|o| o == "protocol=http") + }) + .filter_map(|uri| { + let offset = a.value.find(uri)?; + Some(Hit::new( + &SRC_URI_HTTP, + file, + a.line_at(offset), + format!("Fetched without TLS: {uri}"), + )) + }) + .collect::>() + }) + .collect() +} + +/// `PermitRootLogin yes` and `PasswordAuthentication yes` in an sshd +/// configuration; comments are the stock template's defaults, not settings. +fn sshd_hits(file: &str, text: &str) -> Vec { + text.lines() + .enumerate() + .filter_map(|(index, line)| { + let mut words = line.split_whitespace(); + let key = words.next()?.to_ascii_lowercase(); + let value = words.next()?.to_ascii_lowercase(); + let rule = match (key.as_str(), value.as_str()) { + ("permitrootlogin", "yes") => &SSHD_ROOT_LOGIN, + ("passwordauthentication", "yes") => &SSHD_PASSWORD_AUTH, + _ => return None, + }; + let line_number = u32::try_from(index + 1).ok()?; + Some(Hit::new(rule, file, line_number, String::new())) + }) + .collect() +} + +/// The first certificate in a shipped file. +fn certificate_hit(file: &str, text: &str) -> Option { + let index = text + .lines() + .position(|l| l.contains("-----BEGIN CERTIFICATE-----"))?; + let line = u32::try_from(index + 1).ok()?; + Some(Hit::new(&SHIPPED_CERTIFICATE, file, line, String::new())) +} + +/// Whether `inner` is a distro configuration (`conf/distro/.conf`). +fn is_distro_conf(inner: &str) -> bool { + inner + .strip_prefix("conf/distro/") + .is_some_and(|name| !name.contains('/') && name.ends_with(".conf")) +} + +/// Whether a `local.conf.sample` builds without a distro (`DISTRO` unset or +/// `nodistro`), which OpenEmbedded-Core builds without the security flags. A +/// named distro is checked on its own when it is in the tree, and is not +/// known otherwise. +fn without_distro(found: &[Assignment]) -> bool { + found + .iter() + .rev() + .find(|a| a.var == "DISTRO") + .is_none_or(|a| a.value.trim() == "nodistro") +} + +/// The configuration files of every layer (upstream included), by their path +/// inside the layer, to follow `require` and `include`. +struct ConfIndex<'a> { + root: &'a Path, + by_inner: BTreeMap<&'a str, &'a str>, +} + +impl<'a> ConfIndex<'a> { + fn new(root: &'a Path, layers: &'a [Layer]) -> Self { + let by_inner = layers + .iter() + .flat_map(|l| l.files.iter().map(move |f| (l.inner(f), f.as_str()))) + .filter(|(inner, _)| inner.starts_with("conf/")) + .collect(); + Self { root, by_inner } + } + + /// Whether the configuration `text` of `file` pulls in + /// `security_flags.inc`, itself or through what it requires. Poky's + /// distros include it; an include through a variable cannot be followed + /// and counts as hardened, so nothing is claimed that is not known. + fn hardened(&self, file: &str, text: &str) -> bool { + let mut seen = BTreeSet::from([file.to_string()]); + self.follows(text, &mut seen) + } + + fn follows(&self, text: &str, seen: &mut BTreeSet) -> bool { + let Some(include) = INCLUDE.as_ref() else { + return true; + }; + text.lines() + .filter_map(|line| include.captures(line)?.get(1)) + .map(|target| target.as_str()) + .any(|target| { + let name = target.rsplit('/').next().unwrap_or(target); + if name == "security_flags.inc" || target.contains("${") { + return true; + } + if name.starts_with("poky") && name.ends_with(".conf") { + return true; + } + let Some(file) = self.by_inner.get(target) else { + return false; + }; + if !seen.insert((*file).to_string()) { + return false; + } + read_text(self.root, file).is_some_and(|text| self.follows(&text, seen)) + }) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::super::tests::tree; + use super::*; + + fn rule_lines(lint_root: &Path) -> Vec { + let lint = RecipeLint::for_tree(lint_root, &["bitbake".to_string()], &[]).expect("lint"); + let mut out: Vec = lint + .config_hits(lint_root) + .into_iter() + .map(|h| format!("{} {}:{}", h.rule.id, h.path, h.line)) + .collect(); + out.sort(); + out + } + + const LAYER: &str = "BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n"; + + #[test] + fn assignments_join_continued_lines_and_skip_flags() { + let text = "SRC_URI = \"git://x;protocol=https \\\n file://a.patch \\\n\"\n\ + SRC_URI[sha256sum] = \"abc\"\n# SRC_URI = \"http://commented\"\n\ + SRC_URI:append:arm = \" http://y/z.tgz\"\n"; + let found = assignments(text); + assert_eq!(found.len(), 2); + assert_eq!(found[0].var, "SRC_URI"); + assert_eq!(found[0].line, 1); + assert!(found[0].value.contains("file://a.patch")); + assert_eq!(found[1].var, "SRC_URI"); + assert_eq!(found[1].line, 6); + } + + #[test] + fn a_password_in_extra_users_params_is_reported_with_its_value_hidden() { + let text = "EXTRA_USERS_PARAMS = \"\\\n useradd -m -p '$6$salt$hash' pump; \\\n \ + usermod -p '*' root; \\\n usermod -P secret operator; \\\n \ + usermod -p '${ROOT_HASH}' service; \\\n\"\n"; + let hits = extrausers_hits("image.bb", &assignments(text)); + let lines: Vec = hits.iter().map(|h| h.line).collect(); + // The locked root account and the hash from a variable are not. + assert_eq!(lines, [2, 4]); + let snippet = hits[0].snippet.as_deref().expect("snippet"); + assert!(snippet.starts_with("useradd -m -p")); + assert!(snippet.ends_with("")); + assert!(!hits.iter().any(|h| h + .snippet + .as_deref() + .is_some_and(|s| s.contains("secret") || s.contains("$6$")))); + } + + #[test] + fn plain_http_fetches_are_reported_and_https_ones_are_not() { + let text = "SRC_URI = \"http://a/b.tgz \\\n https://c/d.tgz \\\n \ + git://e/f.git;protocol=http;branch=main \\\n \ + git://g/h.git;protocol=https;branch=main\"\n"; + let hits = http_hits("x.bb", &assignments(text)); + let lines: Vec = hits.iter().map(|h| h.line).collect(); + assert_eq!(lines, [1, 3]); + } + + #[test] + fn sshd_settings_count_only_when_set() { + let text = "#PermitRootLogin yes\nPermitRootLogin yes\nPasswordAuthentication no\n\ + passwordauthentication YES\nPermitRootLogin prohibit-password\n"; + let lines: Vec<(&str, u32)> = sshd_hits("sshd_config", text) + .iter() + .map(|h| (h.rule.id, h.line)) + .collect(); + assert_eq!( + lines, + [ + ("yocto-sshd-root-login", 2), + ("yocto-sshd-password-auth", 4) + ] + ); + } + + #[test] + fn a_tree_reports_each_rule_once_where_it_applies() { + let t = tree(&[ + ("conf/layer.conf", LAYER), + // Requires a distro that includes the flags: hardened. + ( + "conf/distro/pump.conf", + "require conf/distro/include/pump-base.inc\nDISTRO = \"pump\"\n", + ), + ( + "conf/distro/include/pump-base.inc", + "require conf/distro/include/security_flags.inc\n", + ), + // Poky's distros include them too. + ( + "conf/distro/pump-poky.conf", + "require conf/distro/poky.conf\n", + ), + ("conf/distro/bare.conf", "DISTRO = \"bare\"\n"), + ( + "conf/templates/default/local.conf.sample", + "MACHINE ?= \"qemux86-64\"\n", + ), + ( + "recipes-connectivity/openssh/files/sshd_config", + "PermitRootLogin yes\n", + ), + // Not shipped with a recipe: not read. + ("docs/sshd_config", "PermitRootLogin yes\n"), + ( + "recipes-core/ca/files/ca.pem", + "# root CA\n-----BEGIN CERTIFICATE-----\nMII\n-----END CERTIFICATE-----\n", + ), + ( + "recipes-core/ca/files/notes.pem", + "-----BEGIN PUBLIC KEY-----\n", + ), + ]); + assert_eq!( + rule_lines(&t.0), + [ + "yocto-distro-no-security-flags conf/distro/bare.conf:1", + "yocto-files-certificate recipes-core/ca/files/ca.pem:2", + "yocto-local-conf-no-security-flags conf/templates/default/local.conf.sample:1", + "yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:1", + ] + ); + } + + #[test] + fn a_local_conf_with_a_distro_or_flags_is_not_reported() { + let t = tree(&[ + ("conf/layer.conf", LAYER), + ("conf/local.conf.sample", "DISTRO ?= \"poky\"\n"), + ( + "conf/templates/hardened/local.conf.sample", + "require conf/distro/include/security_flags.inc\n", + ), + ]); + assert!(rule_lines(&t.0).is_empty()); + } + + #[test] + fn the_fixture_layer_yields_the_nightly_baseline() { + let root = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer"); + assert_eq!( + rule_lines(&root), + [ + "yocto-distro-no-security-flags conf/distro/pump-distro.conf:1", + "yocto-extrausers-password recipes-core/images/pump-image.bb:13", + "yocto-src-uri-http recipes-app/pump-web/pump-web_2.1.bb:6", + "yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:3", + ] + ); + } + + #[test] + fn upstream_layers_are_not_checked() { + let t = tree(&[ + ( + "poky/meta/conf/layer.conf", + "BBFILE_COLLECTIONS += \"core\"\n", + ), + ("poky/meta/conf/distro/defaultsetup.conf", "DISTRO = \"\"\n"), + ( + "poky/meta/recipes-x/x/x.bb", + "SRC_URI = \"http://x/y.tgz\"\n", + ), + ]); + assert!(rule_lines(&t.0).is_empty()); + } +} diff --git a/compliance-core/src/scan_matrix.rs b/compliance-core/src/scan_matrix.rs index c2539c4..2297e57 100644 --- a/compliance-core/src/scan_matrix.rs +++ b/compliance-core/src/scan_matrix.rs @@ -42,7 +42,7 @@ pub const YOCTO_BUILD_PLANNED: &str = const RECIPE_INVENTORY: Option<&str> = Some("the recipe inventory (SBOM and CVEs from the BitBake recipes) is planned"); /// Recipe lint (oelint-adv and our own rules) over a Yocto layer tree, likewise. -const RECIPE_LINT: Option<&str> = Some("recipe lint (oelint-adv) over the layers is planned"); +const RECIPE_LINT: Option<&str> = None; /// What an artifact a scan needs in order to run. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -715,22 +715,23 @@ mod tests { } #[test] - fn a_yocto_layer_tree_lists_the_planned_recipe_stages_and_runs_its_source_scans() { + fn a_yocto_layer_tree_runs_recipe_lint_and_lists_the_planned_inventory() { let t = target_with( TargetType::EmbeddedLinuxYocto, vec![Artifact::git_repo("https://git/meta-pump", "main")], ); let opts = applicable_scans(&t); - for (scan, reason) in [ - (ScanType::RecipeInventory, RECIPE_INVENTORY), - (ScanType::RecipeLint, RECIPE_LINT), - ] { - let opt = option(&opts, scan).expect("listed for a Yocto target"); - assert!(!opt.default_on, "{scan} must not be pre-selected yet"); - // The layer tree is there, so the run records the stage as not - // done instead of passing over it. - assert_eq!(opt.unavailable_with_artifact(), reason); - } + let inventory = option(&opts, ScanType::RecipeInventory).expect("listed"); + assert!( + !inventory.default_on, + "the inventory must not be pre-selected yet" + ); + // The layer tree is there, so the run records the stage as not done + // instead of passing over it. + assert_eq!(inventory.unavailable_with_artifact(), RECIPE_INVENTORY); + // Recipe lint runs over the layers. + let lint = option(&opts, ScanType::RecipeLint).expect("listed"); + assert!(lint.default_on && lint.unavailable.is_none() && lint.blocked_reason.is_none()); // The source scans (secrets, malware, the source SBOM) still run. let sast = option(&opts, ScanType::Sast).expect("sast"); assert!(sast.default_on && sast.unavailable.is_none()); diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index dafc873..60fc065 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -501,6 +501,10 @@ pub mod scans { de: "Rezept-Prüfung (Yocto)", en: "Recipe lint (Yocto)", }, + "recipe_lint_upstream" => Text { + de: "Upstream-Layer (Poky, OpenEmbedded, BSP)", + en: "Upstream layers (Poky, OpenEmbedded, BSP)", + }, "plc_archive_sbom" => Text { de: "SPS-Bibliotheken (SBOM)", en: "PLC libraries (SBOM)", @@ -1789,13 +1793,14 @@ pub mod findings { } /// Every scan type a finding can carry, in the filter's order. - pub const SCAN_TYPES: [ScanType; 17] = [ + pub const SCAN_TYPES: [ScanType; 18] = [ ScanType::Sast, ScanType::SecretDetection, ScanType::Malware, ScanType::Cve, ScanType::Sbom, ScanType::FirmwareStatic, + ScanType::RecipeLint, ScanType::PlcControlLogic, ScanType::IcsProbe, ScanType::Dast, @@ -1917,6 +1922,14 @@ pub mod findings { de: "iOS-App-Einstellungen", en: "iOS app settings", }, + "oelint-adv" => Text { + de: "Yocto-Rezeptprüfung (oelint-adv)", + en: "Yocto recipe lint (oelint-adv)", + }, + "yocto-config" => Text { + de: "Yocto-Konfiguration", + en: "Yocto configuration", + }, "gdpr-patterns" => Text { de: "Datenschutz-Muster", en: "Privacy patterns", @@ -2828,6 +2841,14 @@ pub mod compliance { crate::i18n::texts::findings::tool_name("mobsfscan", Lang::En), "Mobile app analysis (mobsfscan)" ); + assert_eq!( + crate::i18n::texts::findings::tool_name("oelint-adv", Lang::De), + "Yocto-Rezeptprüfung (oelint-adv)" + ); + assert_eq!( + crate::i18n::texts::findings::tool_name("yocto-config", Lang::En), + "Yocto configuration" + ); assert_eq!( crate::i18n::texts::findings::tool_name("clippy", Lang::De), "clippy" diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index f11c974..f3c365b 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -103,6 +103,40 @@ ], "rules": [], "check": "The shipped configuration must be secure by default; ASP.NET tracing switched on in Web.config violates it." + }, + { + "tool": "oelint-adv", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "oelint.var.badimagefeature.debug-tweaks", + "oelint.var.badimagefeature.allow-empty-password", + "oelint.var.badimagefeature.empty-root-password", + "oelint.var.badimagefeature.serial-autologin-root", + "oelint.var.badimagefeature.allow-root-login", + "oelint.var.badimagefeature.tools-debug", + "oelint.var.badimagefeature.dbg-pkgs", + "oelint.var.badimagefeature.dev-pkgs" + ], + "check": "The product image must be secure by default: an image feature that opens root or password-less logins (debug-tweaks, allow-empty-password, empty-root-password, serial-autologin-root, allow-root-login) or ships debugging tools, debug symbols or development files violates it." + }, + { + "tool": "yocto-config", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "yocto-sshd-root-login", + "yocto-sshd-password-auth", + "yocto-distro-no-security-flags", + "yocto-local-conf-no-security-flags" + ], + "check": "The image's shipped configuration must be secure by default: an sshd_config that permits root or password logins, or a distro built without security_flags.inc (stack protector, FORTIFY_SOURCE, PIE, RELRO), violates it." } ], "note": null, @@ -170,6 +204,33 @@ ], "check": "A committed firmware image whose Intel HEX record checksums or structure do not verify cannot be shown to be the image that was built.", "attach_only": true + }, + { + "tool": "oelint-adv", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "oelint.vars.srcurichecksum", + "oelint.vars.autorev", + "oelint.vars.srcurigittag", + "oelint.task.network" + ], + "check": "What the image is built from must be verifiable: a download without a checksum, a source that follows a branch head (AUTOREV) or a movable tag, or a build task that fetches over the network outside the checksummed fetcher violates it." + }, + { + "tool": "yocto-config", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "yocto-src-uri-http" + ], + "check": "What the image is built from must be fetched over an authenticated channel: a source fetched over plain http violates it." } ], "note": "covered by the grounded surface check (retrieve code surface + grounded LLM judge decides presence/absence); validated live", @@ -308,6 +369,33 @@ ], "rules": [], "check": "No credential (password, key, token) may be written into the product's source or configuration: every installation would ship the same secret. A placeholder does not violate it." + }, + { + "tool": "oelint-adv", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "oelint.var.badimagefeature.debug-tweaks", + "oelint.var.badimagefeature.allow-empty-password", + "oelint.var.badimagefeature.empty-root-password", + "oelint.var.badimagefeature.serial-autologin-root" + ], + "check": "The image must not ship default or empty passwords: an image feature that leaves root or other accounts without a password, or logs root in on the serial console, violates it." + }, + { + "tool": "yocto-config", + "scan_type": "recipe_lint", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "yocto-extrausers-password" + ], + "check": "The image must not ship default passwords: a password or password hash set for an account in EXTRA_USERS_PARAMS is the same on every device and violates it." } ], "note": null, diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 0ee0135..df18e5c 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -337,6 +337,49 @@ mod tests { assert!(c.checked_for(&["python".to_string()])); } + #[test] + fn yocto_recipe_findings_attach_to_their_controls() { + let map = ControlMap::cra().expect("map"); + let controls = |tool: &str, rule: &str| -> Vec<&str> { + map.controls_for_finding(tool, None, Some(rule)) + .into_iter() + .map(|c| c.control.as_str()) + .collect() + }; + let debug = "oelint.var.badimagefeature.debug-tweaks"; + assert_eq!(controls("oelint-adv", debug), ["cra-ai-1", "cra-ai-8"]); + assert_eq!( + controls("oelint-adv", "oelint.var.badimagefeature.tools-debug"), + ["cra-ai-1"] + ); + for rule in [ + "oelint.vars.srcurichecksum", + "oelint.vars.autorev", + "oelint.vars.srcurigittag", + "oelint.task.network", + ] { + assert_eq!(controls("oelint-adv", rule), ["cra-ai-6"], "{rule}"); + } + assert!(controls("oelint-adv", "oelint.vars.insaneskip").is_empty()); + assert_eq!( + controls("yocto-config", "yocto-extrausers-password"), + ["cra-ai-8"] + ); + assert_eq!(controls("yocto-config", "yocto-src-uri-http"), ["cra-ai-6"]); + assert_eq!( + controls("yocto-config", "yocto-sshd-root-login"), + ["cra-ai-1"] + ); + assert!(controls("yocto-config", "yocto-files-certificate").is_empty()); + // A rule id of one tool does not attach a finding of another. + assert!(controls("semgrep", debug).is_empty()); + // A layer tree is checked for these controls. + let bitbake = ["bitbake".to_string()]; + for id in ["cra-ai-1", "cra-ai-6", "cra-ai-8"] { + assert!(map.coverage(id).expect(id).checked_for(&bitbake), "{id}"); + } + } + #[test] fn hardcoded_password_control_is_tool_covered() { let map = ControlMap::cra().unwrap(); diff --git a/docs/features/control-mapping.md b/docs/features/control-mapping.md index 9acb18e..a6bbd2e 100644 --- a/docs/features/control-mapping.md +++ b/docs/features/control-mapping.md @@ -30,6 +30,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too - **Vendored semgrep packs** (GitLab, 0xdea, elttam; #492), bound **by CWE** like off-the-shelf tools, on a semgrep binding of their own per control whose `languages` are exactly those of the vendored rules under those CWEs (a test checks every vendored rule maps to a control that claims its languages). The few elttam rules without a CWE are bound by rule id. Because these bindings are `semgrep` bindings, a CWE they list also attaches our own semgrep findings with that CWE to the control. - **mobsfscan** for Android and iOS apps, bound **by CWE** (a mobsfscan binding only ever attaches mobsfscan findings): `cra-ai-1` (debuggable, exported components, outdated `minSdkVersion`), `7`, `8`, `9`, `13`, `14`, `15` (cleartext, TLS, App Transport Security), `16` and `20`. Each binding lists only the languages mobsfscan has rules for under those CWEs, so `cra-ai-1` covers Java and Kotlin (its manifest checks) but not Swift. - **DevSkim** for C# and VB.NET (#494), bound **by CWE** (each DevSkim rule gets its CWE in `pipeline/devskim.rs`; its SARIF carries none): `cra-ai-1` (tracing), `8`, `10` (cookies without Secure), `13`, `14` (DPAPI without entropy), `15`, `16` and `20` (deserialisation, XXE). +- **Yocto recipe lint** (oelint-adv and our `yocto-config` rules), bound **by rule id** with the language `bitbake`: `cra-ai-1` (debug and root-login image features, sshd root/password logins, a distro without `security_flags.inc`), `cra-ai-8` (empty-password image features, passwords in `EXTRA_USERS_PARAMS`) and `cra-ai-6` (downloads without a checksum, `AUTOREV`, git tags, network access in tasks, `http://` fetches). The attack-surface rules (network tasks, `http://`) bind to `cra-ai-6` because `cra-ai-2` stays not code-checkable. - **8 grounded surface checks** (`cra-ai-6`, `11`, `12`, `24`, `27`, `28`, `29`, `30`): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern. - **Marked not_code_checkable** (`cra-ai-2`, `3`, `4`, `5`, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection. @@ -37,7 +38,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too Each binding in the control map names the **languages** its rules run on (`languages`, empty for language-independent tools such as gitleaks, syft and osv). A test keeps these in step with the rule pack. Each scan run records the source languages it saw outside vendor code (`ScanRun.languages`). -The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp`, `sast_mobile`, `sast_dotnet` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387). +The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp`, `sast_mobile`, `sast_dotnet`, `recipe_lint` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387). At scale, the **master-controls** corpus (breakpilot's deduped clusters, exported as OSCAL) currently provides **~2,882 code-checkable controls** (2,143 `network` + 739 `source_code`), matched semantically. diff --git a/docs/guide/yocto.md b/docs/guide/yocto.md index 1c4c58a..559029a 100644 --- a/docs/guide/yocto.md +++ b/docs/guide/yocto.md @@ -36,15 +36,64 @@ searched. | Code analysis (Semgrep, Cppcheck) | runs over patches and the sources in `files/` | | SBOM from lockfiles (Syft) | runs, but a layer has no lockfiles, so it is usually empty | | Firmware SBOM (Firmwerk) | not run: listed under **Nicht ausgeführt** as "Yocto build analysis is planned (tier 2)" | -| Recipe inventory, recipe lint | in progress (tier 1), listed under **Nicht ausgeführt** until they land | +| Recipe lint (oelint-adv and our own rules) | runs over your layers, see below | +| Recipe inventory | in progress (tier 1), listed under **Nicht ausgeführt** until it lands | | Image SBOM / CVE | needs build artefacts (SPDX / manifest), planned (tier 2) | | DAST | opt-in, with an http(s) address of the running device | | Penetration test | not offered until an image can be booted in an emulation sandbox | +## Recipe lint + +The recipes, appends, classes and the layer configuration are read without a +build. Findings have the type **Rezept-Prüfung (Yocto)** and name the CRA Annex I +requirement they concern. A layer is read with the oldest release its +`LAYERSERIES_COMPAT` names (`_append` syntax before Kirkstone, and rules that only +apply to older releases). + +**oelint-adv** (BSD-2-Clause, pinned in the agent image) runs with its security +rules only, none of its style rules: + +| Rule | Severity | CRA Annex I | Control | +| --- | --- | --- | --- | +| `oelint.var.badimagefeature.debug-tweaks`, `.allow-empty-password`, `.empty-root-password`, `.serial-autologin-root` | high | (2)(b) secure by default | CRA-AI-1, CRA-AI-8 | +| `oelint.var.badimagefeature.allow-root-login` | medium | (2)(b) | CRA-AI-1 | +| `oelint.var.badimagefeature.tools-debug`, `.dbg-pkgs`, `.dev-pkgs` | low | (2)(b) | CRA-AI-1 | +| `oelint.vars.srcurichecksum` (download without `SRC_URI[sha256sum]`) | medium | (2)(f) integrity | CRA-AI-6 | +| `oelint.vars.autorev` (`SRCREV = "${AUTOREV}"`) | medium | (2)(f) | CRA-AI-6 | +| `oelint.vars.srcurigittag` (git `tag=` instead of a commit; up to Walnascar) | low | (2)(f) | CRA-AI-6 | +| `oelint.task.network` (a task with `[network] = "1"`) | medium | (2)(j) attack surface | CRA-AI-6 | +| `oelint.vars.insaneskip` (QA checks skipped) | low | informational | none | + +A `.oelint.cfg` in the repository is ignored, so it cannot switch rules off; +`# nooelint:` comments in a recipe do suppress a finding there, as oelint-adv +intends. If oelint-adv does not complete, the run lists **Rezept-Prüfung (Yocto)** +under **Nicht ausgeführt**, and the controls it checks count as not assessed. + +**Our own rules** (`yocto-config`): + +| Rule | Finds | Severity | CRA Annex I | Control | +| --- | --- | --- | --- | --- | +| `yocto-extrausers-password` | `useradd`/`usermod` with `-p`/`-P`/`--password` in `EXTRA_USERS_PARAMS` (a hash, clear text or an empty password; `'*'` and `'!'` lock the account and are fine, a `${VARIABLE}` is not judged). The value is hidden in the finding. | high | (2)(b) | CRA-AI-8 | +| `yocto-src-uri-http` | `http://` or `protocol=http` in `SRC_URI` | medium | (2)(j) | CRA-AI-6 | +| `yocto-sshd-root-login` | `PermitRootLogin yes` in an `sshd_config*` shipped under `recipes-*` | high | (2)(b) | CRA-AI-1 | +| `yocto-sshd-password-auth` | `PasswordAuthentication yes` there | medium | (2)(b) | CRA-AI-1 | +| `yocto-distro-no-security-flags` | a `conf/distro/*.conf` that neither requires `security_flags.inc` nor a Poky distro or include that does | medium | (2)(b) | CRA-AI-1 | +| `yocto-local-conf-no-security-flags` | a `local.conf.sample` with no `DISTRO` (or `nodistro`) and no `security_flags.inc` | info | (2)(b) | CRA-AI-1 | +| `yocto-files-certificate` | a certificate shipped under `recipes-*` | info | none | none | + +Private keys under `files/` are reported by the secret scan (gitleaks), not a +second time here. A `require` through a variable cannot be followed, so such a +distro is not reported. + +**Upstream layers** (OpenEmbedded-Core and Poky, meta-openembedded, and widely +used security, virtualisation and BSP layers, recognised by their +`BBFILE_COLLECTIONS`) are not linted: their findings are upstream's. The run names +them under **Nicht ausgeführt** as "Upstream-Layer". + ## What is planned | Tier | Input | Analysis | | --- | --- | --- | -| **1: layer tree** (in progress) | the layers in git, no build | **Recipe inventory**: every recipe's name, version, `SRC_URI`, `CVE_PRODUCT` and `CVE_STATUS`, matched against NVD; labelled as a recipe inventory, not the image's SBOM. **Recipe lint**: oelint-adv plus our own rules (debug and empty-password image features, `http://` fetches, keys under `files/`, missing `security_flags.inc`) | +| **1: layer tree** (in progress) | the layers in git, no build | **Recipe inventory**: every recipe's name, version, `SRC_URI`, `CVE_PRODUCT` and `CVE_STATUS`, matched against NVD; labelled as a recipe inventory, not the image's SBOM. **Recipe lint**: done, see above | | **2: build artefacts** | `tmp/deploy/spdx` (SPDX 3.0, or 2.2 up to Scarthgap), `*.vex.json`, the image `.manifest`, the kernel `.config` | **SPDX import** into the SBOM view and CycloneDX export; **sbom-cve-check** with the Yocto VEX annotations; kernel CVEs filtered by the configuration; a nightly re-check without a rebuild | | **3: image / rootfs** | `.wic`, tar, ext4, squashfs | unpacking, ELF hardening of every binary, secrets and default credentials in the root filesystem; DAST and pentest only for a qemu build in an isolated sandbox | diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 9ad5f0c..9fc45cc 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -79,6 +79,21 @@ a `.mobsf` file from your repository, and skips `Pods/`, `build/`, `.gradle/`, `DerivedData/`, `Carthage/` and `node_modules/`. Its findings are **Codeanalyse (SAST)** findings with the tool name `mobsfscan`. +## oelint-adv and our rules -- Yocto Layers + +On trees with BitBake recipes (`.bb`, `.bbappend`, `.bbclass`), +[oelint-adv](https://github.com/priv-kweihmann/oelint-adv) (BSD-2-Clause, used +unchanged) runs with its security rules only: debug and empty-password image +features, downloads without a checksum, `AUTOREV`, git tags instead of commits, +network access in tasks, skipped QA checks. Our own rules (`yocto-config`) add +passwords in `EXTRA_USERS_PARAMS`, `http://` fetches, a shipped `sshd_config` +allowing root or password logins, certificates shipped with a recipe, and a +distro without `security_flags.inc`. oelint-adv never reads a `.oelint.cfg` from +your repository; upstream layers (Poky, OpenEmbedded, BSP vendors) are not +linted. Findings are **Rezept-Prüfung (Yocto)** findings with the tool name +`oelint-adv` or `yocto-config`; the rule list is in [Embedded Linux / +Yocto](../guide/yocto.md#recipe-lint). + ### iOS app settings Prüfwerk reads every `Info.plist` and the `INFOPLIST_KEY_*` build settings of diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index be03a6e..a5d824c 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -3,10 +3,19 @@ "skipped_stages": [ "firmware_sbom", "malware", - "recipe_inventory", - "recipe_lint" + "recipe_inventory" ], "sbom": [], - "findings": [], + "findings": [ + "oelint-adv:oelint.task.network pump-web_2.1.bb:8", + "oelint-adv:oelint.var.badimagefeature.allow-empty-password pump-image.bb:7", + "oelint-adv:oelint.var.badimagefeature.debug-tweaks pump-image.bb:8", + "oelint-adv:oelint.vars.autorev pump-fw_git.bb:6", + "oelint-adv:oelint.vars.srcurichecksum pump-web_2.1.bb:6", + "yocto-config:yocto-distro-no-security-flags pump-distro.conf:1", + "yocto-config:yocto-extrausers-password pump-image.bb:13", + "yocto-config:yocto-src-uri-http pump-web_2.1.bb:6", + "yocto-config:yocto-sshd-root-login sshd_config:3" + ], "cves": [] } diff --git a/fixtures/nightly/firmware/README.md b/fixtures/nightly/firmware/README.md index df6e0dc..b2970f9 100644 --- a/fixtures/nightly/firmware/README.md +++ b/fixtures/nightly/firmware/README.md @@ -19,7 +19,7 @@ SBOM reads as declared dependencies (#317): | `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 | | `embedded-libs` | (ours) | Make; FreeRTOS 10.3.1, lwIP 2.1.2 and Mbed TLS 2.16.2 vendored as source: versions read from their headers, CVEs matched in NVD by CPE. The headers hold only the version defines | -| `yocto-layer` | (ours) | none: detected as a BitBake layer tree (`build_system = bitbake`); its recipe inventory and lint are recorded as not run yet | +| `yocto-layer` | (ours) | none: detected as a BitBake layer tree (`build_system = bitbake`); the recipe lint reports the image's debug-tweaks and allow-empty-password, a password hash in `EXTRA_USERS_PARAMS`, an `http://` fetch without a checksum, a task with network access, `AUTOREV`, `PermitRootLogin yes` and a distro without `security_flags.inc`; the recipe inventory is recorded as not run yet | `make` is also onboarded as a backend service (`fw-make-onboarded-as-service`): the firmware SBOM follows detection, not the type picked in the wizard. diff --git a/fixtures/nightly/firmware/yocto-layer/conf/distro/pump-distro.conf b/fixtures/nightly/firmware/yocto-layer/conf/distro/pump-distro.conf new file mode 100644 index 0000000..bd1e861 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/conf/distro/pump-distro.conf @@ -0,0 +1,5 @@ +# Nightly fixture: the product distro, without the hardening compiler flags +# (no security_flags.inc, and not based on Poky's distro, which has them). +DISTRO = "pump-distro" +DISTRO_NAME = "Pump Distro" +DISTRO_VERSION = "1.0" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-fw/pump-fw_git.bb b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-fw/pump-fw_git.bb new file mode 100644 index 0000000..9dd42bc --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-fw/pump-fw_git.bb @@ -0,0 +1,9 @@ +# Nightly fixture: firmware tools built from whatever the branch head is. +SUMMARY = "Pump firmware tools" +LICENSE = "CLOSED" + +SRC_URI = "git://git.example.com/pump-fw.git;protocol=https;branch=main" +SRCREV = "${AUTOREV}" +PV = "1.0+git" + +S = "${WORKDIR}/git" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb new file mode 100644 index 0000000..ca02210 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb @@ -0,0 +1,11 @@ +# Nightly fixture: a web UI fetched over plain http with no checksum, and a +# compile step that reaches the network. +SUMMARY = "Pump controller web UI" +LICENSE = "CLOSED" + +SRC_URI = "http://downloads.example.com/pump-web-${PV}.tar.gz" + +do_compile[network] = "1" +do_compile() { + oe_runmake +} diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/files/sshd_config b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/files/sshd_config new file mode 100644 index 0000000..2fd8625 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/files/sshd_config @@ -0,0 +1,5 @@ +# Nightly fixture: the sshd configuration shipped on the device. +Port 22 +PermitRootLogin yes +PasswordAuthentication no +Subsystem sftp /usr/libexec/sftp-server diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/openssh_%.bbappend b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/openssh_%.bbappend new file mode 100644 index 0000000..083e65a --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/openssh/openssh_%.bbappend @@ -0,0 +1,3 @@ +# Nightly fixture: the device ships its own sshd configuration. +FILESEXTRAPATHS:prepend := "${THISDIR}/files:" +SRC_URI += "file://sshd_config" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb b/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb new file mode 100644 index 0000000..bc02003 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb @@ -0,0 +1,13 @@ +# Nightly fixture: the product image. It is not a component of its own, and +# it ships with debug-tweaks (empty root password), which a later check flags. +SUMMARY = "Pump controller image" +LICENSE = "MIT" + +IMAGE_INSTALL = "packagegroup-core-boot busybox libmodbus pump-ctl" +IMAGE_FEATURES += "ssh-server-dropbear allow-empty-password" +EXTRA_IMAGE_FEATURES ?= "debug-tweaks" + +inherit core-image extrausers + +# A password hash baked into the image: the same root password on every device. +EXTRA_USERS_PARAMS = "usermod -p '\$6\$pumpsalt\$Qm1sZWFzZWQtZml4dHVyZS1oYXNoLW5vdC1yZWFs' root;" diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index c2e96fb..2c0bd76 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -266,7 +266,7 @@ "key": "fw-yocto-layer", "name": "Firmware · Yocto layer", "target_type": "embedded_linux_yocto", - "description": "A Yocto layer (conf/layer.conf + one recipe). Detected as a BitBake layer tree; the firmware SBOM, the recipe inventory and recipe lint are recorded as skipped with their reasons until those stages land, never completing as if there were no components.", + "description": "A Yocto layer with an insecure product image, recipes and distro. Detected as a BitBake layer tree; recipe lint (oelint-adv and our own rules) reports each insecure setting; the firmware SBOM and the recipe inventory are recorded as skipped with their reasons until those stages land, never completing as if there were no components.", "artifacts": [ { "kind": "source_archive",