Skip to main content

aff4_image/
logical_metadata.rs

1//! Caller-owned logical metadata. Original paths are never ZIP storage names.
2use super::*;
3use base64::Engine;
4
5/// Metadata captured from a source, independent of the examiner's filesystem.
6#[derive(Debug, Clone, Default)]
7pub struct LogicalMetadata {
8    /// Exact original path bytes. Non-UTF8/control bytes receive a raw-name field.
9    pub path: Vec<u8>,
10    /// Previously added folder, or None for an acquisition root.
11    pub parent: Option<String>,
12    /// Creation time in nanoseconds since the Unix epoch.
13    pub created: Option<i128>,
14    /// Last content modification in nanoseconds since the Unix epoch.
15    pub modified: Option<i128>,
16    /// Last access in nanoseconds since the Unix epoch.
17    pub accessed: Option<i128>,
18    /// Last metadata change in nanoseconds since the Unix epoch.
19    pub changed: Option<i128>,
20    /// Native Unix mode bits when available.
21    pub mode: Option<u32>,
22}
23
24/// Descriptive provenance, not proof of origin or a digital signature.
25#[derive(Debug, Clone, Default)]
26pub struct CaseMetadata {
27    /// Case identifier supplied by the operator.
28    pub case_number: String,
29    /// Evidence identifier supplied by the operator.
30    pub evidence_number: String,
31    /// Examiner name supplied by the operator.
32    pub examiner: String,
33    /// Collection notes, including source/snapshot constraints.
34    pub notes: String,
35}
36
37/// Relationship of a non-primary file stream to its parent.
38#[derive(Debug, Clone, Copy)]
39pub enum SubstreamKind {
40    /// NTFS alternate data stream.
41    AlternateDataStream,
42    /// Filesystem extended attribute, including ACL bytes supplied by callers.
43    ExtendedAttribute,
44}
45
46fn literal(value: &str) -> String {
47    oxrdf::Literal::new_simple_literal(value).to_string()
48}
49fn normalized(bytes: &[u8]) -> (String, Option<String>) {
50    if let Ok(value) = std::str::from_utf8(bytes)
51        && !value.chars().any(char::is_control)
52    {
53        return (value.into(), None);
54    }
55    let mut text = String::new();
56    for byte in bytes {
57        if *byte < 32 || *byte >= 127 || *byte == b'%' {
58            text.push_str(&format!("%{byte:02X}"));
59        } else {
60            text.push(*byte as char);
61        }
62    }
63    (
64        text,
65        Some(base64::engine::general_purpose::STANDARD.encode(bytes)),
66    )
67}
68
69impl LogicalMetadata {
70    fn properties(&self) -> Result<(String, String)> {
71        if self.path.is_empty() {
72            return Err(malformed("empty original path"));
73        }
74        let name = {
75            self.path
76                .rsplit(|b| *b == b'/' || *b == b'\\')
77                .next()
78                .unwrap()
79        };
80        let (path, raw_path) = normalized(&self.path);
81        let (_, raw_name) = normalized(name);
82        let mut properties = format!("l:originalPathName {};", literal(&path));
83        for (key, value) in [("originalPathNameRaw", raw_path), ("fileNameRaw", raw_name)] {
84            if let Some(value) = value {
85                properties.push_str(&format!(
86                    " l:{key} {}^^<http://www.w3.org/2001/XMLSchema#base64Binary>;",
87                    literal(&value)
88                ));
89            }
90        }
91        for (key, value) in [
92            ("birthTime", self.created),
93            ("lastWritten", self.modified),
94            ("lastAccessed", self.accessed),
95            ("recordChanged", self.changed),
96        ] {
97            if let Some(value) = value {
98                let time = time::OffsetDateTime::from_unix_timestamp_nanos(value)
99                    .map_err(|_| malformed("timestamp outside supported calendar"))?
100                    .format(&time::format_description::well_known::Rfc3339)
101                    .map_err(|_| malformed("timestamp cannot be represented as RFC3339"))?;
102                properties.push_str(&format!(
103                    " a:{key} {}^^<http://www.w3.org/2001/XMLSchema#dateTime>;",
104                    literal(&time)
105                ));
106            }
107        }
108        if let Some(mode) = self.mode {
109            properties.push_str(&format!(" l:fileMode {mode};"));
110        }
111        Ok((path, properties))
112    }
113}
114
115impl Writer {
116    pub(super) fn logical_parent(&self, parent: Option<&str>) -> Result<()> {
117        self.healthy()?;
118        if self.profile != Profile::Logical {
119            return Err(Error::Unsupported(
120                "logical metadata in physical profile".into(),
121            ));
122        }
123        if parent.is_some_and(|p| !self.folders.contains_key(p)) {
124            return Err(malformed("parent is not a writer-owned folder"));
125        }
126        Ok(())
127    }
128
129    fn register_child(&mut self, parent: Option<&str>, id: &str) {
130        if let Some(parent) = parent {
131            self.folders.get_mut(parent).unwrap().1.push(id.into());
132        } else {
133            self.roots.push(id.into());
134        }
135    }
136
137    /// Adds a folder and returns its stable resource identifier, preserving empties.
138    pub fn add_folder(&mut self, metadata: &LogicalMetadata) -> Result<String> {
139        self.logical_parent(metadata.parent.as_deref())?;
140        let (path, properties) = metadata.properties()?;
141        let id = identifier();
142        let name = {
143            metadata
144                .path
145                .rsplit(|b| *b == b'/' || *b == b'\\')
146                .next()
147                .unwrap()
148        };
149        let (name, _) = normalized(name);
150        let properties = format!(
151            "a a:Folder, a:FolderImage, a:Image; a:fileName {}; a:originalFileName {}; {properties} a:stored <{}>",
152            literal(&name),
153            literal(&path),
154            self.volume
155        );
156        self.register_child(metadata.parent.as_deref(), &id);
157        self.folders.insert(id.clone(), (properties, Vec::new()));
158        Ok(id)
159    }
160
161    /// Acquires a file and preserves timestamps, mode, raw names, and its parent.
162    pub fn add_file_with_metadata(
163        &mut self,
164        metadata: &LogicalMetadata,
165        size: u64,
166        input: &mut impl Read,
167        progress: impl FnMut(u64, u64) -> ControlFlow<()>,
168    ) -> Result<String> {
169        self.logical_parent(metadata.parent.as_deref())?;
170        let (path, properties) = metadata.properties()?;
171        let id = self.add_file_impl(&path, size, input, progress, &properties)?;
172        self.register_child(metadata.parent.as_deref(), &id);
173        Ok(id)
174    }
175
176    /// Records source/operator context as supplied, without claiming authentication.
177    pub fn add_case_metadata(&mut self, metadata: &CaseMetadata) -> Result<String> {
178        self.healthy()?;
179        let id = identifier();
180        self.metadata.push_str(&format!("<{id}> a a:CaseDetails; a:target <{}>; a:caseNumber {}; a:evidenceNumber {}; a:examiner {}; a:notes {} .\n", self.volume, literal(&metadata.case_number), literal(&metadata.evidence_number), literal(&metadata.examiner), literal(&metadata.notes)));
181        Ok(id)
182    }
183
184    /// Preserves a named substream's bytes. Callers capture ADS/xattrs/ACLs using
185    /// source-specific APIs; this method does not infer them from a host path.
186    pub fn add_substream(
187        &mut self,
188        parent: &str,
189        name: &[u8],
190        kind: SubstreamKind,
191        bytes: &[u8],
192    ) -> Result<String> {
193        self.healthy()?;
194        if !self.streams.iter().any(|s| s.id == parent) && !self.folders.contains_key(parent) {
195            return Err(malformed("substream parent is not writer-owned"));
196        }
197        if bytes.len() > 1024 {
198            return Err(Error::Unsupported(
199                "inline substreams are limited to 1 KiB; use a file stream for larger attributes"
200                    .into(),
201            ));
202        }
203        let id = identifier();
204        let (name, raw) = normalized(name);
205        let raw = raw
206            .map(|s| {
207                format!(
208                    "l:fileNameRaw {}^^<http://www.w3.org/2001/XMLSchema#base64Binary>;",
209                    literal(&s)
210                )
211            })
212            .unwrap_or_default();
213        let content = base64::engine::general_purpose::STANDARD.encode(bytes);
214        self.metadata.push_str(&format!("<{id}> a a:FileSubStream, a:Image; a:target <{parent}>; a:name {}; {raw} a:size {}; l:dataStream {}^^<http://www.w3.org/2001/XMLSchema#base64Binary>; a:hash {}^^a:SHA256 .\n", literal(&name), bytes.len(), literal(&content), literal(&hex(&Sha256::digest(bytes)))));
215        let property = match kind {
216            SubstreamKind::AlternateDataStream => "alternateDataStream",
217            SubstreamKind::ExtendedAttribute => "extendedAttribute",
218        };
219        // RDF permits a subject to reappear. Never rewrite its previously emitted metadata.
220        self.metadata
221            .push_str(&format!("<{parent}> l:{property} <{id}> .\n"));
222        Ok(id)
223    }
224
225    /// Sets the source path separator recorded with acquisition roots.
226    pub fn set_path_separator(&mut self, separator: char) -> Result<()> {
227        self.healthy()?;
228        if !matches!(separator, '/' | '\\') {
229            return Err(malformed("unsupported path separator"));
230        }
231        self.path_separator = separator;
232        Ok(())
233    }
234
235    pub(super) fn finish_logical_metadata(&mut self) {
236        for (id, (properties, children)) in &self.folders {
237            self.metadata.push_str(&format!("<{id}> {properties}"));
238            for child in children {
239                self.metadata.push_str(&format!("; a:child <{child}>"));
240            }
241            self.metadata.push_str(" .\n");
242        }
243        if !self.roots.is_empty() {
244            self.metadata.push_str(&format!(
245                "<{}> a a:LogicalAcquisitionTask; l:pathSeparator {}",
246                identifier(),
247                literal(&self.path_separator.to_string())
248            ));
249            for root in &self.roots {
250                self.metadata
251                    .push_str(&format!("; a:filesystemRoot <{root}>"));
252            }
253            self.metadata.push_str(" .\n");
254        }
255    }
256}