-
Notifications
You must be signed in to change notification settings - Fork 0
/
processdumper.cpp
1947 lines (1747 loc) · 58.4 KB
/
processdumper.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
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* processdumper: console utility for software analysis
* Copyright(C) 2017 Peter Bohning
* This program is free software : you can redistribute it and / or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdio.h>
#include <stdexcept>
#include <Windows.h>
#include <Psapi.h>
#include <TlHelp32.h>
#include <VersionHelpers.h>
#include <signal.h>
#include <Shlobj.h>
#include <Shlwapi.h>
#include "kernelreplacements.h"
#include "libraryloader.h"
#include "loadfiles.h"
#include "reconstitute.h"
#include "query.h"
#include "ipcsocket.h"
#include "driver.h"
#include "helperlib/errors.h"
#define NOINJECTIONCOMM
#define FUNCTIONSTOHOOKFILE L"functionstohook.xml"
char * helper_lib_error_strings[] = { "", "",
"helper library imports failed",
"unable to open logging file",
"VirtualAlloc for hooks failed",
"xml file load failed",
"CreateToolhelp failed",
"ModuleFirst failed" };
typedef struct _CLIENT_ID
{
PVOID UniqueProcess;
PVOID UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef WCHAR * PUNICODE_STRING;
typedef struct _OBJECT_ATTRIBUTES {
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor;
PVOID SecurityQualityOfService;
} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
bool produceoutput = true; //a little awkward, basically for testing
bool driver = true;
bool attemptinject = true;
bool hijackthread = false;
HMODULE kernel32DLL = NULL;
HMODULE k32DLL = NULL;
HMODULE ntDLL = NULL;
HMODULE fakentDLL = NULL;
uint32_t g_pid;
BOOL g_wow64;
char * functionstohookfilename;
char * helperlogfilename;
char * g_injectedbaseaddress;
char * unhookaddress;
char * hijackcaller;
HANDLE sync_event = NULL;
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemBasicInformation = 0,
SystemPerformanceInformation = 2,
SystemTimeOfDayInformation = 3,
SystemProcessInformation = 5,
SystemProcessorPerformanceInformation = 8,
SystemInterruptInformation = 23,
SystemExceptionInformation = 33,
SystemRegistryQuotaInformation = 37,
SystemLookasideInformation = 45,
SystemPolicyInformation = 134,
} SYSTEM_INFORMATION_CLASS;
typedef struct _SYSTEM_BASIC_INFORMATION {
BYTE Reserved1[24];
PVOID Reserved2[4];
CCHAR NumberOfProcessors;
} SYSTEM_BASIC_INFORMATION;
typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
BYTE Reserved1[52];
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;
//typedef uint32_t REALADDRESS;
typedef uint64_t REALADDRESS;
#define STATUS_ACCESS_DENIED 0xc0000022
typedef HANDLE (WINAPI * CreateToolhelp32SnapshotPtr)(DWORD dwFlags, DWORD th32ProcessID);
typedef FARPROC (WINAPI * GetProcAddressPtr)(HMODULE hModule, LPCSTR lpProcName);
typedef NTSTATUS (WINAPI * NtQuerySystemInformationPtr)(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);
typedef NTSTATUS (* ZwOpenProcessPtr)(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientID);
typedef int (WINAPI * lstrlenPtr)(LPCTSTR lpString);
CreateToolhelp32SnapshotPtr realCreateToolhelp32Snapshot = NULL;
GetProcAddressPtr realGetProcAddress = NULL;
GetProcAddressPtr ourGetProcAddress = NULL;
NtQuerySystemInformationPtr ourNtQuerySystemInformation = NULL;
NtQuerySystemInformationPtr realNtQuerySystemInformation = NULL;
NtQuerySystemInformationPtr fakeNtQuerySystemInformation = NULL;
ZwOpenProcessPtr ourZwOpenProcess = NULL;
void sigintcatch(int signal);
int filterException(int code, PEXCEPTION_POINTERS ex);
void dump_current_module(HANDLE process, char * name);
int enummodulepulldown(HANDLE processH, char * outputdirname);
void MakeLibrariesExecutable(void);
BOOL EnableDebugPrivilege(BOOL bEnable);
void CheckProcessPrivileges(uint16_t pid);
BOOL GetLogonSID(HANDLE hToken, PSID *ppsid);
WCHAR * GetLastErrorString(void);
int ListProcessThreads(uint32_t pid);
int injectProcess(HANDLE pH, char * code, unsigned int size);
int hijack_some_thread(HANDLE pH, char * routine, LPVOID data);
int uninjectProcess(HANDLE pH);
uint32_t Get32ProcAddress(char * lib, char * _funcname);
extern "C"
{
NTSTATUS __stdcall AMD64_NtQuerySystemInformation(ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);
void GetIDT64(char * idt6);
}
//NTSTATUS __stdcall DirectNTQuerySystemInformation(ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);
void custom_library_loader_stuff(void);
inline void queryidt(void);
#pragma pack(1)
struct idtentry
{
unsigned short base_lo;
unsigned short sel; /* Our kernel segment goes here! */
unsigned char always0; /* This will ALWAYS be set to 0! */
unsigned char flags; /* Set using the above table! */
unsigned short base_hi;
};
#pragma pack(1)
struct idtentry64
{
unsigned short offset1;
unsigned short sel; /* Our kernel segment goes here! */
unsigned char always0; /* This will ALWAYS be set to 0! */
unsigned char flags; /* Set using the above table! */
unsigned short offset2;
unsigned long offset3;
unsigned long reserved0;
};
void queryidt(void)
{
//char idt32[6];
char idt64[10];
uint16_t idtlimit;
//uint32_t idtp;
uint64_t idt64p;
int i;
//struct idtentry * idtentryp;
#ifdef IGUESSWERENOTTHEKERNEL
struct idtentry64 * idtentry64p;
#endif //IGUESSWERENOTTHEKERNEL
memset(idt64, 0, 10);
GetIDT64(idt64);
idtlimit = *(uint16_t *)idt64;
idt64p = *(uint64_t *)(idt64 + 2);
printf("IDT: ");
for(i = 0; i < 10; i++)
printf("%02x", (unsigned char)idt64[i]);
printf("\n");
printf("%04x %08x%08x\n", idtlimit, PRINTARG64(idt64p));
/*idtentryp = (struct idtentry *)idtp;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentryp->base_lo, idtentryp->sel, idtentryp->always0, idtentryp->flags, idtentryp->base_hi);
idtentryp++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentryp->base_lo, idtentryp->sel, idtentryp->always0, idtentryp->flags, idtentryp->base_hi);
idtentryp++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentryp->base_lo, idtentryp->sel, idtentryp->always0, idtentryp->flags, idtentryp->base_hi);
idtentryp++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentryp->base_lo, idtentryp->sel, idtentryp->always0, idtentryp->flags, idtentryp->base_hi);
idtentryp++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentryp->base_lo, idtentryp->sel, idtentryp->always0, idtentryp->flags, idtentryp->base_hi);
idtentryp++;*/
//#define IGUESSWERENOTTHEKERNEL
#ifdef IGUESSWERENOTTHEKERNEL
idtentry64p = (struct idtentry64 *)idt64p;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentry64p->offset1, idtentry64p->sel, idtentry64p->always0, idtentry64p->flags, idtentry64p->offset2);
printf(" hir: %08x res %08x\n", idtentry64p->offset3, idtentry64p->reserved0);
/*idtentry64p++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentry64p->offset1, idtentry64p->sel, idtentry64p->always0, idtentry64p->flags, idtentry64p->offset2);
printf(" hir: %08x res %08x\n", idtentry64p->offset3, idtentry64p->reserved0);
idtentry64p++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentry64p->offset1, idtentry64p->sel, idtentry64p->always0, idtentry64p->flags, idtentry64p->offset2);
printf(" hir: %08x res %08x\n", idtentry64p->offset3, idtentry64p->reserved0);
idtentry64p++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentry64p->offset1, idtentry64p->sel, idtentry64p->always0, idtentry64p->flags, idtentry64p->offset2);
printf(" hir: %08x res %08x\n", idtentry64p->offset3, idtentry64p->reserved0);
idtentry64p++;
printf("low: %04x sel: %04x a0: %02x fl: %02x hi: %04x\n", idtentry64p->offset1, idtentry64p->sel, idtentry64p->always0, idtentry64p->flags, idtentry64p->offset2);
printf(" hir: %08x res %08x\n", idtentry64p->offset3, idtentry64p->reserved0);
idtentry64p++;*/
#endif //IGUESSWERENOTTHEKERNEL
}
void sigintcatch(int signal)
{
HANDLE pH;
if(attemptinject && g_injectedbaseaddress)
{
pH = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, g_pid);
if(!pH || pH == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "uninject process OpenProcess failed (%d)\n", GetLastError());
return;
}
uninjectProcess(pH);
}
printf("Exiting\n");
}
int main(int argc, char ** argv)
{
int i, j;
REALADDRESS addr;
char * outputfilename = NULL;
char * outputdirname = NULL;
char * reconfromdir = NULL;
char * queryfromdir = NULL;
//char * imagepath = NULL;
int len;
WCHAR * errstring;
char * imagepath = NULL;
DWORD err;
functionstohookfilename = NULL;
helperlogfilename = NULL;
g_pid = (uint32_t)-1;
g_injectedbaseaddress = NULL;
hijackthread = false;
for(i = 0; i < argc; i++)
{
if(strcmp("-o", argv[i]) == 0)
{
i++;
outputdirname = (char *)malloc(strlen(argv[i]) + 1);
sprintf(outputdirname, argv[i]);
}
else if(strcmp("-r", argv[i]) == 0)
{
i++;
reconfromdir = (char *)malloc(strlen(argv[i]) + 1);
sprintf(reconfromdir, argv[i]);
}
else if(strcmp("-l", argv[i]) == 0)
{
i++;
helperlogfilename = (char *)malloc(MAX_PATH);
GetFullPathNameA(argv[i], MAX_PATH, helperlogfilename, NULL);
}
else if(strcmp("-q", argv[i]) == 0)
{
i++;
queryfromdir = (char *)malloc(strlen(argv[i]) + 1);
sprintf(queryfromdir, argv[i]);
}
else if(strcmp("-p", argv[i]) == 0)
{
i++;
sscanf(argv[i], "%u", &g_pid);
}
else if(strlen(argv[i]) > 1 && argv[i][0] == '-' && argv[i][1] != '-')
{
j = 1;
while(j < strlen(argv[i]) && argv[i][j] != ' ')
{
switch(argv[i][j])
{
case 'd':
produceoutput = false;
break;
case 'j':
hijackthread = true;
break;
case 'b':
attemptinject = false;
break;
case 'n':
driver = false;
break;
default:
printf("Unknown argument option %c\n", argv[i][j]);
break;
}
j++;
}
}
else if(strcmp("--functions", argv[i]) == 0)
{
i++;
functionstohookfilename = (char *)malloc(strlen(argv[i]) + 1);
sprintf(functionstohookfilename, argv[i]);
}
else if(strcmp("--uninstall", argv[i]) == 0)
{
if(uninstall_driver() < 0)
fprintf(stderr, "Failed to uninstall driver\n");
else
printf("Uninstalled driver\n");
return 0;
}
else if(strcmp("--help", argv[i]) == 0 || strcmp("-h", argv[i]) == 0)
{
printf("./processdumper -bdnj -o [dirname] -p [pid] -r [previousoutdir] -q [previousoutdir] -l [logfile]\n");
printf("\t\t\t--uninstall\n");
printf("\t-r [outdir]: reconstruct from previous output directory\n");
printf("\t-q [outdir]: query previously reconstituted exe/dll\n");
printf("\t-d: don't produce output files or reconstitute\n");
printf("\t-n: don't install driver\n");
printf("\t-b: don't attempt to inject process\n");
printf("\t-j: don't createremotethread, hijack one by default\n");
printf("\t-l [logfilename]: injected library will log to this file\n");
printf("\t--functions [xmlfile]: specify functions to hook\n");
printf("\t--uninstall: uninstall driver and exit\n");
return 0;
}
}
if(reconfromdir)
{
reconstitute_from_directory(reconfromdir);
if(reconstitute() < 0)
fprintf(stderr, "Reconstitution failed\n");
cleanup_reconstitution();
free(reconfromdir);
return 0;
}
else if(queryfromdir)
{
query_from_directory(queryfromdir);
if(reconstitute() < 0)
fprintf(stderr, "Query failed\n");
cleanup_reconstitution();
free(queryfromdir);
return 0;
}
if(g_pid == (uint32_t)-1)
{
fprintf(stderr, "No process id specified, quitting.\n");
if(outputdirname)
free(outputdirname);
return 0;
}
if(!outputdirname)
{
fprintf(stderr, "No output directory specified, using PID...\n");
outputdirname = (char *)malloc(10);
sprintf(outputdirname, "%d", g_pid);
}
if(!helperlogfilename)
{
PWSTR documentsfolder;
documentsfolder = (PWSTR)malloc(500);
char line[500];
SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, (PWSTR *)&documentsfolder);
WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)documentsfolder, -1, line, 500, NULL, NULL);
free(documentsfolder);
sprintf(line, "%s\\%s", line, "processdumper");
if(!PathFileExistsA(line))
{
if(!CreateDirectoryA(line, NULL))
{
fprintf(stderr, "Can't create directory: %s\n", line);
return -1;
}
}
sprintf(line, "%s\\%s.log", line, outputdirname);
helperlogfilename = (char *)malloc(strlen(line) + 1);
sprintf(helperlogfilename, line);
}
if(driver && install_driver() < 0)
fprintf(stderr, "Failed to install driver\n");
if(!EnableDebugPrivilege(TRUE))
{
fprintf(stderr, "Unable to enable debug privileges\n");
//RemoveDirectoryA(outputdirname);
free(outputdirname);
return -1;
}
queryidt();
fakentDLL = LoadLibrary(L"ntdll.dll");
printf("fakentdll.dll: %p\n", fakentDLL);
if(!fakentDLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary fake ntdll.dll failed(%s)\n", errstring);
free(errstring);
}
fakeNtQuerySystemInformation = (NtQuerySystemInformationPtr)GetProcAddress(fakentDLL, "NtQuerySystemInformation");
fakeNtQuerySystemInformation(SystemBasicInformation, 0, 0, (PULONG)fakentDLL);
k32DLL = LoadLibrary(L"kernel32.dll");
if(!k32DLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary fake ntdll.dll failed(%s)\n", errstring);
free(errstring);
}
CheckProcessPrivileges(g_pid);
#ifdef TESTTHIS
/* Let's get something real here: */
//kernel32DLL = LoadLibrary(L".\\kernel32.dll");
kernel32DLL = LoadLibrary(L"C:\\MinGW\\msys\\1.0\\home\\peterius\\projects\\processdumper\\Debug\\realkernel32.dll");
printf("kernel32.dll: %p\n", kernel32DLL);
if(!kernel32DLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary kernel32.dll failed(%s)\n", errstring);
free(errstring);
}
ntDLL = LoadLibrary(L"C:\\MinGW\\msys\\1.0\\home\\peterius\\projects\\processdumper\\Debug\\ntdll.dll");
printf("ntdll.dll: %p\n", ntDLL);
if(!ntDLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary ntdll.dll failed(%s)\n", errstring);
free(errstring);
}
//to get NtQuery... asm...
fakentDLL = LoadLibrary(L"ntdll.dll");
printf("fakentdll.dll: %p\n", fakentDLL);
if(!fakentDLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary fake ntdll.dll failed(%s)\n", errstring);
free(errstring);
}
fakeNtQuerySystemInformation = (NtQuerySystemInformationPtr)GetProcAddress(fakentDLL, "NtQuerySystemInformation");
fakeNtQuerySystemInformation(SystemBasicInformation, 0, 0, (PULONG)fakentDLL);
if(0)
custom_library_loader_stuff();
addr = (REALADDRESS)&LoadLibrary;
if(addr)
{
for(i = 0; i < 0x32; i += 8)
printf("%02x%02x%02x%02x, %02x%02x%02x%02x\n", ((unsigned char *)addr)[i], ((unsigned char *)addr)[i + 1], ((unsigned char *)addr)[i + 2], ((unsigned char *)addr)[i + 3],
((unsigned char *)addr)[i + 4], ((unsigned char *)addr)[i + 5], ((unsigned char *)addr)[i + 6], ((unsigned char *)addr)[i + 7]);
}
if(kernel32DLL)
{
realGetProcAddress = (GetProcAddressPtr)GetProcAddress(kernel32DLL, "GetProcAddress");
if(0) //FIXME 64 bit
printf("Real %p vs %p vs %p ours %p\n", &realGetProcAddress, (uint32_t)&GetProcAddress, KernelGetProcAddress(kernel32DLL, "GetProcAddress"), ourGetProcAddress);
realCreateToolhelp32Snapshot = (CreateToolhelp32SnapshotPtr)GetProcAddress(kernel32DLL, "CreateToolhelp32Snapshot");
}
//HMODULE ntoskernelexe = LoadLibrary(L"C:\\Windows\\System32\\ntoskrnl.exe");
//HMODULE ntoskernelexe = LoadLibrary(L"C:\\Windows\\WinSxS\\amd64_microsoft-windows-os-kernel_31bf3856ad364e35_10.0.15063.483_none_0119a15f1a94826b\\ntoskrnl.exe");
HMODULE ntoskernelexe = LoadLibrary(L"C:\\MinGW\\msys\\1.0\\home\\peterius\\projects\\processdumper\\Debug\\blahblah.lib");
printf("ntoskernelexe: %p\n", ntoskernelexe);
if(!kernel32DLL)
{
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"LoadLibrary ntoskernelexe failed(%s)\n", errstring);
free(errstring);
}
ZwOpenProcessPtr realNtOpenProcess;
//ZwOpenProcessPtr realNtOpenProcess = (ZwOpenProcessPtr)GetProcAddress(ntoskernelexe, "ZwOpenProcess");
if(fakentDLL)
realNtOpenProcess = (ZwOpenProcessPtr)GetProcAddress(fakentDLL, "ZwOpenProcess");
printf("zwopenprocess %p\n", realNtOpenProcess);
#endif //TESTTHIS
if(driver)
{
DWORD * allprocesses;
DWORD allprocesses_size;
//DWORD request;
//request = pid;
DWORD size;
SYSTEM_PROCESS_INFORMATION * processes;
size = 2048 * sizeof(SYSTEM_PROCESS_INFORMATION);
processes = (SYSTEM_PROCESS_INFORMATION *)calloc(size, sizeof(char));
if(driverIoCtl(IOCTL_QUERYPROCESSES, NULL, 0, (char *)processes, &size) < 0)
fprintf(stderr, "driver ioctl receive failed\n");
else
{
allprocesses = (DWORD *)malloc(10000 * sizeof(DWORD));
/*if(EnumProcesses(allprocesses, 10000 * sizeof(DWORD), &allprocesses_size) == 0)
{
fprintf(stderr, "Can't enumerate processes\n");
free(allprocesses);
allprocesses = NULL;
}
else
{
for(i = 0; i < (allprocesses_size / sizeof(DWORD)); i++)
{
if(allprocesses[i] == pid)
{
printf("But the process was there afterall...\n");
break;
}
}
if(i == (allprocesses_size / sizeof(DWORD)))
printf("Couldn't find the process even in enumeration\n");
}*/
/*printf("Fine.\n");
for(i = 0; i < size; i++)
printf("%02x%02x%02x%02x ", ((unsigned char *)processes)[i], ((unsigned char *)processes)[i + 1], ((unsigned char *)processes)[i + 2], ((unsigned char *)processes)[i + 3]);
printf("\n");*/
printf("Notes from afar %d %02x %02x %02x\n", size, ((unsigned char *)processes)[0], ((unsigned char *)processes)[1], ((unsigned char *)processes)[2]);
printf("From the kernel %p %d:\n", processes, size);
SYSTEM_PROCESS_INFORMATION * spi_instance = (SYSTEM_PROCESS_INFORMATION *)processes;
/*while(1)
{
printf("pid: %d %08x handles %d\n", spi_instance->UniqueProcessId, spi_instance->UniqueProcessId, spi_instance->HandleCount);
for(i = 0; i < (allprocesses_size / sizeof(DWORD)); i++)
{
if(allprocesses[i] == (DWORD)spi_instance->UniqueProcessId)
break;
}
if(i == (allprocesses_size / sizeof(DWORD)))
printf("Found unenumerated process: %d\n", spi_instance->UniqueProcessId);
if(spi_instance->NextEntryOffset == 0)
break;
else
spi_instance = (SYSTEM_PROCESS_INFORMATION *)((char *)spi_instance + spi_instance->NextEntryOffset);
}*/
free(allprocesses);
}
free(processes);
}
OBJECT_ATTRIBUTES oa;
CLIENT_ID cid;
SYSTEM_PROCESS_INFORMATION * spi;
SYSTEM_BASIC_INFORMATION * basic;
DWORD * allprocesses;
DWORD allprocesses_size;
DWORD spi_size;
DWORD status;
cid.UniqueProcess = (HANDLE)g_pid;
cid.UniqueThread = 0;
oa.Length = sizeof(OBJECT_ATTRIBUTES);
oa.RootDirectory = NULL;
oa.ObjectName = NULL;
oa.Attributes = 0;
oa.SecurityDescriptor = NULL;
oa.SecurityQualityOfService = NULL;
HANDLE processH = OpenProcess(PROCESS_QUERY_INFORMATION | READ_CONTROL | PROCESS_VM_READ, FALSE, g_pid);
//HANDLE processH = OpenProcess(SYNCHRONIZE, FALSE, pid);
/*HANDLE processH;
if(!realNtOpenProcess(&processH, PROCESS_QUERY_INFORMATION | READ_CONTROL, &oa, &cid))*/ /* PROCESS_TERMINATE*/
if(!processH)
{
err = GetLastError();
switch(err)
{
case ERROR_ACCESS_DENIED:
printf("ACCESS DENIED openprocess\n");
break;
case ERROR_INVALID_PARAMETER:
printf("INVALID PARAMETER openprocess\n");
allprocesses = (DWORD *)malloc(10000 * sizeof(DWORD));
if(EnumProcesses(allprocesses, 10000 * sizeof(DWORD), &allprocesses_size) == 0)
{
fprintf(stderr, "Can't enumerate processes\n");
free(allprocesses);
allprocesses = NULL;
}
else
{
for(i = 0; i < (allprocesses_size / sizeof(DWORD)); i++)
{
if(allprocesses[i] == g_pid)
{
printf("But the process was there afterall...\n");
break;
}
}
if(i == (allprocesses_size / sizeof(DWORD)))
printf("Couldn't find the process even in enumeration\n");
}
basic = (SYSTEM_BASIC_INFORMATION *)malloc(sizeof(SYSTEM_BASIC_INFORMATION));
status = AMD64_NtQuerySystemInformation(SystemBasicInformation, basic, sizeof(SYSTEM_BASIC_INFORMATION), &spi_size);
printf("STATUS: %8x %d\n", status, basic->NumberOfProcessors);
status = fakeNtQuerySystemInformation(SystemBasicInformation, basic, sizeof(SYSTEM_BASIC_INFORMATION), &spi_size);
printf("usual STATUS: %8x %d\n", status, basic->NumberOfProcessors);
free(basic);
spi = (SYSTEM_PROCESS_INFORMATION *)calloc(10000, sizeof(SYSTEM_PROCESS_INFORMATION));
status = fakeNtQuerySystemInformation(SystemProcessInformation, spi, 10000 * sizeof(SYSTEM_PROCESS_INFORMATION), &spi_size);
#define NTSTATUS_SUCCESS 0
#define NTSTATUS_OBJECT_TYPE_MISMATCH 0xc0000024
#define NTSTATUS_ACCESS_VIOLATION 0xc0000005
#define NTSTATUS_INVALID_HANDLE 0xc0000008
if(status == NTSTATUS_SUCCESS)
{
SYSTEM_PROCESS_INFORMATION * spi_instance = spi;
printf("size: %d\n", spi_size);
while(1)
{
printf("pid: %d %08x\n", spi_instance->UniqueProcessId, spi_instance->UniqueProcessId);
for(i = 0; i < sizeof(SYSTEM_PROCESS_INFORMATION); i++)
printf("%02x", ((unsigned char *)spi_instance)[i]);
printf("Exiting so as not to print all this shit out\n");
goto main_exit;
for(i = 0; i < (allprocesses_size / sizeof(DWORD)); i++)
{
if(allprocesses[i] == (DWORD)spi_instance->UniqueProcessId)
break;
}
if(i == (allprocesses_size / sizeof(DWORD)))
printf("Found unenumerated process: %d\n", spi_instance->UniqueProcessId);
if(spi_instance->NextEntryOffset == 0)
break;
}
}
else if(status == NTSTATUS_OBJECT_TYPE_MISMATCH)
{
fprintf(stderr, "DirectNtQuery object type mismatch size: %d\n", spi_size);
}
else if(status == NTSTATUS_ACCESS_VIOLATION)
{
fprintf(stderr, "DirectNtQuery access violation size: %d\n", spi_size);
}
else
{
fprintf(stderr, "DirectNtQuery failed (%u: %08x)\n", status, status);
}
free(spi);
free(allprocesses);
break;
default:
errstring = GetLastErrorString();
//5 ACCESS_DENIED
fwprintf(stderr, L"OpenProcess %d failed(%d: %s)\n", g_pid, err, errstring);
free(errstring);
break;
}
//goto main_exit;
}
#define IMAGE_PATH_LEN 500
if(produceoutput)
{
if(!CreateDirectoryA(outputdirname, NULL))
{
fprintf(stderr, "Can't create directory: %s\n", outputdirname);
CloseHandle(processH);
free(outputdirname);
return -1;
}
}
imagepath = (char *)malloc(IMAGE_PATH_LEN * 2);
len = IMAGE_PATH_LEN * 2;
if(!QueryFullProcessImageName(processH, PROCESS_NAME_NATIVE, (LPWSTR)imagepath, (PDWORD)&len))
{
errstring = GetLastErrorString();
fwprintf(stderr, L"QueryFullProcessImageName failed(%s)\n", errstring);
free(errstring);
}
//for(i = 0; i < len * 2; i++) //since it's wide characters
// printf("%c", imagepath[i]);
printf("Image path: ");
wprintf(L"%s\n", (LPWSTR)imagepath);
free(imagepath);
ListProcessThreads(g_pid);
enummodulepulldown(processH, outputdirname);
CloseHandle(processH);
if(attemptinject)
{
char * dll;
unsigned int dllsize;
HANDLE pH;
//pid = GetProcessId(GetCurrentProcess());
pH = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, g_pid);
if(!pH)
{
fprintf(stderr, "inject process OpenProcess failed (%d)\n", GetLastError());
return -1;
}
IsWow64Process(pH, &g_wow64);
attemptinject = 0;
if(!g_wow64 && load_a_file("helperlib.dll", &dll, &dllsize) < 0)
fprintf(stderr, "Failed to load %s\n", "helperlib.dll");
else if(g_wow64 && load_a_file("helperlib32.dll", &dll, &dllsize) < 0)
fprintf(stderr, "Failed to load %s\n", "helperlib32.dll");
else if(injectProcess(pH, dll, dllsize) < 0)
fprintf(stderr, "inject process failed\n");
else
attemptinject = 1; //injected
pH = NULL;
if(attemptinject)
{
#ifndef NOINJECTIONCOMM
WaitForSingleObject(sync_event, INFINITE);
#endif //!NOINJECTIONCOMM
/*struct sigaction sigIntHandler;
sigIntHandler.sa_handler = sigintcatch;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);*/
//signal(SIGINT, sigintcatch);
//while(1) {} //wait for sigint
printf("Quit and unhook or don't unhook? (u/d)\n");
int done = 0;
char c;
while(!done)
{
scanf("%c", &c);
if(c == 'u' || c == 'd')
done = 1;
}
if(c == 'u')
{
if(g_injectedbaseaddress)
{
pH = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, g_pid);
if(!pH || pH == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "uninject process OpenProcess failed (%d)\n", GetLastError());
}
else
uninjectProcess(pH);
}
}
}
}
if(reconstitute() < 0)
fprintf(stderr, "Reconstitution failed\n");
cleanup_reconstitution();
//ListProcessThreads(pid);
main_exit:
//RemoveDirectoryA(outputdirname);
free(outputdirname);
free(helperlogfilename);
//FIXME silly dll names
//if(fakentDLL)
// FreeLibrary(fakentDLL);
if(ntDLL)
FreeLibrary(ntDLL);
if(kernel32DLL)
FreeLibrary(kernel32DLL);
if(k32DLL)
FreeLibrary(k32DLL);
if(0)
cleanupLibraryLoader();
if(driver && uninstall_driver() < 0)
fprintf(stderr, "Failed to uninstall driver\n");
/*
dump_current_module(GetCurrentProcess(), "ntdll.dll");
dump_current_module(GetCurrentProcess(), "kernel32.dll");
free(outputdirname);*/
}
int filterException(int code, PEXCEPTION_POINTERS ex)
{
printf("Exception: %08x %p\n", code, ex);
return EXCEPTION_EXECUTE_HANDLER;
}
// FIXME FIXME FIXME 64
void dump_current_module(HANDLE process, char * name)
{
HANDLE m;
HMODULE h;
DWORD bytes_written;;
MODULEINFO modinfo;
char * addr, r;
//BOOL wow64;
char * outname = (char *)calloc(strlen(name) + 6, sizeof(char));
//IsWow64Process(process, &wow64);
h = GetModuleHandleA(name);
GetModuleInformation(process, h, &modinfo, sizeof(MODULEINFO));
printf("%s %08x %08x\n", name, h, modinfo.SizeOfImage);
//curent directory, does this work FIXME?
sprintf(outname, "inmem%s", name);
m = CreateFileA(outname, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
for(addr = (char *)h; addr < (char *)h + modinfo.SizeOfImage; addr += 1024)
{
if(!WriteFile(m, (char *)addr, 1024, &bytes_written, NULL))
printf("Error: %d\n", GetLastError());
//printf("Bytes Written: %d\n", bytes_written);
}
addr -= 1024;
r = (char *)h + modinfo.SizeOfImage - addr;
if(r)
WriteFile(m, (char *)addr, r, &bytes_written, NULL);
CloseHandle(m);
}
int enummodulepulldown(HANDLE processH, char * outputdirname)
{
int i;
HMODULE hMods[1024];
DWORD cbNeeded;
BOOL wow64;
int files_of_data_written = 0;
// FIXME FIXME don't we have a global for this now? same process right?
if(IsWow64Process(processH, &wow64) == 0)
{
fprintf(stderr, "IsWow64Process failed: %d\n", GetLastError());
}
if(!wow64)
printf("64 bit process !! \n");
if(EnumProcessModulesEx(processH, hMods, sizeof(hMods), &cbNeeded, LIST_MODULES_ALL))
{
/* Are these always 32 bit ?!?!? FIXME shouldn't we check the process?*/
printf("Enum %d %d\n", cbNeeded, (cbNeeded / sizeof(HMODULE)));
for(i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
{
TCHAR szModName[MAX_PATH];
MODULEINFO modinfo;
char * outname;
HANDLE outfileh;
DWORD bytes_written;
SIZE_T bytes_read;
char * addr;
DWORD remaining;
char * thebuffer;
// Get the full path to the module's file.
if(GetModuleFileNameEx(processH, hMods[i], szModName,
sizeof(szModName) / sizeof(TCHAR)))
{
// Print the module name and handle value.
//printf("\t%s (0x%08X)\n", szModName, hMods[i]);
}
else
fprintf(stderr, "Can't get Module filename %08x\n", hMods[i]);
if(GetModuleInformation(processH, hMods[i], &modinfo, sizeof(MODULEINFO)) == 0)
{
fprintf(stderr, "GetModuleInformation failed: (%d)\n", GetLastError());
continue;
}
/*if(wow64)
printf("%08x : %08x\n", hMods[i], modinfo.SizeOfImage);
else
printf("%08x%08x : %08x\n", PRINTARG64(hMods[i]), modinfo.SizeOfImage);*/
if(szModName[0] != 0x00)
{
outname = (char *)calloc(strlen((char *)szModName) + strlen(outputdirname) + 40, sizeof(char));
if(wow64)
sprintf(outname, "%s/inmem_%08x_%s", outputdirname, hMods[i], (char *)szModName);
else
sprintf(outname, "%s/inmem_%08x%08x_%s", outputdirname, PRINTARG64(hMods[i]), (char *)szModName);
}
else
{
outname = (char *)calloc(8 + strlen(outputdirname) + 40, sizeof(char));
if(wow64)
sprintf(outname, "%s/inmem_%08x.dll", outputdirname, hMods[i]);
else
sprintf(outname, "%s/inmem_%08x%08x.dll", outputdirname, PRINTARG64(hMods[i]));
}
specify_reconstitution_path(outputdirname);
thebuffer = (char *)malloc(modinfo.SizeOfImage);
if(!thebuffer)
{
fprintf(stderr, "Can't allocate read buffer\n");
goto proc_alloc_dump_fail;
}
if(produceoutput)
outfileh = CreateFileA(outname, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
/* So what... just this try/catch block foils or fixes whatever the tencent stuff is crashing on ??? */
try
{
if(produceoutput && !outfileh)
{
fprintf(stderr, "Error creating file %s: %d\n", outname, GetLastError());
}
else if(ReadProcessMemory(processH, hMods[i], thebuffer, modinfo.SizeOfImage, &bytes_read) == 0)
{
if(GetLastError() == ERROR_PARTIAL_COPY)
fprintf(stderr, "Error reading process memory: partial copy?\n");
else
fprintf(stderr, "Error reading process memory: %d\n", GetLastError());
//299 ERROR_PARTIAL_COPY
}
else if(produceoutput)
{
add_module_for_reconstitution((char *)hMods[i], thebuffer, modinfo.SizeOfImage);
for(addr = thebuffer; addr < thebuffer + modinfo.SizeOfImage; addr += 1024)
{
if(!WriteFile(outfileh, (char *)addr, 1024, &bytes_written, NULL))
{
fprintf(stderr, "Write error: %d\n", GetLastError());
CloseHandle(outfileh);
goto proc_alloc_dump_fail;
}
//printf("Bytes Written: %d\n", bytes_written);
}
addr -= 1024;
remaining = thebuffer + modinfo.SizeOfImage - addr;
if(remaining)
{
WriteFile(outfileh, (char *)addr, remaining, &bytes_written, NULL);
files_of_data_written++;
}
else if(bytes_written)
files_of_data_written++;
CloseHandle(outfileh);
}
}
catch(...)