Skip to main content

malware_modeler/
ftype.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::collections::HashMap;
4use std::fmt::Display;
5use std::io::Read;
6use std::path::Path;
7use std::sync::OnceLock;
8
9use anyhow::{Result, bail, ensure};
10use clap::ValueEnum;
11use serde::{Deserialize, Serialize};
12
13/// Known file types for training malware models
14#[allow(clippy::manual_non_exhaustive)]
15#[derive(ValueEnum, Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
16pub enum FileType {
17    /// Docfile, which could be: MS Office, Windows Update, Installer, Visio, or something else!
18    /// For the purposes of making a malware model, each subtype needs to be identified, which is
19    /// not yet implemented.
20    DOCFILE,
21
22    /// Linux, *BSD, Solaris, Haiku, Redox executables
23    ELF,
24
25    /// 32-bit ELF executable
26    ELF32,
27
28    /// 64-bit ELF executable
29    ELF64,
30
31    /// Little Endian ELF executable (ARM, Intel, PowerPC, RISC-V, etc.)
32    #[allow(non_camel_case_types)] // for easier readability
33    ELF_LSB,
34
35    /// Big Endian ELF executable (ARM, M64k, MIPS, PowerPC, SPARC, etc.)
36    #[allow(non_camel_case_types)] // for easier readability
37    ELF_MSB,
38
39    /// 32-bit Little Endian ELF executable
40    #[allow(non_camel_case_types)] // for easier readability
41    ELF32_LSB,
42
43    /// 64-bit Little Endian ELF executable
44    #[allow(non_camel_case_types)] // for easier readability
45    ELF64_LSB,
46
47    /// 32-bit Big Endian ELF executable
48    #[allow(non_camel_case_types)] // for easier readability
49    ELF32_MSB,
50
51    /// 64-bit Big Endian ELF executable
52    #[allow(non_camel_case_types)] // for easier readability
53    ELF64_MSB,
54
55    /// Non-PE32 Windows executable (could be for MS-DOS, OS/2, Windows 3.1, etc.)
56    EXE,
57
58    /// Macho-O for macOS, iOS (and derivatives), and NeXT
59    MachO,
60
61    /// Portable Document Format
62    PDF,
63
64    /// Portable Executables for Windows
65    PE32,
66
67    /// Portable Executables for Windows based on the .NET Framework
68    PE32DotNet,
69
70    /// Portable Executables for Windows explicitly excluding .NET
71    PE32Native,
72
73    /// Rich Text Format
74    RTF,
75
76    /// Extended Common Object Format for AIX
77    XCOFF,
78
79    /// Apple's .DS_Store file, which we want to identify so we can ignore
80    #[doc(hidden)]
81    #[serde(skip)]
82    #[clap(skip)]
83    DsStore,
84
85    /// This is used as a convenience type for when a model isn't yet trained.
86    #[default]
87    #[doc(hidden)]
88    #[serde(skip)]
89    #[clap(skip)]
90    NotSet,
91}
92
93const FILE_DETECTION_BUFFER_SIZE: usize = 384;
94
95const MAGIC32: [u8; 4] = [0xfe, 0xed, 0xfa, 0xce];
96const CIGAM32: [u8; 4] = [0xce, 0xfa, 0xed, 0xfe];
97const MAGIC64: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf];
98const CIGAM64: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe];
99const FAT_MACHO: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE]; // Needs additional checks
100const MACH_O_MAGICS: [[u8; 4]; 4] = [MAGIC32, CIGAM32, MAGIC64, CIGAM64];
101
102const ELF_MAGIC: [u8; 4] = [0x7f, 0x45, 0x4c, 0x46]; // \x7fELF
103const EXE_MAGICS: [[u8; 2]; 2] = [[0x4D, 0x5A], [0x5A, 0x4D]]; // MZ or ZM, the "MZ header"
104const PE_MAGIC: [u8; 4] = [0x50, 0x45, 0x00, 0x00];
105const PDF_MAGIC: [u8; 4] = [0x25, 0x50, 0x44, 0x46]; // %PDF
106const RTF_MAGIC: [u8; 4] = [0x7B, 0x5C, 0x72, 0x74]; // {\rt
107const XCOFF_MAGICS: [[u8; 2]; 2] = [[0x01, 0xDF], [0x01, 0xF7]]; // 32-bit and 64-bit respectively
108
109const DOCFILE_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
110const DS_STORE_MAGIC: [u8; 8] = [0x00, 0x00, 0x00, 0x01, 0x42, 0x75, 0x64, 0x31];
111
112impl FileType {
113    /// Try to match bytes to a known file type
114    /// * ELFs: the byte ordering has a higher precedence of importance. Plain ELF is the fallback
115    ///   if the byte ordering then pointer size isn't determined.
116    #[inline]
117    #[must_use]
118    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
119        if bytes.starts_with(&DOCFILE_MAGIC) {
120            return Some(Self::DOCFILE);
121        }
122
123        if bytes.starts_with(&DS_STORE_MAGIC) {
124            return Some(Self::DsStore);
125        }
126
127        if bytes.starts_with(&ELF_MAGIC) {
128            // This may look ridiculous, but malware is sometimes weird and sometimes values are missing.
129            if bytes[0x4] == 1 && bytes[0x5] == 1 {
130                return Some(Self::ELF32_LSB);
131            }
132            if bytes[0x4] == 1 && bytes[0x5] == 2 {
133                return Some(Self::ELF32_MSB);
134            }
135            if bytes[0x4] == 2 && bytes[0x5] == 1 {
136                return Some(Self::ELF64_LSB);
137            }
138            if bytes[0x4] == 2 && bytes[0x5] == 2 {
139                return Some(Self::ELF64_MSB);
140            }
141
142            if bytes[0x5] == 1 {
143                return Some(Self::ELF_LSB);
144            }
145            if bytes[0x5] == 2 {
146                return Some(Self::ELF_MSB);
147            }
148
149            if bytes[0x4] == 1 {
150                return Some(Self::ELF32);
151            }
152            if bytes[0x4] == 2 {
153                return Some(Self::ELF64);
154            }
155
156            return Some(Self::ELF);
157        }
158
159        if MACH_O_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
160            return Some(Self::MachO);
161        }
162
163        if bytes.starts_with(&FAT_MACHO) && Self::is_fat_macho(bytes) {
164            return Some(Self::MachO);
165        }
166
167        if bytes.starts_with(&PDF_MAGIC) {
168            return Some(Self::PDF);
169        }
170
171        if EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
172            if Self::is_pe32(bytes) {
173                if Self::is_dotnet(bytes) {
174                    return Some(Self::PE32DotNet);
175                }
176                return Some(Self::PE32Native);
177            }
178
179            return Some(Self::EXE);
180        }
181
182        if bytes.starts_with(&RTF_MAGIC) {
183            return Some(Self::RTF);
184        }
185
186        if XCOFF_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
187            return Some(Self::XCOFF);
188        }
189
190        None
191    }
192
193    /// Try to match bytes to a known file type
194    ///
195    /// # Errors
196    ///
197    /// An error will result if the file can't be read or is too small.
198    #[inline]
199    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Option<Self>> {
200        let mut file = std::fs::File::open(path)?;
201        let mut buffer = [0; FILE_DETECTION_BUFFER_SIZE];
202        let read = file.read(&mut buffer)?;
203        Ok(Self::from_bytes(&buffer[..read]))
204    }
205
206    /// Check if the given bytes match the expected file type. This isn't as easy as "make a new
207    /// instance and use the equality operator" due to subtypes.
208    ///
209    /// * A [`FileType::PE32`] file is an [`FileType::EXE`], but an [`FileType::EXE`] isn't necessarily
210    ///   a [`FileType::PE32`].
211    /// * A [`FileType::ELF_LSB`] file is an [`FileType::ELF`], but not necessarily the other way around.
212    /// * ELFs: the byte ordering has a higher precedence of importance.
213    ///
214    /// With subtypes, allow for training a model where you might want all ELFs, or only certain ELFs, so
215    /// others would be disqualified.
216    #[must_use]
217    pub fn matches(&self, bytes: &[u8]) -> bool {
218        match self {
219            // aim for less granular to more granular when dealing with subtypes
220            FileType::DOCFILE => bytes.starts_with(&DOCFILE_MAGIC),
221            FileType::ELF => bytes.starts_with(&ELF_MAGIC),
222            FileType::ELF_LSB => bytes.starts_with(&ELF_MAGIC) && bytes[0x5] == 1,
223            FileType::ELF_MSB => bytes.starts_with(&ELF_MAGIC) && bytes[0x5] == 2,
224            FileType::ELF32 => bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1,
225            FileType::ELF64 => bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2,
226            FileType::ELF32_LSB => {
227                bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1 && bytes[0x5] == 1
228            }
229            FileType::ELF32_MSB => {
230                bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1 && bytes[0x5] == 2
231            }
232            FileType::ELF64_LSB => {
233                bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2 && bytes[0x5] == 1
234            }
235            FileType::ELF64_MSB => {
236                bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2 && bytes[0x5] == 2
237            }
238            FileType::EXE => EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)),
239            FileType::MachO => {
240                MACH_O_MAGICS.iter().any(|magic| bytes.starts_with(magic))
241                    || bytes.starts_with(&FAT_MACHO) && Self::is_fat_macho(bytes)
242            }
243            FileType::PDF => bytes.starts_with(&PDF_MAGIC),
244            FileType::PE32 => {
245                EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && Self::is_pe32(bytes)
246            }
247            FileType::PE32Native => {
248                EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && !Self::is_dotnet(bytes)
249            }
250            FileType::PE32DotNet => {
251                EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && Self::is_dotnet(bytes)
252            }
253            FileType::RTF => bytes.starts_with(&RTF_MAGIC),
254            FileType::XCOFF => XCOFF_MAGICS.iter().any(|magic| bytes.starts_with(magic)),
255            FileType::DsStore => unreachable!("`FileType::DsStore` should never be used"),
256            FileType::NotSet => unreachable!("`FileType::NotSet` should never be used"),
257        }
258    }
259
260    /// Convenience function to read a few bytes of a file to see the file's type matches this type.
261    ///
262    /// # Errors
263    ///
264    /// An error occurs if the file cannot be read.
265    #[inline]
266    pub fn matches_path<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
267        let mut file = std::fs::File::open(path)?;
268        let mut buffer = [0; FILE_DETECTION_BUFFER_SIZE];
269        let read = file.read(&mut buffer)?;
270        Ok(self.matches(&buffer[..read]))
271    }
272
273    /// This function assumes that the file has already been checked for the MZ header.
274    #[inline]
275    fn is_pe32(bytes: &[u8]) -> bool {
276        if bytes.len() < 0x40 {
277            return false;
278        }
279
280        let pe_magic_offset = u32::from_le_bytes([
281            bytes[0x3C],
282            bytes[0x3C + 1],
283            bytes[0x3C + 2],
284            bytes[0x3C + 3],
285        ]) as usize;
286        pe_magic_offset < bytes.len()
287            && pe_magic_offset + PE_MAGIC.len() < bytes.len()
288            && bytes[pe_magic_offset..pe_magic_offset + 4] == PE_MAGIC
289    }
290
291    /// Check if the PE32 has the CLR data, indicating it's a .NET executable.
292    #[inline]
293    fn is_dotnet(bytes: &[u8]) -> bool {
294        if let Ok(pe) = goblin::pe::PE::parse(bytes) {
295            pe.clr_data.is_some()
296        } else {
297            false
298        }
299    }
300
301    /// This function assumes that the file has already been checked for the Fat Mach-O header.
302    #[inline]
303    fn is_fat_macho(bytes: &[u8]) -> bool {
304        u32::from_be_bytes([
305            bytes[0x04],
306            bytes[0x04 + 1],
307            bytes[0x04 + 2],
308            bytes[0x04 + 3],
309        ]) < 0x20
310    }
311
312    /// When trying to find a file type for a collection of files, maybe we can pick a broader
313    /// type from a specific type.
314    ///
315    /// # Examples:
316    /// * [`FileType::PE32DotNet`] or [`FileType::PE32Native`] can drop down to [`FileType::PE32`]
317    /// * Any "PE32*" type can drop down to [`FileType::EXE`]
318    /// * "ELF*" of any subtype can drop down to [`FileType::ELF`].
319    ///
320    /// # Errors
321    /// Any other type is an error.
322    /// For example, [`FileType::RTF`] cannot downgrade, so finding anything but an RTF file
323    /// is an error.
324    pub fn downgrade(self, other: FileType) -> Result<FileType> {
325        // Think of this as FROM mapping to optional TO values
326        // Any types not a KEY in this map will return an error
327        static DOWNGRADES: OnceLock<HashMap<FileType, Vec<FileType>>> = OnceLock::new();
328
329        ensure!(
330            other != FileType::DsStore,
331            "DS_Store files should be ignored."
332        );
333        if self == FileType::NotSet {
334            return Ok(other);
335        }
336
337        let downgrades = DOWNGRADES.get_or_init(|| {
338            let mut m = HashMap::new();
339            m.insert(FileType::EXE, vec![FileType::EXE]);
340            m.insert(FileType::PE32DotNet, vec![FileType::PE32, FileType::EXE]);
341            m.insert(FileType::PE32Native, vec![FileType::PE32, FileType::EXE]);
342            m.insert(FileType::PE32, vec![FileType::EXE]);
343
344            m.insert(FileType::ELF, vec![FileType::ELF]);
345            m.insert(FileType::ELF_LSB, vec![FileType::ELF]);
346            m.insert(FileType::ELF_MSB, vec![FileType::ELF]);
347            m.insert(FileType::ELF64, vec![FileType::ELF]);
348            m.insert(FileType::ELF32, vec![FileType::ELF]);
349
350            m.insert(
351                FileType::ELF64_LSB,
352                vec![FileType::ELF_LSB, FileType::ELF64, FileType::ELF],
353            );
354            m.insert(
355                FileType::ELF64_MSB,
356                vec![FileType::ELF_MSB, FileType::ELF64, FileType::ELF],
357            );
358
359            m.insert(
360                FileType::ELF32_LSB,
361                vec![FileType::ELF_LSB, FileType::ELF32, FileType::ELF],
362            );
363            m.insert(
364                FileType::ELF32_MSB,
365                vec![FileType::ELF_MSB, FileType::ELF32, FileType::ELF],
366            );
367            m
368        });
369
370        if let Some(related_types) = downgrades.get(&self) {
371            let Some(other_related_types) = downgrades.get(&other) else {
372                bail!("Downgrade from {self} to {other} not possible")
373            };
374            let mut common_types = Vec::new();
375
376            // Find common items, preferring the first items in the vector of the HashMap's value
377            for related_type in related_types {
378                if other_related_types.contains(related_type) {
379                    common_types.push(*related_type);
380                }
381            }
382
383            if let Some(common_type) = common_types.first() {
384                return Ok(*common_type);
385            }
386        }
387
388        bail!("Downgrade from {self} to {other} not possible")
389    }
390}
391
392impl From<FileType> for &'static str {
393    fn from(ft: FileType) -> &'static str {
394        match ft {
395            FileType::DOCFILE => "DOCFILE",
396            FileType::DsStore => "DS_Store",
397            FileType::ELF => "ELF",
398            FileType::ELF_LSB => "ELF_LSB",
399            FileType::ELF_MSB => "ELF_MSB",
400            FileType::ELF32 => "ELF32",
401            FileType::ELF64 => "ELF64",
402            FileType::ELF32_LSB => "ELF32_LSB",
403            FileType::ELF64_LSB => "ELF64_LSB",
404            FileType::ELF32_MSB => "ELF32_MSB",
405            FileType::ELF64_MSB => "ELF64_MSB",
406            FileType::EXE => "EXE",
407            FileType::MachO => "MachO",
408            FileType::PDF => "PDF",
409            FileType::PE32 => "PE32",
410            FileType::PE32DotNet => "PE32DotNet",
411            FileType::PE32Native => "PE32Native",
412            FileType::RTF => "RTF",
413            FileType::XCOFF => "XCOFF",
414            FileType::NotSet => "NotSet",
415        }
416    }
417}
418
419impl FileType {
420    /// Resolve a file type from its name, ignoring case.
421    ///
422    /// Dataset headers carry the name as [`Display`] writes it, so `PE32Native`, `MachO`
423    /// and `PE32DotNet` are mixed case. Matching case-insensitively means a header stays
424    /// readable however it was cased on the way in.
425    ///
426    /// Returns `None` for an unknown name, and for the internal [`FileType::DsStore`] and
427    /// [`FileType::NotSet`] variants, which are never valid in a file.
428    #[must_use]
429    pub fn from_name(name: &str) -> Option<Self> {
430        let name = name.trim();
431        <Self as ValueEnum>::value_variants()
432            .iter()
433            .copied()
434            .find(|variant| {
435                let variant_name: &'static str = (*variant).into();
436                variant_name.eq_ignore_ascii_case(name)
437            })
438    }
439}
440
441impl Display for FileType {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        let s: &'static str = (*self).into();
444        write!(f, "{s}")
445    }
446}