Createremotethread and writeprocessmemory Technologies

Source: Internet
Author: User

Createremotethread and writeprocessmemory Technologies

Example program: winspy

Another way to inject code into other process address spaces is to use the writeprocessmemory API. Instead of writing an independent DLL, you can directly copy your code to a remote process (writeprocessmemory) and execute it with createremotethread.

Let's take a look at the createremotethread statement:

Handle createremotethread (
Handle hprocess, // handle to process to create thread in
Lpsecurity_attributes lpthreadattributes, // pointer to security
// Attributes
DWORD dwstacksize, // initial thread stack size, in bytes
Lpthread_start_routine lpstartaddress, // pointer to thread
// Function
Lpvoid lpparameter, // argument for new thread
DWORD dwcreationflags, // creation flags
Lpdword lpthreadid // pointer to returned thread identifier
);

It is different from createthread:
● The hprocess parameter is added. This is the handle of the process in which the thread is to be created.
● The lpstartaddress parameter of createremotethread must point to a function in the address space of the remote process. This function must exist in a remote process, so we cannot simply pass a local threadfucn address. We must copy the code to the remote process.
● Similarly, the data pointed to by the lpparameter parameter must also be stored in a remote process and copied.

Now, let's summarize the steps for using this technology:
1. Obtain the handle (OpenProcess) of the remote process ).
2. allocate memory (virtualallocex ),
3. Copy the initialized injdata structure to the allocated memory (writeprocessmemory ).
4. allocate memory (virtualallocex) for the data to be injected in the remote process ).
5. Copy threadfunc to the allocated memory (writeprocessmemory ).
6. Use createremotethread to start the remote threadfunc.
7. Wait for the end of the remote thread (waitforsingleobject ).
8. retrieving the execution result from a remote process (readprocessmemory or getexitcodethread ).
9. Release virtualfreeex ).
10. Close the open handle in steps 1 and 6th.

In addition, threadfunc must comply with the following rules:
1. threadfunc cannot call the API functions in the dynamic library except kernel32.dll and user32.dll. Only kernel32.dll and user32.dll (if loaded) can ensure the load address is the same locally and in the target process. (Note: USER32 is not necessarily loaded by all Win32 processes !) See Appendix. If you need to call functions in other libraries, use loadlibrary and getprocessaddress to force loading in the injected code. If, for some reason, the dynamic library you need has been mapped to the target process, you can also use getmoudlehandle instead of loadlibrary. Similarly, if you want to call your own functions in threadfunc, copy these functions to the remote process and provide the address to threadfunc through injdata.

2. Do not use static strings. Provide injdata for all strings. Why? The compiler places all static strings in the ". Data" segment of the executable file, and only keeps their references (pointers) in the code ). In this way, threadfunc in a remote process executes non-existent memory data (at least not in its own memory space ).

3. Remove the/GZ compilation option of the compiler. This option is default (see appendix B ).
4. Either declare threadfunc and afterthreadfunc as static, or close the "incremental linking" of the compiler (see appendix C ).
5. the total size of local variables in threadfunc must be smaller than 4 K bytes (see Appendix D ). Note: When degug is compiled, about 10 bytes in the 4 K will be occupied in advance.
6. If there are case statements with more than 3 tch branches, they must be split as follows or replaced by if-else if.

Case constant1: statement1; goto end;
Case constant2: statement2; goto end;
Case constant3: statement2; goto end;
}

Case constant4: statement4; goto end;
Case constant5: statement5; goto end;
Case constant6: statement6; goto end;
}
End:

 

===== Simple createremotethread routine-required for beginners

 

// _ Remotethreaddemo. cpp: defines the entry point for the console application.
// Author: Qiuzhen cuisine

# Include "stdafx. H"
# Include "windows. H"

// ============ Define a code structure. In this example, a dialog box ================
Struct mydata
{
Char SZ [64]; // The content displayed in the dialog box
DWORD dwmessagebox; // address of the dialog box
};

// =========== Functions of the remote thread ================================ ======
DWORD _ stdcall rmtfunc (mydata * pdata)
{
Typedef int (_ stdcall * mmessagebox) (hwnd, lpctstr, lpctstr, uint );
Mmessagebox msgbox = (mmessagebox) pdata-> dwmessagebox;
Msgbox (null, pdata-> SZ, null, mb_ OK );
Return 0;
}
Int main (INT argc, char * argv [])
{
// ==== Obtain the process handle for creating remotethread ======================== =====
Hwnd = findwindow ("Notepad", null); // take notepad as an Example
DWORD dwprocessid;
: Getwindowthreadprocessid (hwnd, & dwprocessid );
Handle hprocess = OpenProcess (
Process_all_access,
False,
Dwprocessid );

// =========== Code structure ====================================== ==================================
Mydata data;
Zeromemory (& Data, sizeof (mydata ));
Strcat (data. sz, "content of the dialog box .");
Hinstance huser = loadlibrary ("user32.dll ");
If (! Huser)
{
Printf ("can not Load Library .");
Return 0;
}
Data. dwmessagebox = (DWORD) getprocaddress (huser, "messageboxa ");
Freelibrary (huser );
If (! Data. dwmessagebox)
Return 0;

// ======================================================= ======================================
Void * premotethread
= Virtualallocex (hprocess, 0,
1024*4, mem_commit | mem_reserve,
Page_execute_readwrite );
If (! Premotethread)
Return 0;
If (! Writeprocessmemory (hprocess, premotethread, & rmtfunc, 1024*4, 0 ))
Return 0;

Mydata * pdata
= (Mydata *) virtualallocex (hprocess, 0,
Sizeof (mydata), mem_commit,
Page_readwrite );
If (! Pdata)
Return 0;

If (! Writeprocessmemory (hprocess, pdata, & Data, sizeof (mydata), 0 ))
Return 0;

// ============== Create a remote thread ================================= ==============================
Handle hthread
= Createremotethread (hprocess, 0,
0, (lpthread_start_routine) premotethread,
Pdata, 0, 0 );
If (! Hthread)
{
Printf ("remote thread creation failed ");
Return 0;
}
Closehandle (hthread );
Virtualfreeex (hprocess, premotethread, 1024*3, mem_release );
Virtualfreeex (hprocess, pdata, sizeof (mydata), mem_release );
Closehandle (hprocess );
Printf ("Hello world! ");
Return 0;
}

The program runs in Windows XP. After MessageBox is displayed, the host process will crash after you click OK.
Besides MessageBox, the same is true for calling other API functions. Why? Is there any solution?
--------------------------------------------------------

When compiled into the release version, no error will occur. The main reason is that the debug version adds a _ chkesp function, resulting in Invalid Address calls.

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.