-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDLL Injection code.cpp
119 lines (96 loc) · 2.58 KB
/
DLL Injection code.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <Windows.h>
#include <TlHelp32.h>
#include <tchar.h>
#include <string>
bool process_name_to_pid(
__out DWORD& pid,
__in const std::wstring& process_name
);
bool dll_injection(
__in DWORD pid,
__in const std::wstring& dll_name
);
int main()
{
DWORD pid = 0;
std::wstring process_name = L"notepad.exe";
std::wstring dll_name = L"C:\\my_dll.dll";
if (process_name_to_pid(pid, process_name)) {
dll_injection(pid, dll_name);
}
return 0;
}
bool process_name_to_pid(
__out DWORD& pid,
__in const std::wstring& process_name
) {
bool result = false;
HANDLE snapshot = nullptr;
PROCESSENTRY32 entry = {};
entry.dwSize = sizeof(PROCESSENTRY32);
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (snapshot != INVALID_HANDLE_VALUE) {
Process32First(snapshot, &entry);
do {
if (!_tcsicmp(process_name.c_str(), entry.szExeFile)) {
pid = entry.th32ProcessID;
result = true;
break;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
}
return result;
}
bool dll_injection(
__in DWORD pid,
__in const std::wstring& dll_name
) {
bool result = false;
HANDLE process_handle = nullptr;
HANDLE thread_handle = nullptr;
LPVOID remote_buffer = nullptr;
HMODULE module = {};
LPTHREAD_START_ROUTINE thread_start_routine = nullptr;
do {
process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (process_handle == nullptr) {
break;
}
remote_buffer = VirtualAllocEx(
process_handle,
nullptr,
dll_name.size(),
MEM_COMMIT,
PAGE_READWRITE
);
if (!remote_buffer) {
break;
}
if (!WriteProcessMemory(
process_handle,
remote_buffer,
dll_name.c_str(),
dll_name.size() * sizeof(wchar_t),
nullptr
)) {
break;
}
module = GetModuleHandle(L"kernel32.dll");
thread_start_routine = (LPTHREAD_START_ROUTINE)GetProcAddress(module, "LoadLibraryW");
thread_handle = CreateRemoteThread(
process_handle,
nullptr,
0,
thread_start_routine,
remote_buffer,
0,
nullptr
);
WaitForSingleObject(thread_handle, INFINITE);
result = true;
} while (false);
CloseHandle(process_handle);
CloseHandle(thread_handle);
return result;
}