Injecting threads with APIs

Source: Internet
Author: User

//Elevate process access rightsBOOLEnabledebugpriv () {HANDLE htoken;      LUID Sedebugnamevalue; Token_privileges TKP;if(! OpenProcessToken (GetCurrentProcess (), Token_adjust_privileges | Token_query, &htoken)) {return false; }if(! Lookupprivilegevalue (NULL, Se_debug_name, &sedebugnamevalue)) {CloseHandle (htoken);return false; } TKP. Privilegecount =1; Tkp. privileges[0].      Luid = Sedebugnamevalue; Tkp. privileges[0]. Attributes = se_privilege_enabled;if(! AdjustTokenPrivileges (Htoken, FALSE, &AMP;TKP,sizeof(TKP), NULL, NULL)) {CloseHandle (htoken);return false; }return true; }structtoremoteproccess{Chartitle[ the];Charcontent[ the]; DWORD msgboxaddress;}; ////function pointer defining the MessageBox typetypedefvoid(__stdcall *msgbox) (HWND hwnd,lpctstr title,lpctstr content,dword utype);D word threadproc (lpvoid lParam) {////program crashes//MessageBox (NULL, "title", "Content", MB_OK);/***************************************************************************************************** The thread body has been modified, we run the program , the thread is injected into the host process. However, an illegal access error occurs at this time. The reason is the MessageBox in the thread body (NULL, "title", "Content", MB_OK); the second and third parameters of the function point to the string that exists in the address space of the current process, and the thread in the host process accesses the string "Hello" There will be an illegal access memory error.                                                                    The solution is to copy the contents of the string into the address space of the host process, and the address of the MessageBox function in User32.dll is also copied to the host process. *****************************************************************************************************/< /c0>    //Correct executionToremoteproccess *TMPTRP = (toremoteproccess *) LParam;    Msgbox Tmpmsgbox;    Tmpmsgbox = (Msgbox) (tmptrp->msgboxaddress); Tmpmsgbox (0, Tmptrp->content,tmptrp->title,0);//Correct execution//__asm//  {//MOV eax,0x00401480//Call EAX//  }    return 0;}voidCremotecallerdlg::onbutton1 () {//Todo:add your control notification handler code here    //Improve the privileges of this programEnabledebugpriv ();//Get remote process handleHWND Hwnd=::findwindow (null,_t ("Bloodtest"));//target process IDDWORD Dwprocessid;//target thread IDDWORD dwThreadID; Dwthreadid=::getwindowthreadprocessid (HWND,&AMP;DWPROCESSID);//target process handleHANDLE handltoremoteprocess=::openprocess (Process_all_access,false, Dwprocessid);if(handltoremoteprocess = = NULL) {AfxMessageBox (_t ("OpenProcess failed"));return; }//Application thread function memory    ConstDWORD dwthreadsize =4096;void* THREADPROCADDR=::VIRTUALALLOCEX (Handltoremoteprocess,0, Dwthreadsize,mem_commit | Mem_reserve, Page_execute_readwrite);if(threadprocaddr = = NULL) {AfxMessageBox (_t ("VirtualAllocEx failed"));return; }//write thread code to the remote processDWORD Numberofbyteswrittenofproc; BOOL Retwriteprocessmemory=::writeprocessmemory (Handltoremoteprocess,threadprocaddr,&threadproc, Dwthreadsize, &numberofbyteswrittenofproc);if(!retwriteprocessmemory) {AfxMessageBox (_t ("WriteProcessMemory failed"));return; }//Construct thread parametersDWORD Numberofbyteswrittenofparam;    Toremoteproccess TRP; ZeroMemory (&AMP;TRP,sizeof(toremoteproccess)); Hmodule HUser32 = LoadLibrary ("User32.dll"); Trp. Msgboxaddress = (DWORD) GetProcAddress (HUser32,"MessageBoxA"); _sntprintf (Trp.title,sizeof("title"),'%s ',"title"); _sntprintf (Trp.content,sizeof("Content"),'%s ',"Content");//Request parameter SpaceToremoteproccess *premoteparamaddr = (toremoteproccess *):: VirtualAllocEx (Handltoremoteprocess,0,sizeof(toremoteproccess), mem_commit,page_readwrite);if(premoteparamaddr = = NULL) {AfxMessageBox (_t ("VirtualAllocEx failed"));return; }//Parameter write-in memoryRetwriteprocessmemory =::writeprocessmemory (HANDLTOREMOTEPROCESS,PREMOTEPARAMADDR,&AMP;TRP,sizeof(toremoteproccess), &numberofbyteswrittenofparam);if(!retwriteprocessmemory) {AfxMessageBox (_t ("WriteProcessMemory failed"));return; }//Create a remote threadDWORD Remotethreadid; HANDLE Retremotethread=::createremotethread (Handltoremoteprocess,null,0, (Lpthread_start_routine) threadprocaddr, (LPVOID) premoteparamaddr,0, &remotethreadid);if(Retremotethread = = NULL) {AfxMessageBox (_t ("CreateRemoteThread failed"));return; }//CleanupVirtualFreeEx (handltoremoteprocess,threadprocaddr,dwthreadsize,mem_release); VirtualFreeEx (HANDLTOREMOTEPROCESS,PREMOTEPARAMADDR,sizeof(toremoteproccess), mem_release);    FreeLibrary (HUSER32); CloseHandle (handltoremoteprocess);/// /// /// /// ///  /// ///   /// ///   /// ///   /// ///   /// ///   /// ///   ///////LPVoid VirtualAllocEx (//HANDLE hprocess,//LPVoid lpaddress,//size_t dwsize,//DWORD Flallocationtype,//DWORD flprotect//     ); // //hprocess://The process handle where the memory is requested. //lpaddress://Preserve the memory address of the page, usually automatically assigned by NULL. //dwsize://memory size to allocate, byte units; Note the actual allocated memory size is an integer multiple of the page memory size// //Flallocationtype The following values are desirable://Mem_commit: Allocates physical storage in memory or in disk's paging file for a specific page area///mem_physical: Allocating physical memory (for address window extended memory only)//Mem_reserve: Preserves the virtual address space of the process without allocating any physical storage. Reserved pages can be occupied by continuing to call VirtualAlloc ()//Mem_reset: Indicates that data specified in memory by parameters lpaddress and dwsize is invalid//Mem_top_down: allocating memory at the highest possible address (Windows 98 ignores this flag)///Mem_write_watch: Must be specified with Mem_reserve to enable the system to track pages that are written to the assigned area (Windows 98 only)// //Flprotect The following values are desirable://Page_readonly: The area is read-only. If an application attempts to access a page in a zone, it will be denied//Page_readwrite area can be read and written by Application//Page_execute: Zone contains code that can be executed by the system. An attempt to read or write to the zone is denied. ///Page_execute_read: The zone contains executable code that the application can read. ///Page_execute_readwrite: The zone contains executable code that the application can read and write to. //Page_guard: When the zone is accessed for the first time, it enters a status_guard_page exception, which is used in combination with other protection flags to indicate that the zone is accessed for the first time//page_noaccess: Any operation that accesses the zone will be rejectedThe page in//Page_nocache:ram will not be cached by the microprocessor when it is mapped to the zone (cached)// //Note: The Page_guard and Page_nochache flags can be combined with other flags to further specify the characteristics of the page. The PAGE_GUARD flag specifies a guard page, that is, when a page is submitted for the first//times are accessed to produce a one-shot exception, followed by the specified access rights. Page_nocache prevents the microprocessor from being cached when it maps to a virtual page. This flag facilitates the use of direct memory access by device drivers//(DMA) to share memory blocks. // //return value://Successful execution returns the first address of the allocated memory, and the unsuccessful is null. //  //     //BOOL WriteProcessMemory (//HANDLE hprocess,//LPVoid lpbaseaddress,//LPVoid lpbuffer,//DWORD nSize,//Lpdword Lpnumberofbyteswritten//  );//    //Parameters://hprocess: Process handle returned by OpenProcess. If the parameter data is Invalid_handle_value "1" The target process is its own process///lpbaseaddress: To write the first memory address, before writing, this function will first check whether the destination address is available, and can hold the data to be written. ///lpbuffer: A pointer to the data to be written. //NSize: The number of bytes to write. //Lpnumberofbyteswritten: The size of the data that was successfully written//      //return value://Non 0 value represents success.// //HANDLE CreateRemoteThread (//HANDLE hprocess,//Lpsecurity_attributes lpthreadattributes,//size_t dwstacksize,//Lpthread_start_routine lpstartaddress,//LPVoid Lpparameter,//DWORD dwcreationflags,//Lpdword Lpthreadid//  );//Parameter description://hprocess: Handle to the target process///lpthreadattributes: A pointer to a thread's security descriptor structure, generally set to NULL, indicating the use of the default security level//dwstacksize: Thread stack size, typically set to 0, indicates the default size, typically 1M//lpstartaddress: Address of the thread function///lpparameter: Thread Parameters//dwCreationFlags: How threads are created///lpthreadid: Output parameter, record the ID of the remote thread created/////////////////////////// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /////}

Injecting threads with APIs

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.