#![forbid(unsafe_code)]
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
pub use forensicnomicon::report::Severity;
use forensicnomicon::report::{Evidence, Finding, Location, Observation, Source};
use refs_core::{BootSector, Checkpoint, MetaBlock, REFS_METADATA_PAGE_SIZE};
const MSB_SIGNATURE: &[u8; 4] = b"MSB+";
const SELF_BLOCK_OFFSET: usize = 0x20;
const TABLE_ID_OFFSET: usize = 72;
const CLUSTER_SIZE: usize = 4096;
const REFS_ROOT_DIRECTORY_TABLE_ID: u64 = 0x600;
const SUPERBLOCK_BLOCK_NUMBER: u64 = 30;
const MAX_SANE_CLUSTER_SIZE: u64 = 1 << 20;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnomalyKind {
BootSignatureInvalid {
found: [u8; 8],
},
MetadataCrcMismatch {
structure: &'static str,
offset: u64,
checksum_type: u8,
},
SelfBlockMismatch {
structure: &'static str,
recorded: u64,
expected: u64,
offset: u64,
},
CheckpointDivergence {
reason: &'static str,
checkpoints: Vec<u64>,
},
OrphanedOrUnresolved {
block: u64,
referrer: &'static str,
},
ImpossibleGeometry {
field: &'static str,
value: u64,
limit: u64,
},
}
impl AnomalyKind {
#[must_use]
pub fn severity(&self) -> Severity {
match self {
AnomalyKind::BootSignatureInvalid { .. }
| AnomalyKind::MetadataCrcMismatch { .. }
| AnomalyKind::SelfBlockMismatch { .. }
| AnomalyKind::CheckpointDivergence { .. }
| AnomalyKind::ImpossibleGeometry { .. } => Severity::High,
AnomalyKind::OrphanedOrUnresolved { .. } => Severity::Medium,
}
}
#[must_use]
pub fn code(&self) -> &'static str {
match self {
AnomalyKind::BootSignatureInvalid { .. } => "REFS-BOOT-SIGNATURE-INVALID",
AnomalyKind::MetadataCrcMismatch { .. } => "REFS-METADATA-CRC-MISMATCH",
AnomalyKind::SelfBlockMismatch { .. } => "REFS-SELF-BLOCK-MISMATCH",
AnomalyKind::CheckpointDivergence { .. } => "REFS-CHECKPOINT-DIVERGENCE",
AnomalyKind::OrphanedOrUnresolved { .. } => "REFS-ORPHANED-OR-UNRESOLVED",
AnomalyKind::ImpossibleGeometry { .. } => "REFS-IMPOSSIBLE-GEOMETRY",
}
}
#[must_use]
pub fn note(&self) -> String {
match self {
AnomalyKind::BootSignatureInvalid { found } => format!(
"boot VBR signature at offset 3 = {found:02x?} is not \"ReFS\\0\\0\\0\\0\" — the volume is not ReFS or the boot record was overwritten"
),
AnomalyKind::MetadataCrcMismatch {
structure,
offset,
checksum_type,
} => format!(
"{structure} at byte {offset}: stored CRC (type {checksum_type}) does not verify over its known coverage range — consistent with corruption or post-write tampering"
),
AnomalyKind::SelfBlockMismatch {
structure,
recorded,
expected,
offset,
} => format!(
"{structure} at byte {offset}: self-recorded block number {recorded} does not equal its location's block number {expected} — consistent with a relocated, tampered, or misparsed page"
),
AnomalyKind::CheckpointDivergence {
reason,
checkpoints,
} => format!(
"checkpoint set {checkpoints:?}: {reason} — consistent with a torn or tampered checkpoint"
),
AnomalyKind::OrphanedOrUnresolved { block, referrer } => format!(
"{referrer} references virtual block {block} which resolves to no resident physical page — a dangling or corrupt reference (recovery lead)"
),
AnomalyKind::ImpossibleGeometry {
field,
value,
limit,
} => format!(
"geometry field {field} = {value} exceeds the sane bound {limit} for this image — consistent with corruption or an allocation-bomb"
),
}
}
fn evidence(&self) -> Vec<Evidence> {
match self {
AnomalyKind::BootSignatureInvalid { found } => vec![Evidence {
field: "boot_signature".to_string(),
value: format!("{found:02x?}"),
location: Some(Location::ByteOffset(3)),
}],
AnomalyKind::MetadataCrcMismatch {
structure,
offset,
checksum_type,
} => vec![Evidence {
field: "metadata_crc".to_string(),
value: format!("{structure} checksum type {checksum_type}"),
location: Some(Location::ByteOffset(*offset)),
}],
AnomalyKind::SelfBlockMismatch {
structure,
recorded,
expected,
offset,
} => vec![Evidence {
field: "self_block_number".to_string(),
value: format!("{structure} recorded={recorded} expected={expected}"),
location: Some(Location::ByteOffset(*offset)),
}],
AnomalyKind::CheckpointDivergence {
reason,
checkpoints,
} => vec![Evidence {
field: "checkpoints".to_string(),
value: format!("{checkpoints:?}: {reason}"),
location: None,
}],
AnomalyKind::OrphanedOrUnresolved { block, referrer } => vec![Evidence {
field: "unresolved_block".to_string(),
value: format!("{referrer} -> {block}"),
location: Some(Location::Other {
space: "refs:vblock".to_string(),
value: *block,
}),
}],
AnomalyKind::ImpossibleGeometry {
field,
value,
limit,
} => vec![Evidence {
field: (*field).to_string(),
value: format!("{value} (limit {limit})"),
location: None,
}],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Anomaly {
pub severity: Severity,
pub code: &'static str,
pub kind: AnomalyKind,
pub note: String,
}
impl Anomaly {
#[must_use]
pub fn new(kind: AnomalyKind) -> Self {
Anomaly {
severity: kind.severity(),
code: kind.code(),
note: kind.note(),
kind,
}
}
}
impl Observation for Anomaly {
fn severity(&self) -> Option<Severity> {
Some(self.severity)
}
fn code(&self) -> &'static str {
self.code
}
fn note(&self) -> String {
self.note.clone()
}
fn evidence(&self) -> Vec<Evidence> {
self.kind.evidence()
}
}
#[must_use]
pub fn audit_image(image: &[u8]) -> Vec<Anomaly> {
let mut out = Vec::new();
let Ok(boot) = BootSector::parse(image) else {
let mut found = [0u8; 8];
if let Some(s) = image.get(3..11) {
found.copy_from_slice(s);
}
if &found != refs_core::REFS_SIGNATURE {
out.push(Anomaly::new(AnomalyKind::BootSignatureInvalid { found }));
}
return out;
};
let cluster = boot.cluster_size();
if cluster == 0 || cluster > MAX_SANE_CLUSTER_SIZE {
out.push(Anomaly::new(AnomalyKind::ImpossibleGeometry {
field: "cluster_size",
value: cluster,
limit: MAX_SANE_CLUSTER_SIZE,
}));
return out;
}
let sb_off = boot.superblock_offset();
if let Some(page) = header_at(image, sb_off) {
if page.get(0..4) == Some(refs_core::SUPB_SIGNATURE.as_slice()) {
let recorded = le_u64(page, SELF_BLOCK_OFFSET);
if recorded != SUPERBLOCK_BLOCK_NUMBER {
out.push(Anomaly::new(AnomalyKind::SelfBlockMismatch {
structure: "SUPB",
recorded,
expected: SUPERBLOCK_BLOCK_NUMBER,
offset: sb_off,
}));
}
check_checkpoints(&mut out, page);
}
}
sweep_resident_self_blocks(&mut out, image, cluster as usize);
out
}
fn check_checkpoints(out: &mut Vec<Anomaly>, superblock_page: &[u8]) {
if let Ok(checkpoints) = Checkpoint::locations_from_superblock(superblock_page) {
if checkpoints.is_empty() {
out.push(Anomaly::new(AnomalyKind::CheckpointDivergence {
reason: "the superblock names zero checkpoint copies (a live volume keeps at least one)",
checkpoints,
}));
}
}
}
fn sweep_resident_self_blocks(out: &mut Vec<Anomaly>, image: &[u8], cluster_size: usize) {
if cluster_size == 0 {
return; }
let clusters = image.len() / cluster_size;
let resident_ceiling = clusters as u64;
for c in 0..clusters {
let off = c * cluster_size;
let Some(page) = block_at(image, off as u64) else {
break; };
if page.get(0..4) != Some(MSB_SIGNATURE.as_slice()) {
continue;
}
let self_block = le_u64(page, SELF_BLOCK_OFFSET);
if self_block < resident_ceiling && self_block != c as u64 {
out.push(Anomaly::new(AnomalyKind::SelfBlockMismatch {
structure: "MSB+",
recorded: self_block,
expected: c as u64,
offset: off as u64,
}));
}
}
}
#[must_use]
pub fn audit_crc_range(
block: &[u8],
offset: u64,
start: usize,
end: usize,
stored: u32,
) -> Option<Anomaly> {
match MetaBlock::verify_crc32c(block, start, end, stored) {
Some(true) | None => None,
Some(false) => Some(Anomaly::new(AnomalyKind::MetadataCrcMismatch {
structure: "caller-supplied range",
offset,
checksum_type: 1,
})),
}
}
#[must_use]
pub fn audit_findings(image: &[u8], scope: &str) -> Vec<Finding> {
let source = Source {
analyzer: "refs-forensic".to_string(),
scope: scope.to_string(),
version: None,
};
audit_image(image)
.iter()
.map(|a| a.to_finding(source.clone()))
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StalePage {
pub self_block: u64,
pub table_id: u64,
pub offset: u64,
pub entries: Vec<String>,
}
#[must_use]
pub fn recover_residue(image: &[u8]) -> Vec<StalePage> {
let mut current: Vec<(u64, u64, Vec<String>)> = Vec::new(); for (off, page) in resident_msb_pages(image) {
let table_id = le_u64(page, TABLE_ID_OFFSET);
if table_id != REFS_ROOT_DIRECTORY_TABLE_ID {
continue;
}
let self_block = le_u64(page, SELF_BLOCK_OFFSET);
let _ = off;
match current.iter_mut().find(|(t, _, _)| *t == table_id) {
Some(entry) if self_block > entry.1 => {
entry.1 = self_block;
entry.2 = carve_directory_entries(page);
}
Some(_) => {}
None => current.push((table_id, self_block, carve_directory_entries(page))),
}
}
let mut out = Vec::new();
for (off, page) in resident_msb_pages(image) {
let table_id = le_u64(page, TABLE_ID_OFFSET);
if table_id != REFS_ROOT_DIRECTORY_TABLE_ID {
continue;
}
let self_block = le_u64(page, SELF_BLOCK_OFFSET);
let Some((_, cur_block, cur_entries)) = current.iter().find(|(t, _, _)| *t == table_id)
else {
continue; };
if self_block >= *cur_block {
continue;
}
let dropped: Vec<String> = carve_directory_entries(page)
.into_iter()
.filter(|name| !cur_entries.contains(name))
.collect();
if dropped.is_empty() {
continue;
}
out.push(StalePage {
self_block,
table_id,
offset: off,
entries: dropped,
});
}
out
}
fn resident_msb_pages(image: &[u8]) -> impl Iterator<Item = (u64, &[u8])> + '_ {
let clusters = image.len() / CLUSTER_SIZE;
(0..clusters).filter_map(move |c| {
let off = c * CLUSTER_SIZE;
let page = block_at(image, off as u64)?;
if page.get(0..4) == Some(MSB_SIGNATURE.as_slice()) {
Some((off as u64, page))
} else {
None
}
})
}
fn carve_directory_entries(page: &[u8]) -> Vec<String> {
let Ok(node) = refs_core::parse_directory(page) else {
return Vec::new(); };
node.into_iter().map(|e| e.name).collect()
}
fn block_at(image: &[u8], offset: u64) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
let end = start.checked_add(REFS_METADATA_PAGE_SIZE)?;
image.get(start..end)
}
fn header_at(image: &[u8], offset: u64) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
image.get(start..)
}
fn le_u64(d: &[u8], o: usize) -> u64 {
d.get(o..o.saturating_add(8))
.and_then(|b| <[u8; 8]>::try_from(b).ok())
.map_or(0, u64::from_le_bytes)
}
#[cfg(test)]
mod unit {
use super::{block_at, le_u64, Anomaly, AnomalyKind};
use crate::Severity;
use forensicnomicon::report::{Observation, Source};
use refs_core::REFS_METADATA_PAGE_SIZE;
#[test]
fn every_anomaly_kind_has_code_severity_note_evidence_and_finding() {
let kinds = [
AnomalyKind::BootSignatureInvalid { found: [0u8; 8] },
AnomalyKind::MetadataCrcMismatch {
structure: "SUPB",
offset: 0x1e000,
checksum_type: 2,
},
AnomalyKind::SelfBlockMismatch {
structure: "MSB+",
recorded: 999,
expected: 3,
offset: 12288,
},
AnomalyKind::CheckpointDivergence {
reason: "torn",
checkpoints: vec![157_156, 1_885_500],
},
AnomalyKind::OrphanedOrUnresolved {
block: 34_494_087_168,
referrer: "directory child",
},
AnomalyKind::ImpossibleGeometry {
field: "cluster_size",
value: u64::MAX,
limit: 1 << 20,
},
];
let source = Source {
analyzer: "refs-forensic".to_string(),
scope: "unit".to_string(),
version: None,
};
for kind in kinds {
let a = Anomaly::new(kind);
assert!(
a.code.starts_with("REFS-"),
"code is scheme-prefixed: {}",
a.code
);
assert!(!a.note.is_empty(), "note is non-empty for {}", a.code);
assert!(
!a.kind.evidence().is_empty(),
"evidence is non-empty for {}",
a.code
);
let sev = a.severity;
assert!(matches!(sev, Severity::High | Severity::Medium));
let f = a.to_finding(source.clone());
assert_eq!(f.code, a.code);
assert_eq!(f.source.analyzer, "refs-forensic");
assert_eq!(f.severity, Some(sev));
}
}
#[test]
fn le_u64_yields_zero_out_of_range() {
assert_eq!(le_u64(&[0, 0, 0], 0), 0);
assert_eq!(le_u64(&[1, 0, 0, 0, 0, 0, 0, 0], 0), 1);
}
#[test]
fn block_at_requires_a_full_page() {
let short = vec![0u8; REFS_METADATA_PAGE_SIZE - 1];
assert!(block_at(&short, 0).is_none());
let full = vec![0u8; REFS_METADATA_PAGE_SIZE];
assert!(block_at(&full, 0).is_some());
assert!(block_at(&full, 1).is_none());
}
}