1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::err::{Error, Result};
use crate::impl_serialize_for_bitflags;
use log::{trace, warn};
use winstructs::ntfs::mft_reference::MftReference;
use byteorder::{LittleEndian, ReadBytesExt};
use bitflags::bitflags;
use serde::ser::{self, SerializeStruct, Serializer};
use serde::Serialize;
use crate::attribute::header::{MftAttributeHeader, ResidentialHeader};
use crate::attribute::x30::{FileNameAttr, FileNamespace};
use crate::attribute::{MftAttribute, MftAttributeContent, MftAttributeType};
use std::io::Read;
use std::io::SeekFrom;
use std::io::{Cursor, Seek};
const SEQUENCE_NUMBER_STRIDE: usize = 512;
pub const ZERO_HEADER: &[u8; 4] = b"\x00\x00\x00\x00";
pub const BAAD_HEADER: &[u8; 4] = b"BAAD";
pub const FILE_HEADER: &[u8; 4] = b"FILE";
#[derive(Debug, Clone)]
pub struct MftEntry {
pub header: EntryHeader,
pub data: Vec<u8>,
pub valid_fixup: Option<bool>,
}
impl ser::Serialize for MftEntry {
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("MftEntry", 2)?;
let attributes: Vec<MftAttribute> = self.iter_attributes().filter_map(Result::ok).collect();
state.serialize_field("header", &self.header)?;
state.serialize_field("attributes", &attributes)?;
state.serialize_field("valid_fixup", &self.valid_fixup)?;
state.end()
}
}
#[derive(Serialize, Debug, Clone)]
pub struct EntryHeader {
pub signature: [u8; 4],
pub usa_offset: u16,
pub usa_size: u16,
pub metadata_transaction_journal: u64,
pub sequence: u16,
pub hard_link_count: u16,
pub first_attribute_record_offset: u16,
pub flags: EntryFlags,
pub used_entry_size: u32,
pub total_entry_size: u32,
pub base_reference: MftReference,
pub first_attribute_id: u16,
pub record_number: u64,
}
bitflags! {
pub struct EntryFlags: u16 {
const ALLOCATED = 0x01;
const INDEX_PRESENT = 0x02;
const UNKNOWN_1 = 0x04;
const UNKNOWN_2 = 0x08;
}
}
impl_serialize_for_bitflags! {EntryFlags}
impl EntryHeader {
pub fn from_reader<R: Read>(reader: &mut R, entry_id: u64) -> Result<EntryHeader> {
let mut signature = [0; 4];
reader.read_exact(&mut signature)?;
let header_is_valid = [FILE_HEADER, BAAD_HEADER, ZERO_HEADER].contains(&&signature);
if !header_is_valid {
return Err(Error::InvalidEntrySignature {
bad_sig: signature.to_vec(),
});
}
if signature == *ZERO_HEADER {
return Ok(Self::zero());
}
let usa_offset = reader.read_u16::<LittleEndian>()?;
let usa_size = reader.read_u16::<LittleEndian>()?;
let logfile_sequence_number = reader.read_u64::<LittleEndian>()?;
let sequence = reader.read_u16::<LittleEndian>()?;
let hard_link_count = reader.read_u16::<LittleEndian>()?;
let first_attribute_offset = reader.read_u16::<LittleEndian>()?;
let flags = EntryFlags::from_bits_truncate(reader.read_u16::<LittleEndian>()?);
let entry_size_real = reader.read_u32::<LittleEndian>()?;
let entry_size_allocated = reader.read_u32::<LittleEndian>()?;
let base_reference =
MftReference::from_reader(reader).map_err(Error::failed_to_read_mft_reference)?;
let first_attribute_id = reader.read_u16::<LittleEndian>()?;
Ok(EntryHeader {
signature,
usa_offset,
usa_size,
metadata_transaction_journal: logfile_sequence_number,
sequence,
hard_link_count,
first_attribute_record_offset: first_attribute_offset,
flags,
used_entry_size: entry_size_real,
total_entry_size: entry_size_allocated,
base_reference,
first_attribute_id,
record_number: entry_id,
})
}
pub fn is_valid(&self) -> bool {
self.signature == *FILE_HEADER
}
pub fn zero() -> Self {
EntryHeader {
signature: *ZERO_HEADER,
usa_offset: 0,
usa_size: 0,
metadata_transaction_journal: 0,
sequence: 0,
hard_link_count: 0,
first_attribute_record_offset: 0,
flags: EntryFlags::from_bits_truncate(0),
used_entry_size: 0,
total_entry_size: 0,
base_reference: MftReference {
entry: 0,
sequence: 0,
},
first_attribute_id: 0,
record_number: 0,
}
}
}
impl MftEntry {
pub fn from_buffer(mut buffer: Vec<u8>, entry_number: u64) -> Result<MftEntry> {
let mut cursor = Cursor::new(&buffer);
let entry_header = EntryHeader::from_reader(&mut cursor, entry_number)?;
trace!("Number of sectors: {:#?}", entry_header);
let valid_fixup = if entry_header.is_valid() {
Some(Self::apply_fixups(&entry_header, &mut buffer)?)
} else {
None
};
Ok(MftEntry {
header: entry_header,
data: buffer,
valid_fixup,
})
}
pub fn from_buffer_skip_fixup(buffer: Vec<u8>, entry_number: u64) -> Result<MftEntry> {
let mut cursor = Cursor::new(&buffer);
let entry_header = EntryHeader::from_reader(&mut cursor, entry_number)?;
trace!("Number of sectors: {:#?}", entry_header);
if !entry_header.is_valid() {
return Err(Error::InvalidEntrySignature {
bad_sig: entry_header.signature.to_vec(),
});
}
Ok(MftEntry {
header: entry_header,
data: buffer,
valid_fixup: None,
})
}
pub fn find_best_name_attribute(&self) -> Option<FileNameAttr> {
let file_name_attributes: Vec<FileNameAttr> = self
.iter_attributes_matching(Some(vec![MftAttributeType::FileName]))
.filter_map(Result::ok)
.filter_map(|a| a.data.into_file_name())
.collect();
let win32_filename = file_name_attributes
.iter()
.find(|a| [FileNamespace::Win32, FileNamespace::Win32AndDos].contains(&a.namespace));
match win32_filename {
Some(filename) => Some(filename.clone()),
None => {
file_name_attributes.get(0).cloned()
}
}
}
fn apply_fixups(header: &EntryHeader, buffer: &mut [u8]) -> Result<bool> {
let mut valid_fixup = true;
let number_of_fixups = u32::from(header.usa_size - 1);
trace!("Number of fixups: {}", number_of_fixups);
let fixups_start_offset = header.usa_offset as usize;
let fixups_end_offset = fixups_start_offset + (header.usa_size * 2) as usize;
let fixups = buffer[fixups_start_offset..fixups_end_offset].to_vec();
let mut fixups = fixups.chunks(2);
let update_sequence = fixups.next().unwrap_or(&[0, 0]);
for (stride_number, fixup_bytes) in (0_usize..number_of_fixups as usize).zip(fixups) {
let sector_start_offset = stride_number * SEQUENCE_NUMBER_STRIDE;
let end_of_sector_bytes_end_offset = sector_start_offset + SEQUENCE_NUMBER_STRIDE;
let end_of_sector_bytes_start_offset = end_of_sector_bytes_end_offset - 2;
let end_of_sector_bytes =
&mut buffer[end_of_sector_bytes_start_offset..end_of_sector_bytes_end_offset];
if end_of_sector_bytes != update_sequence {
warn!(
"[entry: {}] fixup bytes are not equal to update sequence value - stride_number: {}, end_of_sector_bytes: {:?}, fixup_bytes: {:?}",
header.record_number,
stride_number,
end_of_sector_bytes.to_vec(),
fixup_bytes.to_vec()
);
valid_fixup = false;
}
end_of_sector_bytes.copy_from_slice(fixup_bytes);
}
Ok(valid_fixup)
}
pub fn is_allocated(&self) -> bool {
self.header.flags.bits() & 0x01 != 0
}
pub fn is_dir(&self) -> bool {
self.header.flags.bits() & 0x02 != 0
}
pub fn iter_attributes(&self) -> impl Iterator<Item = Result<MftAttribute>> + '_ {
self.iter_attributes_matching(None)
}
pub fn iter_attributes_matching(
&self,
types: Option<Vec<MftAttributeType>>,
) -> impl Iterator<Item = Result<MftAttribute>> + '_ {
let mut cursor = Cursor::new(&self.data);
let mut offset = u64::from(self.header.first_attribute_record_offset);
let mut exhausted = false;
std::iter::from_fn(move || {
loop {
if exhausted {
return None;
}
if let Err(e) = cursor.seek(SeekFrom::Start(offset)) {
exhausted = true;
return Some(Err(e.into()));
};
let header = MftAttributeHeader::from_stream(&mut cursor);
let header = match header {
Ok(h) => h,
Err(e) => {
exhausted = true;
return Some(Err(e));
}
};
let header = match header {
Some(attribute_header) => attribute_header,
None => return None,
};
offset += u64::from(header.record_length);
if let Some(filter) = &types {
if !filter.contains(&header.type_code) {
continue;
}
}
let attribute_content = match header.residential_header {
ResidentialHeader::Resident(ref resident) => {
match MftAttributeContent::from_stream_resident(
&mut cursor,
&header,
resident,
) {
Ok(content) => content,
Err(e) => return Some(Err(e)),
}
}
ResidentialHeader::NonResident(_) => MftAttributeContent::None,
};
return Some(Ok(MftAttribute {
header,
data: attribute_content,
}));
}
})
}
}
#[cfg(test)]
mod tests {
use super::EntryHeader;
use std::io::Cursor;
#[test]
fn mft_header_test_01() {
let header_buffer: &[u8] = &[
0x46, 0x49, 0x4C, 0x45, 0x30, 0x00, 0x03, 0x00, 0xCC, 0xB3, 0x7D, 0x84, 0x0C, 0x00,
0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x38, 0x00, 0x05, 0x00, 0x48, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0xD5, 0x95, 0x00, 0x00, 0x53, 0x57, 0x81, 0x37, 0x00, 0x00, 0x00, 0x00,
];
let entry_header =
EntryHeader::from_reader(&mut Cursor::new(header_buffer), 38357).unwrap();
assert_eq!(&entry_header.signature, b"FILE");
assert_eq!(entry_header.usa_offset, 48);
assert_eq!(entry_header.usa_size, 3);
assert_eq!(entry_header.metadata_transaction_journal, 53_762_438_092);
assert_eq!(entry_header.sequence, 5);
assert_eq!(entry_header.hard_link_count, 1);
assert_eq!(entry_header.first_attribute_record_offset, 56);
assert_eq!(entry_header.flags.bits(), 5);
assert_eq!(entry_header.used_entry_size, 840);
assert_eq!(entry_header.total_entry_size, 1024);
assert_eq!(entry_header.base_reference.entry, 0);
assert_eq!(entry_header.first_attribute_id, 6);
assert_eq!(entry_header.record_number, 38357);
}
}