threatflux-binary-analysis 0.2.0

Comprehensive binary analysis library with multi-format support, disassembly, and security analysis
Documentation
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
#![allow(clippy::uninlined_format_args)]
//! # ThreatFlux Binary Analysis Library
//!
//! A comprehensive binary analysis framework for security research, reverse engineering,
//! and threat detection. Supports multiple binary formats with advanced analysis capabilities.
//!
//! ## Features
//!
//! - **Multi-format Support**: ELF, PE, Mach-O, Java, WASM
//! - **Disassembly**: Multi-architecture support via Capstone and iced-x86
//! - **Control Flow Analysis**: CFG construction, complexity metrics, anomaly detection
//! - **Symbol Resolution**: Debug info parsing, demangling, cross-references
//! - **Entropy Analysis**: Statistical analysis, packing detection
//! - **Security Analysis**: Vulnerability patterns, malware indicators
//!
//! ## Quick Start
//!
//! ```rust
//! use threatflux_binary_analysis::BinaryAnalyzer;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Example with minimal data - analysis may fail for incomplete binaries
//! let data = vec![0x7f, 0x45, 0x4c, 0x46]; // ELF magic
//!
//! let analyzer = BinaryAnalyzer::new();
//! match analyzer.analyze(&data) {
//!     Ok(analysis) => {
//!         println!("Format: {:?}", analysis.format);
//!         println!("Architecture: {:?}", analysis.architecture);
//!     }
//!     Err(e) => {
//!         println!("Analysis failed: {}", e);
//!     }
//! }
//! # Ok(())
//! # }
//! ```

pub mod analysis;
pub mod error;
pub mod formats;
pub mod types;

#[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
pub mod disasm;

pub mod utils;

// Re-export main types
#[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
pub use disasm::DisassemblyEngine;
pub use error::{BinaryError, Result};
pub use types::{
    AnalysisResult, Architecture, BasicBlock, BinaryFormat, BinaryFormatParser, BinaryFormatTrait,
    BinaryMetadata, CallGraph, CallGraphConfig, CallGraphEdge, CallGraphNode, CallGraphStatistics,
    ComplexityMetrics, ControlFlowGraph, EnhancedControlFlowAnalysis, EntropyAnalysis, Export,
    Function, HalsteadMetrics, Import, Instruction, Loop, LoopType, NodeType, Section,
    SecurityIndicators, Symbol,
};

/// Main entry point for binary analysis
pub struct BinaryAnalyzer {
    config: AnalysisConfig,
}

/// Configuration for binary analysis
#[derive(Debug, Clone)]
pub struct AnalysisConfig {
    /// Enable disassembly analysis
    pub enable_disassembly: bool,
    /// Preferred disassembly engine
    #[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
    pub disassembly_engine: DisassemblyEngine,
    /// Enable control flow analysis
    pub enable_control_flow: bool,
    /// Enable call graph analysis
    pub enable_call_graph: bool,
    /// Enable cognitive complexity calculation
    pub enable_cognitive_complexity: bool,
    /// Enable advanced loop analysis
    pub enable_advanced_loops: bool,
    /// Enable entropy analysis
    pub enable_entropy: bool,
    /// Enable symbol resolution
    pub enable_symbols: bool,
    /// Maximum bytes to analyze for large files
    pub max_analysis_size: usize,
    /// Architecture hint (None for auto-detection)
    pub architecture_hint: Option<Architecture>,
    /// Call graph configuration
    pub call_graph_config: Option<CallGraphConfig>,
}

impl Default for AnalysisConfig {
    fn default() -> Self {
        Self {
            enable_disassembly: true,
            #[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
            disassembly_engine: DisassemblyEngine::Auto,
            enable_control_flow: true,
            enable_call_graph: false,
            enable_cognitive_complexity: true,
            enable_advanced_loops: true,
            enable_entropy: true,
            enable_symbols: true,
            max_analysis_size: 100 * 1024 * 1024, // 100MB
            architecture_hint: None,
            call_graph_config: None,
        }
    }
}

impl BinaryAnalyzer {
    /// Create a new analyzer with default configuration
    pub fn new() -> Self {
        Self::with_config(AnalysisConfig::default())
    }

    /// Create a new analyzer with custom configuration
    pub fn with_config(config: AnalysisConfig) -> Self {
        Self { config }
    }

    /// Get a reference to the analysis configuration
    pub fn config(&self) -> &AnalysisConfig {
        &self.config
    }

    /// Analyze a binary file from raw data
    pub fn analyze(&self, data: &[u8]) -> Result<AnalysisResult> {
        let binary_file = BinaryFile::parse(data)?;
        self.analyze_binary(&binary_file)
    }

    /// Analyze a parsed binary file
    pub fn analyze_binary(&self, binary: &BinaryFile) -> Result<AnalysisResult> {
        #[allow(unused_mut)] // mut needed when optional analysis features are enabled
        let mut result = AnalysisResult {
            format: binary.format(),
            architecture: binary.architecture(),
            entry_point: binary.entry_point(),
            sections: binary.sections().to_vec(),
            symbols: binary.symbols().to_vec(),
            imports: binary.imports().to_vec(),
            exports: binary.exports().to_vec(),
            metadata: binary.metadata().clone(),
            ..Default::default()
        };

        // Perform optional analyses based on configuration
        if self.config.enable_disassembly {
            #[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
            {
                result.disassembly = Some(self.perform_disassembly(binary)?);
            }
        }

        if self.config.enable_control_flow {
            #[cfg(feature = "control-flow")]
            {
                result.control_flow = Some(self.perform_control_flow_analysis(binary)?);
            }
        }

        if self.config.enable_call_graph {
            #[cfg(feature = "control-flow")]
            {
                result.call_graph = Some(self.perform_call_graph_analysis(binary)?);
            }
        }

        if self.config.enable_cognitive_complexity || self.config.enable_advanced_loops {
            #[cfg(feature = "control-flow")]
            {
                result.enhanced_control_flow =
                    Some(self.perform_enhanced_control_flow_analysis(binary)?);
            }
        }

        if self.config.enable_entropy {
            #[cfg(feature = "entropy-analysis")]
            {
                result.entropy = Some(self.perform_entropy_analysis(binary)?);
            }
        }

        #[cfg(feature = "symbol-resolution")]
        {
            if self.config.enable_symbols {
                analysis::symbols::demangle_symbols(&mut result.symbols);
            }
        }

        Ok(result)
    }

    #[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
    fn perform_disassembly(&self, binary: &BinaryFile) -> Result<Vec<Instruction>> {
        disasm::disassemble_binary(binary, &self.config)
    }

    #[cfg(feature = "control-flow")]
    fn perform_control_flow_analysis(&self, binary: &BinaryFile) -> Result<Vec<ControlFlowGraph>> {
        analysis::control_flow::analyze_binary(binary)
    }

    #[cfg(feature = "control-flow")]
    fn perform_call_graph_analysis(&self, binary: &BinaryFile) -> Result<CallGraph> {
        let config = self.config.call_graph_config.clone().unwrap_or_default();
        analysis::call_graph::analyze_binary_with_config(binary, config)
    }

    #[cfg(feature = "control-flow")]
    fn perform_enhanced_control_flow_analysis(
        &self,
        binary: &BinaryFile,
    ) -> Result<EnhancedControlFlowAnalysis> {
        // Build enhanced control flow graphs
        let control_flow_config = analysis::control_flow::AnalysisConfig {
            max_instructions: 10000,
            max_depth: 100,
            detect_loops: true,
            calculate_metrics: true,
            enable_call_graph: false,
            enable_cognitive_complexity: self.config.enable_cognitive_complexity,
            enable_advanced_loops: self.config.enable_advanced_loops,
            call_graph_config: None,
        };

        let analyzer = analysis::control_flow::ControlFlowAnalyzer::with_config(
            binary.architecture(),
            control_flow_config,
        );
        let control_flow_graphs = analyzer.analyze_binary(binary)?;

        // Compute summary statistics
        let mut total_cognitive_complexity = 0;
        let mut max_cognitive_complexity = 0;
        let mut most_complex_function = None;
        let mut functions_analyzed = 0;

        let mut total_loops = 0;
        let mut natural_loops = 0;
        let mut irreducible_loops = 0;
        let mut nested_loops = 0;
        let mut max_nesting_depth = 0;
        let mut loops_by_type = std::collections::HashMap::new();

        for cfg in &control_flow_graphs {
            functions_analyzed += 1;

            // Cognitive complexity stats
            let cognitive = cfg.complexity.cognitive_complexity;
            total_cognitive_complexity += cognitive;
            if cognitive > max_cognitive_complexity {
                max_cognitive_complexity = cognitive;
                most_complex_function = Some(cfg.function.name.clone());
            }

            // Loop stats
            total_loops += cfg.loops.len();
            for loop_info in &cfg.loops {
                match loop_info.loop_type {
                    LoopType::Natural => natural_loops += 1,
                    LoopType::Irreducible => irreducible_loops += 1,
                    _ => {}
                }

                if loop_info.nesting_level > 1 {
                    nested_loops += 1;
                }

                if loop_info.nesting_level > max_nesting_depth {
                    max_nesting_depth = loop_info.nesting_level;
                }

                *loops_by_type
                    .entry(loop_info.loop_type.clone())
                    .or_insert(0) += 1;
            }
        }

        let average_cognitive_complexity = if functions_analyzed > 0 {
            total_cognitive_complexity as f64 / functions_analyzed as f64
        } else {
            0.0
        };

        let cognitive_complexity_summary = types::CognitiveComplexityStats {
            total_cognitive_complexity,
            average_cognitive_complexity,
            max_cognitive_complexity,
            most_complex_function,
            functions_analyzed,
        };

        let loop_analysis_summary = types::LoopAnalysisStats {
            total_loops,
            natural_loops,
            irreducible_loops,
            nested_loops,
            max_nesting_depth,
            loops_by_type,
        };

        Ok(EnhancedControlFlowAnalysis {
            control_flow_graphs,
            cognitive_complexity_summary,
            loop_analysis_summary,
        })
    }

    #[cfg(feature = "entropy-analysis")]
    fn perform_entropy_analysis(&self, binary: &BinaryFile) -> Result<EntropyAnalysis> {
        analysis::entropy::analyze_binary(binary)
    }
}

impl Default for BinaryAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

/// Parsed binary file representation
pub struct BinaryFile {
    data: Vec<u8>,
    parsed: Box<dyn BinaryFormatTrait>,
}

impl BinaryFile {
    /// Parse binary data and detect format
    pub fn parse(data: &[u8]) -> Result<Self> {
        let format = formats::detect_format(data)?;
        let parsed = formats::parse_binary(data, format)?;

        Ok(Self {
            data: data.to_vec(),
            parsed,
        })
    }

    /// Get the binary format type
    pub fn format(&self) -> BinaryFormat {
        self.parsed.format_type()
    }

    /// Get the target architecture
    pub fn architecture(&self) -> Architecture {
        self.parsed.architecture()
    }

    /// Get the entry point address
    pub fn entry_point(&self) -> Option<u64> {
        self.parsed.entry_point()
    }

    /// Get binary sections
    pub fn sections(&self) -> &[Section] {
        self.parsed.sections()
    }

    /// Get symbol table
    pub fn symbols(&self) -> &[Symbol] {
        self.parsed.symbols()
    }

    /// Get imports
    pub fn imports(&self) -> &[Import] {
        self.parsed.imports()
    }

    /// Get exports
    pub fn exports(&self) -> &[Export] {
        self.parsed.exports()
    }

    /// Get binary metadata
    pub fn metadata(&self) -> &BinaryMetadata {
        self.parsed.metadata()
    }

    /// Get raw binary data
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_analyzer_creation() {
        let analyzer = BinaryAnalyzer::new();
        assert!(analyzer.config.enable_disassembly);
        assert!(analyzer.config.enable_control_flow);
        assert!(!analyzer.config.enable_call_graph);
        assert!(analyzer.config.enable_cognitive_complexity);
        assert!(analyzer.config.enable_advanced_loops);
        assert!(analyzer.config.enable_entropy);
        assert!(analyzer.config.enable_symbols);
    }

    #[test]
    fn test_custom_config() {
        let config = AnalysisConfig {
            enable_disassembly: false,
            #[cfg(any(feature = "disasm-capstone", feature = "disasm-iced"))]
            disassembly_engine: DisassemblyEngine::Auto,
            enable_control_flow: true,
            enable_call_graph: true,
            enable_cognitive_complexity: false,
            enable_advanced_loops: true,
            enable_entropy: false,
            enable_symbols: true,
            max_analysis_size: 1024,
            architecture_hint: Some(Architecture::X86_64),
            call_graph_config: Some(CallGraphConfig::default()),
        };

        let analyzer = BinaryAnalyzer::with_config(config);
        assert!(!analyzer.config.enable_disassembly);
        assert!(analyzer.config.enable_control_flow);
        assert!(analyzer.config.enable_call_graph);
        assert!(!analyzer.config.enable_cognitive_complexity);
        assert!(analyzer.config.enable_advanced_loops);
        assert!(!analyzer.config.enable_entropy);
        assert!(analyzer.config.enable_symbols);
        assert_eq!(analyzer.config.max_analysis_size, 1024);
        assert!(analyzer.config.call_graph_config.is_some());
    }
}