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
pub mod doc;
pub mod exec;
pub mod utils;

use crate::exec::ExecutableFile;

use std::fmt::{Display, Formatter};

use anyhow::Result;
use chrono::{DateTime, Utc};

/// MDB version
pub const MDB_VERSION: &str = env!("CARGO_PKG_VERSION");

pub trait TypeMagic {
    // Some file types have more than one possible magic number
    const MAGIC: &'static [&'static [u8]];
}

#[allow(clippy::large_enum_variant)]
pub enum KnownType<'a> {
    /// Linux, *BSD, Haiku, etc binaries
    #[cfg(feature = "elf")]
    ELF(exec::elf::Elf<'a>),

    /// Windows, DOS, OS/2 Executables. Anything ending with:
    /// * .cpl
    /// * .dll
    /// * .exe
    /// * .ocx
    /// * .sys
    #[cfg(feature = "pe32")]
    EXE(exec::pe32::EXE<'a>),

    /// Single architecture macOS (and derivatives) binaries
    #[cfg(feature = "macho")]
    MachO(exec::macho::Macho<'a>),

    /// Multiple architecture macOS (and derivatives) binaries
    #[cfg(feature = "macho")]
    FatMachO(exec::macho::fat::FatMacho<'a>),

    /// Classic Mac OS and BeOS
    #[cfg(feature = "pef")]
    PEF(exec::pef::Pef<'a>),

    /// Microsoft Office Compound Document Format
    #[cfg(feature = "office95")]
    Office95(doc::office95::Office95<'a>),

    /// Adobe PDF document
    #[cfg(feature = "pdf")]
    PDF(doc::pdf::PDF<'a>),

    /// Rich Text File
    #[cfg(feature = "rtf")]
    RTF(doc::rtf::Rtf<'a>),

    /// Files for which we don't have an analytic or feature extractor, or are of an unknown type
    Unknown(&'a [u8]),
}

impl<'a> KnownType<'a> {
    pub fn new(data: &'a [u8]) -> Result<Self> {
        // TODO: Replace the checking of byte arrays with a hashing mechanism for faster matching
        #[cfg(feature = "elf")]
        if data.starts_with(exec::elf::Elf::MAGIC[0]) {
            return Ok(Self::ELF(exec::elf::Elf::from(data)?));
        }

        #[cfg(feature = "pe32")]
        if data.starts_with(exec::pe32::EXE::MAGIC[0])
            || data.starts_with(exec::pe32::EXE::MAGIC[1])
        {
            return Ok(Self::EXE(exec::pe32::EXE::from(data)?));
        }

        #[cfg(feature = "macho")]
        for mach_magic in exec::macho::Macho::MAGIC {
            if data.starts_with(mach_magic) {
                return Ok(Self::MachO(exec::macho::Macho::from(data)?));
            }
        }

        #[cfg(feature = "macho")]
        for mach_magic in exec::macho::fat::FatMacho::MAGIC {
            if data.starts_with(mach_magic) {
                return Ok(Self::FatMachO(exec::macho::fat::FatMacho::from(data)?));
            }
        }

        #[cfg(feature = "office95")]
        if data.starts_with(doc::office95::Office95::MAGIC[0]) {
            return Ok(Self::Office95(doc::office95::Office95::from(data)?));
        }

        #[cfg(feature = "pdf")]
        if data.starts_with(doc::pdf::PDF::MAGIC[0]) {
            return Ok(Self::PDF(doc::pdf::PDF::from(data)?));
        }

        #[cfg(feature = "rtf")]
        if data.starts_with(doc::rtf::Rtf::MAGIC[0]) {
            return Ok(Self::RTF(doc::rtf::Rtf::from(data)?));
        }

        #[cfg(feature = "pef")]
        if data.starts_with(exec::pef::Pef::MAGIC[0]) {
            return Ok(Self::PEF(exec::pef::Pef::from(data)?));
        }

        Ok(Self::Unknown(data))
    }

    pub fn is_exec(&self) -> bool {
        match self {
            #[cfg(feature = "elf")]
            KnownType::ELF(_) => true,

            #[cfg(feature = "pe32")]
            KnownType::EXE(_) => true,

            #[cfg(feature = "macho")]
            KnownType::MachO(_) => true,

            #[cfg(feature = "macho")]
            KnownType::FatMachO(_) => true,

            #[cfg(feature = "pef")]
            KnownType::PEF(_) => true,

            _ => false,
        }
    }

    pub fn is_doc(&self) -> bool {
        match self {
            #[cfg(feature = "pdf")]
            KnownType::PDF(_) => true,

            #[cfg(feature = "rtf")]
            KnownType::RTF(_) => true,

            #[cfg(feature = "office95")]
            KnownType::Office95(_) => true,

            _ => false,
        }
    }

    pub fn created(&self) -> Option<DateTime<Utc>> {
        match self {
            #[cfg(feature = "pe32")]
            KnownType::EXE(e) => e.compiled_timestamp(),

            #[cfg(feature = "pef")]
            KnownType::PEF(p) => p.compiled_timestamp(),

            #[cfg(feature = "pdf")]
            KnownType::PDF(p) => p.creation_date,

            _ => None,
        }
    }

    pub fn exec(self) -> Option<Box<dyn ExecutableFile + Send + 'a>> {
        match self {
            #[cfg(feature = "elf")]
            KnownType::ELF(e) => Some(Box::new(e)),

            #[cfg(feature = "pe32")]
            KnownType::EXE(e) => Some(Box::new(e)),

            #[cfg(feature = "macho")]
            KnownType::MachO(m) => Some(Box::new(m)),

            #[cfg(feature = "macho")]
            KnownType::FatMachO(m) => Some(Box::new(m)),

            #[cfg(feature = "pef")]
            KnownType::PEF(p) => Some(Box::new(p)),
            _ => None,
        }
    }

    pub fn children(&self) -> Option<Vec<KnownType>> {
        match self {
            #[cfg(feature = "macho")]
            KnownType::FatMachO(m) => Some(
                m.binaries
                    .iter()
                    .map(|b| KnownType::MachO(b.clone()))
                    .collect(),
            ),

            _ => None,
        }
    }

    pub fn contents(&self) -> Option<&'a [u8]> {
        match self {
            #[cfg(feature = "elf")]
            KnownType::ELF(e) => Some(e.contents),

            #[cfg(feature = "pe32")]
            KnownType::EXE(e) => Some(e.contents),

            #[cfg(feature = "macho")]
            KnownType::MachO(m) => Some(m.contents),

            #[cfg(feature = "macho")]
            KnownType::FatMachO(m) => Some(m.contents),

            #[cfg(feature = "pef")]
            KnownType::PEF(p) => Some(p.contents),

            #[cfg(feature = "office95")]
            KnownType::Office95(p) => Some(p.contents),

            #[cfg(feature = "pdf")]
            KnownType::PDF(p) => Some(p.contents),

            #[cfg(feature = "rtf")]
            KnownType::RTF(r) => Some(r.contents),

            KnownType::Unknown(u) => Some(u),
        }
    }

    // TODO: doc type for more than PDFs
    pub fn doc(self) -> Option<Box<doc::pdf::PDF<'a>>> {
        match self {
            #[cfg(feature = "pdf")]
            KnownType::PDF(p) => Some(Box::new(p)),
            _ => None,
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Ordering {
    /// Big Endian, Most Significant Byte (MSB) is first
    BigEndian,

    /// Little Endian, Least Significant Byte (LSB) is first
    LittleEndian,

    /// An application which may use both in the same file
    BiEndian,
}

impl Display for Ordering {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Ordering::BigEndian => write!(f, "Big Endian"),
            Ordering::LittleEndian => write!(f, "Little Endian"),
            Ordering::BiEndian => write!(f, "Bi-Endian"),
        }
    }
}