• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Rust
  • License
    GNU General Publi...
  • Created about 4 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library for loading and executing PE (Portable Executable) from memory without ever touching the disk

memexec

A library for loading and executing PE (Portable Executable) from memory without ever touching the disk

Features

  • Applicable to EXE and DLL (except .NET assembly)
  • Cross-architecture, applicable to x86 and x86-64
  • Zero-dependency
  • Contains a simple, zero-copy PE parser submodule
  • Provides an IAT hooking interface

Install

# Cargo.toml

[dependencies]
memexec = "0.2"

Usage

Execute from memory

⚠The architecture of target program must be same as current process, otherwise an error will occur

use memexec;
use std::fs::File;
use std::io::Read;

/***********************************************************/
/*                         EXE                             */
/***********************************************************/
let mut buf = Vec::new();
File::open("./test.exe")
    .unwrap()
    .read_to_end(&mut buf)
    .unwrap();

unsafe {
    // If you need to pass command line parameters,
    // try to modify PEB's command line buffer
    // Or use `memexec_exe_with_hooks` to hook related functions (see below)
    memexec::memexec_exe(&buf).unwrap();
}


/***********************************************************/
/*                         DLL                             */
/***********************************************************/
let mut buf = Vec::new();
File::open("./test.dll")
    .unwrap()
    .read_to_end(&mut buf)
    .unwrap();

use memexec::peloader::def::DLL_PROCESS_ATTACH;
unsafe {
    // DLL's entry point is DllMain
    memexec_dll(&buf, 0 as _, DLL_PROCESS_ATTACH, 0 as _).unwrap();
}

IAT hooking

Add the hook feature in Cargo.toml

[dependencies]
memexec = { version="0.2", features=[ "hook" ] }

Hook the __wgetmainargs function (see example/__wgetmainargs_hook.rs)

let mut buf = Vec::new();
File::open("./test.x64.exe")
    .unwrap()
    .read_to_end(&mut buf)
    .unwrap();

let mut hooks = HashMap::new();

unsafe {
    hooks.insert(
        "msvcrt.dll!__wgetmainargs".into(),
        mem::transmute::<extern "win64" fn(_, _, _, _, _) -> _, _>(__wgetmainargs),
    );
    memexec::memexec_exe_with_hooks(&buf, &hooks).unwrap();
}

The definition of __wgetmainargs (notice the calling convention on different archtectures):

// https://docs.microsoft.com/en-us/cpp/c-runtime-library/getmainargs-wgetmainargs?view=msvc-160
/*
int __wgetmainargs (
   int *_Argc,
   wchar_t ***_Argv,
   wchar_t ***_Env,
   int _DoWildCard,
   _startupinfo * _StartInfo)
*/
#[cfg(all(target_arch = "x86_64", target_os = "windows"))]
extern "win64" fn __wgetmainargs(
    _Argc: *mut i32,
    _Argv: *mut *const *const u16,
    _Env: *const c_void,
    _DoWildCard: i32,
    _StartInfo: *const c_void,
) -> i32 {
    unsafe {
        *_Argc = 2;
        let a0: Vec<_> = "program_name\0"
            .chars()
            .map(|c| (c as u16).to_le())
            .collect();
        let a1: Vec<_> = "token::whoami\0"
            .chars()
            .map(|c| (c as u16).to_le())
            .collect();
        *_Argv = [a0.as_ptr(), a1.as_ptr()].as_ptr();

        // Avoid calling destructor
        mem::forget(a0);
        mem::forget(a1);
    }

    0
}

PE parser

PE parser could parse programs which have different architectures from current process

use memexec::peparser::PE;

// Zero copy
// Make sure that the lifetime of `buf` is longer than `pe`
let pe = PE::new(&buf);
println!("{:?}", pe);

TODO

  • Replace LoadLibrary with calling load_pe_into_mem recursively

  • Replace GetProcAddress with self-implemented LdrpSnapThunk, so as to support resolving proc address by IMAGE_IMPORT_BY_NAME.Hint

License

The GPLv3 license

More Repositories

1

iox

Tool for port forwarding & intranet proxy
Go
998
star
2

gld

Go shellcode LoaDer
Go
170
star
3

win32api-practice

Offensive tools written for practice purposes
C++
148
star
4

pker

Automatically converts Python source code to Pickle opcode
Python
124
star
5

nic

🌀 Nic is a HTTP request client with elegant and easy-to-use API
Go
103
star
6

secure-cookie-faker

Security tool to encode/decode Golang web-frameworks' client-side session cookie which use `gorilla/securecookie` or `gorilla/sessions`, such as Gin, Echo or Iris
Go
36
star
7

lessons-robber

CUMT公选课多线程/协程抢课脚本
Python
21
star
8

analog-login

CUMT教务系统模拟登录
Python
14
star
9

ntlmssp

Windows NTLMSSP library
Go
11
star
10

zip_crack

zip压缩文件密码暴力破解
Python
9
star
11

macho-ld

In-memory loading and executing Mach-O files
Rust
6
star
12

ctf-hash-proof

fast cli tool written for CTFer to proof hash (md5, sha1, sha256, sha512)
Go
6
star
13

tar-vuln-server

复现利用tar指令checkpoint-action参数提权的http server程序
Go
4
star
14

nemesis

cli webshell manager
Python
3
star
15

win64-syscall

Windows x64 indirect syscall lib for maldev with no_std supporting
Rust
3
star
16

async-socks5

Rust
3
star
17

EddieIvan01.github.io

SCSS
3
star
18

flask-bbs

simple BBS demo, written in Flask and Bootstrap
JavaScript
2
star
19

roarCTF-dist-casino

roarCTF challenge dist source code and writeup
Python
2
star
20

Generate_Char_By_Xor

CTF中过滤指定字符的webshell,php中由字符异或生成新字符
Python
2
star
21

Dir_Scanner_WithProxies

using proxies to scan websites' dirs
Python
1
star
22

Game

vb小游戏——生死狙击
Visual Basic
1
star
23

x-csrf

middleware to defend CSRF attack for gin framework
Go
1
star
24

ProxyPool

a simple proxy pool written in Golang
Go
1
star
25

flag

1
star
26

functional-programming

some basic data structures written in Scheme
Scheme
1
star