(学习记录)代码注入之远程线程篇

#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
int Pid;
int EnableDebugPriv(const char * name)
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tp;
    LUID luid;
    //打开进程令牌环
    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken);
    //获得进程本地唯一ID
    LookupPrivilegeValueA(NULL, name, &luid) ;
     
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    tp.Privileges[0].Luid = luid;
    //调整权限
    AdjustTokenPrivileges(hToken, 0, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
    return 0;
}

//*****************************************************************************************************************************

BOOL InjectDll(const char *DllFullPath, const DWORD dwRemoteProcessId)
{
    HANDLE hRemoteProcess;
    EnableDebugPriv(SE_DEBUG_NAME);
    //打开远程线程
    hRemoteProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwRemoteProcessId );

    char *pszLibFileRemote;

    //使用VirtualAllocEx函数在远程进程的内存地址空间分配DLL文件名空间
    pszLibFileRemote = (char *) VirtualAllocEx( hRemoteProcess, NULL, lstrlenA(DllFullPath)+1, MEM_COMMIT, PAGE_READWRITE);


    //使用WriteProcessMemory函数将DLL的路径名写入到远程进程的内存空间
    WriteProcessMemory(hRemoteProcess, pszLibFileRemote, (void *) DllFullPath, lstrlenA(DllFullPath)+1, NULL);

//##############################################################################
    //计算LoadLibraryA的入口地址
    PTHREAD_START_ROUTINE pfnStartAddr = (PTHREAD_START_ROUTINE)
            GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryA");
    //(关于GetModuleHandle函数和GetProcAddress函数)

    //启动远程线程LoadLibraryA,通过远程线程调用创建新的线程
    HANDLE hRemoteThread;
    if( (hRemoteThread = CreateRemoteThread( hRemoteProcess, NULL, 0, pfnStartAddr, pszLibFileRemote, 0, NULL) ) == NULL)
    {
       printf("注入线程失败!");
        return FALSE;
    }
    CloseHandle(hRemoteProcess);
    CloseHandle(hRemoteThread);

    return TRUE;
}

//*****************************************************************************************************************************

DWORD GetProcessID(char *FileName)
{
    HANDLE hProcess;
    PROCESSENTRY32 pe;
    BOOL bRet;
    hProcess=::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    bRet=::Process32First(hProcess,&pe);
    while(bRet)
    {
        if (strcmp(pe.szExeFile,FileName) == 0)
        {
            Pid = pe.th32ProcessID;
            return Pid;
        }else
        {
            bRet = Process32Next(hProcess,&pe);
        }
    }
    return 0;
}

int main(int argc,char* argv[])
{
    if (argc < 2)
    {
        printf("[-]:%s Injection_file_name\r\n",argv[0]);
        return 0;
    }
    int id = GetProcessID(argv[1]);
    //printf("%s\r\n",argv[1]);
    InjectDll("c:\\programdata\\test.dll", id) ;//这个数字是你想注入的进程的ID号
    return 0;
}

 

posted @ 2015-01-13 15:38  杀死比特  阅读(300)  评论(0编辑  收藏  举报