Skip to main content

vsc/
lib.rs

1//! # vsc-core — Windows Volume Shadow Copy (VSS) reader
2//!
3//! A panic-free decoder for the on-disk structures of Windows Volume Shadow Copy
4//! (VSS), the `[P^H]` disk-history substrate of the forensic fleet. Given a
5//! positioned `Read + Seek` over an NTFS **volume** (offset 0 = the NTFS boot
6//! sector), [`VssVolume::open`] reads the VSS volume header at byte offset
7//! `0x1E00`, walks the catalog of shadow-copy stores, and exposes each store's
8//! [`StoreInfo`] on demand.
9//!
10//! The reader stays pure: it decodes bytes into typed records and makes no
11//! forensic judgments (those live in the sibling `vsc-forensic` analyzer). It
12//! never loads the whole volume into memory — the real volumes are hundreds of
13//! gigabytes — and every multi-byte read is bounds-checked, so malformed input
14//! yields safe defaults or a typed [`VssError`], never a panic.
15//!
16//! Phase 1 (this crate) enumerates stores and decodes store information plus the
17//! typed diff-area records ([`BlockDescriptor`], [`StoreBlockRange`]). The
18//! copy-on-write block-reconstruction engine is Phase 2 and out of scope here.
19
20#![forbid(unsafe_code)]
21#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
22
23use std::collections::HashSet;
24use std::io::{Read, Seek, SeekFrom};
25
26pub mod block;
27mod bytes;
28pub mod catalog;
29pub mod error;
30pub mod guid;
31pub mod store;
32
33#[cfg(test)]
34mod tests;
35
36pub use block::{BlockDescriptor, BlockDescriptorFlags, StoreBlockRange};
37pub use catalog::{StoreDescriptor, VolumeHeader};
38pub use error::VssError;
39pub use guid::{format_guid, VSS_IDENTIFIER};
40pub use store::{AttributeFlags, StoreBlockHeader, StoreInfo};
41
42use catalog::{
43    catalog_next_block_offset, is_catalog_block, parse_catalog_entry, CatalogEntry, BLOCK_SIZE,
44    CATALOG_BLOCK_HEADER_LEN, CATALOG_ENTRY_LEN, MAX_CATALOG_BLOCKS, VSS_VOLUME_HEADER_OFFSET,
45};
46use store::{MAX_STORE_INFO_LEN, STORE_BLOCK_HEADER_LEN};
47
48/// A read-only view over the Volume Shadow Copy metadata of an NTFS volume.
49///
50/// Construct with [`VssVolume::open`] over a `Read + Seek` positioned at the
51/// start of the NTFS volume. The catalog of stores is read eagerly (it is
52/// small); each store's [`StoreInfo`] is read lazily via
53/// [`VssVolume::store_info`].
54#[derive(Debug)]
55pub struct VssVolume<R> {
56    reader: R,
57    volume_size: u64,
58    has_vss_header: bool,
59    catalog_offset: u64,
60    stores: Vec<StoreDescriptor>,
61}
62
63impl<R: Read + Seek> VssVolume<R> {
64    /// Open a VSS view over a positioned NTFS volume reader.
65    ///
66    /// Reads the volume header at `0x1E00`; if it carries the VSS identifier and
67    /// names a catalog, walks the catalog and enumerates the stores. A volume
68    /// with no VSS header (the header region is zeroed) opens successfully with
69    /// [`VssVolume::has_vss_header`] `== false` and zero stores.
70    ///
71    /// # Errors
72    /// Returns [`VssError::Io`] on an underlying read/seek failure.
73    pub fn open(mut reader: R) -> Result<Self, VssError> {
74        let volume_size = reader.seek(SeekFrom::End(0))?;
75
76        let mut has_vss_header = false;
77        let mut catalog_offset = 0u64;
78        if volume_size >= VSS_VOLUME_HEADER_OFFSET + CATALOG_BLOCK_HEADER_LEN as u64 {
79            reader.seek(SeekFrom::Start(VSS_VOLUME_HEADER_OFFSET))?;
80            let mut hdr = [0u8; CATALOG_BLOCK_HEADER_LEN];
81            reader.read_exact(&mut hdr)?;
82            let vh = VolumeHeader::parse(&hdr);
83            has_vss_header = vh.has_vss_identifier;
84            catalog_offset = vh.catalog_offset;
85        }
86
87        let stores = if has_vss_header && catalog_offset != 0 {
88            walk_catalog(&mut reader, catalog_offset, volume_size)?
89        } else {
90            Vec::new()
91        };
92
93        Ok(VssVolume {
94            reader,
95            volume_size,
96            has_vss_header,
97            catalog_offset,
98            stores,
99        })
100    }
101
102    /// Whether the volume carries a VSS volume header at `0x1E00`.
103    #[must_use]
104    pub fn has_vss_header(&self) -> bool {
105        self.has_vss_header
106    }
107
108    /// The enumerated shadow-copy store descriptors.
109    #[must_use]
110    pub fn stores(&self) -> &[StoreDescriptor] {
111        &self.stores
112    }
113
114    /// The number of enumerated shadow-copy stores.
115    #[must_use]
116    pub fn store_count(&self) -> usize {
117        self.stores.len()
118    }
119
120    /// The catalog offset from the volume header (0 when there is no catalog).
121    #[must_use]
122    pub fn catalog_offset(&self) -> u64 {
123        self.catalog_offset
124    }
125
126    /// The total size of the underlying volume, in bytes.
127    #[must_use]
128    pub fn volume_size(&self) -> u64 {
129        self.volume_size
130    }
131
132    /// Read and decode the store information for store `index`.
133    ///
134    /// # Errors
135    /// - [`VssError::StoreIndexOutOfRange`] if `index` is past the last store.
136    /// - [`VssError::StoreInfoUnavailable`] if the store has no type-0x03
137    ///   catalog pointer.
138    /// - [`VssError::StoreOffsetOutOfBounds`] if the store-header offset runs
139    ///   past the end of the volume.
140    /// - [`VssError::Io`] on an underlying read/seek failure.
141    pub fn store_info(&mut self, index: usize) -> Result<StoreInfo, VssError> {
142        let count = self.stores.len();
143        let header_off = self
144            .stores
145            .get(index)
146            .ok_or(VssError::StoreIndexOutOfRange { index, count })?
147            .store_header_offset
148            .ok_or(VssError::StoreInfoUnavailable { index })?;
149
150        // Range-check the store-header offset before seeking: it comes straight
151        // from the catalog and must not be trusted.
152        let header_end = header_off
153            .checked_add(STORE_BLOCK_HEADER_LEN as u64)
154            .filter(|end| *end <= self.volume_size)
155            .ok_or(VssError::StoreOffsetOutOfBounds {
156                index,
157                offset: header_off,
158                volume_size: self.volume_size,
159            })?;
160
161        self.reader.seek(SeekFrom::Start(header_off))?;
162        let mut hbuf = [0u8; STORE_BLOCK_HEADER_LEN];
163        self.reader.read_exact(&mut hbuf)?;
164        let header = StoreBlockHeader::parse(&hbuf);
165
166        // Cap the store-information read against a lying size field and the tail
167        // of the volume.
168        let remaining = self.volume_size.saturating_sub(header_end) as usize;
169        let want = usize::try_from(header.store_information_size).unwrap_or(usize::MAX);
170        let info_len = want.min(MAX_STORE_INFO_LEN).min(remaining);
171        let mut ibuf = vec![0u8; info_len];
172        self.reader.read_exact(&mut ibuf)?;
173        Ok(StoreInfo::parse(&ibuf))
174    }
175}
176
177/// Walk the catalog block chain starting at `first`, collecting every snapshot
178/// descriptor and attaching each store-header offset from the paired type-0x03
179/// entry.
180///
181/// The walk is bounded three ways against a corrupt or adversarial catalog: a
182/// visited-set breaks any offset cycle, [`MAX_CATALOG_BLOCKS`] caps the chain
183/// length, and every block is range-checked against the volume before it is
184/// read.
185fn walk_catalog<R: Read + Seek>(
186    reader: &mut R,
187    first: u64,
188    volume_size: u64,
189) -> Result<Vec<StoreDescriptor>, VssError> {
190    let mut stores: Vec<StoreDescriptor> = Vec::new();
191    let mut visited: HashSet<u64> = HashSet::new();
192    let mut next = first;
193    let mut blocks = 0usize;
194
195    while next != 0 && blocks < MAX_CATALOG_BLOCKS {
196        if !visited.insert(next) {
197            break; // cycle
198        }
199        match next.checked_add(BLOCK_SIZE as u64) {
200            Some(end) if end <= volume_size => {}
201            _ => break, // out of range / overflow
202        }
203
204        reader.seek(SeekFrom::Start(next))?;
205        let mut block = vec![0u8; BLOCK_SIZE];
206        reader.read_exact(&mut block)?;
207        if !is_catalog_block(&block) {
208            break;
209        }
210
211        let mut off = CATALOG_BLOCK_HEADER_LEN;
212        while off + CATALOG_ENTRY_LEN <= BLOCK_SIZE {
213            match parse_catalog_entry(&block[off..off + CATALOG_ENTRY_LEN]) {
214                CatalogEntry::Snapshot(descriptor) => stores.push(descriptor),
215                CatalogEntry::StorePointer {
216                    store_id,
217                    store_header_offset,
218                } => {
219                    if let Some(descriptor) = stores
220                        .iter_mut()
221                        .rev()
222                        .find(|d| d.store_id == store_id && d.store_header_offset.is_none())
223                    {
224                        descriptor.store_header_offset = Some(store_header_offset);
225                    }
226                }
227                CatalogEntry::Empty | CatalogEntry::Other => {}
228            }
229            off += CATALOG_ENTRY_LEN;
230        }
231
232        blocks += 1;
233        next = catalog_next_block_offset(&block);
234    }
235
236    Ok(stores)
237}