Unable to check dll injection and debug-MS detours

886 views Asked by At

I had written a file monitor using ms detours.i have to hook file related calls like creatfile,readfile in any targetexecutable and collect stats from those calls.

I have an injector

    void CFileStat::MonitorProcess()
    {

    int npos=filename.ReverseFind('\\');
    CString name=filename.Mid(npos+1);
    WCHAR* DirPath = new WCHAR[MAX_PATH];
    WCHAR* FullPath = new WCHAR[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, DirPath);
    DWORD processID = FindProcessId(name);

    if ( processID == 0 )
        AfxMessageBox(L"Could not find ");
        else
          AfxMessageBox(L"Process ID is ");
         swprintf_s(FullPath, MAX_PATH, L"%s\\%s", DirPath,strhookdll);

         LPCTSTR lpszPrivilege = L"SeDebugPrivilege";
// Change this BOOL value to set/unset the SE_PRIVILEGE_ENABLED attribute
    BOOL bEnablePrivilege = TRUE;
    HANDLE hToken;
// Open a handle to the access token for the calling process. That is this running program
 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
 {
    printf("OpenProcessToken() error %u\n", GetLastError());
    return ;
 }

BOOL test = SetPrivilege(hToken, lpszPrivilege, bEnablePrivilege);


HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);

if( ! hProcess ) 
{ 
    return; 
}

LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle(L"kernel32.dll"),
        "LoadLibraryA");

LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, lstrlen(FullPath),
        MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

if( ! LLParam )
{
    printf( "ERROR: Problems with VirtualAllocEx.  Error code: %d\n", GetLastError() );
    return;
}
int n=WriteProcessMemory(hProcess, LLParam, FullPath, lstrlen(FullPath), NULL);

    if(n == 0) {
    printf("Error: there was no bytes written to the process's address space.\n");
}

   HANDLE threadID = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)     LoadLibraryAddr,
        LLParam, NULL, NULL);

   if(threadID == NULL) {
    printf("Error: the remote thread could not be created.\n");
    }
   else 
   {
    printf("Success: the remote thread was successfully created.\n");
    }

   WaitForSingleObject(threadID, INFINITE);

    CloseHandle(hProcess);
    delete [] DirPath;
    delete [] FullPath;

I have the hook dll

  #include <iostream>
  #include <windows.h>
  #include "detours.h"
  #include"FileDetour.h"

  #pragma comment(lib, "detours.lib")




  void AddHook(PVOID* func,PVOID intercept); 
  void DeleteHook(PVOID* func,PVOID intercept); 

  static HANDLE (WINAPI * PCreateFile)(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD      
  dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD 
  dwFlagsAndAttributes, HANDLE hTemplateFile) = CreateFile;

  HANDLE WINAPI InterceptCreateFile(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD    
  dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, 
 DWORD     dwFlagsAndAttributes, HANDLE hTemplateFile);

  BOOL APIENTRY DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved )
   {
  FILE *file;
     fopen_s(&file, "D:\\temp.txt", "a+");
  DWORD Error=0;
      // Perform actions based on the reason for calling.
      switch( fdwReason ) 
    {  
         case DLL_PROCESS_ATTACH:
     // Initialize once for each new process.
     // Return FALSE to fail DLL load.
        fprintf(file, "DLL attach function called.\n");
        DisableThreadLibraryCalls(hinstDLL);
                    OutputDebugString(L"Attaching filedetour.dll");

     // DetourRestoreAfterWith();
           DetourTransactionBegin();
           DetourUpdateThread(GetCurrentThread());
            DetourAttach(&(PVOID&)PCreateFile, InterceptCreateFile);
           Error=DetourTransactionCommit();



        break;

    case DLL_THREAD_ATTACH:
                 break;

    case DLL_THREAD_DETACH:
     // Do thread-specific cleanup.
        break;

    case DLL_PROCESS_DETACH:
        fprintf(file, "DLL dettach function called.\n");
                    OutputDebugString(L"De-Attaching MyDLL.dll");
             DWORD Error=0;

           DetourTransactionBegin();
           DetourUpdateThread(GetCurrentThread());
           DetourDetach(&(PVOID&)PCreateFile,InterceptCreateFile);
           Error=DetourTransactionCommit();

            break;  
         }

          fclose(file);
      return TRUE;  // Successful DLL_PROCESS_ATTACH.

       }


        HANDLE WINAPI InterceptCreateFile(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD 
        dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD 
         dwCreationDisposition,     DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)

     {
     OutputDebugString(lpFileName);
    return PCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, 
        dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
       }

CreateRemotethread returns successfully and I am going to waitforsingleobject in the injector function.

but I am getting no evidence of dll being injected into the target exe process space.i tried ollydbg.the debug is not hitting the hook dll project named "filedetour" when i debug the target exe as well the injector process .Neither the text file temp.txt is being created.when i debug the target exe for one or two lines , I get a debug window message the thread is exiting.The waitforsingleobejct in the injector process immediately signals.

in short there is no evidence a dll was injected sucessfuly and that dllmain was hit at all.

how to debug the entire process?iwant to debug the hook dll throroughly from the target exe as the hook dll collects stats from the file operations.

what are the files I have to copy from the hook dll project(dll,lib,.h) and any extra settings to be made to the injector project?

I am new to this topic.

0

There are 0 answers