forked from AFLplusplus/LibAFL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinjections.rs
501 lines (441 loc) · 14.9 KB
/
injections.rs
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
//! Detect injection vulnerabilities
/*
* TODOs:
* - read in export addresses of shared libraries to resolve functions
*
* Maybe:
* - return code analysis support (not needed currently)
* - regex support (not needed currently)
* - std::string and Rust String support (would need such target functions added)
*
*/
use std::{ffi::CStr, fmt::Display, fs, os::raw::c_char, path::Path};
use hashbrown::HashMap;
use libafl::{inputs::UsesInput, Error};
use libafl_qemu_sys::GuestAddr;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "hexagon"))]
use crate::SYS_execve;
use crate::{
elf::EasyElf,
emu::EmulatorModules,
modules::{EmulatorModule, EmulatorModuleTuple, NopAddressFilter, NOP_ADDRESS_FILTER},
qemu::{ArchExtras, Hook, SyscallHookResult},
CallingConvention, Qemu,
};
#[cfg(feature = "hexagon")]
/// Hexagon syscalls are not currently supported by the `syscalls` crate, so we just paste this here for now.
/// <https://github.com/qemu/qemu/blob/11be70677c70fdccd452a3233653949b79e97908/linux-user/hexagon/syscall_nr.h#L230>
const SYS_execve: u8 = 221;
/// Parses `injections.yaml`
fn parse_yaml<P: AsRef<Path> + Display>(path: P) -> Result<Vec<YamlInjectionEntry>, Error> {
serde_yaml::from_str(&fs::read_to_string(&path)?)
.map_err(|e| Error::serialize(format!("Failed to deserialize yaml at {path}: {e}")))
}
/// Parses `injections.toml`
fn parse_toml<P: AsRef<Path> + Display>(
path: P,
) -> Result<HashMap<String, InjectionDefinition>, Error> {
toml::from_str(&fs::read_to_string(&path)?)
.map_err(|e| Error::serialize(format!("Failed to deserialize toml at {path}: {e}")))
}
/// Converts the injects.yaml format to the internal toml-like format
fn yaml_entries_to_definition(
yaml_entries: &Vec<YamlInjectionEntry>,
) -> Result<HashMap<String, InjectionDefinition>, Error> {
let mut ret = HashMap::new();
for entry in yaml_entries {
let mut functions = HashMap::new();
for function in &entry.functions {
functions.insert(
function.function.clone(),
FunctionDescription {
param: function.parameter,
},
);
}
let mut matches = Vec::new();
let mut tokens = Vec::new();
for test in &entry.tests {
matches.push(test.match_value.clone());
tokens.push(test.input_value.clone());
}
if ret
.insert(
entry.name.clone(),
InjectionDefinition {
tokens,
matches,
functions,
},
)
.is_some()
{
return Err(Error::illegal_argument(format!(
"Entry {} was multiply defined!",
entry.name
)));
}
}
Ok(ret)
}
#[derive(Debug, Clone)]
struct LibInfo {
name: String,
off: GuestAddr,
}
impl LibInfo {
fn add_unique(libs: &mut Vec<LibInfo>, new_lib: LibInfo) {
if !libs.iter().any(|lib| lib.name == new_lib.name) {
libs.push(new_lib);
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Test {
input_value: String,
match_value: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Functions {
function: String,
parameter: u8,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct YamlInjectionEntry {
name: String,
functions: Vec<Functions>,
tests: Vec<Test>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
struct FunctionDescription {
param: u8,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct InjectionDefinition {
tokens: Vec<String>,
matches: Vec<String>,
functions: HashMap<String, FunctionDescription>,
}
#[derive(Clone, Debug)]
pub struct Matches {
id: usize,
lib_name: String,
matches: Vec<Match>,
}
#[derive(Clone, Debug)]
pub struct Match {
bytes_lower: Vec<u8>,
original_value: String,
}
#[derive(Debug)]
pub struct InjectionModule {
pub tokens: Vec<String>,
definitions: HashMap<String, InjectionDefinition>,
matches_list: Vec<Matches>,
}
impl InjectionModule {
/// `configure_injections` is the main function to activate the injection
/// vulnerability detection feature.
pub fn from_yaml<P: AsRef<Path> + Display>(yaml_file: P) -> Result<Self, Error> {
let yaml_entries = parse_yaml(yaml_file)?;
let definition = yaml_entries_to_definition(&yaml_entries)?;
Self::new(definition)
}
/// `configure_injections` is the main function to activate the injection
/// vulnerability detection feature.
pub fn from_toml<P: AsRef<Path> + Display>(toml_file: P) -> Result<Self, Error> {
let definition = parse_toml(toml_file)?;
Self::new(definition)
}
pub fn new(definitions: HashMap<String, InjectionDefinition>) -> Result<Self, Error> {
let tokens = definitions
.iter()
.flat_map(|(_lib_name, definition)| &definition.tokens)
.map(ToString::to_string)
.collect();
let mut matches_list = Vec::with_capacity(definitions.len());
for (lib_name, definition) in &definitions {
let matches: Vec<Match> = definition
.matches
.iter()
.map(|match_str| {
let mut bytes_lower = match_str.as_bytes().to_vec();
bytes_lower.make_ascii_lowercase();
Match {
original_value: match_str.clone(),
bytes_lower,
}
})
.collect();
let id = matches_list.len();
matches_list.push(Matches {
lib_name: lib_name.clone(),
id,
matches,
});
}
Ok(Self {
tokens,
definitions,
matches_list,
})
}
fn on_call_check<ET, S>(emulator_modules: &mut EmulatorModules<ET, S>, id: usize, parameter: u8)
where
ET: EmulatorModuleTuple<S>,
S: Unpin + UsesInput,
{
let qemu = emulator_modules.qemu();
let reg: GuestAddr = qemu
.current_cpu()
.unwrap()
.read_function_argument(CallingConvention::Cdecl, parameter)
.unwrap_or_default();
let module = emulator_modules.get_mut::<Self>().unwrap();
let matches = &module.matches_list[id];
//println!("reg value = {:x}", reg);
if reg != 0x00 {
let mut query = unsafe {
let c_str_ptr = reg as *const c_char;
let c_str = CStr::from_ptr(c_str_ptr);
c_str.to_bytes().to_vec()
};
query.make_ascii_lowercase();
//println!("query={}", query);
log::trace!("Checking {}", matches.lib_name);
for match_value in &matches.matches {
if match_value.bytes_lower.len() > matches.matches.len() {
continue;
}
// "crash" if we found the right value
assert!(
find_subsequence(&query, &match_value.bytes_lower).is_none(),
"Found value \"{}\" for {query:?} in {}",
match_value.original_value,
matches.lib_name
);
}
}
}
}
impl<S> EmulatorModule<S> for InjectionModule
where
S: Unpin + UsesInput,
{
type ModuleAddressFilter = NopAddressFilter;
fn init_module<ET>(&self, emulator_modules: &mut EmulatorModules<ET, S>)
where
ET: EmulatorModuleTuple<S>,
{
emulator_modules.syscalls(Hook::Function(syscall_hook::<ET, S>));
}
fn first_exec<ET>(&mut self, emulator_modules: &mut EmulatorModules<ET, S>, _state: &mut S)
where
ET: EmulatorModuleTuple<S>,
{
let qemu = emulator_modules.qemu();
let mut libs: Vec<LibInfo> = Vec::new();
for region in qemu.mappings() {
if let Some(path) = region.path().map(ToOwned::to_owned) {
// skip [heap], [vdso] and friends
if !path.is_empty() && !path.starts_with('[') {
LibInfo::add_unique(
&mut libs,
LibInfo {
name: path.clone(),
off: region.start(),
},
);
}
}
}
for matches in &self.matches_list {
let id = matches.id;
let lib_name = &matches.lib_name;
for (name, func_definition) in &self.definitions[lib_name].functions {
let hook_addrs = if name.to_lowercase().starts_with(&"0x".to_string()) {
let func_pc = u64::from_str_radix(&name[2..], 16)
.map_err(|e| {
Error::illegal_argument(format!(
"Failed to parse hex string {name} from definition for {lib_name}: {e}"
))
})
.unwrap() as GuestAddr;
log::info!("Injections: Hooking hardcoded function {func_pc:#x}");
vec![func_pc]
} else {
libs.iter()
.filter_map(|lib| find_function(qemu, &lib.name, name, lib.off).unwrap())
.inspect(|&func_pc| {
log::info!("Injections: Function {name} found at {func_pc:#x}");
})
.collect()
};
if hook_addrs.is_empty() {
log::warn!("Injections: Function not found for {lib_name}: {name}",);
}
let param = func_definition.param;
for hook_addr in hook_addrs {
emulator_modules.instructions(
hook_addr,
Hook::Closure(Box::new(move |hooks, _state, _guest_addr| {
Self::on_call_check(hooks, id, param);
})),
true,
);
}
}
}
}
fn address_filter(&self) -> &Self::ModuleAddressFilter {
&NopAddressFilter
}
fn address_filter_mut(&mut self) -> &mut Self::ModuleAddressFilter {
unsafe { (&raw mut NOP_ADDRESS_FILTER).as_mut().unwrap().get_mut() }
}
}
#[allow(clippy::too_many_arguments)]
fn syscall_hook<ET, S>(
// Our instantiated [`EmulatorModules`]
emulator_modules: &mut EmulatorModules<ET, S>,
_state: Option<&mut S>,
// Syscall number
syscall: i32,
// Registers
x0: GuestAddr,
x1: GuestAddr,
_x2: GuestAddr,
_x3: GuestAddr,
_x4: GuestAddr,
_x5: GuestAddr,
_x6: GuestAddr,
_x7: GuestAddr,
) -> SyscallHookResult
where
ET: EmulatorModuleTuple<S>,
S: Unpin + UsesInput,
{
log::trace!("syscall_hook {syscall} {SYS_execve}");
debug_assert!(i32::try_from(SYS_execve).is_ok());
if syscall == SYS_execve as i32 {
let _module = emulator_modules.get_mut::<InjectionModule>().unwrap();
if x0 > 0 && x1 > 0 {
let c_array = x1 as *const *const c_char;
let cmd = unsafe {
let c_str_ptr = x0 as *const c_char;
CStr::from_ptr(c_str_ptr).to_string_lossy()
};
assert_ne!(
cmd.to_lowercase(),
"fuzz",
"Found verified command injection!"
);
//println!("CMD {}", cmd);
let first_parameter = unsafe {
if (*c_array.offset(1)).is_null() {
return SyscallHookResult::new(None);
}
CStr::from_ptr(*c_array.offset(1)).to_string_lossy()
};
let second_parameter = unsafe {
if (*c_array.offset(2)).is_null() {
return SyscallHookResult::new(None);
}
CStr::from_ptr(*c_array.offset(2)).to_string_lossy()
};
if first_parameter == "-c"
&& (second_parameter.to_lowercase().contains("';fuzz;'")
|| second_parameter.to_lowercase().contains("\";fuzz;\""))
{
panic!("Found command injection!");
}
//println!("PARAMETERS First {} Second {}", first_parameter, second_
}
SyscallHookResult::new(Some(0))
} else {
SyscallHookResult::new(None)
}
}
fn find_function(
qemu: Qemu,
file: &str,
function: &str,
loadaddr: GuestAddr,
) -> Result<Option<GuestAddr>, Error> {
let mut elf_buffer = Vec::new();
let elf = EasyElf::from_file(file, &mut elf_buffer)?;
let offset = if loadaddr > 0 {
loadaddr
} else {
qemu.load_addr()
};
Ok(elf.resolve_symbol(function, offset))
}
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
#[cfg(test)]
mod tests {
use hashbrown::HashMap;
use super::{yaml_entries_to_definition, InjectionDefinition, YamlInjectionEntry};
#[test]
fn test_yaml_parsing() {
let injections: Vec<YamlInjectionEntry> = serde_yaml::from_str(
r#"
# LDAP injection tests
- name: "ldap"
functions:
- function: "ldap_search_ext"
parameter: 3
- function: "ldap_search_ext_s"
parameter: 3
tests:
- input_value: "*)(FUZZ=*))(|"
match_value: "*)(FUZZ=*))(|"
# XSS injection tests
# This is a minimal example that only checks for libxml2
- name: "xss"
functions:
- function: "htmlReadMemory"
parameter: 0
tests:
- input_value: "'\"><FUZZ"
match_value: "'\"><FUZZ"
"#,
)
.unwrap();
assert_eq!(injections.len(), 2);
assert_eq!(
injections.len(),
yaml_entries_to_definition(&injections)
.unwrap()
.keys()
.len(),
);
}
#[test]
fn test_toml_parsing() {
let injections: HashMap<String, InjectionDefinition> = toml::from_str(
r#"
[ldap]
tokens = ["*)(FUZZ=*))(|"]
matches = ["*)(FUZZ=*))(|"]
[ldap.functions]
ldap_search_ext = {param = 3}
ldap_search_ext_s = {param = 3}
# XSS injection tests
# This is a minimal example that only checks for libxml2
[xss]
tokens = ["'\"><FUZZ"]
matches = ["'\"><FUZZ"]
[xss.functions]
htmlReadMemory = {param = 0}
"#,
)
.unwrap();
assert_eq!(injections.len(), 2);
}
}