Search code examples
c++windowslinkerlinker-errorsntdll

Creating a process in memory C++


I've been working on this code for hours, and it is driving me crazy!

The entire source is here http://pastebin.com/Urxh68W4 but I'm pretty sure I know the problem.

extern "C" NTSYSAPI LONG NTAPI ZwUnmapViewOfSection(HANDLE, PVOID);

When I run it I get the following error:

Error 1 error LNK2019: unresolved external symbol __imp__ZwUnmapViewOfSection@8 referenced in function _wWinMain@16

I'm guessing that there is some dll or library I should be including so I added Ntoskrnl.lib into my project because it contains the ZwUnmapViewOfSection function.

I have absolutely no idea what to do. Should I have used the Ntdll.dll? If so, how do I even link a dll? I thought you could only use the libraries in Visual Studio 2010.

Also, what exactly is NTSYSAPI and NTAPI? There is hardly any information on the net.


Solution

  • This looks like user-mode code, so you'll likely not want to link against ntoskrnl.lib. You would rather link against ntdll.

    The way I would probably do this is to use dynamic linking and call GetProcAddress passing in a HANDLE to ntdll.dll and ZwUnmapViewOfSection.

    Example code:

    typedef LONG (NTAPI *pfnZwUnmapViewOfSection)(HANDLE, PVOID);
    HMODULE hMod = GetModuleHandle("ntdll.dll");
    pfnZwUnmapViewOfSection pZwUnmapViewOfSection= (pfnZwUnmapViewOfSection)GetProcAddress(hMod, "ZwUnmapViewOfSection");
    

    I haven't compiled this, but it should look something like that (maybe add some error checking, etc).

    With regard to your other questions: NTAPI is a macro that defines the calling-convention, in this case __stdcall. The calling convention has to do with how the arguments to the function are passed, and who will be cleaning up those arguments.

    For example, __stdcall requires the arguments to be pushed on the stack in reverse order and the callee will clean-up the stack.

    Similarly, NTSYSAPI is a macro that just resolves to __declspec(dllimport) if I recall correctly.

    Also, I should point out that calling functions exported by NtDll in user-mode is generally frowned upon. And, the code that you're writing will also have additional problems along the way (even after it appears to be working).

    In case you're looking for another example of code that performs a very similar task to the one you're writing, you might check here. It was a technique used by the Duqu malware. Good luck!