具体过程:

一 使用visualstudio2022创建一个动态链接库项目

dllmain.cpp默认代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}


备注:

附加进程
MessageBox(NULL,L”注入成功”, L”SUCESS”m MB_OK);
附加线程
退出进程
退出线程

1.属性->c/c++->代码生成->运行库设置为MTD,Spectre缓解禁用

2.更改dll代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(NULL,L"注入成功",L"SUCCESS",MB_OK);
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}


3.编译生成dll文件

备注:

LoadLibrayA ASCII(多字节)

LoadLibrayW UNICODE(宽字符)

二 c++语言程序远程注入的代码示例

cpp代码示例

inject.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//inject.cpp
#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <iostream>
#include <tchar.h>


int main() {

DWORD pid = 5784;//进城id
//scanf_s("%d", pid);

const char*DLLPath = "D:\\desktop\\Dll1.dll";//dll的绝对目录

HANDLE hprocess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!hprocess) {
std::cout << "can not get handle" << std::endl;
return 1;
}
SIZE_T PathSize = (strlen(DLLPath) + 1) * sizeof(TCHAR);
LPVOID StartAddress = VirtualAllocEx(hprocess, NULL, sizeof(DLLPath), MEM_COMMIT, PAGE_READWRITE);
if (!StartAddress) {
std::cout << "开辟内存失败" << std::endl;
return 1;
}
if (!WriteProcessMemory(hprocess, StartAddress, DLLPath, PathSize, NULL)) {
std::cout << "无法写入DLL路径" << std::endl;
return 1;
}
PTHREAD_START_ROUTINE pfnStartAddress = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "LoadLibraryA");//FreeLibrary LoadLibraryA

if (!pfnStartAddress) {
std::cout << "无法获取函数地址" << std::endl;
return 1;
}
HANDLE hThread = CreateRemoteThreadEx(hprocess, NULL, NULL, pfnStartAddress, StartAddress, NULL, NULL, NULL);
if (!hThread) {
std::cout << "创建线程失败" << std::endl;
return 1;
}
WaitForSingleObject(hThread, INFINITE);//等待DLL结束
std::cout << "注入成功!\n";
CloseHandle(hThread);
CloseHandle(hprocess);
return 0;
}

备注:

LoadLibraryA加载dll,FreeLibrary卸载dll