-
Notifications
You must be signed in to change notification settings - Fork 193
/
PerfectInjector.cpp
320 lines (251 loc) · 8.78 KB
/
PerfectInjector.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#include <iostream>
#include <Windows.h>
#include <tlhelp32.h>
#include <Psapi.h>
#include <map>
#include "Error.h"
#include "MemoryController.h"
#include "SimpleMapper.h"
#include "LockedMemory.h"
#pragma comment(lib, "psapi.lib")
PVOID AllocateKernelMemory( CapcomContext* CpCtx, KernelContext* KrCtx, SIZE_T Size )
{
NON_PAGED_DATA static auto k_ExAllocatePool = KrCtx->GetProcAddress<fnFreeCall>( "ExAllocatePool" );
NON_PAGED_DATA static uint64_t MemOut;
CpCtx->ExecuteInKernel( NON_PAGED_LAMBDA( PVOID Pv )
{
MemOut = Khk_CallPassive( k_ExAllocatePool, 0ull, Pv );
}, ( PVOID ) Size );
return ( PVOID ) MemOut;
}
BOOL ExposeKernelMemoryToProcess( MemoryController& Mc, PVOID Memory, SIZE_T Size, uint64_t EProcess )
{
Mc.AttachTo( EProcess );
BOOL Success = FALSE;
Mc.IterPhysRegion( Memory, Size, [ & ] ( PVOID Va, uint64_t Pa, SIZE_T Sz )
{
auto Info = Mc.QueryPageTableInfo( Va );
Info.Pml4e->user = TRUE;
Info.Pdpte->user = TRUE;
Info.Pde->user = TRUE;
if ( !Info.Pde || ( Info.Pte && ( !Info.Pte->present ) ) )
{
Success = FALSE;
}
else
{
if ( Info.Pte )
Info.Pte->user = TRUE;
}
} );
Mc.Detach();
return Success;
}
PUCHAR FindKernelPadSinglePage( PUCHAR Start, SIZE_T Size )
{
PUCHAR It = Start;
MEMORY_BASIC_INFORMATION Mbi;
PUCHAR StreakStart = 0;
int Streak = 0;
do
{
if ( ( 0x1000 - ( uint64_t( It ) & 0xFFF ) ) < Size )
{
It++;
continue;
}
if ( *It == 0 )
{
if ( !Streak )
StreakStart = It;
Streak++;
}
else
{
Streak = 0;
StreakStart = 0;
}
if ( Streak >= Size )
return StreakStart;
VirtualQuery( It, &Mbi, sizeof( Mbi ) );
It++;
}
while ( ( Mbi.Protect == PAGE_EXECUTE_READWRITE || Mbi.Protect == PAGE_EXECUTE_READ || Mbi.Protect == PAGE_EXECUTE_WRITECOPY ) );
return 0;
}
uint32_t FindProcess( const std::string& Name )
{
PROCESSENTRY32 ProcessEntry;
ProcessEntry.dwSize = sizeof( PROCESSENTRY32 );
HANDLE ProcessSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );
if ( Process32First( ProcessSnapshot, &ProcessEntry ) )
{
do
{
if ( !stricmp( ProcessEntry.szExeFile, Name.data() ) )
{
CloseHandle( ProcessSnapshot );
return ProcessEntry.th32ProcessID;
}
}
while ( Process32Next( ProcessSnapshot, &ProcessEntry ) );
}
CloseHandle( ProcessSnapshot );
return 0;
}
int main( int argc, char**argv )
{
std::string ProcessName = argc > 1 ? argv[ 1 ] : "";
std::string DllPath = argc > 2 ? argv[ 2 ] : "";
// noloadlib, waitkey
std::map<std::string, bool> Flags;
if ( argc > 3 )
{
for ( int i = 3; i < argc; i++ )
{
std::string Str = argv[ i ];
for ( auto& c : Str )
c = tolower( c );
Flags[ Str ] = true;
}
}
if ( !ProcessName.size() )
{
printf( "Enter the target process name: " );
std::cin >> std::ws;
getline( std::cin, ProcessName );
}
if ( !DllPath.size() )
{
printf( "Enter the path to the module: " );
std::cin >> std::ws;
getline( std::cin, DllPath );
}
printf( "\n" );
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 13 );
printf( "Flags: " );
for ( int i = 3; i < argc; i++ )
printf( "'%s' ", argv[ i ] );
printf( "\n" );
printf( "Dll Path: '%s'\n", DllPath.data() );
printf( "Process Name: '%s'\n", ProcessName.data() );
printf( "\n" );
// Initialize physical memory controller
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 12 );
KernelContext* KrCtx;
CapcomContext* CpCtx;
MemoryController Controller = Mc_InitContext( &CpCtx, &KrCtx );
if ( Controller.CreationStatus )
ERROR( "Controller Raised A Creation Status" );
// Hook a very commonly used function
PUCHAR _TlsGetValue = ( PUCHAR ) GetProcAddress( GetModuleHandleA( "KERNEL32" ), "TlsGetValue" ); // Not &TlsGetValue to avoid __imp intermodule calls
// kernel32._TlsGetValue - EB 1E - jmp kernel32._TlsGetValue+
// KERNEL32._TlsGetValue - E9 CBD70100 - jmp KERNEL32.UTUnRegister+160
assert( *_TlsGetValue == 0xE9 || *_TlsGetValue == 0xEB );
PUCHAR Target = ( *_TlsGetValue == 0xEB ) ? ( _TlsGetValue + 2 + *( int8_t* ) ( _TlsGetValue + 1 ) ) : ( _TlsGetValue + 5 + *( int32_t* ) ( _TlsGetValue + 1 ) );
// Map module to kernel and create a hook stub
std::vector<std::pair<PVOID, SIZE_T>> UsedRegions;
TlsLockedHookController* TlsHookController = Mp_MapDllAndCreateHookEntry( DllPath, _TlsGetValue, Target, !Flags[ "noloadlib" ], [ & ] ( SIZE_T Size )
{
//return VirtualAlloc( 0, Size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE );
PVOID Memory = AllocateKernelMemory( CpCtx, KrCtx, Size );
ExposeKernelMemoryToProcess( Controller, Memory, Size, Controller.CurrentEProcess );
ZeroMemory( Memory, Size );
UsedRegions.push_back( { Memory, Size } );
return Memory;
} );
// Unload driver
Cl_FreeContext( CpCtx );
Kr_FreeContext( KrCtx );
printf( "\n" );
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 10 );
if ( Flags[ "waitkey" ] )
{
printf( "Waiting for F2 key...\n" );
while ( !( GetAsyncKeyState( VK_F2 ) & 0x8000 ) ) Sleep( 10 );
}
printf( "Waiting for %s...\n", ProcessName.data() );
uint64_t Pid = 0;
while ( !Pid )
{
Pid = FindProcess( ProcessName );
Sleep( 10 );
}
printf( "Found %s. Pid 0x%04x!\n", ProcessName.data(), Pid );
printf( "\n" );
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 11 );
uint64_t EProcess = Controller.FindEProcess( Pid );
printf( "[-] EProcess: %16llx\n", EProcess );
if ( !EProcess )
ERROR( "EProcess Not Valid" );
// Expose region to process
for ( auto Region : UsedRegions )
{
printf( "[-] Exposing %16llx (%08x bytes) to pid:%6llx\n", Region.first, Region.second, Pid );
ExposeKernelMemoryToProcess( Controller, Region.first, Region.second, EProcess );
}
std::vector<BYTE> PidBasedHook =
{
0x65, 0x48, 0x8B, 0x04, 0x25, 0x30, 0x00, 0x00, 0x00, // mov rax, gs:[0x30]
0x8B, 0x40, 0x40, // mov eax,[rax+0x40] ; pid
0x3D, 0xDD, 0xCC, 0xAB, 0x0A, // cmp eax, 0xAABCCDD
0x0F, 0x85, 0x00, 0x00, 0x00, 0x00, // jne 0xAABBCC
0x48, 0xB8, 0xAA, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x00, 0x00, // mov rax, 0xAABBCCDDEEAA
0xFF, 0xE0 // jmp rax
};
PUCHAR PadSpace = FindKernelPadSinglePage( _TlsGetValue, PidBasedHook.size() );
if( !PadSpace )
ERROR( "Couldn't Find Appropriate Padding" );
printf( "[-] Hooking TlsGetValue @ %16llx\n", _TlsGetValue );
printf( "[-] TlsGetValue Redirection Target: %16llx\n", Target );
printf( "[-] Stub located at: %16llx\n", PadSpace );
printf( "[-] Image located at: %16llx\n", TlsHookController );
*( uint32_t* ) ( &PidBasedHook[ 0xD ] ) = Pid; // Pid
*( int32_t* ) ( &PidBasedHook[ 0x13 ] ) = Target - ( PadSpace + 0x17 ); // Jmp
*( PUCHAR* ) ( &PidBasedHook[ 0x19 ] ) = &TlsHookController->EntryBytes; // Hook target
// Backup and complete hook
BYTE Jmp[ 5 ];
Jmp[ 0 ] = 0xE9;
*( int32_t* ) ( Jmp + 1 ) = PadSpace - ( _TlsGetValue + 5 );
std::vector<BYTE> Backup1( PidBasedHook.size(), 0 );
std::vector<BYTE> Backup2( 5, 0 );
TlsHookController->NumThreadsWaiting = 0;
TlsHookController->IsFree = FALSE;
Controller.Detach();
auto AssertCoW = [ & ] ( PVOID Page )
{
VirtualLock( Page, 0x1 );
PSAPI_WORKING_SET_EX_INFORMATION Ws;
Ws.VirtualAddress = Page;
QueryWorkingSetEx( HANDLE( -1 ), &Ws, sizeof( Ws ) );
if ( !Ws.VirtualAttributes.Shared )
ERROR( "Page Not CoW" );
VirtualUnlock( Page, 0x1 );
};
// check maching memory checks AND is CoW check
printf( "[-] Writing stub to padding...\n" );
AssertCoW( PadSpace );
Controller.AttachIfCanRead( EProcess, PadSpace );
Controller.ReadVirtual( PadSpace, Backup1.data(), PidBasedHook.size() );
Controller.WriteVirtual( PidBasedHook.data(), PadSpace, PidBasedHook.size() );
printf( "[-] Writing the hook to TlsGetValue...\n" );
AssertCoW( _TlsGetValue );
Controller.AttachIfCanRead( EProcess, _TlsGetValue );
Controller.ReadVirtual( _TlsGetValue, Backup2.data(), 5 );
Controller.WriteVirtual( Jmp, _TlsGetValue, 5 );
printf( "[-] Hooked! Waiting for threads to spin...\n" );
// Wait for threads to lock
while ( !Controller.ReadVirtual<BYTE>( &TlsHookController->NumThreadsWaiting ) && !( GetAsyncKeyState( VK_F1 ) & 0x8000 ) )
Sleep( 1 );
printf( "[-] Threads spinning: %16llx\n", TlsHookController->NumThreadsWaiting );
// Restore Backup
Controller.AttachIfCanRead( EProcess, _TlsGetValue );
Controller.WriteVirtual( Backup2.data(), _TlsGetValue, 5 );
printf( "[-] Unhooked and started thread hijacking!\n" );
TlsHookController->IsFree = TRUE;
Sleep( 2000 );
Controller.AttachIfCanRead( EProcess, PadSpace );
Controller.WriteVirtual( Backup1.data(), PadSpace, PidBasedHook.size() );
system( "pause" );
return 0;
}