SearchPathW hook with FRIDA

Note: This is a quick blog post to answer the issue of an user from the FRIDA IRC / telegram channel.

In this case what we want to do is to hook the SearchPathW WINAPI:

DWORD SearchPathW(
  LPCWSTR lpPath,
  LPCWSTR lpFileName,
  LPCWSTR lpExtension,
  DWORD   nBufferLength,
  LPWSTR  lpBuffer,
  LPWSTR  *lpFilePart
);

In this case, we want to obtain the most meaningful argument which is in this case the second one, lpFileName. It is possible to extract information from the remaining fields if wanted.

An example program:


// searchPathCpp.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <Windows.h>

int main()
{
    TCHAR lpBuffer[MAX_PATH];
    LPWSTR *lpFilePart{};
    DWORD result;

    result = SearchPath(NULL, L"c:\\windows\\", NULL, MAX_PATH, lpBuffer, lpFilePart);
    std::cout << "SearchPath retval: " << result;
}

We just try to check that the c:/windows path exists. Compile it and lets attach to it:

frida -f searchPathCpp.exe

SearchPathW output

[Local::searchPathCpp.exe]-> searchPathPtr = Module.getExportByName("KERNELBASE.DLL", "SearchPathW")
"0x76fc02f0"
[Local::searchPathCpp.exe]-> Interceptor.attach(searchPathPtr, { onEnter: function (args) { console.log(args[1].readUtf
16String()); } })
{}
[Local::searchPathCpp.exe]-> %resume

Step by step:

  1. Extract the pointer to KERNELBASE.DLL!SearchPathW
[Local::searchPathCpp.exe]-> searchPathPtr = Module.getExportByName("KERNELBASE.DLL", "SearchPathW")
"0x76fc02f0"
  1. Write an Interceptor onEnter hook

Interceptor.attach(searchPathPtr, 
    { 
        onEnter: function (args) 
            { 
                console.log(args[1].readUtf16String()); 
            } 
    });
  1. %resume the app, resulting in the following output

[Local::searchPathCpp.exe]-> %resume
SearchPath retval: 11c:\windows\

And that's it, if you have more questions contact me on Twitter @entdark_