0

I am trying to allocate space in memory with ntdll.dll. I am using the NtApi and winapi crates.

When I try to allocate, I get the next error:

exit code: 0xc0000005, STATUS_ACCESS_VIOLATION

How do I need to send the pointer to NtAllocateVirtualMemory()?

Why does VirtualAllocEx() work?

I understand when I call VirtualAllocEx(), the process is kernel32.dll -> ntdll.dll, so why doesn't this work when I send this to NtAllocateVirtualMemory()?

main.rs

use ntapi::ntmmapi::NtAllocateVirtualMemory;
use ntapi::ntpsapi::NtCurrentProcess;
use ntapi::winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE};
use winapi::shared::ntdef::{NT_SUCCESS};
use ntapi::_core::ptr::null_mut;

fn main() {
    unsafe {
        // let null_ptr=std::ptr::null();
        // let null_base:*const winapi::ctypes::c_void=null_ptr as *const _;
        let mut buffer=null_mut();
        let status = NtAllocateVirtualMemory(
            NtCurrentProcess,
            *buffer,
            0,
            0x1000 as *mut _,
            MEM_COMMIT | MEM_RESERVE,
            PAGE_READWRITE,
        );

        if !NT_SUCCESS(status) {
        // if status as usize == 0x0 {
            println!("Allocation Fails");
        } else {
            println!("Allocation Success");
        }
    }
}

Cargo.toml

[package]
name = "allocate_null"
version = "0.1.0"
edition = "2018"

[dependencies]
winapi = {version="0.3.9", features=["ntdef","winnt","memoryapi"]}
ntapi = "0.3.6"
IInspectable
  • 46,945
  • 8
  • 85
  • 181
her0mx
  • 1
  • 4
  • 1
    shouldn't `*buffer` be `&mut buffer`? – kmdreko Nov 03 '21 at 17:51
  • i do the changues and the allocations Fails, but i don't get the error: (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION – her0mx Nov 03 '21 at 18:03
  • 1
    `NtAllocateVirtualMemory` is not really intended to be used from user programs. I'd highly suggest calling `VirtualAlloc` or siblings instead as they are easier to use and guaranteed to be ABI stable. – Mgetz Nov 03 '21 at 18:19
  • @Mgetz - `NtAllocateVirtualMemory ` is not less stable than `VirtualAlloc` . `0x1000 as *mut _,` is wrong - 4 pparameter is pointer to `size_t` and can not be constant – RbMm Nov 03 '21 at 18:28
  • @RbMm i use size_t and works thanks! – her0mx Nov 03 '21 at 18:54
  • @RbMm now i have another problem...I trie to allocate 4096 bytes in memory, but when i see the value of Buffer on memory only have 16*16=256 bytes :S why? thanks for your help – her0mx Nov 03 '21 at 19:12
  • probably you wrong look to this value( this not visible to which value you look and how). – RbMm Nov 03 '21 at 19:20

0 Answers0