Use CreateRemoteThread to remotely inject code into a specified exe for execution

Source: Internet
Author: User

Use CreateRemoteThread to remotely inject code into a specified exe for execution
I am also a newbie. If a friend doesn't know about windows api, I believe reading books or Baidu will be more helpful than I said. I will repeat the process below. The example is as follows: first, an MFC Dialog Box program is created, and then a DLL with an export function (Simple subtraction) is created, the Calc button is to call the subtraction function in the DLL to calculate 1-1, and then create a DLL with the function of modifying the entry code of a function in the process (why is it a DLL, there is a lot of detailed information on the Internet.) Then we create a windows console program that calls CreateRemoteThread to let Calc load the prepared DLL (modify the function entry code ), because the DLL is loaded, we can specify the code to be executed in DLLMain. Before the code is injected: After executing my injection program createremotethread.exe, you can see that the injection is successful. What is the injection? This is the role of CreateRemoteThread. We injected a thread into calc.exe and the thread executed the LoadLibrary function. I told Calc to Load the dll I specified. Why? Because the DLL we specified was created by ourselves, the function code in it can find the address of the original sub function in the Calc process, and then modify the entry code at the sub function address, that is, change jmp xxx to make Calc execute the code we specified. The most important CreateRemoteThread:

HANDLE hThread; char szLibPath [_ MAX_PATH] = "E: \ vs2010project \ InjectDll \ Release \ InjectDll. dll "; // specify the dll dword hLibModule to be loaded by the target process after the injection; HANDLE hProcess = NULL; hProcess = getprocpolicyname (" Calc.exe "); dword erro = GetLastError (); if (hProcess = NULL) return 0; HMODULE modHandle = GetModuleHandle (_ T ("Kernel32 ")); // because kernel32 exists in every windows program process space, it is not a problem for him to call LOADLIBRARY. void * pLibRemote = VirtualAllocEx (hProcess, NULL, sizeof (szLibPath), MEM_COMMIT, PAGE_EXECUTE_READWRITE ); LPTHREAD_START_ROUTINE addr = (callback) GetProcAddress (modHandle, "LoadLibraryA"); WriteProcessMemory (hProcess, pLibRemote, (void *) szLibPath, sizeof (szLibPath), NULL ); hThread = CreateRemoteThread (hProcess, NULL, 0, addr, pLibRemote, 0, NULL); WaitForSingleObject (hThread, INFINITE); CloseHandle (hThread );

 

Obtaining a Process Handle Based on the process name is also a key part of this example. You can take a snapshot of the Process List using the api provided by Microsoft and then traverse and search for the process. The Code is as follows:
HANDLE GetProcessByName(const char* name){    EnableDebugPriv();    DWORD pid = 0;    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    PROCESSENTRY32 process;    ZeroMemory(&process, sizeof(process));    process.dwSize = sizeof(process);    if (Process32First(snapshot, &process))    {        do        {            if( stricmp(UnicodeToAnsi(process.szExeFile), name) == 0)            {                pid = process.th32ProcessID;                break;            }        }while(Process32Next(snapshot, &process));    }    CloseHandle(snapshot);        if(pid != 0)    {        HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);                return hProcess;    }    return NULL;    }

 

Among the core code about CreateRemoteThread, there are many things to note: Before executing OPENPROCESS, You need to enable the privileged code as follows:
 1 void EnableDebugPriv() 2 { 3     HANDLE hToken; 4     LUID luid; 5     TOKEN_PRIVILEGES tkp; 6  7     OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); 8  9     LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);10 11     tkp.PrivilegeCount = 1;12     tkp.Privileges[0].Luid = luid;13     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;14 15     AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);16 17     CloseHandle(hToken); 18 }

 

Next, we can call openprocess to open the target process for further operations (call CreateRemoteThread) to load the specified DLL for the target process, and then specify that the specified code can be executed when the DLL is loaded. Finally, the Code for modifying the function entry code in the dll imported into the process is as follows:
BYTE NewCode [5]; // used to replace the BYTE (jmp xxxx) typedef int (_ cdecl * getsub) (int x, int y) of the original entry code ); // If typedef is rarely used, you can set a function pointer type, that is, getsub mySub = NULL; // define a variable FARPROC pfar_sub with the newly defined type; // The remote pointer to the mySub function HANDLE hProcess = NULL; // The Process handle dword pid; // The process ID // modify void modify () {assert (hProcess! = NULL); DWORD dwTemp = 0; DWORD dwOldProtect; VirtualProtectEx (hProcess, pfar_sub, 5, PAGE_READWRITE, & dwOldProtect); // change the memory protection mode to writable, the original protection mode is saved into dwOldProtect WriteProcessMemory (hProcess, pfar_sub, NewCode, 5, 0); VirtualProtectEx (hProcess, pfar_sub, 5, dwOldProtect, & dwTemp ); // recover memory protection mode} int new_sub (int x, int y) {return 1 ;}int inject () {DWORD dwPid =:: GetCurrentProcessId (); hProcess = OpenProcess (PROCES S_ALL_ACCESS, 0, dwPid); int addr_farpointer = 0; // obtain the address of the My_sub () function HMODULE hmod =: LoadLibrary (_ T ("E: \ vs2010project \ My_Sub \ Debug \ My_Sub.dll "); mySub = (getsub): GetProcAddress (hmod," mySub "); pfar_sub = (FARPROC) mySub; addr_farpointer = (int) pfar_sub; if (pfar_sub = NULL) {MessageBox (NULL, TEXT ("locate mySub failed !! "), TEXT (" info "), MB_ OK); return FALSE;} NewCode [0] = 0xe9; // 0xe9 = jmp _ asm {lea eax, new_sub mov ebx, pfar_sub eax, ebx sub eax, 5 mov dword ptr [NewCode + 1], eax} modify (); MessageBox (NULL, TEXT ("Modified SUCCESSFULLY !! "), TEXT (" info "), MB_ OK); return TRUE ;}

 

The overall process clearly shows that there should be no problems in practice (it still needs to be tossed, and tossing is also a process of progress ).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.