Search code examples
c++windowswinapiassemblymalware

What is the reason to write custom GetModuleHandle function?


I was looking at ZeuS malware, and I've come across this piece of source code:

HMODULE _getKernel32Handle(void)
{
#if defined _WIN64
  return NULL; //FIXME
#else  
  __asm
  {
    cld                    //clear the direction flag for the loop

    mov edx, fs:[0x30]     //get a pointer to the PEB
    mov edx, [edx + 0x0C]  //get PEB-> Ldr
    mov edx, [edx + 0x14]  //get the first module from the InMemoryOrder module list

  next_mod:
    mov esi, [edx + 0x28]  //get pointer to modules name (unicode string)
    mov ecx, 24            //the length we want to check
    xor edi, edi           //clear edi which will store the hash of the module name

  loop_modname:
    xor eax, eax           //clear eax
    lodsb                  //read in the next byte of the name
    cmp al, 'a'            //some versions of Windows use lower case module names
    jl not_lowercase
    sub al, 0x20           //if so normalise to uppercase

  not_lowercase:
    ror edi, 13            //rotate right our hash value
    add edi, eax           //add the next byte of the name to the hash
    loop loop_modname      //loop until we have read enough

    cmp edi, 0x6A4ABC5B    //compare the hash with that of KERNEL32.DLL
    mov eax, [edx + 0x10]  //get this modules base address
    mov edx, [edx]         //get the next module
    jne next_mod           //if it doesn't match, process the next module
  };
#endif
}

Logic is the following:

  1. Read fs segment register (32-bit Windows stores TEB there)
  2. Get pointer to PEB
  3. Get pointer to PEB_LDR_DATA (containing information about loaded modules of the process)
  4. Iterate through the InMemoryOrder list
  5. Compare module name with "kernel32.dll" using custom homebrew hash function

Why wasn't the use of GetModuleHandle appropriate there?


Solution

  • The code snippet is trying to get the module handle (i.e. base address) of kernel32.dll, presumably because it doesn't have a handle to this module yet. GetModuleHandle is exported from kernel32.dll. You cannot call a function when you don't know its address.