Skip to main content

disk_forensic/
lib.rs

1//! # disk-forensic
2//!
3//! Point it at any disk image and it identifies the partitioning scheme — MBR,
4//! GPT, or Apple Partition Map — and dispatches to the matching forensic parser,
5//! so you get the right structural analysis without choosing a crate up front.
6//!
7//! It is pure orchestration: scheme detection comes from the
8//! [`forensicnomicon`](https://docs.rs/forensicnomicon) knowledge base, and every
9//! real parse is delegated to a sibling crate
10//! ([`mbr_forensic`], [`gpt_forensic`], [`apm_forensic`]). Like them, it works
11//! over any `Read + Seek`, so it composes with the container crates (`ewf`,
12//! `vhd`, …) for E01/VHD/VMDK evidence.
13//!
14//! ```no_run
15//! use std::fs::File;
16//! let mut img = File::open("disk.img")?;
17//! let size = img.metadata()?.len();
18//! match disk_forensic::analyse_disk(&mut img, size)? {
19//!     disk_forensic::DiskReport::Gpt(a) => println!("GPT, {} partitions", a.partitions.len()),
20//!     disk_forensic::DiskReport::Mbr(a) => println!("MBR, {} partitions", a.partitions.len()),
21//!     disk_forensic::DiskReport::Apm(a) => println!("APM, {} partitions", a.partitions.len()),
22//! }
23//! # Ok::<(), disk_forensic::Error>(())
24//! ```
25
26use std::io::{Read, Seek, SeekFrom};
27
28pub mod report;
29
30pub use forensicnomicon::partition_schemes::Scheme;
31
32/// Bytes read from the start (LBA 0 + LBA 1) for scheme detection.
33const BOOT_AREA_BYTES: usize = 1024;
34/// Upper bound on bytes the APM parser reads — the map lives in the first blocks.
35const APM_MAX_BYTES: usize = 1 << 20;
36
37/// Crate-level error.
38#[derive(Debug, thiserror::Error)]
39pub enum Error {
40    /// No MBR, GPT, or APM signature was found in the boot area (e.g. a disk
41    /// with a filesystem written directly to it, or unrecognised media).
42    #[error("unrecognised partitioning scheme (no MBR, GPT, or APM signature found)")]
43    UnknownScheme,
44    /// The Apple Partition Map parser failed.
45    #[error("APM analysis failed: {0}")]
46    Apm(#[from] apm_forensic::Error),
47    /// The MBR/GPT parser failed.
48    #[error("MBR/GPT analysis failed: {0}")]
49    Mbr(#[from] mbr_forensic::Error),
50    /// I/O failure while reading the disk image.
51    #[error("I/O error: {0}")]
52    Io(#[from] std::io::Error),
53}
54
55/// A full forensic analysis, tagged by the partitioning scheme that was found.
56///
57/// The `Gpt` variant carries the protective-MBR analysis with its parsed GPT
58/// (`.gpt` is `Some`); `Mbr` is a classic MBR with no GPT.
59#[derive(Debug)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize))]
61pub enum DiskReport {
62    /// Apple Partition Map.
63    Apm(apm_forensic::ApmAnalysis),
64    /// Classic Master Boot Record (no GPT).
65    Mbr(Box<mbr_forensic::MbrAnalysis>),
66    /// GUID Partition Table (protective MBR + parsed GPT).
67    Gpt(Box<mbr_forensic::MbrAnalysis>),
68}
69
70impl DiskReport {
71    /// The detected partitioning scheme.
72    #[must_use]
73    pub fn scheme(&self) -> Scheme {
74        match self {
75            DiskReport::Apm(_) => Scheme::Apm,
76            DiskReport::Mbr(_) => Scheme::Mbr,
77            DiskReport::Gpt(_) => Scheme::Gpt,
78        }
79    }
80
81    /// `true` when the analysis recorded at least one anomaly — the CLI's
82    /// non-zero exit signal for triage pipelines.
83    #[must_use]
84    pub fn has_anomalies(&self) -> bool {
85        match self {
86            DiskReport::Apm(a) => !a.anomalies.is_empty(),
87            DiskReport::Mbr(m) | DiskReport::Gpt(m) => !m.anomalies.is_empty(),
88        }
89    }
90}
91
92/// Detect the partitioning scheme of the disk behind `reader` and run the
93/// matching forensic parser.
94///
95/// `disk_size_bytes` bounds MBR/GPT gap and out-of-bounds analysis (pass the
96/// image length; `0` skips it). The reader is rewound before each parser runs.
97///
98/// # Errors
99/// [`Error::UnknownScheme`] when no scheme signature is present, [`Error::Apm`] /
100/// [`Error::Mbr`] when the chosen parser fails, or [`Error::Io`] on a read error.
101pub fn analyse_disk<R: Read + Seek>(
102    reader: &mut R,
103    disk_size_bytes: u64,
104) -> Result<DiskReport, Error> {
105    let boot = read_boot_area(reader)?;
106    match forensicnomicon::partition_schemes::detect_scheme(&boot) {
107        Some(Scheme::Apm) => Ok(DiskReport::Apm(apm_forensic::analyse_reader(
108            reader,
109            APM_MAX_BYTES,
110        )?)),
111        Some(Scheme::Gpt | Scheme::Mbr) => {
112            let mbr = mbr_forensic::analyse(reader, disk_size_bytes)?;
113            // The parser's own GPT detection is authoritative for the label: a
114            // protective MBR with a parseable GPT → Gpt, otherwise classic Mbr.
115            if mbr.gpt.is_some() {
116                Ok(DiskReport::Gpt(Box::new(mbr)))
117            } else {
118                Ok(DiskReport::Mbr(Box::new(mbr)))
119            }
120        }
121        None => Err(Error::UnknownScheme),
122    }
123}
124
125/// Read up to [`BOOT_AREA_BYTES`] from the start, tolerating short reads and EOF.
126fn read_boot_area<R: Read + Seek>(reader: &mut R) -> Result<Vec<u8>, std::io::Error> {
127    reader.seek(SeekFrom::Start(0))?;
128    let mut buf = vec![0u8; BOOT_AREA_BYTES];
129    let mut filled = 0;
130    while filled < BOOT_AREA_BYTES {
131        match reader.read(&mut buf[filled..]) {
132            Ok(0) => break,
133            Ok(n) => filled += n,
134            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
135            Err(e) => return Err(e),
136        }
137    }
138    buf.truncate(filled);
139    Ok(buf)
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use std::io::{Error as IoError, ErrorKind};
146
147    #[test]
148    fn error_display_covers_every_variant() {
149        assert!(Error::UnknownScheme.to_string().contains("unrecognised"));
150        let apm: Error = apm_forensic::Error::NotApm.into();
151        assert!(apm.to_string().contains("APM"));
152        let mbr: Error = mbr_forensic::Error::TooShort(1).into();
153        assert!(mbr.to_string().contains("MBR"));
154        let io: Error = IoError::other("boom").into();
155        assert!(io.to_string().contains("I/O"));
156    }
157
158    /// Yields `Interrupted` once (must be retried), then a hard error.
159    struct FlakyReader {
160        interrupted_once: bool,
161    }
162    impl Read for FlakyReader {
163        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
164            if self.interrupted_once {
165                Err(IoError::other("hard read failure"))
166            } else {
167                self.interrupted_once = true;
168                Err(IoError::from(ErrorKind::Interrupted))
169            }
170        }
171    }
172    impl Seek for FlakyReader {
173        fn seek(&mut self, _: SeekFrom) -> std::io::Result<u64> {
174            Ok(0)
175        }
176    }
177
178    #[test]
179    fn read_boot_area_retries_interrupted_then_propagates_error() {
180        let mut r = FlakyReader {
181            interrupted_once: false,
182        };
183        let err = read_boot_area(&mut r).unwrap_err();
184        assert_eq!(err.to_string(), "hard read failure");
185    }
186
187    #[test]
188    fn read_boot_area_stops_at_eof_on_short_image() {
189        // A sub-1024-byte reader hits the `Ok(0) => break` path.
190        let mut r = std::io::Cursor::new(vec![0u8; 16]);
191        let boot = read_boot_area(&mut r).unwrap();
192        assert_eq!(boot.len(), 16);
193    }
194}