-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathemufuncs.cpp
5254 lines (4835 loc) · 158 KB
/
emufuncs.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
/*
Source for x86 emulator IdaPro plugin
File: emufuncs.cpp
Copyright (c) 2004-2022, Chris Eagle
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 2 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, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef __NT__
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#endif
/*
#ifndef _MSC_VER
#include <windows.h>
#endif
#include <winsock2.h>
#endif
*/
#include <pro.h>
// #include <windows.h>
#include <winnt.h>
#else
#include <wctype.h>
#include "image.h"
#endif
#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#define closesocket close
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#endif
#include <ctype.h>
#include <stdint.h>
/*
#ifdef PACKED
#undef PACKED
#endif
*/
#include "x86emu_ui.h"
#include "cpu.h"
#include "context.h"
#include "emufuncs.h"
#include "emuheap.h"
#include "hooklist.h"
#include "emuthreads.h"
#include "buffer.h"
#include "peutils.h"
#include "memmgr.h"
#include "linux_syscalls.h"
#include "bsd_syscalls.h"
#include "cgc_syscalls.h"
#include "ansi_cprng.h"
#include <pro.h>
#include <kernwin.hpp>
#include <bytes.hpp>
#include <name.hpp>
#include <typeinf.hpp>
#include <segment.hpp>
#ifndef DEBUG
#define DEBUG 1
#endif
void addVectoredExceptionHandler(bool first, unsigned int handler);
void removeVectoredExceptionHandler(unsigned int handler);
#define FAKE_HANDLE_BASE 0x80000000
struct FakedImport {
unsigned int handle; //module handle the lookup was performed on
unsigned int addr; //returned fake import address
char *name; //name assigned to this function
FakedImport *next;
};
static HandleNode *moduleHead = NULL;
static FunctionInfo *functionInfoList = NULL;
static FakedImport *fakedImportList = NULL;
//static unsigned int fakedImportAddr = 1;
//stick dummy values up in kernel space to distinguish them from
//actual library handles
static unsigned int moduleHandle = FAKE_HANDLE_BASE;
//persistant module identifier
static unsigned int moduleId = 0x10000;
static unemulatedCB unemulated_cb = NULL;
typedef enum {R_FAKE = -1, R_NO = 0, R_YES = 1} Reply;
int emu_alwaysLoadLibrary = ASK;
int emu_alwaysGetModuleHandle = ASK;
unsigned int pCmdLineA;
struct negotiator {
uint32_t rx_vals[4];
uint32_t rx_ptr;
uint32_t queued_bytes;
uint32_t tx_vals[3];
uint32_t tx_ptr;
cprng_ctx prng;
bool built_response;
bool response_sent;
bool closed;
void init(unsigned char *seed, uint32_t slen);
uint32_t write(uint32_t buf, uint32_t slen, size_t *wb);
uint32_t read(uint32_t buf, uint32_t slen, size_t *rb);
};
static negotiator cgc_negotiator;
cprng_ctx prng;
bool is_cgc_pov = false;
#ifndef __NT__
#define _SOCKET int
#define closesocket close
#else
#define _SOCKET SOCKET
//unsigned int
#endif
static _SOCKET cgc_sock = SOCKET_ERROR;
//pointer to til we use to extract function info
til_t *ti = NULL;
HookEntry hookTable[] = {
{"CreateThread", emu_CreateThread},
{"VirtualAlloc", emu_VirtualAlloc},
{"VirtualFree", emu_VirtualFree},
{"VirtualProtect", emu_VirtualProtect},
{"LocalLock", emu_LocalLock},
{"LocalUnlock", emu_LocalUnlock},
{"LocalAlloc", emu_LocalAlloc},
{"LocalReAlloc", emu_LocalReAlloc},
{"LocalFree", emu_LocalFree},
{"GetProcAddress", emu_GetProcAddress},
{"GetModuleHandleA", emu_GetModuleHandleA},
{"GetModuleHandleW", emu_GetModuleHandleW},
{"FreeLibrary", emu_FreeLibrary},
{"LoadLibraryA", emu_LoadLibraryA},
{"LoadLibraryW", emu_LoadLibraryW},
{"LoadLibraryExA", emu_LoadLibraryExA},
{"LoadLibraryExW", emu_LoadLibraryExW},
{"HeapCreate", emu_HeapCreate},
{"HeapDestroy", emu_HeapDestroy},
{"GlobalAlloc", emu_GlobalAlloc},
{"GlobalFree", emu_GlobalFree},
{"GlobalLock", emu_GlobalLock},
{"HeapAlloc", emu_HeapAlloc},
{"HeapSize", emu_HeapSize},
{"RtlAllocateHeap", emu_HeapAlloc},
{"HeapFree", emu_HeapFree},
{"GetProcessHeap", emu_GetProcessHeap},
{"malloc", emu_malloc},
{"calloc", emu_calloc},
{"realloc", emu_realloc},
{"free", emu_free},
{"IsDebuggerPresent", emu_IsDebuggerPresent},
{"CheckRemoteDebuggerPresent", emu_CheckRemoteDebuggerPresent},
{"CloseHandle", emu_CloseHandle},
{"NtQuerySystemInformation", emu_NtQuerySystemInformation},
{"NtQueryInformationProcess", emu_NtQueryInformationProcess},
{"NtSetInformationThread", emu_NtSetInformationThread},
{"lstrlen", emu_lstrlen},
{"lstrcpy", emu_lstrcpy},
{"strncpy", emu_strncpy},
{"strcpy", emu_strcpy},
{"lstrcpyW", emu_lstrcpyW},
{"lstrcat", emu_lstrcat},
{"strcat", emu_strcat},
{"_wcsset", emu_wcsset},
{"_strlwr", emu_strlwr},
{"GetCurrentProcess", emu_GetCurrentProcess},
{"GetCurrentProcessId", emu_GetCurrentProcessId},
{"GetCurrentThreadId", emu_GetCurrentThreadId},
{"GetThreadContext", emu_GetThreadContext},
{"RevertToSelf", emu_RevertToSelf},
{"AreAnyAccessesGranted", emu_AreAnyAccessesGranted},
{"GetBkMode", emu_GetBkMode},
{"GdiFlush", emu_GdiFlush},
{"GetROP2", emu_GetROP2},
{"GetBkColor", emu_GetBkColor},
{"GdiGetBatchLimit", emu_GdiGetBatchLimit},
{"StrChrIW", emu_StrChrIW},
{"StrChrIA", emu_StrChrIA},
{"StrCmpIW", emu_StrCmpIW},
{"StrCmpNIW", emu_StrCmpNIW},
{"StrCmpW", emu_StrCmpW},
{"StrCmpNW", emu_StrCmpNW},
{"StrCpyW", emu_StrCpyW},
{"StrSpnA", emu_StrSpnA},
{"StrCSpnIA", emu_StrCSpnIA},
{"StrCSpnIW", emu_StrCSpnIW},
{"GetACP", emu_GetACP},
{"GetClientRect", emu_GetClientRect},
{"IsCharUpperA", emu_IsCharUpperA},
{"IsCharAlphaA", emu_IsCharAlphaA},
{"GetIconInfo", emu_GetIconInfo},
{"GetWindow", emu_GetWindow},
{"IsChild", emu_IsChild},
{"GetTopWindow", emu_GetTopWindow},
{"GetWindowContextHelpId", emu_GetWindowContextHelpId},
{"WindowFromDC", emu_WindowFromDC},
{"GetWindowPlacement", emu_GetWindowPlacement},
{"CopyIcon", emu_CopyIcon},
{"IsIconic", emu_IsIconic},
{"GetGUIThreadInfo", emu_GetGUIThreadInfo},
{"GetDC", emu_GetDC},
{"GetTitleBarInfo", emu_GetTitleBarInfo},
{"IsWindowUnicode", emu_IsWindowUnicode},
{"IsMenu", emu_IsMenu},
{"GetWindowRect", emu_GetWindowRect},
{"IsWindowVisible", emu_IsWindowVisible},
{"GetForegroundWindow", emu_GetForegroundWindow},
{"InSendMessage", emu_InSendMessage},
{"GetWindowTextA", emu_GetWindowTextA},
{"IsUserAnAdmin", emu_IsUserAnAdmin},
{"GetVersionExA", emu_GetVersionExA},
{"GetVersion", emu_GetVersion},
{"GetTickCount", emu_GetTickCount},
{"GetSystemTimeAsFileTime", emu_GetSystemTimeAsFileTime},
{"QueryPerformanceCounter", emu_QueryPerformanceCounter},
{"NtAllocateVirtualMemory", emu_NtAllocateVirtualMemory},
{"LdrLoadDll", emu_LdrLoadDll},
{"LdrGetProcedureAddress", emu_LdrGetProcedureAddress},
{"InterlockedIncrement", emu_InterlockedIncrement},
{"InterlockedDecrement", emu_InterlockedDecrement},
{"EncodePointer", emu_EncodePointer},
{"DecodePointer", emu_DecodePointer},
{"InitializeCriticalSection", emu_InitializeCriticalSection},
{"InitializeCriticalSectionAndSpinCount", emu_InitializeCriticalSectionAndSpinCount},
{"TryEnterCriticalSection", emu_TryEnterCriticalSection},
{"EnterCriticalSection", emu_EnterCriticalSection},
{"LeaveCriticalSection", emu_LeaveCriticalSection},
{"DeleteCriticalSection", emu_DeleteCriticalSection},
{"AddVectoredExceptionHandler", emu_AddVectoredExceptionHandler},
{"RemoveVectoredExceptionHandler", emu_RemoveVectoredExceptionHandler},
{"Sleep", emu_Sleep},
{"GetLastError", emu_GetLastError},
{"SetLastError", emu_SetLastError},
{"TlsAlloc", emu_TlsAlloc},
{"TlsFree", emu_TlsFree},
{"TlsGetValue", emu_TlsGetValue},
{"TlsSetValue", emu_TlsSetValue},
{"FlsAlloc", emu_FlsAlloc},
{"FlsFree", emu_TlsFree},
{"FlsGetValue", emu_TlsGetValue},
{"FlsSetValue", emu_TlsSetValue},
{"GetEnvironmentStrings", emu_GetEnvironmentStringsA},
{"GetEnvironmentStringsA", emu_GetEnvironmentStringsA},
{"GetEnvironmentStringsW", emu_GetEnvironmentStringsW},
{"FreeEnvironmentStringsA", emu_FreeEnvironmentStringsA},
{"FreeEnvironmentStringsW", emu_FreeEnvironmentStringsW},
{"GetCommandLineA", emu_GetCommandLineA},
{"GetCommandLineW", emu_GetCommandLineW},
{"GetStdHandle", emu_GetStdHandle},
{"GetStartupInfoA", emu_GetStartupInfoA},
{"GetStartupInfoW", emu_GetStartupInfoW},
{"GetCPInfo", emu_GetCPInfo},
{"WideCharToMultiByte", emu_WideCharToMultiByte},
{"MultiByteToWideChar", emu_MultiByteToWideChar},
{"GetStringTypeW", emu_GetStringTypeW},
{"GetStringTypeA", emu_GetStringTypeA},
{"LCMapStringW", emu_LCMapStringW},
{"LCMapStringA", emu_LCMapStringA},
{"GetLocaleInfoA", emu_GetLocaleInfoA},
{"GetLocaleInfoW", emu_GetLocaleInfoW},
{"GetWindowsDirectoryA", emu_GetWindowsDirectoryA},
{"GetWindowsDirectoryW", emu_GetWindowsDirectoryW},
{"GetSystemDirectoryA", emu_GetSystemDirectoryA},
{"GetSystemDirectoryW", emu_GetSystemDirectoryW},
{NULL, NULL}
};
//connect to a remote host as specified by host and port
//host may be either an ip address or a host name
_SOCKET connect_to(const char *host, short port) {
_SOCKET sock;
sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(host);
server.sin_port = qhtons(port);
//If a domain name was specified, we may not have an IP
if (server.sin_addr.s_addr == INADDR_NONE) {
hostent *he = gethostbyname(host);
if (he == NULL) {
msg(PLUGIN_NAME": Unable to resolve name: %s\n", host);
return (_SOCKET)INVALID_SOCKET;
}
server.sin_addr = *(in_addr*) he->h_addr;
}
//create the socket.
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET) {
if (connect(sock, (sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
msg(PLUGIN_NAME": Failed to connect to server.\n");
closesocket(sock);
sock = (_SOCKET)INVALID_SOCKET;
}
msg("done with connect, client: 0x%x\n", sock);
}
else {
msg(PLUGIN_NAME": Failed to create socket.\n");
}
return sock;
}
//accept from a remote host after binding to host and port
//host may be either an ip address or a host name
_SOCKET accept_from(const char *host, short port) {
_SOCKET sock;
sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(host);
server.sin_port = qhtons(port);
//If a domain name was specified, we may not have an IP
if (server.sin_addr.s_addr == INADDR_NONE) {
hostent *he = gethostbyname(host);
if (he == NULL) {
msg(PLUGIN_NAME": Unable to resolve name: %s\n", host);
return (_SOCKET)INVALID_SOCKET;
}
server.sin_addr = *(in_addr*) he->h_addr;
}
//create the socket.
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET) {
if (bind(sock, (sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
msg(PLUGIN_NAME": Failed to bind to address.\n");
closesocket(sock);
sock = (_SOCKET)INVALID_SOCKET;
}
else if (listen(sock, 5) == SOCKET_ERROR) {
msg(PLUGIN_NAME": Failed set listen on socket.\n");
closesocket(sock);
sock = (_SOCKET)INVALID_SOCKET;
}
else {
_SOCKET client;
client = accept(sock, NULL, NULL);
if (client == SOCKET_ERROR) {
closesocket(sock);
sock = (_SOCKET)INVALID_SOCKET;
}
else {
closesocket(sock);
sock = client;
}
msg("done with accept, client: 0x%x\n", sock);
}
}
else {
msg(PLUGIN_NAME": Failed to create client.\n");
}
return sock;
}
void setThreadError(unsigned int err) {
writeDword(fsBase + TEB_LAST_ERROR, err);
}
/*
* check for presence of extension, if missing add
* .dll
* module must be a malloced pointer
*/
char *checkModuleExtension(char *module) {
if (module == NULL) return NULL;
char *result = module;
char *dot = strchr(module, '.');
int len = (int)strlen(module);
if (dot == NULL) {
int newlen = len + 5;
result = (char*)realloc(module, newlen);
if (result) {
qstrncat(result, ".dll", newlen);
}
}
else {
if (dot[1] == 0) {
// single . used to indicate no extension
*dot = 0;
}
}
return result;
}
HandleNode *findModuleByName(const char *h) {
HandleNode *hl;
if (h == NULL) return NULL;
for (hl = moduleHead; hl; hl = hl->next) {
if (stricmp(h, hl->moduleName) == 0) break;
}
return hl;
}
unsigned int myGetModuleHandle(const char *modName) {
HandleNode *h = findModuleByName(modName);
if (h == NULL) return 0xFFFFFFFF;
return h->handle;
}
HandleNode *findModuleByHandle(unsigned int handle) {
HandleNode *hl;
for (hl = moduleHead; hl; hl = hl->next) {
if (hl->handle == handle) break;
if (hl->id == handle) break; //for compatibility with old handle assignment style
}
return hl;
}
//return the end address of a loaded module
//useful to deconflict in the case we loaded module headers only
//return module end address or 0xffffffff for invalid handle
unsigned int getModuleEnd(unsigned int handle) {
HandleNode *hl;
for (hl = moduleHead; hl; hl = hl->next) {
if (hl->handle == handle) break;
}
if (hl) {
unsigned int nt = handle + get_long(handle + 0x3C); //e_lfanew
return handle + get_long(nt + 0x50); //nt.OptionalHeader.SizeOfImage
}
return 0xffffffff;
}
/*
unsigned int getPEoffset(HMODULE mod) {
IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*) mod;
if (mod >= (HMODULE)FAKE_HANDLE_BASE) return 0;
if (hdr->e_magic == IMAGE_DOS_SIGNATURE) {
return hdr->e_lfanew;
}
return 0;
}
IMAGE_NT_HEADERS *getPEHeader(HMODULE mod) {
unsigned int offset = getPEoffset(mod);
if (offset == 0) return NULL;
IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS *)(offset + (char*)mod);
if (pe->Signature != IMAGE_NT_SIGNATURE) {
pe = NULL;
}
return pe;
}
*/
//find an existing faked import
FakedImport *findFakedImportByAddr(HandleNode *mod, unsigned int addr) {
FakedImport *ff = NULL;
for (ff = fakedImportList; ff; ff = ff->next) {
if (ff->handle == mod->handle && ff->addr == addr) break;
}
return ff;
}
FakedImport *findFakedImportByName(HandleNode *mod, char *procName) {
FakedImport *ff = NULL;
for (ff = fakedImportList; ff; ff = ff->next) {
if (ff->handle == mod->handle && strcmp(ff->name, procName) == 0) break;
}
return ff;
}
//add a new faked import after first searching to see if it is already present
FakedImport *addFakedImport(HandleNode *mod, char *procName) {
FakedImport *ff = findFakedImportByName(mod, procName);
if (ff) return ff;
ff = (FakedImport*)malloc(sizeof(FakedImport));
ff->next = fakedImportList;
ff->addr = mod->maxAddr++;
ff->name = _strdup(procName);
ff->handle = mod->handle;
fakedImportList = ff;
return ff;
}
/*
typedef struct _LDR_MODULE {
LIST_ENTRY InLoadOrderModuleList; +0
LIST_ENTRY InMemoryOrderModuleList; +8
LIST_ENTRY InInitializationOrderModuleList; +16
PVOID BaseAddress; +24
PVOID EntryPoint; +28
ULONG SizeOfImage; +32
UNICODE_STRING FullDllName; +36
UNICODE_STRING BaseDllName; +44
ULONG Flags; +52
SHORT LoadCount; +56
SHORT TlsIndex; +58
LIST_ENTRY HashTableEntry; +60
ULONG TimeDateStamp; +68
} LDR_MODULE, *PLDR_MODULE;
*/
/*
typedef struct _LIST_ENTRY {
struct _LIST_ENTRY *Flink;
struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY;
*/
/*
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
*/
#define PEB_LDR_DATA_SIZE 0x24
#define LDR_MODULE_SIZE 0x48
#define BASE_ADDRESS_OFFSET 24
#define BASE_NAME_OFFSET 44
unsigned int getModuleBase(unsigned int ldrModule) {
return get_long(ldrModule + BASE_ADDRESS_OFFSET);
}
void insertTail(unsigned int listHead, unsigned int mod, int doff) {
// msg("Insert tail called to add %x to %x\n", mod, listHead);
unsigned int handle = getModuleBase(mod);
unsigned int modFlink = mod + 24 - doff;
unsigned int blink = listHead;
unsigned int flink;
for (flink = get_long(listHead);
flink != listHead;
flink = get_long(flink)) {
if (get_long(flink + doff) == handle) return; //already in list
blink = flink;
}
blink = get_long(listHead + 4);
patch_long(blink, modFlink);
patch_long(modFlink, listHead); //point mod fwd to head
patch_long(modFlink + 4, blink); //point mod back to former tail
patch_long(listHead + 4, modFlink); //link back to mod
}
void insertHead(unsigned int listHead, unsigned int mod, int doff) {
// msg("Insert head called to add %x to %x\n", mod, listHead);
unsigned int handle = getModuleBase(mod);
// msg("handle is %x mod is %x\n", handle, mod);
unsigned int modFlink = mod + 24 - doff;
// msg("modFlink is %x\n", modFlink);
unsigned int flink;
// msg("listHead is %x\n", listHead);
for (flink = get_long(listHead);
flink != listHead;
flink = get_long(flink)) {
// msg("first check flink = %x\n", flink);
if (get_long(flink + doff) == handle) return; //already in list
}
flink = get_long(listHead);
/*unsigned int back =*/ get_long(flink + 4);
patch_long(flink + 4, modFlink);
patch_long(modFlink + 4, listHead); //point mod back to head
patch_long(modFlink, flink); //point mod fwd to former head
patch_long(listHead, modFlink); //link fwd to mod
}
void insertInOrder(unsigned int listHead, unsigned int mod, int doff) {
// msg("Insert in order called to add %x to %x\n", mod, listHead);
unsigned int handle = getModuleBase(mod);
unsigned int modFlink = mod + 24 - doff;
unsigned int blink = listHead;
unsigned int flink;
for (flink = get_long(listHead);
flink != listHead;
flink = get_long(flink)) {
unsigned int modBase = get_long(flink + doff);
if (modBase == handle) return; //already in list
if (modBase > handle) break; //insert before this
blink = flink;
}
//insert prior to flink
blink = get_long(flink + 4);
patch_long(blink, modFlink);
patch_long(modFlink, flink); //point mod back to head
patch_long(modFlink + 4, blink); //point mod fwd to former head
patch_long(flink + 4, modFlink); //link fwd to mod
}
bool containsModule(unsigned int listHead, unsigned int mod, int doff) {
for (unsigned int flink = get_long(listHead);
flink != listHead;
flink = get_long(flink)) {
if (get_long(flink + doff) == mod) return true; //already in list
}
return false;
}
bool cmp_c_to_dbuni(char *cstr, unsigned int uni) {
unsigned int ustr = get_long(uni + 4);
if (ustr) {
do {
char ch = *cstr++;
short s = get_word(ustr);
if (s != ch) break;
if (!ch) return true;
ustr += 2;
} while (1);
}
return false;
}
unsigned int allocateUnicodeString(const char *str) {
int len = (int)strlen(str);
unsigned int ustr = HeapBase::getHeap()->malloc(len * 2 + 2);
unsigned int uni = HeapBase::getHeap()->malloc(8); //sizeof(UNICODE_STRING)
patch_word(uni, len * 2);
patch_word(uni + 2, len * 2 + 2);
patch_long(uni + 4, ustr);
for (int i = 0; i <= len; i++) {
patch_word(ustr, *str++);
ustr += 2;
}
return uni;
}
unsigned int findPebModuleByName(char *name) {
segment_t *s = get_segm_by_name(".peb");
if (s) {
unsigned int peb = (unsigned int)s->startEA;
unsigned int pebLdr = get_long(peb + 0xC);
unsigned int list = pebLdr + 0xC;
unsigned int blink = list;
unsigned int flink;
for (flink = get_long(list);
flink != list;
flink = get_long(flink)) {
if (cmp_c_to_dbuni(name, flink + BASE_NAME_OFFSET) == 0) {
return get_long(flink + BASE_ADDRESS_OFFSET);
}
blink = flink;
}
}
return (unsigned int)BADADDR;
}
void addModuleToPeb(unsigned int handle, const char *name, bool loading) {
segment_t *s = get_segm_by_name(".peb");
if (s) {
// msg("adding %s (%x) to PEB\n", name, handle);
unsigned int peb = (unsigned int)s->startEA;
unsigned int pebLdr = get_long(peb + 0xC);
unsigned int uni = allocateUnicodeString(name);
// msg("mod name allocated at %x\n", uni);
//mod is the address of the LDR_MODULE that we are allocating
unsigned int mod = HeapBase::getHeap()->malloc(LDR_MODULE_SIZE);
unsigned int pe = handle + get_long(handle + 0x3C);
// msg("mod allocated at %x\n", mod);
patch_long(mod + BASE_ADDRESS_OFFSET, handle); //BaseAddress
patch_long(mod + BASE_ADDRESS_OFFSET + 4, handle + get_long(pe + 0x28)); //EntryPoint
patch_long(mod + BASE_ADDRESS_OFFSET + 8, get_long(pe + 0x50)); //SizeOfImage
// patch_long(mod + 36, 0); //FullDllName
patch_long(mod + 44, get_long(uni)); //BaseDllName
patch_long(mod + 48, get_long(uni + 4)); //BaseDllName
// patch_long(mod + 52, 0); //Flags
patch_long(mod + 56, 1); //LoadCount
// patch_long(mod + 58, 0); //TlsIndex
// patch_long(mod + 60, 0); //HashTableEntry
// patch_long(mod + 68, 0); //TimeDateStamp
unsigned int loadOrder = pebLdr + 0xC;
// msg("addModuleToPeb containsModule\n");
if (containsModule(loadOrder, handle, 24)) return;
// msg("addModuleToPeb containsModule complete\n");
unsigned int memoryOrder = pebLdr + 0x14;
unsigned int initOrder = pebLdr + 0x1C;
if (loading) {
insertHead(initOrder, mod, 8);
}
else {
// msg("addModuleToPeb insertTail, initOrder\n");
insertTail(initOrder, mod, 8);
}
// msg("addModuleToPeb insertTail, loadOrder\n");
insertTail(loadOrder, mod, 24);
// msg("addModuleToPeb insertTail, memoryOrder\n");
insertInOrder(memoryOrder, mod, 16);
msg("module added %s (%x) to PEB\n", name, handle);
}
}
void addModuleToPeb(HandleNode *hn, bool loading, unsigned int uni) {
segment_t *s = get_segm_by_name(".peb");
if (s) {
// msg("adding %s (%x) to PEB\n", hn->moduleName, hn->handle);
unsigned int peb = (unsigned int)s->startEA;
unsigned int pebLdr = get_long(peb + 0xC);
if (uni == 0) {
uni = allocateUnicodeString(hn->moduleName);
}
// msg("mod name allocated at %x\n", uni);
//mod is the address of the LDR_MODULE that we are allocating
unsigned int mod = HeapBase::getHeap()->malloc(LDR_MODULE_SIZE);
unsigned int pe = hn->handle + get_long(hn->handle + 0x3C);
// msg("mod allocated at %x\n", mod);
patch_long(mod + BASE_ADDRESS_OFFSET, hn->handle); //BaseAddress
patch_long(mod + BASE_ADDRESS_OFFSET + 4, hn->handle + get_long(pe + 0x28)); //EntryPoint
patch_long(mod + BASE_ADDRESS_OFFSET + 8, get_long(pe + 0x50)); //SizeOfImage
// patch_long(mod + 36, 0); //FullDllName
patch_long(mod + 44, get_long(uni)); //BaseDllName
patch_long(mod + 48, get_long(uni + 4)); //BaseDllName
// patch_long(mod + 52, 0); //Flags
patch_long(mod + 56, 1); //LoadCount
// patch_long(mod + 58, 0); //TlsIndex
// patch_long(mod + 60, 0); //HashTableEntry
// patch_long(mod + 68, 0); //TimeDateStamp
unsigned int loadOrder = pebLdr + 0xC;
// msg("addModuleToPeb containsModule\n");
if (containsModule(loadOrder, hn->handle, 24)) return;
// msg("addModuleToPeb containsModule complete\n");
unsigned int memoryOrder = pebLdr + 0x14;
unsigned int initOrder = pebLdr + 0x1C;
if (loading) {
insertHead(initOrder, mod, 8);
}
else {
// msg("addModuleToPeb insertTail, initOrder\n");
insertTail(initOrder, mod, 8);
}
// msg("addModuleToPeb insertTail, loadOrder\n");
insertTail(loadOrder, mod, 24);
// msg("addModuleToPeb insertTail, memoryOrder\n");
insertInOrder(memoryOrder, mod, 16);
msg("module added %s (%x) to PEB\n", hn->moduleName, hn->handle);
}
}
static void saveString(int which, char *str) {
#ifdef __IDP__
//only do something if we are in a plugin
x86emu_node.supset(which, str);
#endif
}
static int loadString(int which, char *dir, int len) {
#ifdef __IDP__
//only do something if we are in a plugin
if (len) {
*dir = 0;
}
return (int)x86emu_node.supstr(which, dir, len);
#else
return -1;
#endif
}
static void saveDllDir(char *dir) {
saveString(SYS_DLL_DIR, dir);
}
static int getSavedDllDir(char *dir, int len) {
//only do something if we are in a plugin
return loadString(SYS_DLL_DIR, dir, len);
}
static void savelastDir(char *dir) {
saveString(LAST_DIR, dir);
}
static int getLastDir(char *dir, int len) {
//only do something if we are in a plugin
return loadString(LAST_DIR, dir, len);
}
#ifndef __NT__
#define GetSystemWow64Directory GetSystemDirectory
int GetSystemDirectory(char *dir, int size) {
static char dllDir[512];
if (dllDir[0] == 0) {
char *dir = getDirectoryName("Choose System DLL Directory", dllDir, sizeof(dllDir));
if (dir == NULL) {
dllDir[0] = 0;
}
}
int len = (int)strlen(dllDir);
::qstrncpy(dir, dllDir, size);
return len;
}
#endif
int getSystemDllDirectory(char *dir, int size) {
int len = getSavedDllDir(dir, size);
if (len == -1) {
len = GetSystemWow64Directory(dir, size); //IDA 7.0 and later are 64 bit so we need to look for 32-bit libraries
if (len == 0) {
len = GetSystemDirectory(dir, size);
}
if (len > 0) {
saveDllDir(dir);
}
}
#ifdef DEBUG
msg(PLUGIN_NAME": setting system dll directory to %s\n", dir);
#endif
return len;
}
unsigned int getHandle(HandleNode *m) {
return m->handle;
}
unsigned int getId(HandleNode *m) {
return m->id;
}
HandleNode *addNewModuleNode(const char *mod, unsigned int h, unsigned int id) {
HandleNode *m = (HandleNode*) calloc(1, sizeof(HandleNode));
m->next = moduleHead;
moduleHead = m;
m->moduleName = _strdup(mod);
m->handle = (unsigned int) h;
if (h & FAKE_HANDLE_BASE) {
//faked module with no loaded export table
m->maxAddr = h + 1;
}
else { //good module load
m->id = id ? id : moduleId;
moduleId += 0x10000;
unsigned int pe_addr = m->handle + get_long(0x3C + m->handle); //dos.e_lfanew
m->maxAddr = m->handle + get_long(pe_addr + 0x18 + 0x38); //nt.OptionalHeader.SizeOfImage
unsigned int export_dir = m->handle + get_long(pe_addr + 0x18 + 0x60 + 0x0); //export dir RVA
m->ordinal_base = get_long(export_dir + 0x10); //ed.Base
m->NoF = get_long(export_dir + 0x14); //ed.NumberOfFunctions
m->NoN = get_long(export_dir + 0x18); //ed.NumberOfNames
m->eat = m->handle + get_long(export_dir + 0x1C); //ed.AddressOfFunctions;
m->ent = m->handle + get_long(export_dir + 0x20); //ed.AddressOfNames;
m->eot = m->handle + get_long(export_dir + 0x24); //ed.AddressOfNameOrdinals;
msg("module %s (0x%x-0x%x)\n", mod, h, m->maxAddr);
}
return m;
}
HandleNode *addModule(const char *mod, bool loading, int id, bool addToPeb) {
msg("x86emu: addModule called for %s\n", mod);
HandleNode *m = findModuleByName(mod);
if (m == NULL) {
unsigned int h = 0;
unsigned int len;
char module_name[260];
if ((id & FAKE_HANDLE_BASE) != 0) {
h = id;
}
if (h == 0) {
len = getSystemDllDirectory(module_name, sizeof(module_name));
module_name[len++] = DIR_SEP;
module_name[len] = 0;
::qstrncat(module_name, mod, sizeof(module_name));
FILE *f = fopen(module_name, "rb");
if (f == NULL) { //try it in lower case
for (int i = len; module_name[i]; i++) {
module_name[i] = tolower(module_name[i]);
}
f = fopen(module_name, "rb");
}
if (f == NULL) {
int load = R_YES;
load = askbuttons_c("Yes", "No", "Fake it", 1, "Could not locate %s. Locate it now?", mod);
if (load == R_YES) {
char title[128];
char lastDir[260];
getLastDir(lastDir, sizeof(lastDir));
::qstrncpy(module_name, mod, sizeof(module_name));
#ifndef __QT__
const char *filter = "All (*.*)\0*.*\0";
#else
const char *filter = "All (*.*)";
#endif
::qsnprintf(title, sizeof(title), "Open %s", mod);
char *fname = getOpenFileName(title, module_name, sizeof(module_name), filter, lastDir);
if (fname) {
f = fopen(fname, "rb");
char *end = strrchr(module_name, DIR_SEP);
if (end) {
*end = 0;
savelastDir(module_name);
#ifdef DEBUG
msg(PLUGIN_NAME": saved directory %s\n", module_name);
#endif
}
}
else {
//change to no or fake it option at this point?
}
}
}
if (f) {
h = loadIntoIdb(f);
if (h == 0xFFFFFFFF) {
// msg("loadIntoIdb failed\n");
h = 0;
}
fclose(f);
}
if (h == 0) {
warning("Failure loading %s, faking it.", mod);
h = FAKE_HANDLE_BASE + moduleId;
moduleId += 0x10000;
}
}
m = addNewModuleNode(mod, h, id);
if (h && addToPeb) {
addModuleToPeb(h, mod, loading);
}
}
// msg("addModule returning for %s\n", mod);
return m;
}
void freeModuleList() {
for (HandleNode *p = moduleHead; p; moduleHead = p) {
p = p->next;
free(moduleHead->moduleName);
free(moduleHead);
}
for (FakedImport *f = fakedImportList; f; fakedImportList = f) {