Programming

Dynamically Import Functions

This post will introduce you to a fairly simple concept, the purpose of this is to hide functions from the IAT and also calling functions from Windows Native API.

The way this is done is by:

  • Defining the prototype of the function (use MSDN for that)
  • Loading the DLL (unless it is kernel32.dll) -> LoadLibrary
  • Getting the handle of the module -> GetModuleHandle
  • Getting the function address -> GetProcAddress

Stop here if you want to figure out how to actually code it

Table of Contents

So let’s hop into coding!

The first example I’ll give is for CreateProcessW (check this if you don’t know what W means)

Defining the function’s prototype

By checking the MSDN documentation we come across this prototype:

That green underline is due to VS not finding a definition of that function, ignore it.

WINAPI is just stdcall, a calling conventionI might write a post about those someday.

So, let’s arrange that, make it a function pointer and typedef:

Ps: Note that Asterisk after WINAPI, meaning it refers to a function pointer.

Now we write a variable of that type:

Keep in mind that writing the function pointer is optional but makes the code 100x cleaner and beautiful.

Loading the module

The next step is getting the handle of Kernel32.dll since that’s where CreateProcessW lies (you can find that out by the library requirement in the MSDN page), we don’t need to load it since it gets automatically loaded into every process:

Getting the function address

The final step before actually calling the function is to get the address of the function:

Calling the function

Now let’s call it!


Function from user32.dll

Now let’s try with MessageBoxW(not going to explain the steps since should be pretty clear from now):

Now, let’s run and…

Remember I said that we needed to load the DLL if we weren’t using a Kernel32 function? Yep, that’s right now instead of GetModuleHandle, we use LoadLibrary.

And now it works!

Now I hope you can call this native function “NtGetTickCount”:

The Nt implies it is from ntdll.dll since it is a native function

And that’s it! See? Not rocket science 😛

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s