From ee4a9b8905023738e246e935a63fc2d5512feddc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:52:50 +0200 Subject: [PATCH] feat(binaries): hardening, signatures, .NET references and Intel HEX checks of committed binaries (#495) On top of the committed-binary inventory (#465), natively in Rust: - PE: ASLR (DYNAMICBASE, relocations), high-entropy ASLR, DEP, CFG, SafeSEH, /GS, Authenticode present; IL-only .NET assemblies skip the native-only checks - ELF (dynamically linked only): RELRO, NX stack, PIE, stack protector, FORTIFY; static and bare-metal ELF are not assessed - .NET: AssemblyRefs from the CLI metadata tables (own ECMA-335 reader) - native PE: CPE/purl candidates from the version resource, low confidence - Intel HEX: record checksums, address ranges, size, start address Evidence goes on the inventory finding; each gap is its own Low/Info finding per rule (grouped by #477). ASLR/NX/RELRO gaps bind to cra-ai-1 and a damaged HEX image to cra-ai-6 through attach-only control-map bindings, which never make a control count as checked. PE/ELF headers are read with the object crate, already in the build via firmwerk-sbom: no new crate, no Python helper, no image change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- Cargo.lock | 1 + compliance-agent/Cargo.toml | 3 + compliance-agent/src/pipeline/binaries.rs | 211 ++++++++- .../src/pipeline/binary_depth/dotnet.rs | 326 +++++++++++++ .../src/pipeline/binary_depth/elf.rs | 189 ++++++++ .../src/pipeline/binary_depth/ihex.rs | 247 ++++++++++ .../src/pipeline/binary_depth/mod.rs | 273 +++++++++++ .../src/pipeline/binary_depth/pe.rs | 342 ++++++++++++++ .../src/pipeline/binary_depth/tests.rs | 443 ++++++++++++++++++ compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 2 +- control-map/data/cra_control_map.json | 24 + control-map/src/lib.rs | 29 +- .../release/staging-test-plan-after-v0.4.5.md | 47 ++ 14 files changed, 2127 insertions(+), 11 deletions(-) create mode 100644 compliance-agent/src/pipeline/binary_depth/dotnet.rs create mode 100644 compliance-agent/src/pipeline/binary_depth/elf.rs create mode 100644 compliance-agent/src/pipeline/binary_depth/ihex.rs create mode 100644 compliance-agent/src/pipeline/binary_depth/mod.rs create mode 100644 compliance-agent/src/pipeline/binary_depth/pe.rs create mode 100644 compliance-agent/src/pipeline/binary_depth/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 58556d2..f4a1ee5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -685,6 +685,7 @@ dependencies = [ "hmac", "jsonwebtoken", "mongodb", + "object", "octocrab", "rand 0.9.2", "regex", diff --git a/compliance-agent/Cargo.toml b/compliance-agent/Cargo.toml index bbed909..933b55c 100644 --- a/compliance-agent/Cargo.toml +++ b/compliance-agent/Cargo.toml @@ -67,6 +67,9 @@ futures-core = "0.3" dashmap = { workspace = true } tokio-stream = { workspace = true } rand = { workspace = true } +# PE/ELF headers of committed binaries (hardening, #495). The same version and +# features firmwerk-sbom already pulls in, so it adds nothing to the build. +object = { version = "0.36", default-features = false, features = ["read", "std"] } [dev-dependencies] compliance-core = { workspace = true, features = ["mongodb", "axum", "secrets"] } diff --git a/compliance-agent/src/pipeline/binaries.rs b/compliance-agent/src/pipeline/binaries.rs index 35355e6..b566b7b 100644 --- a/compliance-agent/src/pipeline/binaries.rs +++ b/compliance-agent/src/pipeline/binaries.rs @@ -14,6 +14,12 @@ //! (`MZ` with a `PE` header), ELF, Mach-O, and firmware images (`.bin`, //! `.hex`, `.srec`/`.s19`, `.uf2`, `.dfu`) of at least [`MIN_IMAGE_BYTES`]. //! Java class files share Mach-O's fat magic and are told apart. +//! +//! What each file is made of (#495: hardening, signature, .NET references, +//! CPE/purl candidates, Intel HEX layout) comes from +//! [`crate::pipeline::binary_depth`]: as evidence on the file's finding, and +//! as findings of their own for missing mitigations, missing signatures and +//! damaged images. use std::io::Read; use std::path::Path; @@ -21,6 +27,7 @@ use std::path::Path; use compliance_core::models::{Finding, ScanType, Severity}; use sha2::{Digest, Sha256}; +use crate::pipeline::binary_depth::{self, Depth, Gap}; use crate::pipeline::dedup; /// The scanner name of these findings. @@ -42,6 +49,9 @@ const MIN_IMAGE_BYTES: u64 = 1024; /// How much of a PE file is searched for its version resource. const MAX_PE_READ: u64 = 32 * 1024 * 1024; +/// The largest ELF file and Intel HEX image whose contents are analysed. +const MAX_DEPTH_READ: u64 = 64 * 1024 * 1024; + /// What a committed binary is. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Binary { @@ -55,6 +65,8 @@ pub struct Binary { /// The version resource of a Windows file: `ProductName`, /// `FileVersion`, `CompanyName`, `OriginalFilename`, as present. pub version_info: Vec<(&'static str, String)>, + /// What it is made of (#495). + pub depth: Depth, } /// The committed binaries under `root`. @@ -86,15 +98,27 @@ fn describe(root: &Path, file: &Path) -> Option { let read = std::fs::File::open(file).ok()?.read(&mut head).ok()?; let head = &head[..read]; let name = file.file_name()?.to_string_lossy().to_ascii_lowercase(); - let (format, version_info) = if head.starts_with(b"MZ") { + let (format, version_info, depth) = if head.starts_with(b"MZ") { let bytes = read_prefix(file, MAX_PE_READ)?; - (pe_format(&bytes)?, version_strings(&bytes)) + let format = pe_format(&bytes)?; + let version_info = version_strings(&bytes); + let depth = binary_depth::analyse_pe(&bytes, &version_info); + (format, version_info, depth) } else if head.starts_with(b"\x7fELF") { - (elf_format(head), Vec::new()) + let depth = read_whole(file, size) + .map_or_else(too_large, |bytes| binary_depth::analyse_elf(&bytes)); + (elf_format(head), Vec::new(), depth) } else if macho(head) { - ("Mach-O".to_string(), Vec::new()) + ("Mach-O".to_string(), Vec::new(), Depth::default()) } else { - (image_format(&name, head, size)?, Vec::new()) + let format = image_format(&name, head, size)?; + let depth = if format == INTEL_HEX { + read_whole(file, size) + .map_or_else(too_large, |bytes| binary_depth::analyse_intel_hex(&bytes)) + } else { + Depth::default() + }; + (format, Vec::new(), depth) }; Some(Binary { path: file @@ -106,9 +130,28 @@ fn describe(root: &Path, file: &Path) -> Option { size, sha256: sha256_of(file)?, version_info, + depth, }) } +/// The whole of `file` when it is at most [`MAX_DEPTH_READ`] bytes. +fn read_whole(file: &Path, size: u64) -> Option> { + (size <= MAX_DEPTH_READ) + .then(|| read_prefix(file, MAX_DEPTH_READ)) + .flatten() +} + +/// What is said of a file too large to analyse. +fn too_large() -> Depth { + Depth { + evidence: vec![format!( + "Larger than {} MiB or unreadable: its contents were not analysed.", + MAX_DEPTH_READ / (1024 * 1024) + )], + ..Depth::default() + } +} + /// Up to `limit` bytes of `file`. fn read_prefix(file: &Path, limit: u64) -> Option> { let mut bytes = Vec::new(); @@ -212,6 +255,9 @@ fn macho(head: &[u8]) -> bool { } } +/// The format of an Intel HEX image. +const INTEL_HEX: &str = "firmware image (Intel HEX)"; + /// The format of a firmware image, by its name and first bytes. fn image_format(name: &str, head: &[u8], size: u64) -> Option { if size < MIN_IMAGE_BYTES { @@ -219,9 +265,7 @@ fn image_format(name: &str, head: &[u8], size: u64) -> Option { } let ext = name.rsplit_once('.').map(|(_, e)| e)?; match ext { - "hex" | "ihex" if head.first() == Some(&b':') => { - Some("firmware image (Intel HEX)".to_string()) - } + "hex" | "ihex" if head.first() == Some(&b':') => Some(INTEL_HEX.to_string()), "srec" | "s19" | "s28" | "s37" if head.first() == Some(&b'S') => { Some("firmware image (Motorola S-record)".to_string()) } @@ -292,6 +336,12 @@ pub fn into_finding(repo_id: &str, binary: &Binary) -> Finding { for (key, value) in &binary.version_info { description.push_str(&format!("\n{key}: {value}")); } + if !binary.depth.evidence.is_empty() { + description.push('\n'); + for line in &binary.depth.evidence { + description.push_str(&format!("\n{line}")); + } + } description.push_str( "\n\nA component nobody builds here belongs in the SBOM with its source, version and \ licence, and its updates must be tracked like any other dependency.", @@ -316,6 +366,58 @@ pub fn into_finding(repo_id: &str, binary: &Binary) -> Finding { finding } +/// The findings for a committed binary: what it is, and one per gap in what +/// it is made of. +pub fn findings(repo_id: &str, binary: &Binary) -> Vec { + std::iter::once(into_finding(repo_id, binary)) + .chain( + binary + .depth + .gaps + .iter() + .map(|gap| gap_finding(repo_id, binary, gap)), + ) + .collect() +} + +/// The finding for a gap in a committed binary. Its title and description +/// are the rule's, so that a group of them (#477) reads right; the file is +/// its place. The control map links it to its controls directly: there is no +/// code for the control triage to read. +fn gap_finding(repo_id: &str, binary: &Binary, gap: &Gap) -> Finding { + let mut finding = Finding::new( + repo_id.to_string(), + dedup::compute_fingerprint(&[repo_id, gap.rule, &binary.path, &binary.sha256]), + SCANNER.to_string(), + ScanType::Malware, + gap.title.to_string(), + format!( + "{}\n\nThe file's finding \"Committed binary\" lists what was found in it.", + gap.description + ), + gap.severity.clone(), + ); + finding.rule_id = Some(gap.rule.to_string()); + finding.file_path = Some(binary.path.clone()); + finding.remediation = Some(gap.remediation.to_string()); + finding.control_refs = controls_of(gap.rule); + finding +} + +/// The controls the CRA control map binds `rule` of this scanner to. +fn controls_of(rule: &str) -> Vec { + static MAP: std::sync::OnceLock> = std::sync::OnceLock::new(); + MAP.get_or_init(|| control_map::ControlMap::cra().ok()) + .as_ref() + .map(|map| { + map.controls_for_finding(SCANNER, None, Some(rule)) + .into_iter() + .map(|c| c.control.clone()) + .collect() + }) + .unwrap_or_default() +} + #[cfg(test)] #[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { @@ -420,6 +522,98 @@ mod tests { ); } + #[test] + fn what_a_binary_is_made_of_is_evidence_and_gaps_are_findings() { + use crate::pipeline::binary_depth::{rules, tests as fixtures}; + let mut hex = String::new(); + for line in 0..80_u16 { + // Sixteen zero bytes at line * 16; the checksum is minus the + // count, address and type. + let address = line * 16; + let sum = 16_u8 + .wrapping_add((address >> 8) as u8) + .wrapping_add(address as u8); + hex.push_str(&format!( + ":10{address:04X}00{}{:02X}\n", + "00".repeat(16), + 0_u8.wrapping_sub(sum) + )); + } + let mut damaged = hex.clone(); + hex.push_str(":00000001FF\n"); + damaged.replace_range(9..11, "01"); + let dir = tree(&[ + ( + "bin/legacy.exe", + fixtures::pe(fixtures::PeSpec { + dll_characteristics: 0x0100 | 0x4000, + signed: false, + ..fixtures::HARDENED + }), + ), + ("bin/tool", fixtures::elf(fixtures::HARDENED_ELF)), + ("fw/app.hex", hex.into_bytes()), + ("fw/broken.hex", damaged.into_bytes()), + ]); + let binaries = committed_binaries(&dir); + let _ = std::fs::remove_dir_all(&dir); + let all: Vec = binaries.iter().flat_map(|b| findings("r", b)).collect(); + let found: Vec<(&str, &str, Vec)> = all + .iter() + .map(|f| { + ( + f.file_path.as_deref().unwrap(), + f.rule_id.as_deref().unwrap(), + f.control_refs.clone(), + ) + }) + .collect(); + assert_eq!( + found, + [ + ("bin/legacy.exe", RULE, vec![]), + ( + "bin/legacy.exe", + rules::NO_ASLR, + vec!["cra-ai-1".to_string()] + ), + ("bin/legacy.exe", rules::UNSIGNED, vec![]), + ("bin/tool", RULE, vec![]), + ("fw/app.hex", RULE, vec![]), + ("fw/broken.hex", RULE, vec![]), + ( + "fw/broken.hex", + rules::HEX_INVALID, + vec!["cra-ai-6".to_string()] + ), + ] + ); + assert!(all[0] + .description + .contains("Hardening: ASLR no, high-entropy ASLR no, DEP yes, CFG yes, /GS yes.")); + assert_eq!(all[1].severity, Severity::Low); + assert_eq!(all[1].scan_type, ScanType::Malware); + assert_eq!(all[2].severity, Severity::Info); + assert!(all[3] + .description + .contains("Hardening: RELRO full, NX yes, PIE yes")); + assert!(all[4].description.contains( + "Intel HEX: 81 records, 1280 bytes of data in 1 address range \ + (0x00000000-0x000004FF).\nEvery record checksum is valid." + )); + assert!(all[5].description.contains("wrong checksum on line 1")); + // A gap is its own finding, apart from the file's. + assert_ne!(all[0].fingerprint, all[1].fingerprint); + } + + #[test] + fn gap_rules_are_distinct_and_titles_name_no_file() { + let gaps = crate::pipeline::binary_depth::ALL_GAPS; + let rules: std::collections::BTreeSet<&str> = gaps.iter().map(|g| g.rule).collect(); + assert_eq!(rules.len(), gaps.len()); + assert!(gaps.iter().all(|g| g.severity <= Severity::Low)); + } + #[test] fn a_changed_binary_is_a_new_finding() { let binary = |hash: &str| Binary { @@ -428,6 +622,7 @@ mod tests { size: 10, sha256: hash.into(), version_info: Vec::new(), + depth: Depth::default(), }; let a = into_finding("t", &binary("aa")); let b = into_finding("t", &binary("bb")); diff --git a/compliance-agent/src/pipeline/binary_depth/dotnet.rs b/compliance-agent/src/pipeline/binary_depth/dotnet.rs new file mode 100644 index 0000000..a77f15c --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/dotnet.rs @@ -0,0 +1,326 @@ +//! The assemblies a .NET assembly references: the AssemblyRef table of its +//! CLI metadata (ECMA-335, partition II, 22.5 and 24.2). +//! +//! The metadata root names its streams; the `#~` stream holds the tables, +//! each one's row count, and the rows one table after the other. A row's +//! width depends on the row counts (an index into a table of 65536 rows or +//! more takes four bytes instead of two), so every table before AssemblyRef +//! has to be measured to find it. Names come from the `#Strings` heap. + +use super::{u16_at, u32_at, u64_at}; + +/// The metadata root's signature, `BSJB`. +const SIGNATURE: u32 = 0x424a_5342; + +/// Most references read from one assembly. +const MAX_REFS: usize = 2000; + +// Table numbers (II.22). +const MODULE: usize = 0x00; +const TYPE_REF: usize = 0x01; +const TYPE_DEF: usize = 0x02; +const FIELD: usize = 0x04; +const METHOD_DEF: usize = 0x06; +const PARAM: usize = 0x08; +const INTERFACE_IMPL: usize = 0x09; +const MEMBER_REF: usize = 0x0a; +const DECL_SECURITY: usize = 0x0e; +const STAND_ALONE_SIG: usize = 0x11; +const EVENT: usize = 0x14; +const PROPERTY: usize = 0x17; +const MODULE_REF: usize = 0x1a; +const TYPE_SPEC: usize = 0x1b; +const ASSEMBLY: usize = 0x20; +const ASSEMBLY_REF: usize = 0x23; +const FILE: usize = 0x26; +const EXPORTED_TYPE: usize = 0x27; +const MANIFEST_RESOURCE: usize = 0x28; +const GENERIC_PARAM: usize = 0x2a; +const METHOD_SPEC: usize = 0x2b; +const GENERIC_PARAM_CONSTRAINT: usize = 0x2c; + +/// The sizes of indexes, which depend on the heaps and the row counts. +struct Widths { + rows: [u32; 64], + string: usize, + guid: usize, + blob: usize, +} + +impl Widths { + /// An index into `table`. + fn index(&self, table: usize) -> usize { + if self.rows[table] < 1 << 16 { + 2 + } else { + 4 + } + } + + /// A coded index with `tag_bits` over `tables` (II.24.2.6). + fn coded(&self, tag_bits: u32, tables: &[usize]) -> usize { + let largest = tables.iter().map(|t| self.rows[*t]).max().unwrap_or(0); + if largest < 1 << (16 - tag_bits) { + 2 + } else { + 4 + } + } + + /// The width of a row of `table`, for the tables before AssemblyRef. + fn row(&self, table: usize) -> Option { + let (s, g, b) = (self.string, self.guid, self.blob); + let type_def_or_ref = self.coded(2, &[TYPE_DEF, TYPE_REF, TYPE_SPEC]); + let width = match table { + 0x00 => 2 + s + 3 * g, + 0x01 => self.coded(2, &[MODULE, MODULE_REF, ASSEMBLY_REF, TYPE_REF]) + 2 * s, + 0x02 => 4 + 2 * s + type_def_or_ref + self.index(FIELD) + self.index(METHOD_DEF), + 0x03 => self.index(FIELD), + 0x04 => 2 + s + b, + 0x05 => self.index(METHOD_DEF), + 0x06 => 8 + s + b + self.index(PARAM), + 0x07 => self.index(PARAM), + 0x08 => 4 + s, + 0x09 => self.index(TYPE_DEF) + type_def_or_ref, + 0x0a => self.coded(3, &[TYPE_DEF, TYPE_REF, MODULE_REF, METHOD_DEF, TYPE_SPEC]) + s + b, + 0x0b => 2 + self.coded(2, &[FIELD, PARAM, PROPERTY]) + b, + 0x0c => { + self.coded( + 5, + &[ + METHOD_DEF, + FIELD, + TYPE_REF, + TYPE_DEF, + PARAM, + INTERFACE_IMPL, + MEMBER_REF, + MODULE, + DECL_SECURITY, + PROPERTY, + EVENT, + STAND_ALONE_SIG, + MODULE_REF, + TYPE_SPEC, + ASSEMBLY, + ASSEMBLY_REF, + FILE, + EXPORTED_TYPE, + MANIFEST_RESOURCE, + GENERIC_PARAM, + GENERIC_PARAM_CONSTRAINT, + METHOD_SPEC, + ], + ) + self.coded(3, &[METHOD_DEF, MEMBER_REF]) + + b + } + 0x0d => self.coded(1, &[FIELD, PARAM]) + b, + 0x0e => 2 + self.coded(2, &[TYPE_DEF, METHOD_DEF, ASSEMBLY]) + b, + 0x0f => 6 + self.index(TYPE_DEF), + 0x10 => 4 + self.index(FIELD), + 0x11 => b, + 0x12 => self.index(TYPE_DEF) + self.index(EVENT), + 0x13 => self.index(EVENT), + 0x14 => 2 + s + type_def_or_ref, + 0x15 => self.index(TYPE_DEF) + self.index(PROPERTY), + 0x16 => self.index(PROPERTY), + 0x17 => 2 + s + b, + 0x18 => 2 + self.index(METHOD_DEF) + self.coded(1, &[EVENT, PROPERTY]), + 0x19 => self.index(TYPE_DEF) + 2 * self.coded(1, &[METHOD_DEF, MEMBER_REF]), + 0x1a => s, + 0x1b => b, + 0x1c => 2 + self.coded(1, &[FIELD, METHOD_DEF]) + s + self.index(MODULE_REF), + 0x1d => 4 + self.index(FIELD), + 0x1e => 8, + 0x1f => 4, + 0x20 => 16 + b + 2 * s, + 0x21 => 4, + 0x22 => 12, + _ => return None, + }; + Some(width) + } +} + +/// The assemblies the metadata in `metadata` references, as (name, +/// `major.minor.build.revision`), or `None` when it cannot be read. +pub(super) fn assembly_refs(metadata: &[u8]) -> Option> { + if u32_at(metadata, 0)? != SIGNATURE { + return None; + } + let version_length = usize::try_from(u32_at(metadata, 12)?).ok()?; + let mut at = 16_usize.checked_add(version_length)?; + let streams = u16_at(metadata, at + 2)?; + at += 4; + let (mut tables, mut strings) = (None, None); + for _ in 0..streams { + let offset = usize::try_from(u32_at(metadata, at)?).ok()?; + let size = usize::try_from(u32_at(metadata, at + 4)?).ok()?; + let name_start = at + 8; + let name_length = metadata + .get(name_start..)? + .iter() + .take(32) + .position(|b| *b == 0)?; + let name = metadata.get(name_start..name_start + name_length)?; + at = name_start + (name_length + 1).next_multiple_of(4); + let data = metadata.get(offset..offset.checked_add(size)?); + match name { + b"#~" | b"#-" => tables = data, + b"#Strings" => strings = data, + _ => {} + } + } + let (tables, strings) = (tables?, strings?); + + let heap_sizes = *tables.get(6)?; + let valid = u64_at(tables, 8)?; + let mut rows = [0_u32; 64]; + let mut at = 24; + for (table, count) in rows.iter_mut().enumerate() { + if valid >> table & 1 == 1 { + *count = u32_at(tables, at)?; + at += 4; + } + } + // An uncompressed (`#-`) stream may carry four more bytes. + if heap_sizes & 0x40 != 0 { + at += 4; + } + let wide = |bit: u8| if heap_sizes & bit != 0 { 4 } else { 2 }; + let widths = Widths { + rows, + string: wide(0x01), + guid: wide(0x02), + blob: wide(0x04), + }; + for table in 0..ASSEMBLY_REF { + let size = usize::try_from(widths.rows[table]) + .ok()? + .checked_mul(widths.row(table)?)?; + at = at.checked_add(size)?; + } + let (s, b) = (widths.string, widths.blob); + let width = 12 + b + 2 * s + b; + let index = |bytes: &[u8], at: usize, width: usize| -> Option { + if width == 4 { + usize::try_from(u32_at(bytes, at)?).ok() + } else { + Some(usize::from(u16_at(bytes, at)?)) + } + }; + let count = usize::try_from(widths.rows[ASSEMBLY_REF]).ok()?; + let mut refs = Vec::with_capacity(count.min(MAX_REFS)); + for row in 0..count.min(MAX_REFS) { + let start = at.checked_add(row.checked_mul(width)?)?; + let version: Vec = (0..4) + .map(|i| u16_at(tables, start + 2 * i).map(|v| v.to_string())) + .collect::>()?; + let name = index(tables, start + 12 + b, s)?; + let name = heap_string(strings, name)?; + if !name.is_empty() { + refs.push((name, version.join("."))); + } + } + Some(refs) +} + +/// The zero-terminated UTF-8 string at `at` in the `#Strings` heap. +fn heap_string(heap: &[u8], at: usize) -> Option { + let rest = heap.get(at..)?; + let end = rest.iter().position(|b| *b == 0).unwrap_or(rest.len()); + String::from_utf8(rest[..end].to_vec()).ok() +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// CLI metadata with a Module row, `type_refs` TypeRef rows, an Assembly + /// row and an AssemblyRef row per entry of `refs`. From 2^14 TypeRef rows + /// on, the TypeRef rows' ResolutionScope index takes four bytes. + pub(crate) fn metadata(refs: &[(&str, [u16; 4])], type_refs: u32) -> Vec { + let mut strings = vec![0_u8]; + let mut intern = |s: &str| { + let at = strings.len() as u16; + strings.extend(s.as_bytes()); + strings.push(0); + at + }; + let module_name = intern("Pump.Tools.dll"); + let assembly_name = intern("Pump.Tools"); + let ref_names: Vec = refs.iter().map(|(n, _)| intern(n)).collect(); + while !strings.len().is_multiple_of(4) { + strings.push(0); + } + + let mut tables = vec![0, 0, 0, 0, 2, 0, 0, 1]; + let valid: u64 = 1 << MODULE | 1 << TYPE_REF | 1 << ASSEMBLY | 1 << ASSEMBLY_REF; + tables.extend(valid.to_le_bytes()); + tables.extend(0_u64.to_le_bytes()); + for count in [1, type_refs, 1, refs.len() as u32] { + tables.extend(count.to_le_bytes()); + } + // Module: generation, name, mvid, encid, encbaseid (guid 2 bytes). + tables.extend([0, 0]); + tables.extend(module_name.to_le_bytes()); + tables.extend([1, 0, 0, 0, 0, 0]); + // TypeRef: resolution scope (2 or 4), name, namespace. + let scope_width = if type_refs < 1 << 14 { 2 } else { 4 }; + for _ in 0..type_refs { + tables.extend(vec![0; scope_width + 4]); + } + // Assembly: hash alg, version, flags, public key, name, culture. + tables.extend([0; 4 + 8 + 4 + 2]); + tables.extend(assembly_name.to_le_bytes()); + tables.extend([0, 0]); + // AssemblyRef: version, flags, token, name, culture, hash. + for ((_, version), name) in refs.iter().zip(&ref_names) { + for part in version { + tables.extend(part.to_le_bytes()); + } + tables.extend([0; 4 + 2]); + tables.extend(name.to_le_bytes()); + tables.extend([0; 4]); + } + while !tables.len().is_multiple_of(4) { + tables.push(0); + } + + let version = b"v4.0.30319\0\0"; + let mut root = Vec::new(); + root.extend(SIGNATURE.to_le_bytes()); + root.extend([1, 0, 1, 0, 0, 0, 0, 0]); + root.extend((version.len() as u32).to_le_bytes()); + root.extend(version); + root.extend([0, 0, 2, 0]); + let headers = 8 + 4 + 8 + 12; + let tables_at = (root.len() + headers) as u32; + let strings_at = tables_at + tables.len() as u32; + root.extend(tables_at.to_le_bytes()); + root.extend((tables.len() as u32).to_le_bytes()); + root.extend(b"#~\0\0"); + root.extend(strings_at.to_le_bytes()); + root.extend((strings.len() as u32).to_le_bytes()); + root.extend(b"#Strings\0\0\0\0"); + root.extend(tables); + root.extend(strings); + root + } + + #[test] + fn assembly_refs_are_read_from_the_metadata_tables() { + let refs = [ + ("mscorlib", [4, 0, 0, 0]), + ("Newtonsoft.Json", [13, 0, 0, 0]), + ]; + let expected = vec![ + ("mscorlib".to_string(), "4.0.0.0".to_string()), + ("Newtonsoft.Json".to_string(), "13.0.0.0".to_string()), + ]; + assert_eq!(assembly_refs(&metadata(&refs, 3)), Some(expected.clone())); + // A TypeRef table large enough to widen its coded index. + assert_eq!(assembly_refs(&metadata(&refs, 20_000)), Some(expected)); + assert_eq!(assembly_refs(b"not metadata"), None); + } +} diff --git a/compliance-agent/src/pipeline/binary_depth/elf.rs b/compliance-agent/src/pipeline/binary_depth/elf.rs new file mode 100644 index 0000000..f85dfcd --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/elf.rs @@ -0,0 +1,189 @@ +//! ELF files: RELRO, non-executable stack, PIE, stack protector, FORTIFY. + +use std::collections::BTreeSet; + +use object::elf as raw; +use object::read::elf::{Dyn, ElfFile, FileHeader, ProgramHeader}; +use object::{Endianness, FileKind, Object, ObjectSymbol}; + +use super::{yes, Depth}; + +/// C library functions `_FORTIFY_SOURCE` replaces with a checked variant. +const FORTIFIABLE: [&str; 16] = [ + "memcpy", + "memmove", + "memset", + "strcpy", + "stpcpy", + "strncpy", + "strcat", + "strncat", + "sprintf", + "snprintf", + "vsprintf", + "vsnprintf", + "gets", + "fgets", + "read", + "realpath", +]; + +/// What the headers and symbols say. +struct Facts { + e_type: u16, + interp: bool, + dynamic: bool, + /// `None`: no PT_GNU_STACK; else whether it is executable. + stack_exec: Option, + relro: bool, + bind_now: bool, + flags_1_pie: bool, + symbols: BTreeSet, +} + +pub(super) fn analyse(bytes: &[u8], depth: &mut Depth) { + let facts = match FileKind::parse(bytes) { + Ok(FileKind::Elf32) => facts::>(bytes), + Ok(FileKind::Elf64) => facts::>(bytes), + _ => None, + }; + let Some(facts) = facts else { + depth + .evidence + .push("ELF headers could not be read: hardening not assessed.".to_string()); + return; + }; + if !matches!(facts.e_type, raw::ET_EXEC | raw::ET_DYN) { + depth.evidence.push( + "ELF object or core file, not an executable or library: hardening not assessed." + .to_string(), + ); + return; + } + // A bare-metal image or a statically linked program has no loader to + // apply RELRO or ASLR; its mitigations are the firmware's business. + if !facts.interp && !facts.dynamic { + depth.evidence.push( + "Statically linked or bare-metal ELF: RELRO, NX, PIE, stack protector and FORTIFY \ + not assessed." + .to_string(), + ); + return; + } + let pie = facts.e_type == raw::ET_DYN && (facts.flags_1_pie || facts.interp); + let executable = facts.e_type == raw::ET_EXEC || pie; + let mut parts = Vec::new(); + + let relro = match (facts.relro, facts.bind_now) { + (false, _) => { + depth.gap(super::NO_RELRO); + "none" + } + (true, false) => { + depth.gap(super::PARTIAL_RELRO); + "partial" + } + (true, true) => "full", + }; + parts.push(format!("RELRO {relro}")); + + let nx = facts.stack_exec == Some(false); + parts.push(format!("NX {}", yes(nx))); + if !nx { + depth.gap(super::NO_NX); + } + + if executable { + parts.push(format!("PIE {}", yes(pie))); + if !pie { + depth.gap(super::NO_ASLR); + } + } else { + parts.push("PIE n/a (shared library)".to_string()); + } + + let canary = facts + .symbols + .iter() + .any(|s| s == "__stack_chk_fail" || s == "__stack_chk_guard"); + parts.push(format!("stack protector {}", yes(canary))); + if !canary { + depth.gap(super::NO_STACK_PROTECTOR); + } + + let fortified = facts + .symbols + .iter() + .any(|s| s.starts_with("__") && s.ends_with("_chk") && s != "__stack_chk_fail"); + let fortifiable = FORTIFIABLE.iter().any(|f| facts.symbols.contains(*f)); + if fortified { + parts.push("FORTIFY yes".to_string()); + } else if fortifiable { + parts.push("FORTIFY no".to_string()); + depth.gap(super::NO_FORTIFY); + } else { + parts.push("FORTIFY n/a".to_string()); + } + depth + .evidence + .push(format!("Hardening: {}.", parts.join(", "))); +} + +/// The facts of an ELF file of header type `H`. +fn facts>(bytes: &[u8]) -> Option { + let file = ElfFile::::parse(bytes).ok()?; + let endian = file.endian(); + let mut facts = Facts { + e_type: file.elf_header().e_type(endian), + interp: false, + dynamic: false, + stack_exec: None, + relro: false, + bind_now: false, + flags_1_pie: false, + symbols: BTreeSet::new(), + }; + for segment in file.elf_program_headers() { + match segment.p_type(endian) { + raw::PT_INTERP => facts.interp = true, + raw::PT_GNU_STACK => { + facts.stack_exec = Some(segment.p_flags(endian) & raw::PF_X != 0); + } + raw::PT_GNU_RELRO => facts.relro = true, + raw::PT_DYNAMIC => { + facts.dynamic = true; + let Ok(Some(entries)) = segment.dynamic(endian, bytes) else { + continue; + }; + for entry in entries { + let tag: u64 = entry.d_tag(endian).into(); + let value: u64 = entry.d_val(endian).into(); + match u32::try_from(tag) { + Ok(raw::DT_BIND_NOW) => facts.bind_now = true, + Ok(raw::DT_FLAGS) if value & u64::from(raw::DF_BIND_NOW) != 0 => { + facts.bind_now = true; + } + Ok(raw::DT_FLAGS_1) => { + if value & u64::from(raw::DF_1_NOW) != 0 { + facts.bind_now = true; + } + if value & u64::from(raw::DF_1_PIE) != 0 { + facts.flags_1_pie = true; + } + } + _ => {} + } + } + } + _ => {} + } + } + for symbol in file.dynamic_symbols().chain(file.symbols()) { + if let Ok(name) = symbol.name() { + if !name.is_empty() { + facts.symbols.insert(name.to_string()); + } + } + } + Some(facts) +} diff --git a/compliance-agent/src/pipeline/binary_depth/ihex.rs b/compliance-agent/src/pipeline/binary_depth/ihex.rs new file mode 100644 index 0000000..b79b0fc --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/ihex.rs @@ -0,0 +1,247 @@ +//! Intel HEX images: records, checksums, address ranges. + +use super::Depth; + +/// How many address ranges and bad lines are listed. +const LISTED: usize = 10; + +/// What the records say. +#[derive(Debug, Default, PartialEq, Eq)] +struct Image { + records: usize, + /// Merged, sorted `(first, last)` addresses holding data. + ranges: Vec<(u64, u64)>, + data_bytes: u64, + /// 1-based line numbers. + bad_checksums: Vec, + malformed: Vec, + overlapping: bool, + eof: bool, + after_eof: bool, + start: Option, +} + +impl Image { + fn valid(&self) -> bool { + self.bad_checksums.is_empty() + && self.malformed.is_empty() + && !self.overlapping + && self.eof + && !self.after_eof + } +} + +pub(super) fn analyse(text: &[u8], depth: &mut Depth) { + let image = parse(text); + let ranges: Vec = image + .ranges + .iter() + .take(LISTED) + .map(|(first, last)| format!("0x{first:08X}-0x{last:08X}")) + .collect(); + let mut line = format!( + "Intel HEX: {} records, {} bytes of data in {} address range{}", + image.records, + image.data_bytes, + image.ranges.len(), + if image.ranges.len() == 1 { "" } else { "s" }, + ); + if !ranges.is_empty() { + line.push_str(&format!(" ({}", ranges.join(", "))); + if image.ranges.len() > LISTED { + line.push_str(&format!(" and {} more", image.ranges.len() - LISTED)); + } + line.push(')'); + } + if let Some(start) = image.start { + line.push_str(&format!(", start address 0x{start:08X}")); + } + line.push('.'); + depth.evidence.push(line); + if image.valid() { + depth + .evidence + .push("Every record checksum is valid.".to_string()); + return; + } + let lines = |numbers: &[usize]| { + let mut listed: Vec = numbers.iter().take(LISTED).map(usize::to_string).collect(); + if numbers.len() > LISTED { + listed.push(format!("and {} more", numbers.len() - LISTED)); + } + listed.join(", ") + }; + let mut problems = Vec::new(); + if !image.bad_checksums.is_empty() { + problems.push(format!( + "wrong checksum on line {}", + lines(&image.bad_checksums) + )); + } + if !image.malformed.is_empty() { + problems.push(format!("not a record on line {}", lines(&image.malformed))); + } + if image.overlapping { + problems.push("records overlap".to_string()); + } + if !image.eof { + problems.push("no end-of-file record (truncated?)".to_string()); + } + if image.after_eof { + problems.push("records after the end-of-file record".to_string()); + } + depth + .evidence + .push(format!("The image is damaged: {}.", problems.join("; "))); + depth.gap(super::HEX_INVALID); +} + +/// Read the records of `text`. +fn parse(text: &[u8]) -> Image { + let mut image = Image::default(); + let mut base: u64 = 0; + let mut spans: Vec<(u64, u64)> = Vec::new(); + for (index, raw_line) in text.split(|b| *b == b'\n').enumerate() { + let number = index + 1; + let line = raw_line.trim_ascii(); + if line.is_empty() { + continue; + } + let Some(bytes) = line.strip_prefix(b":").and_then(decode) else { + image.malformed.push(number); + continue; + }; + // count, address (2), type, data, checksum + let Some(&count) = bytes.first() else { + image.malformed.push(number); + continue; + }; + if bytes.len() != usize::from(count) + 5 { + image.malformed.push(number); + continue; + } + image.records += 1; + if image.eof { + image.after_eof = true; + } + if bytes.iter().fold(0_u8, |sum, b| sum.wrapping_add(*b)) != 0 { + image.bad_checksums.push(number); + } + let address = u64::from(u16::from_be_bytes([bytes[1], bytes[2]])); + let data = &bytes[4..bytes.len() - 1]; + match bytes[3] { + 0x00 if count > 0 => { + let first = base + address; + spans.push((first, first + u64::from(count) - 1)); + } + 0x00 => {} + 0x01 => image.eof = true, + 0x02 if data.len() == 2 => { + base = u64::from(u16::from_be_bytes([data[0], data[1]])) << 4; + } + 0x04 if data.len() == 2 => { + base = u64::from(u16::from_be_bytes([data[0], data[1]])) << 16; + } + 0x03 | 0x05 if data.len() == 4 => { + image.start = Some(u32::from_be_bytes([data[0], data[1], data[2], data[3]])); + } + _ => { + image.records -= 1; + image.malformed.push(number); + } + } + } + spans.sort_unstable(); + for (first, last) in spans { + image.data_bytes += last - first + 1; + match image.ranges.last_mut() { + Some((_, end)) if first <= *end => { + image.overlapping = true; + *end = (*end).max(last); + } + Some((_, end)) if first == *end + 1 => *end = last, + _ => image.ranges.push((first, last)), + } + } + image +} + +/// The bytes of an even-length string of hex digits. +fn decode(hex: &[u8]) -> Option> { + if !hex.len().is_multiple_of(2) { + return None; + } + hex.chunks(2) + .map(|pair| { + let text = std::str::from_utf8(pair).ok()?; + u8::from_str_radix(text, 16).ok() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A data record at `address` with a correct checksum. + fn record(kind: u8, address: u16, data: &[u8]) -> String { + let mut bytes = vec![data.len() as u8]; + bytes.extend(address.to_be_bytes()); + bytes.push(kind); + bytes.extend(data); + let sum = bytes.iter().fold(0_u8, |s, b| s.wrapping_add(*b)); + bytes.push(0_u8.wrapping_sub(sum)); + format!(":{}\n", hex::encode_upper(bytes)) + } + + #[test] + fn a_valid_image_has_its_ranges_and_size() { + let text = [ + record(0x04, 0, &[0x08, 0x00]), + record(0x00, 0x0000, &[1; 16]), + record(0x00, 0x0010, &[2; 16]), + record(0x00, 0x1000, &[3; 4]), + record(0x05, 0, &[0x08, 0x00, 0x01, 0x01]), + record(0x01, 0, &[]), + ] + .concat(); + let mut depth = Depth::default(); + analyse(text.as_bytes(), &mut depth); + assert!(depth.gaps.is_empty()); + assert_eq!( + depth.evidence, + [ + "Intel HEX: 6 records, 36 bytes of data in 2 address ranges \ + (0x08000000-0x0800001F, 0x08001000-0x08001003), start address 0x08000101." + .to_string(), + "Every record checksum is valid.".to_string() + ] + ); + } + + #[test] + fn a_damaged_image_is_a_gap() { + let mut bad = record(0x00, 0x0010, &[2; 16]); + bad.replace_range(bad.len() - 3..bad.len() - 1, "00"); + let text = [ + record(0x00, 0x0000, &[1; 16]), + bad, + "garbage\r\n".to_string(), + record(0x00, 0x0008, &[1; 4]), + ] + .concat(); + let image = parse(text.as_bytes()); + assert_eq!(image.bad_checksums, [2]); + assert_eq!(image.malformed, [3]); + assert!(image.overlapping); + assert!(!image.eof); + let mut depth = Depth::default(); + analyse(text.as_bytes(), &mut depth); + assert_eq!(depth.gaps, [crate::pipeline::binary_depth::HEX_INVALID]); + assert_eq!( + depth.evidence[1], + "The image is damaged: wrong checksum on line 2; not a record on line 3; records \ + overlap; no end-of-file record (truncated?)." + ); + } +} diff --git a/compliance-agent/src/pipeline/binary_depth/mod.rs b/compliance-agent/src/pipeline/binary_depth/mod.rs new file mode 100644 index 0000000..ed91b62 --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/mod.rs @@ -0,0 +1,273 @@ +//! What a committed binary is made of (#495), on top of the inventory of +//! #465. +//! +//! * **PE** (Windows EXE/DLL): the exploit mitigations the linker switched on +//! (ASLR, high-entropy ASLR, DEP, Control Flow Guard, SafeSEH, `/GS`), +//! whether an Authenticode signature is attached, the assemblies a .NET +//! assembly references, and CPE/purl candidates from the version resource +//! of a native file. +//! * **ELF** (Linux/Unix executables and shared libraries): RELRO, a +//! non-executable stack, PIE, the stack protector and `_FORTIFY_SOURCE`. +//! Statically linked and bare-metal ELF files (firmware) have none of these +//! by design and are not assessed. +//! * **Intel HEX** firmware images: every record's checksum, the address +//! ranges and the size of the data, for a later comparison with the image +//! Firmwerk builds. +//! +//! What is found goes two ways: as evidence lines on the file's inventory +//! finding, and as a [`Gap`] for each missing mitigation, missing signature +//! or damaged image, which becomes a finding of its own rule so that a +//! repository with many such files gets one finding per rule (#477). +//! +//! Everything is read natively: PE and ELF headers with the `object` crate, +//! the .NET metadata tables and Intel HEX records with the small readers in +//! this module. + +mod dotnet; +mod elf; +mod ihex; +mod pe; + +use compliance_core::models::Severity; + +/// A missing exploit mitigation, a missing signature or a damaged image. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Gap { + /// The rule of its finding. + pub rule: &'static str, + pub severity: Severity, + /// The finding's title. Rule-wide, not naming the file: a group of these + /// (#477) keeps its first member's title. + pub title: &'static str, + /// What it means, rule-wide for the same reason. + pub description: &'static str, + pub remediation: &'static str, +} + +/// What [`analyse_pe`], [`analyse_elf`] and [`analyse_intel_hex`] found. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Depth { + /// Lines for the inventory finding: mitigations, signature, references, + /// candidates, image layout. + pub evidence: Vec, + pub gaps: Vec, + /// The assemblies a .NET assembly references, as (name, version): input + /// for the NuGet mapping of #474. + pub assembly_refs: Vec<(String, String)>, +} + +impl Depth { + fn gap(&mut self, gap: Gap) { + if !self.gaps.contains(&gap) { + self.gaps.push(gap); + } + } +} + +/// The rules of [`Gap`]s, for the control map and the tests. +pub mod rules { + pub const NO_ASLR: &str = "binary-no-aslr"; + pub const NO_NX: &str = "binary-no-nx"; + pub const NO_RELRO: &str = "binary-no-relro"; + pub const PARTIAL_RELRO: &str = "binary-partial-relro"; + pub const NO_HIGH_ENTROPY_VA: &str = "binary-no-high-entropy-va"; + pub const NO_CFG: &str = "binary-no-cfg"; + pub const NO_SAFESEH: &str = "binary-no-safeseh"; + pub const NO_STACK_PROTECTOR: &str = "binary-no-stack-protector"; + pub const NO_FORTIFY: &str = "binary-no-fortify"; + pub const UNSIGNED: &str = "binary-unsigned"; + pub const HEX_INVALID: &str = "binary-hex-invalid"; +} + +pub(crate) const NO_ASLR: Gap = Gap { + rule: rules::NO_ASLR, + severity: Severity::Low, + title: "Committed binary without ASLR", + description: "A committed executable or library is loaded at a fixed address: a Windows \ + file without DYNAMICBASE (or without the relocations it needs), or a Linux \ + executable that is not position-independent (PIE). Its code and data are where \ + an attacker expects them, which makes memory-corruption bugs easier to exploit.", + remediation: "Link Windows files with /DYNAMICBASE, Linux executables with -fPIE -pie. \ + Rebuild, or ask the vendor for a build that has it.", +}; + +pub(crate) const NO_NX: Gap = Gap { + rule: rules::NO_NX, + severity: Severity::Low, + title: "Committed binary without DEP / non-executable stack", + description: "A committed executable or library lets data run as code: a Windows file \ + without NX_COMPAT (DEP), or a Linux file whose stack is executable or not \ + marked (no PT_GNU_STACK). Injected code on the stack or heap can then run.", + remediation: "Link Windows files with /NXCOMPAT, Linux files with -z noexecstack, and \ + find the object file that asks for an executable stack.", +}; + +pub(crate) const NO_RELRO: Gap = Gap { + rule: rules::NO_RELRO, + severity: Severity::Low, + title: "Committed binary without RELRO", + description: "A committed Linux executable or library keeps its relocation tables and \ + global offset table writable after loading (no PT_GNU_RELRO), so a memory \ + write can redirect its calls.", + remediation: "Link with -z relro -z now (full RELRO).", +}; + +pub(crate) const PARTIAL_RELRO: Gap = Gap { + rule: rules::PARTIAL_RELRO, + severity: Severity::Info, + title: "Committed binary with partial RELRO only", + description: "A committed Linux executable or library has RELRO but resolves its symbols \ + lazily (no BIND_NOW), so the part of the global offset table used for calls \ + stays writable.", + remediation: "Link with -z now in addition to -z relro (full RELRO).", +}; + +pub(crate) const NO_HIGH_ENTROPY_VA: Gap = Gap { + rule: rules::NO_HIGH_ENTROPY_VA, + severity: Severity::Info, + title: "Committed 64-bit binary without high-entropy ASLR", + description: "A committed 64-bit Windows file has ASLR but not HIGH_ENTROPY_VA, so it is \ + placed within a much smaller range of addresses than 64-bit Windows allows.", + remediation: "Link with /HIGHENTROPYVA (the default of current Visual Studio linkers).", +}; + +pub(crate) const NO_CFG: Gap = Gap { + rule: rules::NO_CFG, + severity: Severity::Info, + title: "Committed binary without Control Flow Guard", + description: "A committed native Windows file is not built with Control Flow Guard \ + (GUARD_CF), which checks the targets of indirect calls.", + remediation: "Compile and link with /guard:cf.", +}; + +pub(crate) const NO_SAFESEH: Gap = Gap { + rule: rules::NO_SAFESEH, + severity: Severity::Info, + title: "Committed 32-bit binary without SafeSEH", + description: "A committed 32-bit x86 Windows file uses structured exception handling but \ + has no table of safe exception handlers (SafeSEH), so an overwritten handler \ + record is followed.", + remediation: "Link with /SAFESEH.", +}; + +pub(crate) const NO_STACK_PROTECTOR: Gap = Gap { + rule: rules::NO_STACK_PROTECTOR, + severity: Severity::Info, + title: "Committed binary without stack protector", + description: "No stack protector was found in a committed executable or library: no \ + security cookie (/GS) in a native Windows file, no __stack_chk_fail in a \ + Linux one. A stack buffer overflow then overwrites the return address \ + unnoticed. A stripped file can hide it; the finding is a hint.", + remediation: "Compile with /GS (Windows) or -fstack-protector-strong (GCC, Clang).", +}; + +pub(crate) const NO_FORTIFY: Gap = Gap { + rule: rules::NO_FORTIFY, + severity: Severity::Info, + title: "Committed binary without _FORTIFY_SOURCE", + description: "A committed Linux executable or library calls C library functions that \ + _FORTIFY_SOURCE can check (memcpy, strcpy, sprintf …), but none of their \ + checked variants (__memcpy_chk …).", + remediation: "Compile with -O2 -D_FORTIFY_SOURCE=2 (or 3).", +}; + +pub(crate) const UNSIGNED: Gap = Gap { + rule: rules::UNSIGNED, + severity: Severity::Info, + title: "Committed executable without a signature", + description: "A committed Windows executable or library carries no Authenticode signature, \ + so neither Windows nor a person can tell who built it or whether it was \ + changed since. A signature that is present is not verified here.", + remediation: "Prefer the vendor's signed build, or sign your own builds; record the \ + vendor's published hash where no signed build exists.", +}; + +pub(crate) const HEX_INVALID: Gap = Gap { + rule: rules::HEX_INVALID, + severity: Severity::Low, + title: "Committed Intel HEX image is damaged", + description: "A committed Intel HEX firmware image does not read cleanly: a record's \ + checksum is wrong, a line is not a record, addresses overlap, or the \ + end-of-file record is missing. Flashing it writes something other than what \ + was built.", + remediation: "Regenerate the image from its build, or fetch it again from its source, and \ + compare it with the build's output.", +}; + +/// The hardening of a PE file, its signature, the references of a .NET +/// assembly and the CPE/purl candidates of a native file. +/// +/// # Arguments +/// +/// * `bytes` - the file, or its first part when it is very large +/// * `version_info` - its version resource strings (see +/// [`crate::pipeline::binaries::Binary::version_info`]) +pub fn analyse_pe(bytes: &[u8], version_info: &[(&'static str, String)]) -> Depth { + let mut depth = Depth::default(); + pe::analyse(bytes, version_info, &mut depth); + depth +} + +/// The hardening of an ELF file. +pub fn analyse_elf(bytes: &[u8]) -> Depth { + let mut depth = Depth::default(); + elf::analyse(bytes, &mut depth); + depth +} + +/// The records of an Intel HEX image. +pub fn analyse_intel_hex(text: &[u8]) -> Depth { + let mut depth = Depth::default(); + ihex::analyse(text, &mut depth); + depth +} + +/// Every gap there is, for the control map test. +#[cfg(test)] +pub(crate) const ALL_GAPS: [Gap; 11] = [ + NO_ASLR, + NO_NX, + NO_RELRO, + PARTIAL_RELRO, + NO_HIGH_ENTROPY_VA, + NO_CFG, + NO_SAFESEH, + NO_STACK_PROTECTOR, + NO_FORTIFY, + UNSIGNED, + HEX_INVALID, +]; + +/// A little-endian `u16` at `at`. +fn u16_at(bytes: &[u8], at: usize) -> Option { + Some(u16::from_le_bytes( + bytes.get(at..at.checked_add(2)?)?.try_into().ok()?, + )) +} + +/// A little-endian `u32` at `at`. +fn u32_at(bytes: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes( + bytes.get(at..at.checked_add(4)?)?.try_into().ok()?, + )) +} + +/// A little-endian `u64` at `at`. +fn u64_at(bytes: &[u8], at: usize) -> Option { + Some(u64::from_le_bytes( + bytes.get(at..at.checked_add(8)?)?.try_into().ok()?, + )) +} + +/// `yes` or `no`. +fn yes(on: bool) -> &'static str { + if on { + "yes" + } else { + "no" + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::cast_possible_truncation)] +pub(crate) mod tests; diff --git a/compliance-agent/src/pipeline/binary_depth/pe.rs b/compliance-agent/src/pipeline/binary_depth/pe.rs new file mode 100644 index 0000000..102c572 --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/pe.rs @@ -0,0 +1,342 @@ +//! PE files: mitigations, signature, .NET references, CPE/purl candidates. + +use object::pe as raw; +use object::read::pe::{ImageNtHeaders, ImageOptionalHeader, PeFile}; +use object::{FileKind, LittleEndian as LE}; + +use super::{dotnet, u32_at, u64_at, yes, Depth}; + +/// `IMAGE_FILE_RELOCS_STRIPPED`: an image that cannot be moved, ASLR or not. +const RELOCS_STRIPPED: u16 = 0x0001; + +/// How many referenced assemblies are listed on the finding. +const LISTED_REFS: usize = 40; + +/// What the headers say. +struct Facts { + pe32_plus: bool, + i386: bool, + dll_characteristics: u16, + relocs_stripped: bool, + signed: bool, + /// `None`: no load configuration directory. + load_config: Option, + /// The CLR header's flags and metadata, for a .NET assembly. + clr: Option<(u32, Option>)>, +} + +/// The parts of the load configuration directory that tell `/GS` and +/// SafeSEH. +struct LoadConfig { + security_cookie: bool, + se_handlers: bool, +} + +pub(super) fn analyse(bytes: &[u8], version_info: &[(&'static str, String)], depth: &mut Depth) { + let facts = match FileKind::parse(bytes) { + Ok(FileKind::Pe32) => facts::(bytes), + Ok(FileKind::Pe64) => facts::(bytes), + _ => None, + }; + let Some(facts) = facts else { + depth + .evidence + .push("PE headers could not be read: hardening not assessed.".to_string()); + return; + }; + let dc = facts.dll_characteristics; + let il_only = facts + .clr + .as_ref() + .is_some_and(|(flags, _)| flags & raw::COMIMAGE_FLAGS_ILONLY != 0); + + let aslr = dc & raw::IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE != 0 && !facts.relocs_stripped; + let high_entropy = dc & raw::IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA != 0; + let dep = dc & raw::IMAGE_DLLCHARACTERISTICS_NX_COMPAT != 0; + let cfg = dc & raw::IMAGE_DLLCHARACTERISTICS_GUARD_CF != 0; + let no_seh = dc & raw::IMAGE_DLLCHARACTERISTICS_NO_SEH != 0; + + let mut parts = vec![format!("ASLR {}", yes(aslr))]; + if !aslr { + depth.gap(super::NO_ASLR); + } + if facts.pe32_plus { + parts.push(format!("high-entropy ASLR {}", yes(high_entropy))); + if aslr && !high_entropy { + depth.gap(super::NO_HIGH_ENTROPY_VA); + } + } + parts.push(format!("DEP {}", yes(dep))); + if !dep { + depth.gap(super::NO_NX); + } + // Control Flow Guard, SafeSEH and /GS are about native code; an IL-only + // assembly has none, the runtime's JIT output is what runs. + if il_only { + parts.push("CFG, SafeSEH and /GS n/a (IL-only .NET assembly)".to_string()); + } else { + parts.push(format!("CFG {}", yes(cfg))); + if !cfg { + depth.gap(super::NO_CFG); + } + if facts.i386 { + let safe_seh = facts.load_config.as_ref().is_some_and(|l| l.se_handlers); + if no_seh { + parts.push("SafeSEH n/a (no exception handlers)".to_string()); + } else { + parts.push(format!("SafeSEH {}", yes(safe_seh))); + if !safe_seh { + depth.gap(super::NO_SAFESEH); + } + } + } + let gs = facts + .load_config + .as_ref() + .is_some_and(|l| l.security_cookie); + parts.push(format!("/GS {}", yes(gs))); + if !gs { + depth.gap(super::NO_STACK_PROTECTOR); + } + } + depth + .evidence + .push(format!("Hardening: {}.", parts.join(", "))); + if facts.signed { + depth + .evidence + .push("Authenticode signature: present (not verified).".to_string()); + } else { + depth + .evidence + .push("Authenticode signature: none.".to_string()); + depth.gap(super::UNSIGNED); + } + + match &facts.clr { + Some((_, Some(metadata))) => { + if let Some(refs) = dotnet::assembly_refs(metadata) { + if !refs.is_empty() { + let mut line = format!("References {} assemblies: ", refs.len()); + let listed: Vec = refs + .iter() + .take(LISTED_REFS) + .map(|(name, version)| format!("{name} {version}")) + .collect(); + line.push_str(&listed.join(", ")); + if refs.len() > LISTED_REFS { + line.push_str(&format!(" and {} more", refs.len() - LISTED_REFS)); + } + line.push('.'); + depth.evidence.push(line); + } + depth.assembly_refs = refs; + } + } + Some((_, None)) => {} + None => { + if let Some((cpe, purl)) = candidates(version_info) { + depth.evidence.push(format!( + "Candidates from the version resource (low confidence, for NVD matching): \ + {cpe}, {purl}." + )); + } + } + } +} + +/// The facts of a PE file of header type `Pe`. +fn facts(bytes: &[u8]) -> Option { + let file = PeFile::::parse(bytes).ok()?; + let nt = file.nt_headers(); + let header = nt.file_header(); + let characteristics = header.characteristics.get(LE); + let pe32_plus = nt.is_type_64(); + let sections = file.section_table(); + let directory = |id: usize| { + file.data_directory(id) + .map(|d| (d.virtual_address.get(LE), d.size.get(LE))) + .filter(|(at, size)| *at != 0 && *size != 0) + }; + // The certificate table's address is a file offset, not an RVA; its + // presence is what counts. + let signed = directory(raw::IMAGE_DIRECTORY_ENTRY_SECURITY).is_some(); + let load_config = directory(raw::IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG) + .and_then(|(rva, _)| sections.pe_data_at(bytes, rva)) + .map(|data| load_config(data, pe32_plus)); + let clr = directory(raw::IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) + .and_then(|(rva, _)| sections.pe_data_at(bytes, rva)) + .and_then(|cli| { + let flags = u32_at(cli, 16)?; + let metadata = u32_at(cli, 8).zip(u32_at(cli, 12)).and_then(|(rva, size)| { + let data = sections.pe_data_at(bytes, rva)?; + data.get(..usize::try_from(size).ok()?).map(<[u8]>::to_vec) + }); + Some((flags, metadata)) + }); + Some(Facts { + pe32_plus, + i386: header.machine.get(LE) == raw::IMAGE_FILE_MACHINE_I386, + dll_characteristics: nt.optional_header().dll_characteristics(), + relocs_stripped: characteristics & RELOCS_STRIPPED != 0, + signed, + load_config, + clr, + }) +} + +/// The security cookie and the SafeSEH table of a load configuration +/// directory, each only where its `Size` field covers it. +fn load_config(data: &[u8], pe32_plus: bool) -> LoadConfig { + let size = u32_at(data, 0).map_or(0, |s| s as usize); + let field = |at: usize, wide: bool| -> u64 { + let width = if wide { 8 } else { 4 }; + if at + width > size { + return 0; + } + if wide { + u64_at(data, at).unwrap_or(0) + } else { + u32_at(data, at).map_or(0, u64::from) + } + }; + if pe32_plus { + LoadConfig { + security_cookie: field(0x58, true) != 0, + se_handlers: false, + } + } else { + LoadConfig { + security_cookie: field(0x3c, false) != 0, + se_handlers: field(0x40, false) != 0 && field(0x44, false) != 0, + } + } +} + +/// A CPE 2.3 and a purl candidate from `CompanyName`, `ProductName` and +/// `FileVersion`, or `None` when the product or a version is missing. Version +/// resources are free text; a person or the NVD lookup has to confirm them. +fn candidates(version_info: &[(&'static str, String)]) -> Option<(String, String)> { + let get = |key: &str| { + version_info + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| v.as_str()) + }; + let product = cpe_part(get("ProductName")?); + let version = version(get("FileVersion")?)?; + if product.is_empty() { + return None; + } + let vendor = get("CompanyName") + .map(vendor) + .map(|v| cpe_part(&v)) + .filter(|v| !v.is_empty()); + let cpe = format!( + "cpe:2.3:a:{}:{product}:{version}:*:*:*:*:*:*:*", + vendor.as_deref().unwrap_or("*") + ); + let purl = match &vendor { + Some(v) => format!("pkg:generic/{v}/{product}@{version}"), + None => format!("pkg:generic/{product}@{version}"), + }; + Some((cpe, purl)) +} + +/// A company name without its legal form (`Acme Corporation` → `Acme`). +fn vendor(company: &str) -> String { + const FORMS: [&str; 12] = [ + "incorporated", + "corporation", + "corp.", + "corp", + "inc.", + "inc", + "gmbh", + "ltd.", + "ltd", + "llc", + "co.", + "ag", + ]; + let mut words: Vec<&str> = company + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|w| !w.is_empty()) + .collect(); + while words.len() > 1 + && words + .last() + .is_some_and(|w| FORMS.contains(&w.to_ascii_lowercase().as_str())) + { + words.pop(); + } + words.join(" ") +} + +/// A name as a CPE component: lower case, word characters only, spaces as +/// `_`. +fn cpe_part(text: &str) -> String { + let mapped: String = text + .trim() + .to_lowercase() + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { + c + } else { + '_' + } + }) + .collect(); + let mut out = String::with_capacity(mapped.len()); + for c in mapped.chars() { + if !(c == '_' && out.ends_with('_')) { + out.push(c); + } + } + out.trim_matches('_').to_string() +} + +/// The dotted version at the start of a `FileVersion` (`10.0.19041.1 +/// (WinBuild…)` → `10.0.19041.1`, `2, 4, 1, 0` → `2.4.1.0`). +fn version(text: &str) -> Option { + let text = text.replace(", ", ".").replace(',', "."); + let version: String = text + .trim() + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let version = version.trim_end_matches('.'); + (!version.is_empty() && version.chars().next().is_some_and(|c| c.is_ascii_digit())) + .then(|| version.to_string()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn version_resources_become_low_confidence_candidates() { + let info = [ + ("ProductName", "Pump Control Runtime".to_string()), + ("FileVersion", "2, 4, 1, 0".to_string()), + ("CompanyName", "Acme Automation GmbH".to_string()), + ]; + assert_eq!( + candidates(&info).unwrap(), + ( + "cpe:2.3:a:acme_automation:pump_control_runtime:2.4.1.0:*:*:*:*:*:*:*".to_string(), + "pkg:generic/acme_automation/pump_control_runtime@2.4.1.0".to_string() + ) + ); + assert_eq!( + version("10.0.19041.1 (WinBuild.160101.0800)").as_deref(), + Some("10.0.19041.1") + ); + assert_eq!(version("beta"), None); + assert_eq!(vendor("Example Corp."), "Example"); + // Without a version there is nothing to match. + assert_eq!(candidates(&info[..1]), None); + } +} diff --git a/compliance-agent/src/pipeline/binary_depth/tests.rs b/compliance-agent/src/pipeline/binary_depth/tests.rs new file mode 100644 index 0000000..016b145 --- /dev/null +++ b/compliance-agent/src/pipeline/binary_depth/tests.rs @@ -0,0 +1,443 @@ +//! Tests on PE and ELF files built here, byte by byte: no third-party +//! binaries in the repository. + +use super::*; + +/// What a test PE file has. +#[derive(Clone, Copy)] +pub(crate) struct PeSpec { + pub pe32_plus: bool, + pub i386: bool, + pub dll_characteristics: u16, + pub signed: bool, + /// A load configuration with a security cookie and, for PE32, a SafeSEH + /// table. + pub load_config: bool, + /// A CLR header (IL-only) with metadata naming these references. + pub dotnet: bool, +} + +const DYNAMIC_BASE: u16 = 0x0040; +const HIGH_ENTROPY_VA: u16 = 0x0020; +const NX_COMPAT: u16 = 0x0100; +const GUARD_CF: u16 = 0x4000; + +/// A hardened, signed native PE32+ DLL. +pub(crate) const HARDENED: PeSpec = PeSpec { + pe32_plus: true, + i386: false, + dll_characteristics: DYNAMIC_BASE | HIGH_ENTROPY_VA | NX_COMPAT | GUARD_CF, + signed: true, + load_config: true, + dotnet: false, +}; + +fn put(bytes: &mut [u8], at: usize, value: &[u8]) { + bytes[at..at + value.len()].copy_from_slice(value); +} + +/// A PE file as `spec` says, with one section holding the load +/// configuration, the CLR header and the metadata. +pub(crate) fn pe(spec: PeSpec) -> Vec { + const SECTION_VA: u32 = 0x1000; + const SECTION_RAW: usize = 0x200; + let mut file = vec![0_u8; SECTION_RAW + 0x1000]; + put(&mut file, 0, b"MZ"); + put(&mut file, 0x3c, &0x80_u32.to_le_bytes()); + put(&mut file, 0x80, b"PE\0\0"); + let machine: u16 = if spec.i386 { 0x014c } else { 0x8664 }; + let optional_size: u16 = if spec.pe32_plus { 240 } else { 224 }; + put(&mut file, 0x84, &machine.to_le_bytes()); + put(&mut file, 0x86, &1_u16.to_le_bytes()); + put(&mut file, 0x94, &optional_size.to_le_bytes()); + put(&mut file, 0x96, &0x2022_u16.to_le_bytes()); + let opt = 0x98; + put( + &mut file, + opt, + &(if spec.pe32_plus { 0x20b_u16 } else { 0x10b }).to_le_bytes(), + ); + put(&mut file, opt + 32, &0x1000_u32.to_le_bytes()); + put(&mut file, opt + 36, &0x200_u32.to_le_bytes()); + put(&mut file, opt + 56, &0x2000_u32.to_le_bytes()); + put(&mut file, opt + 60, &0x200_u32.to_le_bytes()); + put(&mut file, opt + 70, &spec.dll_characteristics.to_le_bytes()); + let (rva_count_at, directories) = if spec.pe32_plus { + (opt + 108, opt + 112) + } else { + (opt + 92, opt + 96) + }; + put(&mut file, rva_count_at, &16_u32.to_le_bytes()); + let directory = |file: &mut Vec, id: usize, rva: u32, size: u32| { + put(file, directories + id * 8, &rva.to_le_bytes()); + put(file, directories + id * 8 + 4, &size.to_le_bytes()); + }; + // Section .rdata, 0x1000 bytes at VA 0x1000. + let section = opt + usize::from(optional_size); + put(&mut file, section, b".rdata\0\0"); + put(&mut file, section + 8, &0x1000_u32.to_le_bytes()); + put(&mut file, section + 12, &SECTION_VA.to_le_bytes()); + put(&mut file, section + 16, &0x1000_u32.to_le_bytes()); + put(&mut file, section + 20, &(SECTION_RAW as u32).to_le_bytes()); + put(&mut file, section + 36, &0x4000_0040_u32.to_le_bytes()); + + if spec.load_config { + let raw = SECTION_RAW; + if spec.pe32_plus { + put(&mut file, raw, &0x94_u32.to_le_bytes()); + put(&mut file, raw + 0x58, &0x1_4000_3000_u64.to_le_bytes()); + directory(&mut file, 10, SECTION_VA, 0x94); + } else { + put(&mut file, raw, &0x48_u32.to_le_bytes()); + put(&mut file, raw + 0x3c, &0x1000_3000_u32.to_le_bytes()); + put(&mut file, raw + 0x40, &0x1000_3100_u32.to_le_bytes()); + put(&mut file, raw + 0x44, &2_u32.to_le_bytes()); + directory(&mut file, 10, SECTION_VA, 0x48); + } + } + if spec.dotnet { + let metadata = + dotnet::tests::metadata(&[("mscorlib", [4, 0, 0, 0]), ("log4net", [2, 0, 8, 0])], 1); + let cli = SECTION_RAW + 0x100; + put(&mut file, cli, &72_u32.to_le_bytes()); + put(&mut file, cli + 8, &(SECTION_VA + 0x200).to_le_bytes()); + put(&mut file, cli + 12, &(metadata.len() as u32).to_le_bytes()); + put(&mut file, cli + 16, &1_u32.to_le_bytes()); + put(&mut file, SECTION_RAW + 0x200, &metadata); + directory(&mut file, 14, SECTION_VA + 0x100, 72); + } + if spec.signed { + let at = file.len() as u32; + file.extend([8, 0, 0, 0, 0, 2, 2, 0]); + directory(&mut file, 4, at, 8); + } + file +} + +/// What a test ELF file has. +#[derive(Clone, Copy)] +pub(crate) struct ElfSpec { + pub e_type: u16, + pub interp: bool, + pub dynamic: bool, + /// `None`: no PT_GNU_STACK. + pub stack_exec: Option, + pub relro: bool, + pub bind_now: bool, + pub pie_flag: bool, + pub symbols: &'static [&'static str], +} + +/// A hardened, dynamically linked PIE. +pub(crate) const HARDENED_ELF: ElfSpec = ElfSpec { + e_type: 3, + interp: true, + dynamic: true, + stack_exec: Some(false), + relro: true, + bind_now: true, + pie_flag: true, + symbols: &["__stack_chk_fail", "__memcpy_chk", "memcpy", "puts"], +}; + +/// A little-endian ELF64 x86-64 file as `spec` says: program headers, a +/// dynamic segment, and `.dynstr`/`.dynsym` sections with undefined +/// symbols. +pub(crate) fn elf(spec: ElfSpec) -> Vec { + // Data after the headers: interp, dynstr, dynsym, dynamic, shstrtab. + let interp = b"/lib64/ld-linux-x86-64.so.2\0".to_vec(); + let mut dynstr = vec![0_u8]; + let mut name_offsets = Vec::new(); + for name in spec.symbols { + name_offsets.push(dynstr.len() as u32); + dynstr.extend(name.as_bytes()); + dynstr.push(0); + } + let mut dynsym = vec![0_u8; 24]; + for offset in &name_offsets { + let mut symbol = [0_u8; 24]; + symbol[..4].copy_from_slice(&offset.to_le_bytes()); + symbol[4] = 0x12; // global function, undefined (section 0) + dynsym.extend(symbol); + } + let mut dynamic = Vec::new(); + let mut entry = |tag: u64, value: u64| { + dynamic.extend(tag.to_le_bytes()); + dynamic.extend(value.to_le_bytes()); + }; + if spec.bind_now { + entry(30, 8); // DT_FLAGS = DF_BIND_NOW + } + if spec.pie_flag { + entry(0x6fff_fffb, 0x0800_0000); // DT_FLAGS_1 = DF_1_PIE + } + entry(0, 0); + let shstrtab = b"\0.dynstr\0.dynsym\0.shstrtab\0".to_vec(); + + let mut phdrs: Vec<(u32, u32, usize, usize)> = Vec::new(); // type, flags, offset, size + let mut body = Vec::new(); + let data_start = 64 + 56 * 5; // room for up to five program headers + let place = |body: &mut Vec, bytes: &[u8]| { + while !body.len().is_multiple_of(8) { + body.push(0); + } + let at = data_start + body.len(); + body.extend(bytes); + at + }; + let interp_at = place(&mut body, &interp); + let dynstr_at = place(&mut body, &dynstr); + let dynsym_at = place(&mut body, &dynsym); + let dynamic_at = place(&mut body, &dynamic); + let shstrtab_at = place(&mut body, &shstrtab); + if spec.interp { + phdrs.push((3, 4, interp_at, interp.len())); + } + if spec.dynamic { + phdrs.push((2, 6, dynamic_at, dynamic.len())); + } + if let Some(exec) = spec.stack_exec { + phdrs.push((0x6474_e551, if exec { 7 } else { 6 }, 0, 0)); + } + if spec.relro { + phdrs.push((0x6474_e552, 4, dynamic_at, dynamic.len())); + } + while !body.len().is_multiple_of(8) { + body.push(0); + } + let shoff = data_start + body.len(); + + let mut file = vec![0_u8; 64]; + put(&mut file, 0, &[0x7f, b'E', b'L', b'F', 2, 1, 1, 0]); + put(&mut file, 16, &spec.e_type.to_le_bytes()); + put(&mut file, 18, &62_u16.to_le_bytes()); + put(&mut file, 20, &1_u32.to_le_bytes()); + put(&mut file, 32, &64_u64.to_le_bytes()); + put(&mut file, 40, &(shoff as u64).to_le_bytes()); + put(&mut file, 52, &64_u16.to_le_bytes()); + put(&mut file, 54, &56_u16.to_le_bytes()); + put(&mut file, 56, &(phdrs.len() as u16).to_le_bytes()); + put(&mut file, 58, &64_u16.to_le_bytes()); + put(&mut file, 60, &4_u16.to_le_bytes()); + put(&mut file, 62, &3_u16.to_le_bytes()); + for (p_type, flags, offset, size) in &phdrs { + let mut header = [0_u8; 56]; + header[..4].copy_from_slice(&p_type.to_le_bytes()); + header[4..8].copy_from_slice(&flags.to_le_bytes()); + header[8..16].copy_from_slice(&(*offset as u64).to_le_bytes()); + header[16..24].copy_from_slice(&(*offset as u64).to_le_bytes()); + header[24..32].copy_from_slice(&(*offset as u64).to_le_bytes()); + header[32..40].copy_from_slice(&(*size as u64).to_le_bytes()); + header[40..48].copy_from_slice(&(*size as u64).to_le_bytes()); + header[48..56].copy_from_slice(&8_u64.to_le_bytes()); + file.extend(header); + } + file.resize(data_start, 0); + file.extend(body); + // Section headers: null, .dynstr, .dynsym, .shstrtab. + let section = |name: u32, kind: u32, offset: usize, size: usize, link: u32, entsize: u64| { + let mut header = [0_u8; 64]; + header[..4].copy_from_slice(&name.to_le_bytes()); + header[4..8].copy_from_slice(&kind.to_le_bytes()); + header[16..24].copy_from_slice(&(offset as u64).to_le_bytes()); + header[24..32].copy_from_slice(&(offset as u64).to_le_bytes()); + header[32..40].copy_from_slice(&(size as u64).to_le_bytes()); + header[40..44].copy_from_slice(&link.to_le_bytes()); + header[44..48].copy_from_slice(&1_u32.to_le_bytes()); // sh_info: first global + header[48..56].copy_from_slice(&8_u64.to_le_bytes()); + header[56..64].copy_from_slice(&entsize.to_le_bytes()); + header + }; + file.extend([0_u8; 64]); + file.extend(section(1, 3, dynstr_at, dynstr.len(), 0, 0)); + file.extend(section(9, 11, dynsym_at, dynsym.len(), 1, 24)); + file.extend(section(17, 3, shstrtab_at, shstrtab.len(), 0, 0)); + file +} + +fn rules_of(depth: &Depth) -> Vec<&'static str> { + depth.gaps.iter().map(|g| g.rule).collect() +} + +#[test] +fn a_hardened_signed_dll_has_no_gaps() { + let depth = analyse_pe(&pe(HARDENED), &[]); + assert!(depth.gaps.is_empty(), "{:?}", depth.gaps); + assert_eq!( + depth.evidence, + [ + "Hardening: ASLR yes, high-entropy ASLR yes, DEP yes, CFG yes, /GS yes.", + "Authenticode signature: present (not verified)." + ] + ); +} + +#[test] +fn an_old_32_bit_exe_lacks_every_mitigation() { + let spec = PeSpec { + pe32_plus: false, + i386: true, + dll_characteristics: 0, + signed: false, + load_config: false, + dotnet: false, + }; + let info = [ + ("ProductName", "Pump Service".to_string()), + ("FileVersion", "3.1.0.7".to_string()), + ("CompanyName", "Acme Inc.".to_string()), + ]; + let depth = analyse_pe(&pe(spec), &info); + assert_eq!( + rules_of(&depth), + [ + rules::NO_ASLR, + rules::NO_NX, + rules::NO_CFG, + rules::NO_SAFESEH, + rules::NO_STACK_PROTECTOR, + rules::UNSIGNED + ] + ); + assert_eq!( + depth.evidence[0], + "Hardening: ASLR no, DEP no, CFG no, SafeSEH no, /GS no." + ); + assert_eq!( + depth.evidence[2], + "Candidates from the version resource (low confidence, for NVD matching): \ + cpe:2.3:a:acme:pump_service:3.1.0.7:*:*:*:*:*:*:*, \ + pkg:generic/acme/pump_service@3.1.0.7." + ); + // With a load configuration: /GS and SafeSEH are there. + let depth = analyse_pe( + &pe(PeSpec { + load_config: true, + ..spec + }), + &[], + ); + assert!(!rules_of(&depth).contains(&rules::NO_SAFESEH)); + assert!(!rules_of(&depth).contains(&rules::NO_STACK_PROTECTOR)); +} + +#[test] +fn a_dotnet_assembly_lists_its_references() { + let spec = PeSpec { + pe32_plus: false, + i386: true, + dll_characteristics: DYNAMIC_BASE | NX_COMPAT, + signed: false, + load_config: false, + dotnet: true, + }; + let info = [ + ("ProductName", "Pump Tools".to_string()), + ("FileVersion", "1.0.0.0".to_string()), + ]; + let depth = analyse_pe(&pe(spec), &info); + // IL-only: no CFG, SafeSEH or /GS gaps; no CPE candidate (NuGet's job). + assert_eq!(rules_of(&depth), [rules::UNSIGNED]); + assert_eq!( + depth.assembly_refs, + [ + ("mscorlib".to_string(), "4.0.0.0".to_string()), + ("log4net".to_string(), "2.0.8.0".to_string()) + ] + ); + assert_eq!( + depth.evidence, + [ + "Hardening: ASLR yes, DEP yes, CFG, SafeSEH and /GS n/a (IL-only .NET assembly).", + "Authenticode signature: none.", + "References 2 assemblies: mscorlib 4.0.0.0, log4net 2.0.8.0." + ] + ); +} + +#[test] +fn a_64_bit_dll_without_high_entropy_aslr_is_info() { + let depth = analyse_pe( + &pe(PeSpec { + dll_characteristics: DYNAMIC_BASE | NX_COMPAT | GUARD_CF, + ..HARDENED + }), + &[], + ); + assert_eq!(rules_of(&depth), [rules::NO_HIGH_ENTROPY_VA]); + assert_eq!(depth.gaps[0].severity, Severity::Info); +} + +#[test] +fn a_hardened_elf_has_no_gaps() { + let depth = analyse_elf(&elf(HARDENED_ELF)); + assert!(depth.gaps.is_empty(), "{:?}", depth.gaps); + assert_eq!( + depth.evidence, + ["Hardening: RELRO full, NX yes, PIE yes, stack protector yes, FORTIFY yes."] + ); +} + +#[test] +fn an_unhardened_elf_executable_has_its_gaps() { + let depth = analyse_elf(&elf(ElfSpec { + e_type: 2, + stack_exec: None, + relro: false, + bind_now: false, + pie_flag: false, + symbols: &["strcpy", "printf"], + ..HARDENED_ELF + })); + assert_eq!( + rules_of(&depth), + [ + rules::NO_RELRO, + rules::NO_NX, + rules::NO_ASLR, + rules::NO_STACK_PROTECTOR, + rules::NO_FORTIFY + ] + ); + assert_eq!( + depth.evidence, + ["Hardening: RELRO none, NX no, PIE no, stack protector no, FORTIFY no."] + ); +} + +#[test] +fn a_shared_library_with_partial_relro_and_an_executable_stack() { + let depth = analyse_elf(&elf(ElfSpec { + interp: false, + stack_exec: Some(true), + bind_now: false, + pie_flag: false, + ..HARDENED_ELF + })); + assert_eq!(rules_of(&depth), [rules::PARTIAL_RELRO, rules::NO_NX]); + assert!(depth.evidence[0].contains("PIE n/a (shared library)")); +} + +#[test] +fn bare_metal_firmware_elf_is_not_assessed() { + let depth = analyse_elf(&elf(ElfSpec { + e_type: 2, + interp: false, + dynamic: false, + stack_exec: None, + relro: false, + bind_now: false, + pie_flag: false, + symbols: &["Reset_Handler", "memcpy"], + })); + assert!(depth.gaps.is_empty()); + assert!(depth.evidence[0].starts_with("Statically linked or bare-metal ELF")); +} + +#[test] +fn unreadable_headers_say_so() { + let mut bytes = elf(HARDENED_ELF); + bytes.truncate(70); + assert!(analyse_elf(&bytes).evidence[0].contains("could not be read")); + assert!(analyse_pe(b"MZ", &[]).evidence[0].contains("could not be read")); +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index b8159d7..87a36d2 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -1,4 +1,5 @@ pub mod binaries; +pub mod binary_depth; pub mod build_lifecycle; pub mod change; pub mod clamav; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 8bf3560..af34218 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -1856,7 +1856,7 @@ impl PipelineOrchestrator { run_findings.completed(binaries::SCANNER); let mut findings: Vec = listed .iter() - .map(|b| binaries::into_finding(repo_id, b)) + .flat_map(|b| binaries::findings(repo_id, b)) .collect(); let Some(clamd) = clamav::Clamd::from_env() else { self.skip_stage( diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index f7d4587..998e4af 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -50,6 +50,19 @@ "dotnet-config-custom-errors-off" ], "check": "The shipped configuration must be secure by default; ASP.NET debug compilation or detailed errors shown to every client violates it." + }, + { + "tool": "binary-inventory", + "scan_type": "malware", + "languages": [], + "cwe": [], + "rules": [ + "binary-no-aslr", + "binary-no-nx", + "binary-no-relro" + ], + "check": "A committed executable or library must be built with the operating system's basic exploit mitigations on (ASLR/PIE, DEP/non-executable stack, RELRO); one without them is not secure by default. Defence-in-depth extras (CFG, SafeSEH, stack protector, FORTIFY, high-entropy ASLR) are reported but not bound here.", + "attach_only": true } ], "note": null, @@ -106,6 +119,17 @@ ], "cwe": [], "rules": [] + }, + { + "tool": "binary-inventory", + "scan_type": "malware", + "languages": [], + "cwe": [], + "rules": [ + "binary-hex-invalid" + ], + "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 } ], "note": "covered by the grounded surface check (retrieve code surface + grounded LLM judge decides presence/absence); validated live", diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 66c94ed..0ee0135 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -46,12 +46,18 @@ pub struct ScanBinding { /// CI/CD pipeline"); a buffer overflow is judged against this instead. #[serde(default, skip_serializing_if = "Option::is_none")] pub check: Option, + /// The binding links its findings to the control but never makes the + /// control count as checked: a tool that only looks at some files (the + /// committed binaries, #495) says nothing about a tree without them. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub attach_only: bool, } impl ScanBinding { /// Whether this binding checks code in any of `languages`. pub fn applies_to(&self, languages: &[String]) -> bool { - self.languages.is_empty() || self.languages.iter().any(|l| languages.contains(l)) + !self.attach_only + && (self.languages.is_empty() || self.languages.iter().any(|l| languages.contains(l))) } } @@ -299,7 +305,7 @@ mod tests { for scan in &control.scans { let reads_code = !matches!( scan.tool.as_str(), - "gitleaks" | "secret-files" | "syft" | "osv" + "gitleaks" | "secret-files" | "syft" | "osv" | "binary-inventory" ); assert_eq!( reads_code, @@ -312,6 +318,25 @@ mod tests { } } + #[test] + fn binary_findings_attach_without_claiming_coverage() { + let map = ControlMap::cra().expect("map"); + let controls = |rule: &str| -> Vec<&str> { + map.controls_for_finding("binary-inventory", None, Some(rule)) + .into_iter() + .map(|c| c.control.as_str()) + .collect() + }; + assert_eq!(controls("binary-no-aslr"), ["cra-ai-1"]); + assert_eq!(controls("binary-hex-invalid"), ["cra-ai-6"]); + assert!(controls("binary-unsigned").is_empty()); + assert!(controls("binary-no-cfg").is_empty()); + // A Go tree without binaries does not make cra-ai-1 checked. + let c = map.coverage("cra-ai-1").expect("cra-ai-1"); + assert!(!c.checked_for(&["go".to_string()])); + assert!(c.checked_for(&["python".to_string()])); + } + #[test] fn hardcoded_password_control_is_tool_covered() { let map = ControlMap::cra().unwrap(); diff --git a/docs/release/staging-test-plan-after-v0.4.5.md b/docs/release/staging-test-plan-after-v0.4.5.md index 61cf070..0b9169e 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -20,6 +20,7 @@ together on stage in one pass before the next prod promotion. | #467 (follow-up) | npm and Maven licenses from their public registries | | #491 | Findings keyed by the code they flag, not its line number | | #491 (PLC) | PLC findings keyed the same way | +| #495 | Binary depth: PE/ELF hardening, signatures, .NET references, CPE/purl candidates, Intel HEX checks | **Customer-visible on the next prod rescan** is marked **[visible]**: these change what a customer sees on their existing targets, without them doing @@ -368,6 +369,52 @@ target with history (findings, at least one marked by a person, issues). - **[visible]** PLC targets no longer get a duplicate finding for every line shift in an export. +### 21. #495 Binary depth: hardening, signatures, references, HEX + +Builds on check 15 (committed binaries). Nothing to switch on; no ClamAV +needed. Make the files locally, never commit them: + +```sh +printf '#include \n#include \nint main(int c,char**v){char b[16];strcpy(b,v[0]);puts(b);return 0;}\n' > t.c +gcc -O2 -fno-stack-protector -no-pie -Wl,-z,norelro -o weak t.c +gcc -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -pie -fPIE -Wl,-z,relro,-z,now -o strong t.c +cp fixtures/nightly/firmware/c-sensor-node/Prebuilt/bootloader.hex good.hex +sed '3s/^\(:10.......\)./\1F/' good.hex > broken.hex # one data digit changed +``` + +plus one .NET DLL and one native Windows DLL (e.g. `lib/net45/Newtonsoft.Json.dll` +from the nupkg on nuget.org, and any unsigned native DLL you have). + +- **Do:** upload an archive with `weak`, `strong`, `good.hex`, `broken.hex` + and the two DLLs under `bin/`. +- **Expect:** + - every file keeps its **Info** finding **Committed binary …**, whose text + now ends with what was found: `Hardening: RELRO none, NX yes, PIE no, + stack protector no, FORTIFY no.` for `weak`, `RELRO full, NX yes, PIE + yes, stack protector yes, FORTIFY yes.` for `strong`; for the .NET DLL `References N assemblies: + …` (mscorlib, System …); for the native DLL `Candidates from the version + resource (low confidence …): cpe:2.3:a:…, pkg:generic/…`; for + `good.hex` `Intel HEX: 129 records, 2048 bytes of data in 1 address range + (0x00000000-0x000007FF).` and `Every record checksum is valid.` + - for `weak`, **Niedrig** findings **Committed binary without ASLR** and + **… without RELRO**, and **Info** **… without stack protector** and + **… without _FORTIFY_SOURCE**; none for `strong`; + - **Niedrig** **Committed Intel HEX image is damaged** on `broken.hex` + (its inventory finding says `wrong checksum on line 3`); + - **Info** **Committed executable without a signature** for each unsigned + DLL; a signed one says `Authenticode signature: present (not verified)`; + - the ASLR/NX/RELRO findings show control **cra-ai-1**, the HEX finding + **cra-ai-6**; in the CRA view a target without binaries does not turn + cra-ai-1 green because of this stage; + - a bare-metal firmware `.elf` (no dynamic section) gets no hardening + findings: `Statically linked or bare-metal ELF: … not assessed.`; + - more than five files with the same gap become one finding per rule + (#477), listing the files. +- **Log:** nothing new; the stage runs inside the binary inventory. +- **[visible]** repositories with committed DLLs, executables or `.hex` + images get Low/Info hardening, signature and HEX findings and longer + inventory texts on the next rescan. + ## After the pass - The nightly job on `main` is green with the new mobile targets.