Skip to main content

disk_forensic/
lib.rs

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