-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathThreadIn.h
99 lines (72 loc) · 2.57 KB
/
ThreadIn.h
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
#pragma once
#ifdef _WIN64
#define XIP Rip
#else
#define XIP Eip
#endif
#include <thread>
#include <TlHelp32.h>
#include <Windows.h>
namespace ii {
class ThreadIn final {
public:
explicit ThreadIn(__int64 threadStartAddress) : m_currentProcessId(GetCurrentProcessId()), m_thread([this]() { ViciousCircle(); }) {}
ThreadIn(__int64 threadStartAddress, __int64 forwardAddress) : m_currentProcessId(GetCurrentProcessId()), m_thread([this]() { ViciousCircle(); }) {}
ThreadIn(__int32 processId, __int64 threadStartAddress, __int64 forwardAddress)
: m_currentProcessId(processId), m_thread([this]() { ViciousCircle(); }) {}
ThreadIn(__int32 processId, __int64 threadStartAddress) : m_currentProcessId(processId), m_thread([this]() { ViciousCircle(); }) {}
private:
__int32 m_currentProcessId = 0;
__int64 m_threadStartAddress = 0;
__int64 m_forwardAddress = 0;
std::jthread m_thread;
enum THREADINFOCLASS {
ThreadQuerySetWin32StartAddress = 9,
};
typedef DWORD(__stdcall* f_NtQueryInformationThread)(HANDLE, THREADINFOCLASS, void*, ULONG_PTR, ULONG_PTR*);
inline void ViciousCircle() {
for (;;)
FreezeOrForwardTargetThread(m_threadStartAddress, m_forwardAddress);
}
[[nodiscard]] static ULONG_PTR GetThreadStartAddress(HANDLE hThread) {
auto NtQueryInformationThread =
reinterpret_cast<f_NtQueryInformationThread>(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryInformationThread"));
if (!NtQueryInformationThread)
return 0;
ULONG_PTR ulStartAddress = 0;
DWORD ret = NtQueryInformationThread(hThread, ThreadQuerySetWin32StartAddress, &ulStartAddress, sizeof(ULONG_PTR), nullptr);
if (ret)
return 0;
return ulStartAddress;
}
void FreezeOrForwardTargetThread(__int64 tSA, __int64 forwardAddress) {
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32;
CONTEXT ctx;
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return;
te32.dwSize = sizeof(te32);
ctx.ContextFlags = CONTEXT_FULL;
Thread32First(hThreadSnap, &te32);
while (Thread32Next(hThreadSnap, &te32)) {
if (te32.th32OwnerProcessID == m_currentProcessId) {
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (GetThreadStartAddress(hThread) == tSA || tSA == 0) {
GetThreadContext(hThread, &ctx);
if (forwardAddress == 0) {
ctx.XIP = (__int64)+[]() noexcept {
if (__rdtsc())
WaitMessage();
};
}
else
ctx.XIP = forwardAddress;
SetThreadContext(hThread, &ctx);
}
}
}
CloseHandle(hThreadSnap);
}
};
} // namespace ii