Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute raw instructions from a memory buffer in Rust?

Tags:

rust

I'm attempting to make a buffer of memory executable, then execute it in Rust. I've gotten all the way until I need to cast the raw executable bytes as code/instructions. You can see a working example in C below.

Extra details:

  • Rust 1.34
  • Linux
  • CC 8.2.1
unsigned char code[] = {
0x55,                           //    push   %rbp
0x48, 0x89, 0xe5,               //    mov    %rsp,%rbp
0xb8, 0x37, 0x00, 0x00, 0x00,   //    mov    $0x37,%eax
0xc9,                           //    leaveq
0xc3                            //    retq
};


void reflect(const unsigned char *code) {
  void *buf;

  /* copy code to executable buffer */    
  buf = mmap(0, sizeof(code), PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_ANON,-1,0);
  memcpy(buf, code, sizeof(code));

  ((void (*) (void))buf)();
}
extern crate mmap;

use mmap::{MapOption, MemoryMap};

unsafe fn reflect(instructions: &[u8]) {
    let map = MemoryMap::new(
        instructions.len(),
        &[
            MapOption::MapAddr(0 as *mut u8),
            MapOption::MapOffset(0),
            MapOption::MapFd(-1),
            MapOption::MapReadable,
            MapOption::MapWritable,
            MapOption::MapExecutable,
            MapOption::MapNonStandardFlags(libc::MAP_ANON),
            MapOption::MapNonStandardFlags(libc::MAP_PRIVATE),
        ],
    )
    .unwrap();

    std::ptr::copy(instructions.as_ptr(), map.data(), instructions.len());
    // How to cast into extern "C" fn() ?
}
like image 727
Skarlett Avatar asked Jan 01 '23 01:01

Skarlett


1 Answers

Use mem::transmute to cast a raw pointer to a function pointer type.

use std::mem;

let func: unsafe extern "C" fn() = mem::transmute(map.data());
func();
like image 104
Francis Gagné Avatar answered Jan 05 '23 17:01

Francis Gagné