Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Simple Remote Thread DLL Injection Not Working

Posted on 2008-10-28
4
Medium Priority
?
1,267 Views
Last Modified: 2012-06-21
Download VS2008 project at http://sigma.homeunix.com/SampleInjection.zip -- or use the code directly from: http://www.rohitab.com/discuss/index.php?showtopic=17456 -- if using the site from the rohitab.com link, make sure to download his 1KB zip file with two functions not posted in his thread.

Any help would be MUCH appreciated.  I've spent most of today beating my head against a wall, getting nowhere.  I have many years of programming experience, but this is my first attempt at a Windows app, and it's driving me nuts!

Only two changes, both seem necessary to the code on the thread (changes are made in the project downloadable at http://sigma.homeunix.com/SampleInjection.zip) :
(1) He accidentally (I think) typed taskmgr where he meant notepad.  Changed 'hProcess = GetProcessHandle("taskmgr.exe")' where he meant '...notepad.exe'
(2) FindWindow() at least in VS08 has two paramters, LPCSTR lpClassName and LPCSTR lpWindowName.  So, I tried both 'FindWindow("Untitled - Notepad", NULL)' and 'FindWindow(NULL, "Untitled - Notepad")'.  I'm virtually certain "Untitled - Notepad" is for lpWindowName, but I tried both just in case.

Oh, I also threw in a MessageBox that states the Dll injection was successful, so there isn't just one upon an error.

The program message box'es success, but the injected dll never seems to execute.  Even with a MessageBox as the first instruction in DllMain, nothing seems to happen.

I'm running on Vista, if it matters.  Changing the attached project to release form (and moving both solutions over to multi-byte character sets) and copying the .exe and .dll to an XP machine is even worse.  The .exe eats up a ton of memory and brings my system to its knees.
0
Comment
Question by:darlingm2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 19

Accepted Solution

by:
drichards earned 2000 total points
ID: 22828577
You probably don't have permission to open the notepad process with PROCESS_ALL_ACCESS.  I added a few lines of code to acquire the correct access and it seems to work.  The new GetProcessHandle function is shown below.

Also, I had to add a full path to Dll.dll so it would load correctly, and your logic to print success/fail of the injection is backwards, I think.  Should be "if (!DllInject..."
HANDLE GetProcessHandle(LPSTR szExeName)
{
	PROCESSENTRY32 Pc = { sizeof(PROCESSENTRY32) } ;
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
    HANDLE phandle = NULL;
	if(Process32First(hSnapshot, &Pc)){
		do{
			if(!strcmp(Pc.szExeFile, szExeName)) {
                HANDLE token;
                if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token))
                {
                    LUID luid;
                    if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
                    {
                        TOKEN_PRIVILEGES tp;
                        tp.PrivilegeCount = 1;
                        tp.Privileges[0].Luid = luid;
                        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
                        if (AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
                        {
            				phandle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, Pc.th32ProcessID);
                        }
                    }
                }
                if (phandle == NULL)
                {
                    DWORD err = GetLastError();
                    err = 0;
                }
			}
		}while(Process32Next(hSnapshot, &Pc));
	}
 
	return phandle;
}

Open in new window

0
 

Author Comment

by:darlingm2
ID: 22831950
Thank you very much for your time on this.  Your version of GetProcessHandle() works, and puts the addition into Notepad.  You're also right also about the original writer's logic on the message box being incorrect.  All this time it was not giving an error when it should have been for me.
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 34256118
After coming across the same article darlingm2 mentioned, I found the above code from drichards very useful, so thanks drichards for that!

I also spent some time figuring out why my code would not work in Unicode mode: for future searchers I post the simple changes I made here.  Basically it is about modifying DllInject() to writ ethe correct number of bytes out within WriteProcessMemory...
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 34256120
BOOL DllInject(HANDLE hProcess, LPCTSTR lpszDllPath)
{
      HMODULE hmKernel = GetModuleHandle(_T("Kernel32"));//heres the DLL
      if(hmKernel == NULL || hProcess == NULL) return FALSE;
      int nBytes = ( _tcslen(lpszDllPath) + 1 ) * sizeof ( TCHAR );
      LPVOID lpvMem = VirtualAllocEx(hProcess, NULL, nBytes, MEM_COMMIT, PAGE_READWRITE);
      BOOL bRet = WriteProcessMemory(hProcess, lpvMem, lpszDllPath, nBytes, NULL);
      DWORD dwWaitResult, dwExitResult = 0;
#ifdef _UNICODE
      HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(hmKernel, "LoadLibraryW"), lpvMem, 0, NULL);
#else
      HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(hmKernel, "LoadLibraryA"), lpvMem, 0, NULL);
#endif
      if(hThread != NULL){
            dwWaitResult = WaitForSingleObject(hThread, 10000); // 10 seconds
            bRet = GetExitCodeThread(hThread, &dwExitResult);
            bRet = CloseHandle(hThread);
      }
      VirtualFreeEx(hProcess, lpvMem, 0, MEM_RELEASE);
      return ((dwWaitResult != WAIT_TIMEOUT) && (dwExitResult > 0));
}
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question