When programming in C ++, we sometimes get more room for programming, and to reduce code, we often use the plug-in assembly language for joint programming.
Below we practice embedding assembly in C ++ to implement DLL injection source code.
The DLL dynamic function link library interface is as follows.
# Include "stdafx. H "# include" resource. H "////////////////////////////////////// //////////////////////////////////////** * ***** global variable declaration ******* hinstance hinst = NULL; hwnd hdlg; //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /// // The function prototype declaration ****** * ****** extern "C" _ declspec (dllexport) void waiguaproc (); bool callbac K dlgproc (hwnd hdlg, uint message, wparam, lparam ); //////////////////////////////////////// //// // bool apientry dllmain (handle hmodule, DWORD keys, lpvoid lpreserved) {Switch (KEYS) {Case dll_process_attach: hinst = (hinstance) hmodule; waiguaproc (); break; Case dll_process_detach: break;} return true ;} extern "C" _ declspec (dllexp ORT) void waiguaproc () {hdlg = createdialog (hinst, makeintresource (idd_maindlg), null, (dlgproc); MessageBox (null, "test! "," Test ", mb_ OK); return;} bool callback dlgproc (hwnd hwnddlg, // handle to dialog box uint umsg, // message wparam, // first message parameter lparam // second message parameter) {Switch (umsg) {Case wm_initdialog: showwindow (hwnddlg, sw_show); Return true; Case wm_close: destroywindow (hwnddlg ); return true; Case wm_command: If (loword (wparam) = idok) {MessageBox (null, "insert DLL success! "," Test! ", Mb_ OK);} return true;} return false ;}
Below we conduct C ++ and Assembly joint programming, Please carefully read the code comments,
# Include "tlhelp32.h" # ifdef _ debug # define new debug_new # UNDEF this_filestatic char this_file [] = _ file __; # endif ////////////////////////////////////// //////////////////////////////////////// /caboutdlg Dialog used for app aboutclass caboutdlg: public cdialog {public: caboutdlg (); // dialog data // {afx_data (caboutdlg) Enum {IDD = idd_aboutbox}; //} afx_data // classwizard generated virtual function ove Rrides // {afx_virtual (caboutdlg) protected: Virtual void dodataexchange (cdataexchange * PDX); // DDX/DDV support //} afx_virtual // implementationprotected: // {afx_msg (caboutdlg) //} specify ()}; caboutdlg: caboutdlg (): cdialog (caboutdlg: IDD) {// {afx_data_init (caboutdlg) //} afx_data_init} void caboutdlg: dodataexchange (cdataexchange * PDX) {cdialog: dodataexchange (PDX); // {afx_data_map (C Aboutdlg) //} afx_data_map} begin_message_map (caboutdlg, cdialog) // {afx_msg_map (caboutdlg) // No message handlers //} Handle () //////////////////////////////////////// /// // cwaiguatestdlg dialogcwaiguatestdlg:: cwaiguatestdlg (cwnd * pparent/* = NULL */): cdialog (cwaiguatestdlg: IDD, pparent) {// {afx_data_init (cwaiguatestdlg) m_procname = _ T (""); //} afx _ Data_init // note that loadicon does not require a subsequent destroyicon in response = afxgetapp ()-> loadicon (idr_mainframe);} void metadata: dodataexchange (cdataexchange * PDX) {cdidialog :: dodataexchange (PDX); // {afx_data_map (region) ddx_cbstring (PDX, idc_com_proc, m_procname); //} afx_data_map} begin_message_map (Region, cdialog) // {afx_msg_map (cwaiguatestdlg) on_wm_syscommand () on _ Wm_paint () on_wm_querydragicon () on_bn_clicked (idc_but_getproc, onbutgetproc) on_bn_clicked (idc_but_execution, onbutexecution) //} else () //////////////////////////////////////// /// // cwaiguatestdlg message handlersbool cwaiguatestdlg:: oninitdialog () {cdialog: oninitdialog (); // Add "about... "menu item to system menu. // idm_aboutbox must be in System Command range. Assert (idm_aboutbox & 0xfff0) = idm_aboutbox); Assert (idm_aboutbox <0xf000); cmenu * psysmenu = getsystemmenu (false); If (psysmenu! = NULL) {cstring straboutmenu; straboutmenu. loadstring (ids_aboutbox); If (! Straboutmenu. isempty () {psysmenu-> appendmenu (mf_separator); psysmenu-> appendmenu (mf_string, idm_aboutbox, straboutmenu); }}// set the icon for this dialog. the framework does this automatically // when the application's main window is not a dialogseticon (m_hicon, true); // set big iconseticon (m_hicon, false ); // set small icon // todo: add extra initialization herereturn true; // return true unless you s Et the focus to a control} void cwaiguatestdlg: onsyscommand (uint NID, lparam) {If (NID & 0xfff0) = idm_aboutbox) {caboutdlg dlgabout; dlgabout. domodal ();} else {cdialog: onsyscommand (NID, lparam) ;}// if you add a Minimize button to your dialog, you will need the code below // to draw the icon. for MFC applications using the document/view model, // This is automatically done for you by the frame Work. void cwaiguatestdlg: onpaint () {If (isiconic () {cpaintdc DC (this); // device context for paintingsendmessage (wm_iconerasebkgnd, (wparam) DC. getsafehdc (), 0); // center icon in client rectangleint cxicon = getsystemmetrics (sm_cxicon); int cyicon = getsystemmetrics (sm_cyicon); crect rect; getclientrect (& rect ); int x = (rect. width ()-cxicon + 1)/2; int y = (rect. height ()-cyicon + 1)/2; // draw t He icondc. drawicon (X, Y, m_hicon);} else {cdialog: onpaint ();}} // The system callthis to obtain the cursor to display while the user drags // The minimized window. hcursor cursor: onquerydragicon () {return (hcursor) m_hicon;} void cwaiguatestdlg: onbutgetproc () {// todo: add your control notification handler code here (ccombobox *) getdlgitem (idc_com_proc)-> resetcontent (); For (INT I = 0; I <100; I ++) szthreadid [I] = 0; handle hsnapshot; processentry32 szentry; szentry. dwsize = sizeof (processentry32); hsnapshot = createconlhelp32snapshot (th32cs_snapprocess, 0); If (hsnapshot = invalid_handle_value) {MessageBox ("createconlhelp32snapshot error! "); Return;} If (process32first (hsnapshot, & szentry) {int I = 1; (ccombobox *) getdlgitem (idc_com_proc)-> addstring (szentry. szexefile); szthreadid [0] = szentry. th32processid; while (process32next (hsnapshot, & szentry) {(ccombobox *) getdlgitem (idc_com_proc)-> addstring (szentry. szexefile); szthreadid [I] = szentry. th32processid; I ++;} MessageBox ("succeeded in listing system processes"); (ccombobox *) getdlgitem (idc_com_proc)-> setcursel (I-1 ); Return ;}} void cwaiguatestdlg: onbutexecution () {// todo: add your control notification handler code here // ****** skip the remote thread code, execute this program ****** goto remote_thread_end; //////////////////////////////////////// //////////////////////////////////////// * ******* remote thread code *******/////////////////////// //////////////////////////////////////// /// // remote_thread_begin: _ ASM {// ******** placeholder for the loadlibrary function address ******** loadlibrar Yaddr: nopnopnopnop // ******* placeholder for the freelibrary function address ******* freelibraryaddr: nopnopnopnop // ******* give the Dynamic Linked database name a placeholder ******* libraryname: nopnopnopnopnopnopnopnop // The real location where the code starts ******* remote_thread_code: // ******* implements address relocation, EBX saves the difference ******* callrelocalrelocal: popebxsubebx, offset relocal ////////////////////////////////////// //////////////////////////////////////** * ***** call loadlibrary *******////////////////////////// /////// //////////////////////////////////////// /// ******* Press the loadlibrary parameter (Dynamic Link Library name) * ****** moveax, ebxaddeax, offset librarynamepusheax // ******* call loadlibrary ****** moveax, ebxaddeax, offset loadlibraryaddrmoveax, [eax] calleaxoreax, eaxjnznext1ret /////////////////////////////////////// /////////////////////////////////////*** ***** call loadlibrary *******////////////////////////// //////////////////////////// /// // Next1: // ******* press the freelibrary parameter ******** pusheax // ******** call freelibrary ******* moveax, ebxaddeax, offset freelibraryaddrmoveax, [eax] calleax //////////////////////////////////// //////////////////////////////////////// * ****** call freelibrary *******/////////////////////// //////////////////////////////////////// /// // RET} remote_thread_end: //////////////////////////////////////// /// // Remote thread code ///////////////////////////////////// ///////////////////////////////////////* * ***** first obtain the selected Process Handle ****** int nselectedthreadid; nselectedthreadid = (ccombobox *) getdlgitem (rows)-> getcursel (); nselectedthreadid = szthreadid [nselectedthreadid]; handle hselectedprochandle; handler = OpenProcess ); If (! Hselectedprochandle) {MessageBox ("failed to open the process! "); Return;} // ******* obtain the length of the remote thread code ******* int nremotethreadcodelength; _ ASM {moveax, offset remote_thread_endmovebx, offset remote_thread_beginsubeax, ebxmovnremotethreadcodelength, eax} // ******* apply for a remote thread code space in the host process ******** lpvoid premotethreadaddr; premotethreadaddr = virtualallocex (hselectedprochandle, null, nremotethreadcodelength, mem_commit, page_execute_readwrite); If (! Premotethreadaddr) {MessageBox ("alloc memory error! "); Return;} // ******* copy the remote thread code to the host process space ******** lpvoidpremotethreadcodebuf; dwordnwritennum, nsuccess; _ ASM moveax, offset remote_thread_begin_asm success, eaxnsuccess = writeprocessmemory (hselectedprochandle, premotethreadaddr, premotethreadcodebuf, callback, & nwritennum); If (! Nsuccess) {MessageBox ("Copy remote thread code error! "); Return ;} // ******** modify the remote thread code ******* // ********* first obtain the addresses of two key functions **** * ** hmodule hkernel32; hkernel32 = loadlibrary ("kernel32.dll"); If (! Hkernel32) {MessageBox ("error in importing kernel32.dll! "); Return;} lpvoid ploadlibrary, pgetprocaddress, pfreelibrary; ploadlibrary = (lpvoid) getprocaddress (hkernel32," loadlibrarya "); If (! Ploadlibrary) {MessageBox ("An error occurred while obtaining the loadlibrary function address! "); Return;} pgetprocaddress = (lpvoid) getprocaddress (hkernel32," getprocaddress "); If (! Pgetprocaddress) {MessageBox ("An error occurred while obtaining the getprocaddress function address! "); Return;} pfreelibrary = (lpvoid) getprocaddress (hkernel32," freelibrary "); If (! Pgetprocaddress) {MessageBox ("An error occurred while obtaining the freelibrary function address! "); Return;} // ******* corrected the code ******** pbyte premoteaddrmove; premoteaddrmove = (pbyte) premotethreadaddr; // ******* modify the loadlibrary address ******* nsuccess = writeprocessmemory (hselectedprochandle, premoteaddrmove, & ploadlibrary, 4, & nwritennum); If (! Nsuccess) {MessageBox ("fixed the loadlibrary address error! "); Return;} // ******* corrected freelibrary address ******* premoteaddrmove + = 4; nsuccess = writeprocessmemory (hselectedprochandle, premoteaddrmove, & pfreelibrary, 4, & nwritennum); If (! Nsuccess) {MessageBox ("corrected freelibrary address error! "); Return;} // ******** transfer the dynamic link library name ******* char szdllname [8] = {" DLL. DLL "}; premoteaddrmove + = 4; nsuccess = writeprocessmemory (hselectedprochandle, premoteaddrmove, szdllname, 8, & nwritennum); If (! Nsuccess) {MessageBox ("fixed the getprocaddress address error! "); Return;} // ******** move the pointer to the start of the remote thread code ******** premoteaddrmove + = 8; // ******** create a remote thread ******* handle hremotethreadhandle; // ******* define the remote thread function type ******** typedef unsigned long (winapi * stremotethreadproc) (lpvoid); stremotethreadproc premotethreadproc; // ******* assign the entry address to the declared function ******** forward = (stremotethreadproc) premoteaddrmove; hremotethreadhandle = createremotethread (hselectedprochandle, null, 0, premotethreadproc, 0, 0, null); // ******** test ******** cstring szbuf; szbuf. format ("START address: % x \ nloadlibrary address: % x \ ngetprocaddress address % x \ n code start address: % x", premotethreadaddr, ploadlibrary, pgetprocaddress, premoteaddrmove ); messageBox (szbuf); return ;}