首页
论坛
课程
招聘
[原创]HOOK技术 学习总结
2021-9-26 18:05 4268

[原创]HOOK技术 学习总结

2021-9-26 18:05
4268

HOOK技术

Hook 的关键就是通过一定的手段埋下“钩子",“钩”住我们关心的重要流程,然后根据需要对执行过程进行干预。

 

HOOK技术导致了程序执行流程的改变。通过在执行真正的目标函数之前执行事先插入的代码,获得了程序执行过程的决定权——“插入特定代码以干预程序的执行流程”就是 Hook 的奥义。

 

在这里插入图片描述

 

在这里插入图片描述

IAT-hook

(通过修改IAT的方式拦截对API的调用,所以称为IAT Hook

 

注意:如果是通过动态加载的就不行了,因为动态加载的dll的API不在iat中,而是动态生成的.

 

在这里插入图片描述

 

执行地址01002628处的CALL命令后,运行将转移至user32.SetWindowTextW()函数的起始地址(77D0960E)处(1),函数执行完毕后返回(2)。

 

在这里插入图片描述

 

执行地址01002628处的CALL命令后,运行将转移至user32.SetWindowTextW()函数的起始地址(77D0960E)处(1),函数执行完毕后返回(2)。

 

hookiat.dll文件中提供了名为MySetWindowTextWO)的钩取函数( 10001000 )。

 

跟踪进入01001110地址中发现,它的值已经变为10001000,地址10001000是hookiat.MySetWindowTextW()函数的起始地址。也就是说,在保持运行代码不变的前提下,将IAT中保存的API起始地址变为用户函数的起始地址。这就是IAT钩取的基本工作原理。在IAT中找到的是被修改的函数地址,但是程序并不知道这一点,而是直接跑到被修改的地址处执行了

 

使用IAT Hook的程序,一般会读取PE文件头信息,解析PE结构,查找IAT

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
/*
  函数说明:
      获取进程IAT列表
 
  输入参数:
      INode **iNode    :  IAT表项结构体二级指针
      PNode *pNode     :  进程结构体指针
      unsigned int pid :  进程PID
 
  输出参数:
 
*/
int GetIAT(INode **iNode, PNode *pNode, unsigned int pid)
{
    unsigned char buff[1025] = {0};              //用于临时保存读取的buff
    unsigned char nameAddrBuff[513] = {0};       //IAT表项函数名地址列表
    unsigned char addrBuff[513] = {0};           //IAT表项函数地址列表
    char dllName[NAMESIZE] = {0};                //IAT表项所属dll名
    unsigned char nameBuff[NAMESIZE] = {0};      //IAT表项函数名
 
    PNode *bkPNode = pNode;           //初始化进程结构体链表操作指针
    INode *bkINode = NULL;            //定义IAT表项结构体操作指针
    INode *newINode = NULL;           //定义新的IAT表项结构体指针
 
    HANDLE handle = NULL;             //初始化进程句柄
 
    LPCVOID addr = 0;                 //地址指针
    int offset = 0;                   //保存PE结构偏移
    LPDWORD readBuffCount = 0;        //保存ReadProcessMemory实际读取的字节数
    int flag = 0;                     //函数调用标记
    int error = 0;                    //函数调用出错代码
    int order = 0;                    //函数在列表中的序号
    int IATaddr = 0;                  //IAT表的地址
 
    int descriptorBaseAddr = 0;       //IMAGE_IMPORT_DESCRIPTOR结构体首地址
    int dllNameAddr = 0;              //dll名地址
    int funcNameAddr = 0;             //函数名列表地址
    int funcAddrAddr = 0;             //函数地址列表地址
    int funcName = 0;                 //函数名地址
 
 
    int i = 0;                        //循环计数
    int j = 0;                        //循环变量
 
    InitINode(iNode);                 //初始化IAT表项结构体链表头指针
    bkINode = *iNode;                 //初始化IAT表项结构体链表操作指针
 
    if (NULL == bkPNode)              //如果进程链表为空,则出错退出
    {
        return -1;
    }
 
    for (;;)                          //循环遍历进程结构体中与所给进程PID相符进程结构体
    {
        if (pid == bkPNode->pe32.th32ProcessID)
        {
            break;
        }
        else
        {
            if (NULL == bkPNode->next)
            {
                return -1;
            }
            else
            {
                bkPNode = bkPNode->next;
            }
        }
    }
 
    if (EnableDebugPriv(SE_DEBUG_NAME))    //获取进程调试权限
    {
        printf("Add Privilege error\n");
 
        return -1;
    }
 
    handle=OpenProcess(PROCESS_ALL_ACCESS,1,pid);  //获取进程句柄
    if (handle == INVALID_HANDLE_VALUE)
    {
        return -1;
    }
 
    addr = bkPNode->me32.modBaseAddr;              //获取进程加载基址
    flag = ReadProcessMemory(handle, addr, buff, 512, readBuffCount); // 读取进程前512字节信息
    offset = buff[60] + buff[61] * 256 + buff[62] * 256 * 256 + buff[63] * 256 * 256 * 256;
    offset = offset + 0x18;
    offset = offset + 0x60;
    offset = offset + 0x8;
    IATaddr = buff[offset] + buff[offset+1] *256 + buff[offset+2] * 256* 256 + buff[offset+3] * 256 * 256 * 256;
    addr = bkPNode->me32.modBaseAddr + IATaddr;    //根据PE文件结构获取进程IAT表地址
 
    flag = ReadProcessMemory(handle, addr, buff, 1024, readBuffCount); //读取进程IAT表所在内存的1024字节信息
 
    descriptorBaseAddr = 0;
    for (order = 0;;)
    {
        //根据IMAGE_INPORT_DESCRIPTOR结构,获取相应dll名地址,函数名地址列表首地址,函数地址列表首地址
        funcNameAddr = buff[descriptorBaseAddr+0] + buff[descriptorBaseAddr+1] *256 + buff[descriptorBaseAddr+2] * 256* 256 + buff[descriptorBaseAddr+3] * 256 * 256 * 256;
        dllNameAddr = buff[descriptorBaseAddr+12] + buff[descriptorBaseAddr+13] *256 + buff[descriptorBaseAddr+14] * 256* 256 + buff[descriptorBaseAddr+15] * 256 * 256 * 256;
        funcAddrAddr = buff[descriptorBaseAddr+16] + buff[descriptorBaseAddr+17] *256 + buff[descriptorBaseAddr+18] * 256* 256 + buff[descriptorBaseAddr+19] * 256 * 256 * 256;
 
        //读取函数名地址列表
        flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+funcNameAddr, nameAddrBuff, 512, readBuffCount);
        if (0 == flag)
        {
            error  = GetLastError();
            printf("Read funcNameAddr failed!!\nError : %d\n",error);
            return -1;
        }
 
        //读取函数地址列表
        flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+funcAddrAddr, addrBuff, 512, readBuffCount);
        if (0 == flag)
        {
            error  = GetLastError();
            printf("Read funcAddrAddr failed!!\nError : %d\n",error);
            return -1;
        }
 
        //读取dll文件名
        flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+dllNameAddr, nameBuff, NAMESIZE-1, readBuffCount);
        if (0 == flag)
        {
            error  = GetLastError();
            printf("Read funcName failed!!\nError : %d\n",error);
            return -1;
        }
        for (j = 0; j < NAMESIZE-1; j++)
        {
            if (0 == nameBuff[j])
            {
                break;
            }
            else
            {
                dllName[j] = nameBuff[j];
            }
        }
        dllName[j] = 0;
 
 
        for (i = 0;;)  //循环获取IAT表项
        {
            bkINode->order = order;                //函数序号
            order++;
 
            strcpy(bkINode->dllname,dllName);      //函数所属dll名
 
            bkINode->addrOfAddr = funcAddrAddr + i;  //函数地址所在内存地址
 
            //获取函数名所在内存首地址
            funcName = nameAddrBuff[i] + nameAddrBuff[i+1]*256 + nameAddrBuff[i+2]*256*256 + nameAddrBuff[i+3]*256*256*256;
            if (0x80000000 == (0x80000000&funcName)) //如果函数名所在地址最高位为1,则说明是以序号导入的
            {
                sprintf(bkINode->name,"Oridinal : %#0 8X",0x7fffffff&funcName);
                bkINode->address = funcName;       //这种导入方式我不知道地址是多少
            }
            else
            {
                //读取函数名
                flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+funcName, nameBuff, NAMESIZE-1, readBuffCount);
                if (0 == flag)
                {
                    error  = GetLastError();
                    printf("Read funcName failed!!\nError : %d\n",error);
                    return -1;
                }
 
                //获得函数名
                for (j = 0; j < NAMESIZE-1; j++)
                {
                    if (0 == nameBuff[j+2])
                    {
                        break;
                    }
                    else
                    {
                        bkINode->name[j] = nameBuff[j+2];
                    }
                }
                bkINode->name[j] = 0;
 
                //获取函数在内存中的地址
                bkINode->address = addrBuff[i] + addrBuff[i+1]*256 + addrBuff[i+2]*256*256 + addrBuff[i+3]*256*256*256;
            }
 
            i = i + 4;    //如果下个函数名地址为0,则说明这个dll的导入函数结束了
            if (0 == nameAddrBuff[i] && 0 == nameAddrBuff[i+1] && 0 == nameAddrBuff[i+2] && 0 == nameAddrBuff[i+3])
            {
                break;
            }
            if (512 == i)  //如果函数名地址列表超过512字节,则重新获取函数名地址列表和函数地址列表
            {
                i = 0;
                funcNameAddr += 512;       //指针向前移51字节
                funcAddrAddr += 512;
                flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+funcNameAddr, nameAddrBuff, 512, readBuffCount);
                if (0 == flag)
                {
                    error  = GetLastError();
                    printf("Read funcNameAddr failed!!\nError : %d\n",error);
                    return -1;
                }
 
                funcName = nameAddrBuff[0] + nameAddrBuff[1] *256 + nameAddrBuff[2] * 256* 256 + nameAddrBuff[3] * 256 * 256 * 256;
                flag = ReadProcessMemory(handle, bkPNode->me32.modBaseAddr+funcAddrAddr, addrBuff, 512, readBuffCount);
                if (0 == flag)
                {
                    error  = GetLastError();
                    printf("Read funcAddrAddr failed!!\nError : %d\n",error);
                    return -1;
                }
            }
            InitINode(&newINode);
            bkINode->next = newINode;
            bkINode = newINode;
            newINode = NULL;
        }
 
        descriptorBaseAddr += 20; //如果下一个IMAGE_IMPORT_DESCRIPTOR结构体为空,则退出
        if (0 == buff[descriptorBaseAddr] && 0 == buff[descriptorBaseAddr+1] && 0 == buff[descriptorBaseAddr+2] && 0 == buff[descriptorBaseAddr+3])
        {
            break;
        }
        InitINode(&newINode);
        bkINode->next = newINode;
        bkINode = newINode;
        newINode = NULL;
    }
 
    CloseHandle(handle);
    return 0;
}
 
/*
  函数说明:
      hooking 某个IAT表中的函数
 
  输入参数:
      INode **iNode    :  IAT表项结构体二级指针
      PNode *pNode     :  进程结构体指针
      int order        :  函数序号
      unsigned int pid :  进程PID
 
  输出参数:
 
*/
int IATHook(INode *iNode, PNode *pNode, int order, unsigned int pid)
{
    char addr[5] = {0};            //保存四字节地址信息
 
    INode *bkINode = iNode;        //初始化IAT表项结构体链表操作指针
    HANDLE hProcess;               //进程句柄
    DWORD dwHasWrite;              //实际读取的字节数
    LPVOID lpRemoteBuf;            //新申请的内存空间指针
    int temp = 0;                  //临时变量
 
    //数据
    char data[] = "\x74\x65\x73\x74\x00\xCC\xCC\xCC"
        "\xD7\xE9\xB3\xA4\x20\x3A\x20\xBA"
        "\xCE\xC4\xDC\xB1\xF3\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x32\x30\x0A\xD7\xE9\xD4\xB1"
        "\x20\x3A\x20\xCD\xF5\x20\x20\xEC"
        "\xB3\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x30\x35\x0A"
        "\x20\x20\x20\x20\x20\x20\x20\xB5"
        "\xCB\xB9\xE3\xF6\xCE\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x31\x34\x0A\x20\x20\x20\x20"
        "\x20\x20\x20\xB9\xA8\xD3\xF1\xB7"
        "\xEF\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x32\x31\x00";
 
    //shellcode
    char shellcode[] =
        "\x9C\x50\x51\x52\x53\x55\x56\x57"
        "\x6A\x00\x68\x00\x10\x40\x00\x68"
        "\x00\x10\x40\x00\x6A\x00\xB8\xEA"
        "\x07\xD5\x77\xFF\xD0\x5F\x5E\x5D"
        "\x5B\x5A\x59\x58\x9D\xB8\xEA\x07"
        "\xD5\x7C\xFF\xE0";
 
    //循环遍历IAT表项结构体链表,寻找与所给函数序号相同的IAT表项结构体
    if (NULL == iNode)
    {
        return -1;
    }
    for (;;)
    {
        if (NULL == iNode->next)
        {
            if (iNode->order == order)
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (iNode->order ==order)
            {
                break;
            }
            else
            {
                iNode = iNode->next;
            }
        }
    }
 
    //循环遍历IAT表项结构体链表,寻找MessageBoxA的IAT表项结构体
    for (;;)
    {
        if (NULL == bkINode->next)
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                bkINode = bkINode->next;
            }
        }
    }
 
    //循环遍历进程结构体链表,寻找与所给函数所属进程PID相同的进程结构体
    if (NULL == pNode)
    {
        return -1;
    }
    for (;;)
    {
        if (pid == pNode->pe32.th32ProcessID)
        {
            break;
        }
        else
        {
            if (NULL == pNode->next)
            {
                return -1;
            }
            else
            {
                pNode = pNode->next;
            }
        }
    }
 
    if (EnableDebugPriv(SE_DEBUG_NAME))   //获取调试权限
    {
        fprintf(stderr,"Add Privilege error\n");
 
        return -1;
    }
 
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); //获取进程句柄
    if(hProcess == NULL)
    {
        fprintf(stderr,"\n获取进程句柄错误%d",GetLastError());
        return -1;
    }
 
    //申请120字节的数据空间,并写入我们需要的数据
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 120, MEM_COMMIT, PAGE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, data, 120, &dwHasWrite))
    {
        if(dwHasWrite != 120)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,120,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;   //数据所在首地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
 
    shellcode[11] = addr[0];  //"test" 的地址
    shellcode[12] = addr[1];
    shellcode[13] = addr[2];
    shellcode[14] = addr[3];
 
    shellcode[16] = addr[0]+8;//"所要显示的字符串首地址"
    shellcode[17] = addr[1];
    shellcode[18] = addr[2];
    shellcode[19] = addr[3];
 
    temp = (int)bkINode->address; //MessageBoxA的地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
    shellcode[23] = addr[0];
    shellcode[24] = addr[1];
    shellcode[25] = addr[2];
    shellcode[26] = addr[3];
 
    temp = (int)iNode->address;  //原函数的地址,用于jmp回原来的函数
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
    shellcode[38] = addr[0];
    shellcode[39] = addr[1];
    shellcode[40] = addr[2];
    shellcode[41] = addr[3];
 
    //申请44字节的可读可写可执行的shellcode空间,并写入shellcode
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 44, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, shellcode, 44, &dwHasWrite))
    {
        if(dwHasWrite != 44)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,44,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;  //获取shellcode的首地址,并替换IAT表中相应的函数地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
    if(WriteProcessMemory(hProcess, pNode->me32.modBaseAddr+iNode->addrOfAddr, addr, 4, &dwHasWrite))
    {
        return 0;
    }
    else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
    }
 
    CloseHandle(hProcess);
    return -1;
}
 
/*
  函数说明:
      inline hooking 某个IAT表中的函数
 
  输入参数:
      INode **iNode    :  IAT表项结构体二级指针
      PNode *pNode     :  进程结构体指针
      int order        :  函数序号
      unsigned int pid :  进程PID
 
  输出参数:
 
*/
int InlineHook(INode *iNode, PNode *pNode, int order, unsigned int pid)
{
    char addr[5] = {0};      //用于保存4字节的地址
    char buff[6] = {0};      //用于保存jmp xxx指令和所要hook的函数起始五个字节
 
    INode *bkINode = iNode;  //初始化IAT表项结构体链表操作指针
    HANDLE hProcess;         //进程句柄
    DWORD dwHasWrite;        //实际写入的字节数
    LPVOID lpRemoteBuf;      //申请的内存首地址
    int temp = 0;            //临时变量
 
    //数据
    char data[] = "\x74\x65\x73\x74\x00\xCC\xCC\xCC"
        "\xD7\xE9\xB3\xA4\x20\x3A\x20\xBA"
        "\xCE\xC4\xDC\xB1\xF3\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x32\x30\x0A\xD7\xE9\xD4\xB1"
        "\x20\x3A\x20\xCD\xF5\x20\x20\xEC"
        "\xB3\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x30\x35\x0A"
        "\x20\x20\x20\x20\x20\x20\x20\xB5"
        "\xCB\xB9\xE3\xF6\xCE\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x31\x34\x0A\x20\x20\x20\x20"
        "\x20\x20\x20\xB9\xA8\xD3\xF1\xB7"
        "\xEF\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x32\x31\x00";
 
    //shellcode
    char shellcode[] =
        "\x9C\x50\x51\x52\x53\x55\x56\x57"
        "\x6A\x00\x68\x00\x10\x40\x00\x68"
        "\x00\x10\x40\x00\x6A\x00\xB8\xEA"
        "\x07\xD5\x77\xFF\xD0\x5F\x5E\x5D"
        "\x5B\x5A\x59\x58\x9D\x8b\xff\x55\x8b\xec"  //shellco中有所要hooking的函数前五个字节了
        "\xe9\x90\x90\x90\x90";                     //所以后面jmp 回到的是函数的第六个字节
 
    if (NULL == iNode)         //如果IAT表项链表为空,则退出
    {
        return -1;
    }
    for (;;)
    {
        if (NULL == iNode->next)
        {
            if (iNode->order == order)
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (iNode->order ==order)
            {
                break;
            }
            else
            {
                iNode = iNode->next;
            }
        }
    }
 
    //获取MessageBoxA的IAT表项结构体
    for (;;)
    {
        if (NULL == bkINode->next)
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                bkINode = bkINode->next;
            }
        }
    }
 
    //获取所要hook的函数所属进程结构体
    if (NULL == pNode)
    {
        return -1;
    }
    for (;;)
    {
        if (pid == pNode->pe32.th32ProcessID)
        {
            break;
        }
        else
        {
            if (NULL == pNode->next)
            {
                return -1;
            }
            else
            {
                pNode = pNode->next;
            }
        }
    }
 
    //获取调试权限
    if (EnableDebugPriv(SE_DEBUG_NAME))
    {
        fprintf(stderr,"Add Privilege error\n");
 
        return -1;
    }
 
    //获取进程句柄
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if(hProcess == NULL)
    {
        fprintf(stderr,"\n获取进程句柄错误%d",GetLastError());
        return -1;
    }
 
    //读取所要hook的函数前五个字节
    if(ReadProcessMemory(hProcess, iNode->address, buff, 5, &dwHasWrite))
    {
        if(dwHasWrite != 5)
        {
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n读取远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    //如果函数前五个字节不是 mov edi,edi push ebp mov ebp,esp则退出inline hooking
    if (0 != strcmp(buff,"\x8b\xff\x55\x8b\xec"))
    {
        return -1;
    }
 
    //申请120字节的数据空间
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 120, MEM_COMMIT, PAGE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, data, 120, &dwHasWrite))
    {
        if(dwHasWrite != 120)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,120,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;  //获取数据在内存中的首地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
 
    shellcode[11] = addr[0];  //"test"的首地址
    shellcode[12] = addr[1];
    shellcode[13] = addr[2];
    shellcode[14] = addr[3];
 
    shellcode[16] = addr[0]+8; //所要显示的字符串首地址
    shellcode[17] = addr[1];
    shellcode[18] = addr[2];
    shellcode[19] = addr[3];
 
    temp = (int)bkINode->address; //MessageBoxA的地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
    shellcode[23] = addr[0];
    shellcode[24] = addr[1];
    shellcode[25] = addr[2];
    shellcode[26] = addr[3];
 
    //先写入42字节的shellcode
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 42, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, shellcode, 42, &dwHasWrite))
    {
        if(dwHasWrite != 42)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,42,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;        //获得shellcode的首地址
    temp = temp - iNode->address-5; //计算jmp到shellcode的偏移
    buff[0] = 0xe9;
    buff[1] = temp&0xff;
    buff[2] = temp>>8&0xff;
    buff[3] = temp>>16&0xff;
    buff[4] = temp>>24&0xff;       //得到jmp xxx的二进制数据并写入函数的其实五个字节
    if(!WriteProcessMemory(hProcess, iNode->address, buff, 5, &dwHasWrite))
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
    }
 
    temp = (int)lpRemoteBuf;         //获取shellcode的地址
    temp = temp+47;                  //得到shellcode中jmp xx的下条指令的地址
    temp = iNode->address - temp+5//得到jmp回原来函数第六个字节的起始地址
    buff[0] = 0xe9;
    buff[1] = temp&0xff;
    buff[2] = temp>>8&0xff;
    buff[3] = temp>>16&0xff;
    buff[4] = temp>>24&0xff;
    temp = (int)lpRemoteBuf+42;      //得到jmp xxx在shellcode中的地址,并写入shellcode最后五个字节
    if(WriteProcessMemory(hProcess,temp , buff, 5, &dwHasWrite))
    {
        return 0;
    }
    else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
    }
 
    CloseHandle(hProcess);
    return -1;
}

局限性:1当程序运用一种叫late-demand binding技术,函数被调用时才定位地址,这样以来就不能在IAT中定位目标函数地址了.2当目标程序用动态加载(LoadLibrary)时,这种方法也将失效.(如果是通过动态加载的就不行了
因为动态加载的dll的API不在iat中,而是动态生成的.)

Inline Hook

Inline Hook根据修改的字节数不同可以分为5字节修改技术和7字节修改技术( HotFix Hook)

 

Inline Hook直接修改内存中任意函数的代码,将其劫持至Hook API。同时,它比IAT Hook的适用范围更广,因为只要是内存中有的函数它都能Hook,而后者只能Hook IAT表里存在的函数(有些程序会动态加载函数)。

 

img

 

img

 

技术原理

首先把stealth.dll注入目标进程,钩取ntdll.ZwQuerySystemInformation() API。ntdll.ZwQuery-SystemInformation()API起始地址(7C93D92E)的5个字节代码被修改为JMP 10001120((仅修改5个字节代码)。10001120是stealth.MyZwQuerySystemInformation()函数的地址。此时,在procexp.exe代码中调用ntdll.ZwQuerySystemInformation() API,.程序将按如下顺序执行。

(1)在422CF7地址处调用ntdll.ZwQuerySystemInformation() API ( 7C93D92E)。

(2)位于7C93D92E地址处的(修改后的)JMP 10001120指令将执行流转到10001120地址处( hooking函数)。1000116A地址处的CALL unhook()指令用来将ntdll.ZwQuerySystemInformation()API的起始5个字节恢复原值。

(3)位于1000119B地址处的CALL EAX(7C93D92E)指令将调用原来的函数( ntdll.ZwQuery-SystemInformation()API )(由于前面已经“脱钩”,所以可以正常调用执行)。

(4)ntdll.ZwQuerySystemInformation()执行完毕后,由7C93D93A地址处的RETN 10指令返回到stealth.dll代码区域(调用自身的位置)。然后10001212地址处的CALL hook()指令再次钩取ntdll.ZwQuerySystemInformation)API(即将开始的5字节修改为JMP 10001120指令)。

(5)stealth.MyZwQuerySystemInformation()函数执行完毕后,由10001233地址处的RETN 10命令返回到procexp.exe进程的代码区域,继续执行。

 

==使用该技术,一定要在控制程序流程后修复API。==

 

代码

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
#include "stdafx.h"
#include <Windows.h>
#include <wchar.h>
#include <malloc.h>
#include<stdio.h>
#define funcName "ZwQuerySystemInformation"
#define dllName "ntdll.dll"
#define processName L"calc.exe"
typedef LONG NTSTATUS;
typedef enum _SYSTEM_INFORMATION_CLASS {
    SystemBasicInformation = 0,
    SystemPerformanceInformation = 2,
    SystemTimeOfDayInformation = 3,
    SystemProcessInformation = 5,
    SystemProcessorPerformanceInformation = 8,
    SystemInterruptInformation = 23,
    SystemExceptionInformation = 33,
    SystemRegistryQuotaInformation = 37,
    SystemLookasideInformation = 45
} SYSTEM_INFORMATION_CLASS;
 
typedef struct _SYSTEM_PROCESS_INFORMATION {
    ULONG NextEntryOffset;
    ULONG NumberOfThreads;
    BYTE Reserved1[48];
    PVOID Reserved2[3];
    HANDLE UniqueProcessId;
    PVOID Reserved3;
    ULONG HandleCount;
    BYTE Reserved4[4];
    PVOID Reserved5[11];
    SIZE_T PeakPagefileUsage;
    SIZE_T PrivatePageCount;
    LARGE_INTEGER Reserved6[6];
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
 
typedef NTSTATUS(WINAPI *PFZWQUERYSYSTEMINFORMATION)
(SYSTEM_INFORMATION_CLASS SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength);
 
 
BYTE orgCode[5];//原始指令
BYTE fakeCode[5]; //伪造的jmp指令
DWORD funcBase;  //我们的函数基址
 
 //   char debug[100]={0};
 
DWORD WINAPI myZwQuerySystemInformation
(SYSTEM_INFORMATION_CLASS SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength);
 
 
DWORD hook(DWORD funcbase, DWORD fakeFunc);
DWORD unhook(DWORD funcbase);
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{  //获取目标函数基址和伪造函数基址
    DWORD fakeFunc;
    funcBase = (DWORD)GetProcAddress(GetModuleHandleA(dllName), funcName);
    fakeFunc = (DWORD)myZwQuerySystemInformation;
 
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    //加载时就hook掉
        hook(funcBase, fakeFunc);
        break;
    case DLL_PROCESS_DETACH:
        unhook(funcBase);
        break;
    }
    return TRUE;
}
 
DWORD hook(DWORD funcbase, DWORD fakeFunc)
{
    DWORD page;//如果已经被hook了就不再继续
    if(*(BYTE*)funcbase==0xe9)
    {
        return 0;
    }
    VirtualProtect((LPVOID)funcbase, 5, PAGE_EXECUTE_READWRITE, &page);
 
    memcpy(orgCode, (LPVOID)funcbase, 5);
    fakeCode[0] = 0xe9;
    DWORD opCode = fakeFunc -funcBase -  5;//jmp指令的操作码计算公式为:目标地址-当前指令地址-5(指令长度为5
  //  sprintf(debug,"hook  fakeFunc is %p, funcbase is %p",fakeFunc,funcbase);
    memcpy(fakeCode + 1, &opCode, 4);//填充为指令
    memcpy((LPVOID)funcBase, fakeCode, 5); //修改代码
    VirtualProtect((LPVOID)funcbase, 5, page, &page);
    return 1;
}
 
DWORD unhook(DWORD funcbase)
{
    DWORD page;
    if(*(BYTE*)funcbase!=0xe9)
    {
        return 0;
    }
    VirtualProtect((LPVOID)funcbase, 5, PAGE_EXECUTE_READWRITE, &page);
    memcpy((LPVOID)funcBase, orgCode, 4); //恢复代码
    VirtualProtect((LPVOID)funcbase, 5, page, &page);
    return 1;
}
 
DWORD WINAPI myZwQuerySystemInformation
(SYSTEM_INFORMATION_CLASS SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength)
    /*
    这个函数的hook和一般的函数不同,这种函数属于查询类的函数,真正有用的信息
    在该函数调用完了后才会写到缓冲区类的参数,而调用前的参数信息基本没用,
    因此我们要对该函数进行正常调用,完后了再截取信息
    */
{
    DWORD fakeFunc;
    funcBase = (DWORD)GetProcAddress(GetModuleHandleA(dllName), funcName);
    fakeFunc = (DWORD)myZwQuerySystemInformation;
    PSYSTEM_PROCESS_INFORMATION p, pPre;
    unhook(funcBase); //取消hook以正常调用
    DWORD status=4;
    status=((PFZWQUERYSYSTEMINFORMATION)funcBase)(SystemInformationClass,
        SystemInformation,
        SystemInformationLength,
        ReturnLength);//正常调用该函数
 
    if(status!=0)
    {
        hook(funcBase, fakeFunc); //hook住
        return 0;
    }
 
    if (SystemInformationClass== SystemProcessInformation) //只对查询进程的信息感兴趣
    {
        = ((PSYSTEM_PROCESS_INFORMATION)SystemInformation);
 
        while (1)
        {
 
            if(p->Reserved2[1]!=0)
            {       
                if (lstrcmpiW((WCHAR*)p->Reserved2[1], processName)==0)
                {
 
                    if (p->NextEntryOffset==0)//说明是最后一个了
                    {
                        pPre->NextEntryOffset = 0; //将后面一个节点的next指针置0即可
                    }
                    else
                    {
                        //跳过本节点 NextEntryOffset字段是相对于本节点的偏移,而不是绝对地址
                        //当当前节点是第一个节点时这个式子也成立
                        pPre->NextEntryOffset += p->NextEntryOffset;
                    }
                }
                else
                {
                    pPre = p;
 
                }
            }
            if(p->NextEntryOffset==0)
            {
                break;
            }
            p =((PSYSTEM_PROCESS_INFORMATION)((DWORD)p + p->NextEntryOffset));
        }
 
    }
    hook(funcBase, fakeFunc); //hook住
    return 1;
 
}

HotFix Hook

从上节对Code Hook方法的讲解中,我们会发现Code Hook存在一个效率的问题,因为每次Code Hook都要进行“挂钩+脱钩”的操作,也就是要对API的前5字节修改两次,这样,当我们要进行全局Hook的时候,系统运行效率会受影响。而且,当一个线程尝试运行某段代码时,若另一个线程正在对该段代码进行“写”操作,这时就会程序冲突,最终引发一些错误。
有没有办法避免这种隐患呢?答案是有的,可以使用HotFix Hook(“热补丁”)方法。

技术原理

API起始代码有如下两个明显的相似点:
[1]API代码以“MOV EDI,EDI”指令开始。
[2]API代码上方有5个NOP指令。

 

MOV EDI,EDI用于将EDI的值再次复制给EDI,这没有什么实际意义。也就是说,API起始代码的MOV指令(2个字节)与其上方的5个NOP指令(5个字节)合起来共7个字节的指令没有任何意义。所以我们就可以通过修改这7个字节来实现Hook操作。这种方法因为可以在进程处于运行状态时临时更改进程内存中的库文件,所以微软也常用这种方法来打“热补丁”。

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
/*
  函数说明:
      inline hooking 某个IAT表中的函数
 
  输入参数:
      INode **iNode    :  IAT表项结构体二级指针
      PNode *pNode     :  进程结构体指针
      int order        :  函数序号
      unsigned int pid :  进程PID
 
  输出参数:
 
*/
int InlineHook(INode *iNode, PNode *pNode, int order, unsigned int pid)
{
    char addr[5] = {0};      //用于保存4字节的地址
    char buff[6] = {0};      //用于保存jmp xxx指令和所要hook的函数起始五个字节
 
    INode *bkINode = iNode;  //初始化IAT表项结构体链表操作指针
    HANDLE hProcess;         //进程句柄
    DWORD dwHasWrite;        //实际写入的字节数
    LPVOID lpRemoteBuf;      //申请的内存首地址
    int temp = 0;            //临时变量
 
    //数据
    char data[] = "\x74\x65\x73\x74\x00\xCC\xCC\xCC"
        "\xD7\xE9\xB3\xA4\x20\x3A\x20\xBA"
        "\xCE\xC4\xDC\xB1\xF3\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x32\x30\x0A\xD7\xE9\xD4\xB1"
        "\x20\x3A\x20\xCD\xF5\x20\x20\xEC"
        "\xB3\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x30\x35\x0A"
        "\x20\x20\x20\x20\x20\x20\x20\xB5"
        "\xCB\xB9\xE3\xF6\xCE\x20\x32\x30"
        "\x31\x33\x33\x30\x32\x35\x33\x30"
        "\x30\x31\x34\x0A\x20\x20\x20\x20"
        "\x20\x20\x20\xB9\xA8\xD3\xF1\xB7"
        "\xEF\x20\x32\x30\x31\x33\x33\x30"
        "\x32\x35\x33\x30\x30\x32\x31\x00";
 
    //shellcode
    char shellcode[] =
        "\x9C\x50\x51\x52\x53\x55\x56\x57"
        "\x6A\x00\x68\x00\x10\x40\x00\x68"
        "\x00\x10\x40\x00\x6A\x00\xB8\xEA"
        "\x07\xD5\x77\xFF\xD0\x5F\x5E\x5D"
        "\x5B\x5A\x59\x58\x9D\x8b\xff\x55\x8b\xec"  //shellco中有所要hooking的函数前五个字节了
        "\xe9\x90\x90\x90\x90";                     //所以后面jmp 回到的是函数的第六个字节
 
    if (NULL == iNode)         //如果IAT表项链表为空,则退出
    {
        return -1;
    }
    for (;;)
    {
        if (NULL == iNode->next)
        {
            if (iNode->order == order)
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (iNode->order ==order)
            {
                break;
            }
            else
            {
                iNode = iNode->next;
            }
        }
    }
 
    //获取MessageBoxA的IAT表项结构体
    for (;;)
    {
        if (NULL == bkINode->next)
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                return -1;
            }
        }
        else
        {
            if (0 == strcmp(bkINode->name,"MessageBoxA"))
            {
                break;
            }
            else
            {
                bkINode = bkINode->next;
            }
        }
    }
 
    //获取所要hook的函数所属进程结构体
    if (NULL == pNode)
    {
        return -1;
    }
    for (;;)
    {
        if (pid == pNode->pe32.th32ProcessID)
        {
            break;
        }
        else
        {
            if (NULL == pNode->next)
            {
                return -1;
            }
            else
            {
                pNode = pNode->next;
            }
        }
    }
 
    //获取调试权限
    if (EnableDebugPriv(SE_DEBUG_NAME))
    {
        fprintf(stderr,"Add Privilege error\n");
 
        return -1;
    }
 
    //获取进程句柄
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if(hProcess == NULL)
    {
        fprintf(stderr,"\n获取进程句柄错误%d",GetLastError());
        return -1;
    }
 
    //读取所要hook的函数前五个字节
    if(ReadProcessMemory(hProcess, iNode->address, buff, 5, &dwHasWrite))
    {
        if(dwHasWrite != 5)
        {
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n读取远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    //如果函数前五个字节不是 mov edi,edi push ebp mov ebp,esp则退出inline hooking
    if (0 != strcmp(buff,"\x8b\xff\x55\x8b\xec"))
    {
        return -1;
    }
 
    //申请120字节的数据空间
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 120, MEM_COMMIT, PAGE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, data, 120, &dwHasWrite))
    {
        if(dwHasWrite != 120)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,120,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;  //获取数据在内存中的首地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
 
    shellcode[11] = addr[0];  //"test"的首地址
    shellcode[12] = addr[1];
    shellcode[13] = addr[2];
    shellcode[14] = addr[3];
 
    shellcode[16] = addr[0]+8; //所要显示的字符串首地址
    shellcode[17] = addr[1];
    shellcode[18] = addr[2];
    shellcode[19] = addr[3];
 
    temp = (int)bkINode->address; //MessageBoxA的地址
    addr[0] = temp&0xff;
    addr[1] = temp>>8&0xff;
    addr[2] = temp>>16&0xff;
    addr[3] = temp>>24&0xff;
    shellcode[23] = addr[0];
    shellcode[24] = addr[1];
    shellcode[25] = addr[2];
    shellcode[26] = addr[3];
 
    //先写入42字节的shellcode
    lpRemoteBuf = VirtualAllocEx(hProcess, NULL, 42, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if(WriteProcessMemory(hProcess, lpRemoteBuf, shellcode, 42, &dwHasWrite))
    {
        if(dwHasWrite != 42)
        {
            VirtualFreeEx(hProcess,lpRemoteBuf,42,MEM_COMMIT);
            CloseHandle(hProcess);
            return -1;
        }
 
    }else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
        CloseHandle(hProcess);
        return -1;
    }
 
    temp = (int)lpRemoteBuf;        //获得shellcode的首地址
    temp = temp - iNode->address-5; //计算jmp到shellcode的偏移
    buff[0] = 0xe9;
    buff[1] = temp&0xff;
    buff[2] = temp>>8&0xff;
    buff[3] = temp>>16&0xff;
    buff[4] = temp>>24&0xff;       //得到jmp xxx的二进制数据并写入函数的其实五个字节
    if(!WriteProcessMemory(hProcess, iNode->address, buff, 5, &dwHasWrite))
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
    }
 
    temp = (int)lpRemoteBuf;         //获取shellcode的地址
    temp = temp+47;                  //得到shellcode中jmp xx的下条指令的地址
    temp = iNode->address - temp+5//得到jmp回原来函数第六个字节的起始地址
    buff[0] = 0xe9;
    buff[1] = temp&0xff;
    buff[2] = temp>>8&0xff;
    buff[3] = temp>>16&0xff;
    buff[4] = temp>>24&0xff;
    temp = (int)lpRemoteBuf+42;      //得到jmp xxx在shellcode中的地址,并写入shellcode最后五个字节
    if(WriteProcessMemory(hProcess,temp , buff, 5, &dwHasWrite))
    {
        return 0;
    }
    else
    {
        printf("\n写入远程进程内存空间出错%d。",GetLastError());
    }
 
    CloseHandle(hProcess);
    return -1;
}

SetWindowsHook

详细内容看《dll注入&代码注入》

SetWinEventHook

SetWinEventHook function (winuser.h) - Win32 apps | Microsoft Docs

The client thread that calls SetWinEventHook must have a message loop in order to receive events.(调用SetWinEventHook的客户端线程必须具有消息循环才能接收事件。)

1
2
3
4
5
6
7
8
9
HWINEVENTHOOK SetWinEventHook(
  DWORD        eventMin,
  DWORD        eventMax,
  HMODULE      hmodWinEventProc,
  WINEVENTPROC pfnWinEventProc,
  DWORD        idProcess,
  DWORD        idThread,
  DWORD        dwFlags
);

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FCrTomvH-1632650145285)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210926175447773.png)]

dwFlags:

WINEVENT_INCONTEXT | WINEVENT_SKIPOWNPROCESS
WINEVENT_INCONTEXT | WINEVENT_SKIPOWNTHREAD
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD

此外,客户申请可以指定WINEVENT_INCONTEXT,或单独WINEVENT_OUTOFCONTEXT

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3CoWST1u-1632650145286)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210926175413574.png)]

 

区别:

 

SetWinEventHook 和 SetWindowsHookEx 都可以指定钩子函数(hook function)来截取别的进程中的消息,但是他们之间有一些不同。

 

SetWindowsHookEx 有两种钩子函数,一种是全局钩子(global hook),另一种是线程钩子(thread hook)。全局钩子能够截取所有线程的消息,但是全局钩子函数必须存在于一个 dll 中。线程钩子只能截取属于当前进程中的线程的消息,钩子函数不需要放在 dll 中。SetWinEventHook 也有两种钩子函数,一种是进程内钩子(in-context hook),另一种是进程外钩子(out-of-context hook)。进程内钩子函数必须放在 dll 中,将被映射到所有进程中。进程外钩子函数不会被映射到别的进程中,所以也不需要被放到 dll 中。不管进程内或进程外钩子都能截取到所有进程的消息,区别仅是进程内钩子效率更高。

 

SetWindowsHookEx 和 SetWinEventHook 两种方法截取的消息的类型不一样。SetWindowsHookEx 能截取所有WM 开头的消息。而 SetWinEventHook 截取的消息都是 EVENT 开头的,这些消息所有都是跟对象的状态相关的,所以它无法获取根鼠标键盘相关的消息。

 

SetWindowsHookEx 设定的全局钩子必须被注入到别的进程中,所以就无法截取到一些有限制的进程的消息,比如命令行窗口(console window)。而 SetWinEventHook 的进程外钩子就没有这个限制。

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
// Global variable.
HWINEVENTHOOK g_hook;
 
// Initializes COM and sets up the event hook.
//
void InitializeMSAA()
{
    CoInitialize(NULL);
    g_hook = SetWinEventHook(
        EVENT_SYSTEM_MENUSTART, EVENT_SYSTEM_MENUEND,  // Range of events (4 to 5).
        NULL,                                          // Handle to DLL.
        HandleWinEvent,                                // The callback.
        0, 0,              // Process and thread IDs of interest (0 = all)
        WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // Flags.
}
 
// Unhooks the event and shuts down COM.
//
void ShutdownMSAA()
{
    UnhookWinEvent(g_hook);
    CoUninitialize();
}
 
// Callback function that handles events.
//
void CALLBACK HandleWinEvent(HWINEVENTHOOK hook, DWORD event, HWND hwnd,
                             LONG idObject, LONG idChild,
                             DWORD dwEventThread, DWORD dwmsEventTime)
{
    IAccessible* pAcc = NULL;
    VARIANT varChild;
    HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &varChild); 
    if ((hr == S_OK) && (pAcc != NULL))
    {
        BSTR bstrName;
        pAcc->get_accName(varChild, &bstrName);
        if (event == EVENT_SYSTEM_MENUSTART)
        {
            printf("Begin: ");
        }
        else if (event == EVENT_SYSTEM_MENUEND)
        {
            printf("End:   ");
        }
        printf("%S\n", bstrName);
        SysFreeString(bstrName);
        pAcc->Release();
    }
}

SSDT Hook

SSDT表

全称:System Services Descriptor Table(系统服务描述符表)

 

SSDT表 把 Ring3 的 Win32 API 和 Ring0 的内核 API 联系起来

 

SSDT的每个成员叫做系统服务表

 

SSDT结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// KSYSTEM_SERVICE_TABLE 和 KSERVICE_TABLE_DESCRIPTOR
// 用来定义 SSDT 结构
typedef struct _KSYSTEM_SERVICE_TABLE
{
    PULONG  ServiceTableBase;                               // SSDT (System Service Dispatch Table)的基地址
    PULONG  ServiceCounterTableBase;                        // 用于 checked builds, 包含 SSDT 中每个服务被调用的次数
    ULONG   NumberOfService;                                // 服务函数的个数, NumberOfService * 4 就是整个地址表的大小
    ULONG   ParamTableBase;                                 // SSPT(System Service Parameter Table)的基地址
} KSYSTEM_SERVICE_TABLE, *PKSYSTEM_SERVICE_TABLE;
 
typedef struct _KSERVICE_TABLE_DESCRIPTOR
{
    KSYSTEM_SERVICE_TABLE   ntoskrnl;                       // ntoskrnl.exe 的服务函数
    KSYSTEM_SERVICE_TABLE   win32k;                         // win32k.sys 的服务函数(GDI32.dll/User32.dll 的内核支持)
    KSYSTEM_SERVICE_TABLE   notUsed1;
    KSYSTEM_SERVICE_TABLE   notUsed2;
}KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR;

查看SSDT表

1
kd> dd nt!KeServiceDescriptorTable

img

 

第二张表为0,使用KeServiceDescriptorTable这个公开的导出函数,我们无法看到win32k.sys这张表结构

 

img

 

win32k.sys系统服务表已经可见

1
2
内核中有两个系统服务描述符表,一个是KeServiceDescriptorTable(由ntoskrnl.exe导出),一个是KeServieDescriptorTableShadow(没有导出)。
两者的区别是,KeServiceDescriptorTable仅有ntoskrnel一项,KeServieDescriptorTableShadow包含了ntoskrnel以及win32k。一般的Native API的服务地址由KeServiceDescriptorTable分派,gdi.dll/user.dll的内核API调用服务地址由KeServieDescriptorTableShadow分派。还有要清楚一点的是win32k.sys只有在GUI线程中才加载,一般情况下是不加载的,所以要Hook KeServieDescriptorTableShadow的话,一般是用一个GUI程序通过IoControlCode来触发

实验:ring3 调用ReadVirtualMemory 函数

 

查看系统服务函数地址:

 

img

 

[函数地址表 + 系统服务号*4] = 内核函数地址 805aa712

 

img

 

查看参数地址

 

img

 

[参数表 + 系统服务号] = 内核函数参数个数(单位:字节)14

 

img
查看内核函数反汇编:

 

img

 

SSDT HOOK 原理:

 

将805aa712改为指向我们函数的地址:MyNtReadVirtualMemory。系统就会直接调用MyNtReadVirtualMemory 而不是原来的 NtReadVirtualMemory 函数。

 

注意:修改SSDT表,这个表必须可写,但在xp以后的系统中他都是只读的。

 

修改:

 

(1) 更改注册表
恢复页面保护:HKLM\SYSTEM\CurrentControlset\Control\Session Manger\Memory Management\EnforceWriteProtection=0
去掉页面保护:HKLM\SYSTEM\CurrentControlset\Control\Session Manger\Memory Management\DisablePagingExecutive=1
(2)改变CR0寄存器的第1位
Windows对内存的分配,是采用的分页管理。其中有个CR0寄存器,如图
img

 

其中第1位叫做保护属性位,控制着页的读或写属性。如果为1,则可以读/写/执行;如果为0,则只可以读/执行。

 

SSDT,IDT的页属性在默认下都是只读,可执行的,但不能写

 

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 关闭页保护
VOID PageProtectOff()
{
    __asm
    {
        cli; // 关闭中断
        mov eax, cr0;
        and eax, not 0x10000; // WP位置0
        mov cr0, eax;
    }
}
 
// 开启页保护
VOID PageProtectOn()
{
    __asm
    {
        mov eax, cr0;
        or eax, 0x10000; // WP位置1
        mov cr0, eax;
        sti; // 恢复中断
    }
}

(3)通过Memory Descriptor List

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
#include <ntddk.h>
#include <ntstatus.h>
 
 
// 系统服务表
typedef struct _KSYSTEM_SERVICE_TABLE
{
    PULONG ServiceTableBase;            // 函数地址表(SSDT)
    PULONG ServiceCounterTableBase;        // SSDT 函数被调用的次数
    ULONG NumberOfService;                // 函数个数
    PULONG ParamTableBase;                // 函数参数表(SSPT)
} KSYSTEM_SERVICE_TABLE, *PKSYSTEM_SERVICE_TABLE;
 
typedef struct _KSERVICE_TABLE_DESCRIPTOR
{
    KSYSTEM_SERVICE_TABLE ntoskrnl;        // 内核函数
    KSYSTEM_SERVICE_TABLE win32k;        // win32k.sys 函数
    KSYSTEM_SERVICE_TABLE unUsed1;
    KSYSTEM_SERVICE_TABLE unUsed2;
} KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR;
 
// NTOPENPROCESS
typedef NTSTATUS (*NTOPENPROCESS) (PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId);
 
 
 
VOID DriverUnload(PDRIVER_OBJECT pDriver);
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriver, PUNICODE_STRING reg_path);
VOID PageProtectOff();
VOID PageProtectOn();
VOID HookNtOpenProcess();
VOID UnHookNtOpenProcess();
NTSTATUS HbgNtOpenProcess(PHANDLE  ProcessHandle, ACCESS_MASK  DesiredAccess, POBJECT_ATTRIBUTES  ObjectAttributes, PCLIENT_ID  ClientId);
 
 
 
 
extern PKSERVICE_TABLE_DESCRIPTOR KeServiceDescriptorTable; // ntoskrnl.exe 导出的全局变量
ULONG uOldNtOpenProcess; // 旧的函数地址
 
 
 
 
// 驱动入口
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriver, PUNICODE_STRING reg_path)
{
    // HOOK
    HookNtOpenProcess();
 
    pDriver->DriverUnload = DriverUnload;
 
    return STATUS_SUCCESS;
}
 
// 卸载驱动
VOID DriverUnload(PDRIVER_OBJECT pDriver)
{
    UnHookNtOpenProcess();
    DbgPrint("Driver unloaded.\n");
}
 
// 关闭页保护
VOID PageProtectOff()
{
    __asm
    {
        cli; // 关闭中断
        mov eax, cr0;
        and eax, not 0x10000; // WP位置0
        mov cr0, eax;
    }
}
 
// 开启页保护
VOID PageProtectOn()
{
    __asm
    {
        mov eax, cr0;
        or eax, 0x10000; // WP位置1
        mov cr0, eax;
        sti; // 恢复中断
    }
}
 
// HOOK NtOpenProcess
//关闭页面保护
//对未进行SSDT Hook前的SSDT表进行了备份,一个索引号对应一个当前地址。
//SSDT HOOK
//开启页面保护
VOID HookNtOpenProcess()
{
    PageProtectOff();
    uOldNtOpenProcess = KeServiceDescriptorTable->ntoskrnl.ServiceTableBase[0x7A];
    KeServiceDescriptorTable->ntoskrnl.ServiceTableBase[0x7A] = (ULONG)HbgNtOpenProcess;
    PageProtectOn();
 
 
// UnHOOK NtOpenProcess
//关闭页面保护
//通过之前保存的地址,恢复SSDT表
//开启页面保护
VOID UnHookNtOpenProcess()
{
    PageProtectOff();
    KeServiceDescriptorTable->ntoskrnl.ServiceTableBase[0x7A] = uOldNtOpenProcess;
    PageProtectOn();
}
 
// 被修改的 NtOpenProcess 函数,简单打印参数
NTSTATUS HbgNtOpenProcess(PHANDLE  ProcessHandle, ACCESS_MASK  DesiredAccess, POBJECT_ATTRIBUTES  ObjectAttributes, PCLIENT_ID  ClientId)
{
    DbgPrint("%x %x %x %x\n", ProcessHandle, DesiredAccess, ObjectAttributes, ClientId);
    return ((NTOPENPROCESS)uOldNtOpenProcess)(ProcessHandle, DesiredAccess, ObjectAttributes, ClientId);
}

只做笔记整理。代码非原创。


[注意] 欢迎加入看雪团队!base上海,招聘CTF安全工程师,将兴趣和工作融合在一起!看雪20年安全圈的口碑,助你快速成长!

最后于 2021-9-29 20:52 被pyikaaaa编辑 ,原因: 改标题
收藏
点赞6
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回