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
use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter};
use std::ops::Deref;

use anyhow::Result;
use chrono::{DateTime, Utc};
use fuzzyhash::FuzzyHash;
use md5::{Digest, Md5};

#[cfg(feature = "elf")]
pub mod elf;

#[cfg(feature = "macho")]
pub mod macho;

#[cfg(feature = "pe32")]
pub mod pe32;

#[cfg(feature = "pef")]
pub mod pef;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Architecture {
    Alpha,
    ARM,
    ARMThumb,
    ARM64,
    HitachiSH3,
    HitachiSH4,
    HitachiSH5,
    Itanium,
    LoongArch32,
    LoongArch64,
    M68k,
    M88k,
    MIPS,
    MIPS64,
    MIPSEL,
    MIPSEL64,
    PowerPC,
    PowerPC64,
    PowerPCLE,
    PowerPC64LE,
    RISCV,
    RISCV64,
    RISCV128,
    Sparc,
    Sparc64,
    S390,
    S390x,
    X86,
    X86_64,
    Other(u16),
    Unknown,
}

impl Display for Architecture {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Architecture::Alpha => write!(f, "DEC Alpha"),
            Architecture::ARM => write!(f, "ARM"),
            Architecture::ARMThumb => write!(f, "ARM Thumb"),
            Architecture::ARM64 => write!(f, "ARM64"),
            Architecture::HitachiSH3 => write!(f, "Hitachi SH3"),
            Architecture::HitachiSH4 => write!(f, "Hitachi SH4"),
            Architecture::HitachiSH5 => write!(f, "Hitachi SH5"),
            Architecture::Itanium => write!(f, "Intel Itanium"),
            Architecture::LoongArch32 => write!(f, "LoongArch"),
            Architecture::LoongArch64 => write!(f, "LoongArch64"),
            Architecture::M68k => write!(f, "M68k"),
            Architecture::M88k => write!(f, "M88k"),
            Architecture::MIPS => write!(f, "MIPS"),
            Architecture::MIPS64 => write!(f, "MIPS64"),
            Architecture::MIPSEL => write!(f, "MIPSEL"),
            Architecture::MIPSEL64 => write!(f, "MIPSEL64"),
            Architecture::PowerPC => write!(f, "PowerPC"),
            Architecture::PowerPC64 => write!(f, "PowerPC64"),
            Architecture::PowerPCLE => write!(f, "PowerPCLE"),
            Architecture::PowerPC64LE => write!(f, "PowerPC64LE"),
            Architecture::RISCV => write!(f, "RISC-V"),
            Architecture::RISCV64 => write!(f, "RISC-V 64"),
            Architecture::RISCV128 => write!(f, "RISC-V 128"),
            Architecture::Sparc => write!(f, "Sparc"),
            Architecture::Sparc64 => write!(f, "Sparc64"),
            Architecture::S390 => write!(f, "S390"),
            Architecture::S390x => write!(f, "S390x"),
            Architecture::X86 => write!(f, "x86"),
            Architecture::X86_64 => write!(f, "x86_64"),
            Architecture::Other(other) => write!(f, "Other: 0x{other:02X}"),
            Architecture::Unknown => write!(f, "Unknown architecture, or architecture-independent"),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperatingSystem {
    /// IBM AIX
    AIX,

    /// Linux (includes "SystemV" type in ELFs)
    Linux,

    /// FreeBSD
    FreeBSD,

    /// OpenBSD
    OpenBSD,

    /// NetBSD
    NetBSD,

    /// HP's UX
    HPUX,

    /// SGI's Irix
    Irix,

    /// Sun then Oracle Solaris
    Solaris,

    /// Unknown Unix or Unix-like
    UnknownUnixLike,

    /// Haiku, the BeOS successor
    Haiku,

    /// Apple's Mac OS X (now macOS)
    MacOS,

    /// Apple's older Mac OS, now referred to Classic Mac OS
    #[allow(non_camel_case_types)]
    MacOS_Classic,

    /// MS-DOS, IBM-DOS, or FreeDOS
    DOS,

    /// Microsoft Windows
    Windows,

    /// Something else?
    Other(u16),
}

impl Display for OperatingSystem {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            OperatingSystem::AIX => write!(f, "AIX"),
            OperatingSystem::Linux => write!(f, "Linux"),
            OperatingSystem::FreeBSD => write!(f, "FreeBSD"),
            OperatingSystem::OpenBSD => write!(f, "OpenBSD"),
            OperatingSystem::NetBSD => write!(f, "NetBSD"),
            OperatingSystem::HPUX => write!(f, "HP-UX"),
            OperatingSystem::Irix => write!(f, "Irix"),
            OperatingSystem::Solaris => write!(f, "Solaris"),
            OperatingSystem::UnknownUnixLike => write!(f, "Unknown Unix or Unix-like"),
            OperatingSystem::Haiku => write!(f, "Haiku"),
            OperatingSystem::MacOS => write!(f, "Mac OS (or maybe iOS)"),
            OperatingSystem::MacOS_Classic => write!(f, "Classic Mac OS (7.0 - 9.2)"),
            OperatingSystem::DOS => write!(f, "MS-DOS or compatible"),
            OperatingSystem::Windows => write!(f, "Windows"),
            OperatingSystem::Other(other) => write!(f, "Other: 0x{other:02X}"),
        }
    }
}

#[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"),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ExecutableType {
    /// Core file, from a crash
    Core,

    /// Shared library
    Library,

    /// Directly executable program or application
    Program,

    /// Something else?
    Unknown(u16),
}

impl Display for ExecutableType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ExecutableType::Core => write!(f, "Core file"),
            ExecutableType::Library => write!(f, "Shared library"),
            ExecutableType::Program => write!(f, "Program/Application"),
            ExecutableType::Unknown(other) => write!(f, "Unknown 0x{other:02X}"),
        }
    }
}

pub trait ExecutableFile {
    fn type_name(&self) -> String;

    fn architecture(&self) -> &Architecture;
    fn pointer_size(&self) -> usize;
    fn operating_system(&self) -> &OperatingSystem;
    fn compiled_timestamp(&self) -> Option<DateTime<Utc>>;

    fn num_sections(&self) -> u32;
    fn sections(&self) -> Result<&Sections>;
}

#[derive(Clone, Debug, PartialEq)]
pub struct Section<'a> {
    /// Name of the section, can be empty, not a reliable way to identify attributes of it
    pub name: String,

    /// Whether or not an execute bit was set
    pub is_executable: bool,

    /// Size of the section
    pub size: usize,

    /// Offset in the file where the section starts
    pub offset: usize,

    /// Address of the section once loaded into memory, not for all executable types
    pub virtual_address: u32,

    /// Size of the section once loaded into memory, not for all executable types
    pub virtual_size: u32,

    /// Entropy of the section
    pub entropy: f32,

    pub data: Option<&'a [u8]>,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Sections<'a>(Vec<Section<'a>>);

impl<'a> Display for Section<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} at 0x{:02x}, size 0x{:02x}",
            self.name, self.offset, self.size
        )?;
        if self.virtual_address > 0 {
            write!(f, ", v address: 0x{:02x}", self.virtual_address)?;
        }
        if self.is_executable {
            write!(f, " - executable")?;
        }
        Ok(())
    }
}

impl<'a> Display for Sections<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for section in self.0.iter() {
            writeln!(f, "{section}")?;
        }
        Ok(())
    }
}

impl<'a> Deref for Sections<'a> {
    type Target = Sections<'a>;

    fn deref(&self) -> &Self::Target {
        // Seems silly, but seems required for making an Option<Sections> into Result<&Sections>
        self
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Import {
    /// Library file, .dll in Windows, .so in Unix/Linux, .dylib in macOS
    pub library: String,

    /// Function name imported
    pub function: String,
}

impl Display for Import {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.library, self.function)
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Imports {
    /// The collection of found imports
    pub imports: Vec<Import>,

    /// The total number of imports which should have been found, in case some couldn't be parsed
    pub expected_imports: u32,
}

impl Display for Imports {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for import in self.imports.iter() {
            writeln!(f, "{import}")?;
        }
        Ok(())
    }
}

impl Imports {
    /// Build a string with library.function for each pair, sorted.
    pub fn build_import_string(&self) -> String {
        // A HashSet probably isn't needed, but malware might do something funny.
        let mut imports_map: HashMap<String, HashSet<String>> = HashMap::new();

        // Collect all function names by library
        for import in self.imports.iter() {
            let mut lib = import.library.clone().to_lowercase();
            if lib.ends_with(".dll") {
                lib = lib.replace(".dll", "");
            } else if lib.ends_with(".sys") {
                lib = lib.replace(".sys", "");
            } else if let Some(idx) = lib.find(".so") {
                lib.truncate(lib.len() - idx);
            }

            if !imports_map.contains_key(&lib) {
                imports_map.insert(lib.clone(), HashSet::new());
            }

            imports_map
                .get_mut(&lib)
                .unwrap()
                .insert(import.function.to_lowercase());
        }

        // Sort the libraries
        let mut libs: Vec<&String> = imports_map.keys().collect();
        libs.sort();

        // Get the mapping of lib.func
        let mut imports_string = Vec::new();
        for lib in libs {
            // Sort the functions
            let functions = imports_map.get(lib).unwrap();
            let mut functions = Vec::from_iter(functions);
            functions.sort();
            for function in functions.iter() {
                imports_string.push(format!("{lib}.{function}"));
            }
        }

        imports_string.join(",")
    }

    /// The Import Hash, or "ImpHash" is the MD5 of the imports string
    pub fn hash(&self) -> Vec<u8> {
        let mut hasher = Md5::new();
        hasher.update(self.build_import_string());
        let result = hasher.finalize();
        result.to_vec()
    }

    /// The fuzzy import hash is the SSDeep hash of the import string
    pub fn fuzzy_hash(&self) -> String {
        let import_string = self.build_import_string();
        let fuzzy = FuzzyHash::new(import_string.into_bytes());
        fuzzy.to_string()
    }
}