码迷,mamicode.com
首页 > 其他好文 > 详细

[00027]-[2015-09-20]-[02]-[代码注入技术 --- 2 直接代码写入]

时间:2015-09-20 17:29:39      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

DWORD m_dwPid;

void CPureCode_InJectDlg::OnBtnInject() 
{
    // TODO: Add your control notification handler code here
    UpdateData(TRUE);
    if(m_dwPid == 0)
    {
        MessageBox("PID is UnValid !");
        return ;
    }

    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_dwPid);
    if(hProcess == NULL)
    {
        MessageBox("Open Process Failed !");
        return ;
    }

    DATA data;
    DWORD dwWriteNum = 0;
    strcpy(data.text, "Hello, World");
    strcpy(data.title, "Info");
    data.dwMessageBox = (DWORD)GetProcAddress(GetModuleHandle("User32.dll"), "MessageBoxA");

    LPVOID lpData = VirtualAllocEx(hProcess, NULL, sizeof(DATA), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
    WriteProcessMemory(hProcess, lpData, &data, sizeof(DATA), &dwWriteNum);

    LPVOID lpCode = VirtualAllocEx(hProcess, NULL, 0x200, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    WriteProcessMemory(hProcess, lpCode, RemoteThreadProc, 0x200, &dwWriteNum);

    HANDLE hThread = CreateRemoteThread(hProcess,
                                        NULL,
                                        0,
                                        (LPTHREAD_START_ROUTINE)lpCode,
                                        lpData,
                                        0,
                                        NULL);
    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(hThread);

    VirtualFreeEx(hProcess, lpCode, 0, MEM_RELEASE);            // 待远程线程执行结束以后 可以Free 掉内存空间
    VirtualFreeEx(hProcess, lpData, 0, MEM_RELEASE);            // 待远程线程执行结束以后 可以Free 掉内存空间

    CloseHandle(hProcess);
}


typedef struct  
{
    char text[20];
    char title[20];
    DWORD dwMessageBox;
}DATA, *PDATA;

typedef int (__stdcall * MY_MESSAGEBOX)(HWND, LPCTSTR, LPCTSTR, DWORD); 

DWORD WINAPI RemoteThreadProc(LPVOID pParam)
{
    PDATA pData = (PDATA)pParam;
    MY_MESSAGEBOX MyMessageBox;
    MyMessageBox = MY_MESSAGEBOX(pData->dwMessageBox);
    MyMessageBox(NULL, pData->text, pData->title, MB_OK);
    // MessageBox(NULL, pData->text, pData->title, MB_OK);     // 这里不能直接调用MessageBox()函数 因为编译的地址不在远程线程的地址空间内
    // MessageBox(NULL, "Hello", "Title", MB_OK);         // 也不能这样直接调用,“Hello”, "Title" 也不在远程线程的地址空间内 会访问出错
     return 0;
}

 

[00027]-[2015-09-20]-[02]-[代码注入技术 --- 2 直接代码写入]

标签:

原文地址:http://www.cnblogs.com/Auris/p/4823677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!