Repository navigation
Expand file tree
/
Copy pathrecursive.rs
More file actions
172 lines (152 loc) · 5.71 KB
/
Copy pathrecursive.rs
File metadata and controls
172 lines (152 loc) · 5.71 KB
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
use crate::error::{CryptoTraceError, Result};
use crate::types::Layer;
use std::collections::HashSet;
const DEFAULT_MAX_DEPTH: usize = 10;
const DEFAULT_MAX_TIME_SECS: u64 = 30;
const DEFAULT_MAX_EXPANSION_RATIO: f64 = 100.0;
/// Recursive layer analyzer configuration.
pub struct RecursiveConfig {
pub max_depth: usize,
pub max_time_secs: u64,
pub max_expansion_ratio: f64,
}
impl Default for RecursiveConfig {
fn default() -> Self {
Self {
max_depth: DEFAULT_MAX_DEPTH,
max_time_secs: DEFAULT_MAX_TIME_SECS,
max_expansion_ratio: DEFAULT_MAX_EXPANSION_RATIO,
}
}
}
/// Analyze input recursively, unwrapping layers of encoding/compression/encryption.
/// Each layer is detected, the content is decoded/decompressed, and analysis continues
/// on the result up to max_depth.
pub fn analyze_recursive(data: &[u8], config: &RecursiveConfig) -> Result<Vec<Layer>> {
let start = std::time::Instant::now();
let mut seen_hashes = HashSet::new();
let mut layers = Vec::new();
let mut current_data = data.to_vec();
let mut depth = 0;
while depth < config.max_depth {
// Check timeout
if start.elapsed().as_secs() > config.max_time_secs {
return Err(CryptoTraceError::RecursionTimeout {
timeout: config.max_time_secs,
});
}
// Check for cycle
let current_hash = crate::core::hashing::sha256_hex(¤t_data);
if !seen_hashes.insert(current_hash) {
return Err(CryptoTraceError::CycleDetected);
}
// Detect the current layer
let input_str = String::from_utf8_lossy(¤t_data);
let _hash_detection = crate::core::hashing::detect_hash(&input_str);
let encoding_detection = crate::core::encoding::detect_encoding(&input_str);
let compression_detection = crate::core::compression::detect_compression(¤t_data);
let (entropy, _) = crate::core::entropy::shannon_entropy(¤t_data);
let encryption_detection =
crate::core::encryption::detect_encryption(¤t_data, entropy);
// Determine if we should try to unwrap
let (detected_type, algorithm, confidence) = if let Some(e) = encoding_detection.as_ref() {
(
"encoding".to_string(),
e.encoding_type.clone(),
e.confidence,
)
} else if let Some(c) = compression_detection.as_ref() {
("compression".to_string(), c.format.clone(), c.confidence)
} else if let Some(e) = encryption_detection.as_ref() {
("encryption".to_string(), e.algorithm.clone(), e.confidence)
} else {
// No more layers to unwrap
break;
};
// Try to decode/decompress
let decoded: Option<Vec<u8>> = if let Some(e) = &encoding_detection {
// For Base64, attempt decode
if e.encoding_type == "Base64" {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD
.decode(¤t_data)
.ok()
} else if e.encoding_type == "Hex" {
let input_str = String::from_utf8_lossy(¤t_data);
(0..input_str.len())
.step_by(2)
.filter_map(|i| u8::from_str_radix(&input_str[i..i + 2], 16).ok())
.collect::<Vec<u8>>()
.into()
} else {
None
}
} else if let Some(c) = &compression_detection {
crate::core::compression::try_decompress(¤t_data, &c.format)
.ok()
.map(|r| r.data)
} else {
None
};
// Check expansion ratio
if let Some(ref decoded) = decoded {
if !decoded.is_empty() && !current_data.is_empty() {
let ratio = decoded.len() as f64 / current_data.len() as f64;
if ratio > config.max_expansion_ratio {
return Err(CryptoTraceError::CompressionBomb {
ratio,
limit: config.max_expansion_ratio,
});
}
}
}
let expansion_ratio = decoded.as_ref().map(|d| {
if !current_data.is_empty() {
d.len() as f64 / current_data.len() as f64
} else {
1.0
}
});
let preview = decoded
.as_ref()
.map(|d| d.iter().take(64).cloned().collect());
let layer = Layer {
depth,
detected_type,
algorithm,
confidence,
decoded_preview: preview,
decoded_length: decoded.as_ref().map_or(0, |d| d.len()),
expansion_ratio,
children: vec![],
};
layers.push(layer);
depth += 1;
// Continue with decoded content if available
if let Some(decoded) = decoded {
current_data = decoded;
} else {
break;
}
}
Ok(layers)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_input_no_layers() {
let config = RecursiveConfig::default();
let layers = analyze_recursive(b"hello world", &config).unwrap();
assert!(layers.is_empty());
}
#[test]
fn test_single_base64_layer() {
use base64::Engine;
let data = base64::engine::general_purpose::STANDARD.encode(b"hello world");
let config = RecursiveConfig::default();
let layers = analyze_recursive(data.as_bytes(), &config).unwrap();
assert_eq!(layers.len(), 1);
assert_eq!(layers[0].detected_type, "encoding");
}
}