Author Topic: Inject DLL  (Read 1090 times)

0 Members and 1 Guest are viewing this topic.

xC

  • Guest
Inject DLL
« on: May 06, 2013, 08:21:24 am »

Some code I found in another old project.. probably been posted a million times but here you are anyhow.

Code: [Select]
InjectDLL( FindPID( "explorer.exe" ), "C:\blah.dll" );

Code: [Select]
unsigned long FindPID( char* szProcess )
{
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof( PROCESSENTRY32 );
   
    HANDLE hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
    if( hSnapShot != INVALID_HANDLE_VALUE ) {


    Process32First( hSnapShot, &pe32 );
    while( Process32Next( hSnapShot, &pe32 ) ) {
        if( strstr( pe32.szExeFile, szProcess ) ) {
            return( pe32.th32ProcessID );
        }
    }


    return 0;
};


unsigned long InjectDLL( unsigned long dwPID, char* szLibraryPath )
{
   unsigned long dwWritten;
   HANDLE hProcess, hThread;
   LPTHREAD_START_ROUTINE lpModule;


   void* lpBuffer;


   hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwPID );
   if( !hProcess )
      return 1;


   lpModule = (LPTHREAD_START_ROUTINE)GetProcAddress( GetModuleHandle( "kernel32.dll" ), "LoadLibraryA" );
   lpBuffer = VirtualAllocEx( hProcess, NULL, strlen( szLibraryPath ) + 1, MEM_COMMIT, PAGE_READWRITE );


   if( !lpBuffer )
      return 2;


   if( !WriteProcessMemory( hProcess, lpBuffer, szLibraryPath, strlen( szLibraryPath ) + 1, &dwWritten ) )
      return 3;


   hThread = CreateRemoteThread( hProcess, NULL, 0, lpModule, lpBuffer, 0, NULL );
   if( !hThread )
      return 4;


   CloseHandle( hThread );
   CloseHandle( hProcess );


   return 0;
};
« Last Edit: May 06, 2013, 08:23:06 am by xC »