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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! # Multi-Format Binary Parser and Metadata Extractor
//!
//! This module defines the [`Parser`] structure, which provides a unified,
//! format-agnostic abstraction for retrieving executable segments, OS target information,
//! and CPU architecture across ELF, PE, and Mach-O files.
//!
//! # Example
//! ```rust
//! use goblin::Object;
//! use rbat::core::parser::Parser;
//!
//! # fn run(buffer: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
//! let obj = Object::parse(buffer)?;
//! let parser = Parser::new(buffer, &obj);
//!
//! let metadata = parser.parse_buffer()?;
//! let entropy = parser.evaluate_section_entropy()?;
//! # Ok(())
//! # }
//! ```
use crate::utils::get_txt::get_txt_from_file;
use crate::{core::SectionRange, utils::entropy::calculate_entropy};
use goblin::Object;
use std::collections::{HashMap, HashSet};
use super::{BinaryArch, BinaryOS, MapValue, RbatError, Result, yarahandler::YaraHandler};
/// A central struct for binary analysis that abstracts over ELF, PE, and Mach-O formats.
/// It holds the raw binary buffer and the parsed object from the `goblin` crate.
#[derive(Debug)]
pub struct Parser<'bin> {
/// Raw bytes of the binary.
buffer: &'bin [u8],
/// The parsed object representation.
binary_object: &'bin Object<'bin>,
}
impl<'bin> Parser<'bin> {
/// Creates a new `Parser` instance.
pub fn new(buffer: &'bin [u8], binary_object: &'bin Object<'bin>) -> Self {
Parser {
buffer,
binary_object,
}
}
/// Evaluates the Shannon entropy for each section of the binary.
///
/// This is useful for identifying packed or encrypted sections where entropy is typically high (>= 7.5).
pub fn evaluate_section_entropy(&self) -> Result<HashMap<String, f64>> {
let mut section_entropy: HashMap<String, f64> = HashMap::new();
match &self.binary_object {
Object::Elf(elf) => {
for sh in &elf.section_headers {
if let Some(name) = elf.shdr_strtab.get_at(sh.sh_name) {
let start = sh.sh_offset as usize;
let size = sh.sh_size as usize;
if size > 0 && start + size <= self.buffer.len() {
let data = &self.buffer[start..start + size];
section_entropy.insert(name.to_string(), calculate_entropy(data));
}
}
}
}
Object::PE(pe) => {
for section in &pe.sections {
if let Ok(name) = section.name() {
let start = section.pointer_to_raw_data as usize;
let size = section.size_of_raw_data as usize;
if size > 0 && start + size <= self.buffer.len() {
let data = &self.buffer[start..start + size];
section_entropy.insert(name.to_string(), calculate_entropy(data));
}
}
}
}
Object::Mach(mach) => match mach {
goblin::mach::Mach::Binary(macho) => {
for segment in &macho.segments {
for (section, section_data) in segment.into_iter().flatten() {
if let Ok(name) = section.name()
&& !section_data.is_empty()
{
section_entropy
.insert(name.to_string(), calculate_entropy(section_data));
}
}
}
}
goblin::mach::Mach::Fat(fat) => {
for arch in fat {
if let Ok(goblin::mach::SingleArch::MachO(macho)) = arch {
for segment in &macho.segments {
for (section, section_data) in segment.into_iter().flatten() {
if let Ok(name) = section.name()
&& !section_data.is_empty()
{
section_entropy.insert(
name.to_string(),
calculate_entropy(section_data),
);
}
}
}
break;
}
}
}
},
_ => {}
}
Ok(section_entropy)
}
/// Extracts essential metadata from the binary buffer, including the target OS type,
/// entry point address, and raw executable bytes for disassembly.
pub fn parse_buffer(&self) -> Result<HashMap<String, MapValue>> {
match &self.binary_object {
Object::Elf(elf) => {
let mut binary_data: HashMap<String, MapValue> = HashMap::new();
binary_data.insert("os".to_string(), MapValue::OS(BinaryOS::Linux));
let arch = match elf.header.e_machine {
3 => BinaryArch::X86,
62 => BinaryArch::X64,
40 => BinaryArch::Arm,
183 => BinaryArch::Arm64,
other => {
return Err(RbatError::UnsupportedBinaryFormat(format!(
"Unsupported ELF machine architecture: {:#x}",
other
)));
}
};
binary_data.insert("arch".to_string(), MapValue::Arch(arch));
binary_data.insert("entry_addr".to_string(), MapValue::Word(elf.entry));
for ph in &elf.program_headers {
if ph.p_type == goblin::elf::program_header::PT_LOAD
&& ph.p_flags & goblin::elf::program_header::PF_X != 0
{
let start = ph.p_offset as usize;
let size = ph.p_filesz as usize;
let end = start.checked_add(size).ok_or_else(|| {
RbatError::InvalidBinaryLayout(
"Executable segment offset overflowed file bounds".to_string(),
)
})?;
let text_bytes = self.buffer.get(start..end).ok_or_else(|| {
RbatError::InvalidBinaryLayout(format!(
"Executable segment range {start}..{end} is outside file bounds"
))
})?;
binary_data.insert(
"text_bytes".to_string(),
MapValue::Bytes(text_bytes.to_vec()),
);
break;
}
}
if !binary_data.contains_key("text_bytes") {
for sh in &elf.section_headers {
if let (Some(name), Some(end)) = (
elf.shdr_strtab.get_at(sh.sh_name),
(sh.sh_offset as usize).checked_add(sh.sh_size as usize),
) && name == ".text"
{
let start = sh.sh_offset as usize;
let text_bytes = self.buffer.get(start..end).ok_or_else(|| {
RbatError::InvalidBinaryLayout(format!(
"Executable section range {start}..{end} is outside file bounds"
))
})?;
binary_data.insert(
"text_bytes".to_string(),
MapValue::Bytes(text_bytes.to_vec()),
);
break;
}
}
}
if !binary_data.contains_key("text_bytes") {
return Err(RbatError::MissingExecutableSection);
}
Ok(binary_data)
}
Object::PE(pe) => {
let mut binary_data: HashMap<String, MapValue> = HashMap::new();
binary_data.insert("os".to_string(), MapValue::OS(BinaryOS::Win));
let arch = match pe.header.coff_header.machine {
0x014c => BinaryArch::X86,
0x8664 => BinaryArch::X64,
0x01c4 => BinaryArch::Arm,
0xaa64 => BinaryArch::Arm64,
other => {
return Err(RbatError::UnsupportedBinaryFormat(format!(
"Unsupported PE machine architecture: {:#x}",
other
)));
}
};
binary_data.insert("arch".to_string(), MapValue::Arch(arch));
binary_data.insert(
"entry_addr".to_string(),
MapValue::Word(pe.image_base + pe.entry as u64),
);
const IMAGE_SCN_MEM_EXECUTE: u32 = 0x20000000;
let entry_rva = pe.entry;
let executable_section = pe
.sections
.iter()
.find(|section| {
let start = section.virtual_address;
let size = section.virtual_size.max(section.size_of_raw_data);
let end = start.saturating_add(size);
section.characteristics & IMAGE_SCN_MEM_EXECUTE != 0
&& entry_rva >= start
&& entry_rva < end
})
.or_else(|| {
pe.sections
.iter()
.find(|section| section.characteristics & IMAGE_SCN_MEM_EXECUTE != 0)
});
if let Some(section) = executable_section {
let start = section.pointer_to_raw_data as usize;
let size = section.size_of_raw_data as usize;
let end = start.checked_add(size).ok_or_else(|| {
RbatError::InvalidBinaryLayout(
"PE executable section offset overflowed file bounds".to_string(),
)
})?;
let text_bytes = self.buffer.get(start..end).ok_or_else(|| {
RbatError::InvalidBinaryLayout(format!(
"PE executable section range {start}..{end} is outside file bounds"
))
})?;
binary_data.insert(
"text_bytes".to_string(),
MapValue::Bytes(text_bytes.to_vec()),
);
}
if !binary_data.contains_key("text_bytes") {
return Err(RbatError::MissingExecutableSection);
}
Ok(binary_data)
}
Object::Mach(mach) => {
let mut binary_data: HashMap<String, MapValue> = HashMap::new();
binary_data.insert("os".to_string(), MapValue::OS(BinaryOS::Mac));
match mach {
goblin::mach::Mach::Binary(macho) => {
let arch = match macho.header.cputype {
7 => BinaryArch::X86,
16777223 => BinaryArch::X64,
12 => BinaryArch::Arm,
16777228 => BinaryArch::Arm64,
other => {
return Err(RbatError::UnsupportedBinaryFormat(format!(
"Unsupported Mach-O CPU type: {:#x}",
other
)));
}
};
binary_data.insert("arch".to_string(), MapValue::Arch(arch));
binary_data.insert("entry_addr".to_string(), MapValue::Word(macho.entry));
for segment in &macho.segments {
for (section, section_data) in segment.into_iter().flatten() {
let section_name = section.name().unwrap_or("");
let segment_name = section.segname().unwrap_or("");
if segment_name == "__TEXT" && section_name == "__text" {
binary_data.insert(
"text_bytes".to_string(),
MapValue::Bytes(section_data.to_vec()),
);
break;
}
}
if binary_data.contains_key("text_bytes") {
break;
}
}
}
goblin::mach::Mach::Fat(fat) => {
for arch_item in fat {
if let Ok(goblin::mach::SingleArch::MachO(macho)) = arch_item {
let arch = match macho.header.cputype {
7 => BinaryArch::X86,
16777223 => BinaryArch::X64,
12 => BinaryArch::Arm,
16777228 => BinaryArch::Arm64,
other => {
return Err(RbatError::UnsupportedBinaryFormat(format!(
"Unsupported Mach-O CPU type: {:#x}",
other
)));
}
};
binary_data.insert("arch".to_string(), MapValue::Arch(arch));
binary_data
.insert("entry_addr".to_string(), MapValue::Word(macho.entry));
for segment in &macho.segments {
for (section, section_data) in segment.into_iter().flatten() {
let section_name = section.name().unwrap_or("");
let segment_name = section.segname().unwrap_or("");
if segment_name == "__TEXT" && section_name == "__text" {
binary_data.insert(
"text_bytes".to_string(),
MapValue::Bytes(section_data.to_vec()),
);
break;
}
}
if binary_data.contains_key("text_bytes") {
break;
}
}
break;
}
}
}
}
if !binary_data.contains_key("entry_addr")
|| !binary_data.contains_key("text_bytes")
{
return Err(RbatError::MissingExecutableSection);
}
Ok(binary_data)
}
Object::Archive(_) => Err(RbatError::UnsupportedBinaryFormat(
"Archive files are not supported for disassembly".to_string(),
)),
Object::Unknown(magic) => Err(RbatError::UnsupportedBinaryFormat(format!(
"Unknown file format magic: {magic:#x}"
))),
_ => Err(RbatError::UnsupportedBinaryFormat(
"Unsupported file type for disassembly".to_string(),
)),
}
}
/// Scans for suspicious functions related to process injection, memory manipulation,
/// or dynamic code loading across ELF, PE, and Mach-O binaries.
pub fn check_process_injec(&self) -> Result<HashSet<String>> {
let blacklist = get_txt_from_file("blacklisted_process_injec.txt")?;
let mut sus_func: HashSet<String> = HashSet::new();
match &self.binary_object {
Object::Elf(elf) => {
// For ELF, check dynamic symbols that are imported (st_shndx == 0)
for dy in &elf.dynsyms {
if dy.st_shndx == 0
&& let Some(name) = elf.dynstrtab.get_at(dy.st_name)
&& blacklist.contains(&name.to_string())
{
sus_func.insert(name.to_owned());
}
}
Ok(sus_func)
}
Object::PE(pe) => {
for import in &pe.imports {
let import_name = import.name.to_string();
if blacklist
.iter()
.any(|item: &String| item.eq_ignore_ascii_case(&import_name))
{
sus_func.insert(import_name);
}
}
Ok(sus_func)
}
Object::Mach(mach) => {
let matches_blacklist = |name: &str| {
let normalized = name.trim_start_matches('_');
blacklist
.iter()
.any(|item: &String| item.eq_ignore_ascii_case(normalized))
};
let mut collect_from_macho = |macho: &goblin::mach::MachO<'_>| -> Result<()> {
if let Ok(imports) = macho.imports() {
for import in imports {
if matches_blacklist(import.name) {
sus_func.insert(import.name.to_string());
}
}
}
for (name, nlist) in macho.symbols().flatten() {
if nlist.is_undefined() && matches_blacklist(name) {
sus_func.insert(name.to_string());
}
}
Ok(())
};
match mach {
goblin::mach::Mach::Binary(macho) => collect_from_macho(macho)?,
goblin::mach::Mach::Fat(fat) => {
for arch in fat {
if let Ok(goblin::mach::SingleArch::MachO(macho)) = arch {
collect_from_macho(&macho)?;
}
}
}
}
Ok(sus_func)
}
_ => Err(RbatError::UnsupportedBinaryFormat(
"Process injection checks currently support ELF, PE, and Mach-O binaries only"
.to_string(),
)),
}
}
/// Detects potential API hooking activity by scanning for exported functions and known hooking patterns.
///
/// Combines static symbol table analysis with a YARA scan for specific code signatures.
pub fn detect_api_hooking(
&self,
section_ranges: &[SectionRange],
) -> Result<HashMap<String, u64>> {
let mut api_hooking_func: HashMap<String, u64> = HashMap::new();
let blacklist = get_txt_from_file("api_hooking_apis.txt")?;
match &self.binary_object {
Object::Elf(elf) => {
for dy in &elf.dynsyms {
if dy.st_shndx > 0
&& let Some(name) = elf.dynstrtab.get_at(dy.st_name)
&& blacklist.iter().any(|b| name.contains(b))
{
// Only flag if it's a known hooking-related name or suspicious export
api_hooking_func.insert(name.to_owned(), dy.st_value);
}
}
}
Object::PE(pe) => {
for import in &pe.imports {
let function = import.name.to_string();
if blacklist.iter().any(|b| function.contains(b)) {
api_hooking_func
.insert(format!("{}!{}", import.dll, function), import.rva as u64);
}
}
}
Object::Mach(mach) => {
let mut collect_from_macho = |macho: &goblin::mach::MachO<'_>| -> Result<()> {
for (name, symbol) in macho.symbols().flatten() {
if symbol.is_global()
&& !symbol.is_undefined()
&& blacklist.iter().any(|b| name.contains(b))
{
api_hooking_func.insert(name.to_string(), symbol.n_value);
}
}
Ok(())
};
match mach {
goblin::mach::Mach::Binary(macho) => collect_from_macho(macho)?,
goblin::mach::Mach::Fat(fat) => {
for arch in fat {
if let Ok(goblin::mach::SingleArch::MachO(macho)) = arch {
collect_from_macho(&macho)?;
}
}
}
}
}
_ => {}
}
// Supplement with YARA scan for patterns and strings
let yara = YaraHandler::new("api_hooking.yar".to_owned());
if let Ok(rules) = yara.compile_yara_rule()
&& let Ok(matches) = yara.scan_mem(&rules, self.buffer, section_ranges)
{
for (rule_name, instances) in matches {
for m in instances {
let key = format!("{}:{}", rule_name, m.data);
api_hooking_func.entry(key).or_insert(m.offset as u64);
}
}
}
Ok(api_hooking_func)
}
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::tempdir;
use super::*;
use crate::utils::test_helpers::test_helpers;
#[test]
fn test_evaluate_section_entropy_elf() {
let dir = tempdir().unwrap();
let path = dir.path().join("dummy_elf");
test_helpers::generate_elf(&path);
let buffer = fs::read(&path).unwrap();
let binary_object = Object::parse(&buffer).unwrap();
let parser = Parser::new(&buffer, &binary_object);
let result = parser.evaluate_section_entropy();
assert!(result.is_ok());
let entropy = result.unwrap();
assert!(entropy.contains_key(".text"));
}
#[test]
fn test_parse_buffer_elf() {
let dir = tempdir().unwrap();
let path = dir.path().join("dummy_elf");
test_helpers::generate_elf(&path);
let buffer = fs::read(&path).unwrap();
let binary_object = Object::parse(&buffer).unwrap();
let parser = Parser::new(&buffer, &binary_object);
let result = parser.parse_buffer();
match result {
Ok(data) => {
assert!(data.contains_key("os"));
assert!(data.contains_key("text_bytes"));
}
Err(e) => panic!("parse_buffer failed with: {:?}", e),
}
}
#[test]
fn test_evaluate_section_entropy_macho() {
let dir = tempdir().unwrap();
let path = dir.path().join("dummy_macho");
test_helpers::generate_macho(&path);
let buffer = fs::read(&path).unwrap();
let binary_object = Object::parse(&buffer).unwrap();
let parser = Parser::new(&buffer, &binary_object);
let result = parser.evaluate_section_entropy();
assert!(result.is_ok());
let entropy = result.unwrap();
assert!(entropy.contains_key("__text"));
}
#[test]
fn test_parse_buffer_unsupported_arch() {
let dir = tempdir().unwrap();
let path = dir.path().join("unsupported_elf");
test_helpers::generate_elf_unsupported(&path);
let buffer = fs::read(&path).unwrap();
let binary_object = Object::parse(&buffer).unwrap();
let parser = Parser::new(&buffer, &binary_object);
let result = parser.parse_buffer();
match result {
Err(RbatError::UnsupportedBinaryFormat(msg)) => {
assert!(msg.contains("Unsupported ELF machine architecture: 0xffff"));
}
_ => panic!("Expected UnsupportedBinaryFormat error, got {:?}", result),
}
}
}