Bypassing code signing for pentesting (Windows)

One of the thick clients that I frequently test sign all of their executable files and DLLs and verify the signature before executing/loading them. This was a hindrance when we had to patch DLLs to bypass SSL certificate verification. After a quick check, it was apparent that the executable did not verify the signature after the DLL is loaded in memory. So the plan is simple. Listen all calls to LoadLibrary and when the target DLL is passed as an argument, modify the argument to point to the patched DLL. There are number of ways to do this (EasyHook, CreateRemoteThread). But all these requires you to develop code that might not be reusable.

Let us just use a powerful debugger (windbg)
and one liner to achieve the same results. Save the below script as
“replace_dll.cmd”

bp LoadLibraryExW “as /mu ${/v:fileName} poi(esp+4); .block{.if($spat(@\”${fileName}\”, @\”*<Target DLL >.DLL*\”)){ ezu poi(esp+4) \”<Path of Modified DLL>.dll\”} }; g”

Here is the breakdown of what it does

  • bp – Breakpoint
  • as /mu ${/v:filename} poi(esp+4)  – filename = *(esp+4)
  • as – alias
  • /mu – Unicode
  • ${/v:filename} – variable “filename”
  • Poi(address)
    – equivalent of *(address) in C
  • $spat(@\”${filename}\”,@\”*<Target DLL>.dll*\”) – pattern matching the filename
    with DLL
  • ezu poi(esp+4) \”<Path of Modified DLL>.dll\” – ezu address value– Write Unicode value to the specified address.
  • Write the modified DLL path to the address. Care should be taken to make sure the
    modified path is equal to or less than the size of the original DLL path.
  • g – continue with process load

I failed to mention that the target process is a windows service that runs at startup. As all DLLs gets loaded before we get a chance to attach to the process, we need to debug the process at startup and we also need to execute the above commands as soon as the debugging starts.  Debugging a windows service at startup is different from that of a regular process. You can modify the registry key as shown below to debug a windows service.

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Image File Execution Options\<process
name>.exe]
“Debugger”=”C:\Program Files\Debugging Tools for Windows (x86)\windbg.exe” -c “$$><C:\replace_dll.cmd”

Now whenever the process starts, windbg.exe will automatically attach to the service at start up and execute the specified script that will inturn load the patched DLL.

[This was originally written in 2014. Frida is probably much more handy for this usecase these days. A useful reference nevertheless]