use std::borrow::Cow;
use crate::json::{Array, Object};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Severity {
Cosmetic,
Conformance,
Integrity,
Structural,
}
crate::naming::named_choice!(Severity {
Severity::Cosmetic => "cosmetic",
Severity::Conformance => "conformance",
Severity::Integrity => "integrity",
Severity::Structural => "structural",
});
crate::naming::serialize_as_name!(Severity);
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Family {
#[cfg(feature = "ext")]
Ext,
#[cfg(feature = "fat")]
Fat,
#[cfg(feature = "exfat")]
ExFat,
#[cfg(feature = "btrfs")]
Btrfs,
#[cfg(feature = "apfs")]
Apfs,
}
impl Family {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
#[cfg(feature = "ext")]
Family::Ext => "ext",
#[cfg(feature = "fat")]
Family::Fat => "fat",
#[cfg(feature = "exfat")]
Family::ExFat => "exfat",
#[cfg(feature = "btrfs")]
Family::Btrfs => "btrfs",
#[cfg(feature = "apfs")]
Family::Apfs => "apfs",
}
}
}
crate::naming::serialize_as_name!(Family);
pub type Coordinate = (Cow<'static, str>, u64);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Finding {
pub severity: Severity,
pub family: Family,
pub category: Cow<'static, str>,
pub offset: Option<u64>,
pub coordinates: Vec<Coordinate>,
pub detail: String,
}
pub const FINDINGS_SCHEMA_VERSION: u32 = 3;
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FindingReport {
findings: Vec<Finding>,
source_failures: Vec<Finding>,
truncated: bool,
#[cfg_attr(feature = "serde", serde(skip))]
cap: usize,
}
impl Default for FindingReport {
fn default() -> Self {
Self {
findings: Vec::new(),
source_failures: Vec::new(),
truncated: false,
cap: Self::MAX_FINDINGS,
}
}
}
impl FindingReport {
pub const MAX_FINDINGS: usize = 10_000;
#[must_use]
pub fn new(findings: Vec<Finding>, truncated: bool, cap: usize) -> Self {
Self {
findings,
source_failures: Vec::new(),
truncated,
cap,
}
}
#[must_use]
pub fn with_source_failures(mut self, failures: Vec<Finding>) -> Self {
self.source_failures = failures;
self
}
#[must_use]
pub fn findings(&self) -> &[Finding] {
&self.findings
}
#[must_use]
pub fn source_failures(&self) -> &[Finding] {
&self.source_failures
}
#[must_use]
pub fn is_truncated(&self) -> bool {
self.truncated
}
#[must_use]
pub fn is_clean(&self) -> bool {
!self.truncated && self.findings.is_empty() && self.source_failures.is_empty()
}
#[must_use]
pub fn worst_severity(&self) -> Option<Severity> {
self.findings.iter().map(|f| f.severity).max()
}
#[must_use]
pub fn has_fatal(&self, policy: crate::ReadPolicy) -> bool {
self.findings.iter().any(|f| policy.is_fatal(f.severity))
}
#[must_use]
pub fn to_json(&self) -> String {
let mut out = String::new();
let mut o = Object::new(&mut out);
o.u64("schema", u64::from(FINDINGS_SCHEMA_VERSION));
o.bool("clean", self.is_clean());
o.u64("count", self.findings.len() as u64);
o.bool("truncated", self.truncated);
let mut findings = o.arr("findings");
for f in &self.findings {
push_finding_json(findings.obj(), f);
}
findings.end();
let mut failures = o.arr("source_failures");
for f in &self.source_failures {
push_finding_json(failures.obj(), f);
}
failures.end();
o.end();
out
}
#[must_use]
pub fn to_sarif(&self, artifact_uri: Option<&str>) -> String {
let mut out = String::new();
let mut doc = Object::new(&mut out);
doc.str("$schema", "https://json.schemastore.org/sarif-2.1.0.json");
doc.str("version", "2.1.0");
let mut runs = doc.arr("runs");
let mut run = runs.obj();
let mut tool = run.obj("tool");
let mut driver = tool.obj("driver");
driver.str("name", "ferrosys");
push_sarif_rules(driver.arr("rules"), &self.findings);
driver.end();
tool.end();
let mut results = run.arr("results");
for f in &self.findings {
push_sarif_result(results.obj(), f, artifact_uri);
}
results.end();
if self.truncated || !self.source_failures.is_empty() {
let mut invocations = run.arr("invocations");
let mut invocation = invocations.obj();
invocation.bool("executionSuccessful", self.source_failures.is_empty());
let mut notifications = invocation.arr("toolExecutionNotifications");
for f in &self.source_failures {
let mut notification = notifications.obj();
notification.str("level", "error");
let mut message = notification.obj("message");
message.str("text", &source_failure_line(f));
message.end();
notification.end();
}
if self.truncated {
let mut notification = notifications.obj();
notification.str("level", "warning");
let mut message = notification.obj("message");
message.str("text", &self.truncation_notice());
message.end();
notification.end();
}
notifications.end();
invocation.end();
invocations.end();
}
run.end();
runs.end();
doc.end();
out
}
#[must_use]
pub fn to_table(&self) -> String {
let mut out = self.findings_table();
if !self.source_failures.is_empty() {
out.push('\n');
for f in &self.source_failures {
out.push_str(&source_failure_line(f));
out.push('\n');
}
}
if self.truncated {
out.push('\n');
out.push_str(&self.truncation_notice());
out.push('\n');
}
out
}
fn findings_table(&self) -> String {
if self.findings.is_empty() {
return String::from("no findings\n");
}
let rows: Vec<(&str, &str, String, &str)> = self
.findings
.iter()
.map(|f| {
(
f.severity.as_str(),
f.category.as_ref(),
location_compact(f),
f.detail.as_str(),
)
})
.collect();
let mut sev_w = "SEVERITY".len();
let mut cat_w = "CATEGORY".len();
let mut loc_w = "LOCATION".len();
for (s, c, l, _) in &rows {
sev_w = sev_w.max(s.len());
cat_w = cat_w.max(c.len());
loc_w = loc_w.max(l.len());
}
let mut out = format!(
"{:<sev_w$} {:<cat_w$} {:<loc_w$} {}\n",
"SEVERITY", "CATEGORY", "LOCATION", "DETAIL"
);
for (s, c, l, d) in &rows {
out.push_str(&format!("{s:<sev_w$} {c:<cat_w$} {l:<loc_w$} {d}\n"));
}
out
}
fn truncation_notice(&self) -> String {
format!(
"report truncated at {} findings; the rest of the image was not scanned",
self.cap
)
}
}
fn source_failure_line(f: &Finding) -> String {
let location = location_compact(f);
if location == "-" {
format!("source failure: {}", f.detail)
} else {
format!("source failure at {location}: {}", f.detail)
}
}
pub trait Deviation {
fn severity(&self) -> Severity;
fn to_finding(&self, unit: u32) -> Finding;
fn is_source_failure(&self) -> bool;
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) fn project(
severity: Severity,
family: Family,
category: &'static str,
coordinates: &[(&'static str, Option<u64>)],
addressed: Option<u64>,
unit: u32,
detail: &str,
) -> Finding {
Finding {
severity,
family,
category: Cow::Borrowed(category),
offset: addressed.and_then(|value| value.checked_mul(u64::from(unit))),
coordinates: coordinates
.iter()
.filter_map(|&(name, value)| value.map(|value| (Cow::Borrowed(name), value)))
.collect(),
detail: detail.to_string(),
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ScanReport<A> {
anomalies: Vec<A>,
source_failures: Vec<A>,
truncated: bool,
#[cfg_attr(feature = "serde", serde(skip))]
cap: usize,
#[cfg_attr(feature = "serde", serde(skip))]
unit: u32,
}
impl<A> Default for ScanReport<A> {
fn default() -> Self {
Self {
anomalies: Vec::new(),
source_failures: Vec::new(),
truncated: false,
cap: FindingReport::MAX_FINDINGS,
unit: 0,
}
}
}
impl<A> ScanReport<A> {
#[must_use]
pub fn anomalies(&self) -> &[A] {
&self.anomalies
}
#[must_use]
pub fn source_failures(&self) -> &[A] {
&self.source_failures
}
#[must_use]
pub fn is_truncated(&self) -> bool {
self.truncated
}
#[must_use]
pub fn is_clean(&self) -> bool {
!self.truncated && self.anomalies.is_empty() && self.source_failures.is_empty()
}
}
impl<A: Deviation> ScanReport<A> {
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) fn new(met: Vec<A>, truncated: bool, cap: usize, unit: u32) -> Self {
let (source_failures, anomalies) = met.into_iter().partition(Deviation::is_source_failure);
Self {
anomalies,
source_failures,
truncated,
cap,
unit,
}
}
#[must_use]
pub fn worst_severity(&self) -> Option<Severity> {
self.anomalies.iter().map(Deviation::severity).max()
}
#[must_use]
pub fn has_fatal(&self, policy: crate::ReadPolicy) -> bool {
self.anomalies.iter().any(|a| policy.is_fatal(a.severity()))
}
#[must_use]
pub fn to_report(&self) -> FindingReport {
let project = |met: &[A]| met.iter().map(|a| a.to_finding(self.unit)).collect();
FindingReport::new(project(&self.anomalies), self.truncated, self.cap)
.with_source_failures(project(&self.source_failures))
}
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) const NOT_CLEANLY_UNMOUNTED: &str =
"the filesystem was not cleanly unmounted, so its metadata may not describe its contents";
#[cfg(any(feature = "fat", feature = "exfat"))]
pub(crate) const MEDIUM_FAILURE: &str =
"a driver recorded a failure of the medium this filesystem is on";
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) struct Findings<A> {
anomalies: Vec<A>,
cap: usize,
truncated: bool,
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
impl<A> Findings<A> {
pub(crate) fn new(cap: usize) -> Self {
Self {
anomalies: Vec::new(),
cap,
truncated: false,
}
}
pub(crate) fn push(&mut self, anomaly: A) {
if self.anomalies.len() >= self.cap {
self.truncated = true;
} else {
self.anomalies.push(anomaly);
}
}
pub(crate) fn is_full(&mut self) -> bool {
if self.anomalies.len() >= self.cap {
self.truncated = true;
}
self.truncated
}
#[cfg(feature = "exfat")]
pub(crate) fn extend_from(&mut self, other: &Findings<A>)
where
A: Clone,
{
for anomaly in &other.anomalies {
if self.is_full() {
break;
}
self.anomalies.push(anomaly.clone());
}
self.truncated |= other.truncated;
}
#[cfg(feature = "exfat")]
pub(crate) fn into_parts(self) -> (Vec<A>, bool) {
(self.anomalies, self.truncated)
}
#[cfg(all(test, feature = "exfat"))]
pub(crate) fn held(&self) -> (usize, bool) {
(self.anomalies.len(), self.truncated)
}
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
impl<A: Deviation> Findings<A> {
pub(crate) fn into_report(self, unit: u32) -> ScanReport<A> {
ScanReport::new(self.anomalies, self.truncated, self.cap, unit)
}
#[cfg(any(feature = "fat", feature = "exfat"))]
pub(crate) fn met_source_failure(&self) -> bool {
self.anomalies.iter().any(Deviation::is_source_failure)
}
}
fn push_finding_json(mut o: Object<'_>, f: &Finding) {
let Finding {
severity,
family,
category,
offset,
coordinates,
detail,
} = f;
o.str("severity", severity.as_str());
o.str("family", family.as_str());
o.str("category", category);
if let Some(offset) = offset {
o.u64("offset", *offset);
}
push_coordinates_json(o.obj("location"), coordinates);
o.str("detail", detail);
o.end();
}
fn push_coordinates_json(mut o: Object<'_>, coordinates: &[Coordinate]) {
for (name, value) in coordinates {
o.u64(name, *value);
}
o.end();
}
fn location_compact(f: &Finding) -> String {
if f.coordinates.is_empty() {
return "-".to_string();
}
f.coordinates
.iter()
.map(|(name, value)| format!("{name} {value}"))
.collect::<Vec<_>>()
.join(" ")
}
fn sarif_level(severity: Severity) -> &'static str {
match severity {
Severity::Structural | Severity::Integrity => "error",
Severity::Conformance => "warning",
Severity::Cosmetic => "note",
}
}
fn push_sarif_rules(mut rules: Array<'_>, findings: &[Finding]) {
let mut seen: Vec<String> = Vec::new();
for f in findings {
let id = rule_id(f);
if seen.contains(&id) {
continue;
}
let mut rule = rules.obj();
rule.str("id", &id);
rule.str("name", &id);
let mut description = rule.obj("shortDescription");
description.str(
"text",
&format!("{} {} finding", f.family.as_str(), f.category),
);
description.end();
rule.end();
seen.push(id);
}
rules.end();
}
fn rule_id(f: &Finding) -> String {
format!("{}/{}", f.family.as_str(), f.category)
}
fn push_sarif_result(mut result: Object<'_>, f: &Finding, artifact_uri: Option<&str>) {
result.str("ruleId", &rule_id(f));
result.str("level", sarif_level(f.severity));
let mut message = result.obj("message");
message.str("text", &f.detail);
message.end();
let has_address = !f.coordinates.is_empty();
if artifact_uri.is_some() || f.offset.is_some() || has_address {
let mut locations = result.arr("locations");
let mut location = locations.obj();
if artifact_uri.is_some() || f.offset.is_some() {
let mut physical = location.obj("physicalLocation");
if let Some(uri) = artifact_uri {
let mut artifact = physical.obj("artifactLocation");
artifact.str("uri", uri);
artifact.end();
}
if let Some(offset) = f.offset {
let mut address = physical.obj("address");
address.u64("absoluteAddress", offset);
address.end();
}
physical.end();
}
if has_address {
let mut logical = location.arr("logicalLocations");
let mut named = logical.obj();
named.str("fullyQualifiedName", &location_compact(f));
named.end();
logical.end();
}
location.end();
locations.end();
}
push_sarif_properties(result.obj("properties"), f);
result.end();
}
fn push_sarif_properties(mut o: Object<'_>, f: &Finding) {
o.str("severity", f.severity.as_str());
o.str("family", f.family.as_str());
o.str("category", &f.category);
if let Some(offset) = f.offset {
o.u64("offset", offset);
}
for (name, value) in &f.coordinates {
o.u64(name, *value);
}
o.end();
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "ext")]
fn finding(
severity: Severity,
category: &'static str,
coords: &[(&'static str, u64)],
) -> Finding {
Finding {
severity,
family: Family::Ext,
category: Cow::Borrowed(category),
offset: None,
coordinates: coords
.iter()
.map(|(n, v)| (Cow::Borrowed(*n), *v))
.collect(),
detail: "something is wrong".to_string(),
}
}
#[test]
fn severity_orders_least_to_most_serious() {
assert!(Severity::Cosmetic < Severity::Conformance);
assert!(Severity::Conformance < Severity::Integrity);
assert!(Severity::Integrity < Severity::Structural);
}
#[cfg(feature = "ext")]
#[test]
fn a_finding_renders_its_coordinates_as_a_location_object() {
let mut f = finding(Severity::Integrity, "group descriptor", &[("group", 3)]);
f.offset = Some(4096);
let report = FindingReport::new(vec![f], false, 10);
let json = report.to_json();
assert!(json.contains("\"family\":\"ext\""), "{json}");
assert!(json.contains("\"category\":\"group descriptor\""), "{json}");
assert!(json.contains("\"offset\":4096"), "{json}");
assert!(json.contains("\"location\":{\"group\":3}"), "{json}");
}
#[cfg(feature = "ext")]
#[test]
fn a_finding_with_no_coordinates_renders_an_empty_location() {
let report = FindingReport::new(
vec![finding(Severity::Cosmetic, "superblock", &[])],
false,
10,
);
assert!(report.to_json().contains("\"location\":{}"));
assert!(report.to_table().contains(" - "));
}
#[cfg(feature = "ext")]
#[test]
fn a_clean_report_is_clean_and_a_truncated_one_never_is() {
let clean = FindingReport::default();
assert!(clean.is_clean());
assert_eq!(clean.worst_severity(), None);
assert_eq!(clean.to_table(), "no findings\n");
let stopped = FindingReport::new(Vec::new(), true, 0);
assert!(!stopped.is_clean());
let table = stopped.to_table();
assert!(table.contains("truncated at 0 findings"), "{table}");
assert!(stopped.to_json().contains("\"truncated\":true"));
}
#[cfg(feature = "ext")]
#[test]
fn the_worst_severity_is_the_maximum() {
let report = FindingReport::new(
vec![
finding(Severity::Cosmetic, "superblock", &[]),
finding(Severity::Structural, "inode", &[("inode", 12)]),
finding(Severity::Conformance, "directory", &[]),
],
false,
10,
);
assert_eq!(report.worst_severity(), Some(Severity::Structural));
}
#[cfg(feature = "ext")]
#[test]
fn a_sarif_rule_is_named_for_the_family_as_well_as_the_subsystem() {
let report = FindingReport::new(
vec![finding(Severity::Structural, "directory", &[])],
false,
10,
);
let sarif = report.to_sarif(None);
assert!(sarif.contains("\"id\":\"ext/directory\""), "{sarif}");
assert!(sarif.contains("\"ruleId\":\"ext/directory\""), "{sarif}");
assert!(sarif.contains("\"level\":\"error\""), "{sarif}");
}
#[cfg(feature = "ext")]
#[test]
fn a_known_byte_offset_becomes_a_sarif_address() {
let mut f = finding(Severity::Integrity, "superblock", &[]);
f.offset = Some(1024);
let sarif = FindingReport::new(vec![f], false, 10).to_sarif(None);
assert!(sarif.contains("\"absoluteAddress\":1024"), "{sarif}");
}
#[cfg(feature = "ext")]
#[test]
fn a_detail_reaches_a_document_escaped() {
let mut f = finding(Severity::Structural, "directory", &[]);
f.detail = "a name \u{1b}[2J\u{202e} chose".to_string();
for document in [
FindingReport::new(vec![f.clone()], false, 10).to_json(),
FindingReport::new(vec![f], false, 10).to_sarif(None),
] {
assert!(document.contains(r"\u001b[2J\u202e chose"), "{document}");
assert!(!document.chars().any(char::is_control), "{document}");
}
}
}