Search code examples
assemblynasmshellcode

NASM linking libraries during runtime


This post on windows shellcoding that i came across shows how to make a simple shellcode for Sleep function that is located in kernel32.dll. I understand the code but it seems as though that you can't call the function without knowing the exact address of the function in the library for which you have to use arwin32.exe that's provided by the author of the post.

;sleep.asm
[SECTION .text]

global _start


_start:
        xor eax,eax
        mov ebx, 0x77e61bea ;address of Sleep
        mov ax, 5000        ;pause for 5000ms
        push eax
        call ebx        ;Sleep(ms);

Shellcoding for Linux and Windows

In MASM32, one simply includes the libraries and dll's but I don't know if this is the same case in NASM, i tried to include kernel32.lib using RadAasm but got error.

Undefined Reference to Sleep.

My question is: How would one call the Sleep function in NASM without knowing the exact address of any of the functions, neither GetProcAddress or the like.

NOTE: Even the other examples, he provides absolute addresses for the functions.


Solution

  • You can use extern keyword.

    For example:

    section .text
    
    extern Sleep
    
    global Start
    Start:
      push ebp
      mov ebp, esp
      push 2000
      call Sleep
      mov esp, ebp
      pop ebp
      ret
    

    You have to link the compiled object file with the kernel32.dll. Here is how it is done with GoLink:

    nasm -f win32 sleep.asm -o sleep.obj
    GoLink /files /console sleep.obj kernel32.dll
    

    You can find GoLink here: www.godevtool.com/Golink.zip

    You probably have to use GetProcAddress with hardcoded address if you need functions from other libraries without using extern at all. kernel32.dll is loaded automatically to same address for every process so Sleep (and other kernel32 functions) should have constant address. So you have to use some tool to get the address of the desired function and then use that as hardcoded value (like in the example). I actually tried this long time ago and it worked but I suspect that it depends on the Windows version.