/
CDynPatcher.cpp
1335 lines (1184 loc) · 34.4 KB
/
CDynPatcher.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
//#include <stdafx.h>
#ifdef _WIN32
#include <SDKDDKVer.h>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winnt.h>
#pragma pack(push, 1)
struct FuncHook2_s
{
unsigned char _jmp; //e9
int addr;
};
#pragma pack(pop)
#else
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <dlfcn.h>
#include <elf.h>
#ifndef PAGESIZE
#define PAGESIZE 4096
#endif
#pragma push()
#pragma pack(1)
struct FuncHook2_s {
unsigned char _jmp; //e9
int addr;
};
#pragma pop()
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#ifndef _WIN32
#define MAX_PATH FILENAME_MAX
#include <tier1/strtools.h>
#endif
#include "CDynPatcher.h"
#include "CSectionData.h"
CDynPatcher::CDynPatcher() :DllHandler(0), DllBase(0), bSelfLoaded(false), szLibName(0)
{
HookData.clear();
szLibName=0;
}
CDynPatcher::~CDynPatcher()
{
CloseLib();
}
void CDynPatcher::Error(const char *File, const char *Func, int Line, bool IsCritical, char *Fmt, ...)
{
static char Buff[0x1000];
int len=0;
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher] %serror",IsCritical?"critical":"");
if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300)
{
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line);
}
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":");
va_list marker;
if(!Fmt)
{
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n");
}
else
{
va_start( marker, Fmt );
len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker );
}
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n");
printf("%s",Buff);
if(IsCritical)
{
#ifdef WIN32
__asm{int 3};
if(!IsDebuggerPresent())
{
exit(0);
}
#else
exit(0);
#endif
}
}
void CDynPatcher::Message(const char *File, const char *Func, int Line, char *Fmt, ...)
{
static char Buff[0x1000];
int len=0;
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher]");
if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300)
{
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line);
}
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":");
va_list marker;
if(!Fmt)
{
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n");
}
else
{
va_start( marker, Fmt );
len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker );
}
len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n");
printf("%s",Buff);
}
bool CDynPatcher::Init(const char *LibName,bool ForceLoad)
{
if (!LibName)
{
szLibName = "<<===NO LIBRARY NAME===>>";
return false;
}
if(!LoadLib(LibName,ForceLoad))
{
DynErr(false,"Unable to load \"%s\"",LibName);
return false;
}
#ifdef WIN32
if(!ParseGenericDllData_PE())
{
DynErr(false,"Failed to parse \"%s\"",szLibName);
return false;
}
DynMsg("\"%s\" parsed",szLibName);
#else
FILE *fl = fopen(szLibName, "rb");
int LibSize;
void* LibBuf;
if (fl == NULL)
{
DynErr(false,"Failed to open '%s' for read\n", szLibName);
return false;
}
fseek(fl, 0, SEEK_END);
LibSize = ftell(fl);
fseek(fl, 0, SEEK_SET);
if (LibSize < 0)
LibSize = 0;
LibBuf = malloc(LibSize + 4);
fread(LibBuf, 1, LibSize, fl);
fclose(fl);
if(!ParseGenericDllData_ELF(LibBuf, LibSize))
{
DynErr(false,"Failed to parse \"%s\"",szLibName);
return false;
}
#endif
return true;
}
bool CDynPatcher::Init(const wchar_t *LibName, bool ForceLoad /*= false*/)
{
return 0;
static char UTF8LibName[MAX_PATH];
//Q_UnicodeToUTF8(LibName, UTF8LibName, MAX_PATH-1);
return Init(UTF8LibName, ForceLoad);
}
bool CDynPatcher::Init(void *FuncAddr)
{
char szTmpName[400];
sprintf(szTmpName, "Unk_load_by_func_addr_%p", FuncAddr);
szLibName = new char[strlen(szTmpName) + 1];
strcpy(szLibName, szTmpName);
bSelfLoaded = false;
#ifdef _WIN32
MEMORY_BASIC_INFORMATION mem;
VirtualQuery(FuncAddr, &mem, sizeof(mem));
szTmpName[0] = 0;
GetModuleFileNameA(reinterpret_cast<HMODULE>(mem.AllocationBase ), szTmpName, sizeof(szTmpName) - 1);
if (szTmpName[0] != 0)
{
delete[]szLibName;
szLibName = new char[strlen(CSectionData::GetFileName(szTmpName)) + 1];
strcpy(szLibName, CSectionData::GetFileName(szTmpName));
}
IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER*)mem.AllocationBase;
IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS*)((unsigned long)dos + (unsigned long)dos->e_lfanew);
if (pe->Signature == IMAGE_NT_SIGNATURE)
{
this->DllHandler = mem.AllocationBase;
if (!ParseGenericDllData_PE())
{
DynErr(false, "Failed to parse \"%s\"", szLibName);
return false;
}
DynMsg("\"%s\" parsed",szLibName);
}
#else
Dl_info info;
if (dladdr(FuncAddr, &info) && info.dli_fbase &&info.dli_fname)
{
delete [] szLibName;
szLibName = new char[strlen(info.dli_fname) + 1];
strcpy(szLibName, info.dli_fname);
bool ParseOK=false;
size_t LoadLibSize=0;
DllBase = info.dli_fbase;
LoadLibSize = (size_t)GetBaseLen(DllBase);
DllHandler = dlopen(info.dli_fname, RTLD_NOW);
dlclose(DllHandler);
DynMsg("Found library \"%s\" at addr %p. Base=%p, size=%x, handler=%p",szLibName,FuncAddr,DllBase,LoadLibSize,DllHandler);
FILE *fl = fopen(szLibName, "rb");
int LibSize;
void* LibBuf;
if (fl)
{
fseek(fl, 0, SEEK_END);
LibSize = ftell(fl);
fseek(fl, 0, SEEK_SET);
DynMsg("Reading \"%s\" as file. Size=%x",szLibName,LibSize);
if (LibSize < 0)
LibSize = 0;
LibBuf = malloc(LibSize + 4);
fread(LibBuf, 1, LibSize, fl);
fclose(fl);
ParseOK=ParseGenericDllData_ELF(LibBuf, LibSize);
free(LibBuf);
}
else
{
DynMsg("Unable to read \"%s\" as file. Trying to use information from Dl_info.",szLibName);
ParseOK=ParseGenericDllData_ELF(DllBase, LoadLibSize);
}
if (!ParseOK)
{
DynErr(false, "Failed to parse \"%s\"", szLibName);
return false;
}
}
#endif
else
{
DynErr(false, "Failed find library at %p",FuncAddr);
return false;
}
return true;
}
#ifdef WIN32
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
bool CDynPatcher::ParseGenericDllData_PE()
{
if(!this->DllHandler)
return false;
DynMsg(("Base addr=%p\n"), this->DllHandler);
int i = 0;
PIMAGE_DOS_HEADER dosHeader = reinterpret_cast<PIMAGE_DOS_HEADER>( this->DllHandler);
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
DynErr(false,"Invalid dos header signature");
return false;
}
PIMAGE_NT_HEADERS NTHeaders = (PIMAGE_NT_HEADERS) ((size_t)this->DllHandler + dosHeader->e_lfanew);
if (NTHeaders->Signature != 0x4550)
{
DynErr(false,"Invalid NT Headers signature");
return false;
}
PIMAGE_OPTIONAL_HEADER opt = &NTHeaders->OptionalHeader;
PIMAGE_SECTION_HEADER cSection = (PIMAGE_SECTION_HEADER) ((size_t)(&NTHeaders->OptionalHeader) + NTHeaders->FileHeader.SizeOfOptionalHeader);
PIMAGE_SECTION_HEADER CodeSection = NULL;
char SectionName[IMAGE_SIZEOF_SHORT_NAME + 1];
for (i = 0; i < NTHeaders->FileHeader.NumberOfSections; i++, cSection++)
{
memcpy(&SectionName, cSection->Name, IMAGE_SIZEOF_SHORT_NAME);
SectionName[IMAGE_SIZEOF_SHORT_NAME] = 0;
DynMsg(("Section: \"%s\": "), SectionName);
if (cSection->VirtualAddress == NTHeaders->OptionalHeader.BaseOfCode)
{
DynMsg("(%p-%p) (%p-%p) ", vtr(cSection->VirtualAddress), reinterpret_cast<DWORD>(vtr(cSection->VirtualAddress)) + cSection->SizeOfRawData, vtr(cSection->VirtualAddress), reinterpret_cast<DWORD>(vtr(cSection->VirtualAddress)) + cSection->Misc.VirtualSize);
CodeSection = cSection;
}
if (cSection->VirtualAddress >= NTHeaders->OptionalHeader.BaseOfData)
{
DynMsg("(%p-%p) (%p-%p) ", vtr(cSection->VirtualAddress), reinterpret_cast<DWORD>(vtr(cSection->VirtualAddress)) + cSection->SizeOfRawData, vtr(cSection->VirtualAddress), reinterpret_cast<DWORD>(vtr(cSection->VirtualAddress)) + cSection->Misc.VirtualSize);
rdata.Add((uint32_t)this->DllHandler + cSection->VirtualAddress,cSection->SizeOfRawData,this);
vdata.Add((uint32_t)this->DllHandler + cSection->VirtualAddress,cSection->Misc.VirtualSize,this);
}
DynMsg(("\n"));
}
if (CodeSection == NULL)
{
DynErr(false,"Code section not found");
return false;
}
if (!rdata.IsValid())
{
DynErr(false,"RData sections not found", __FUNCTION__);
return false;
}
if (!vdata.IsValid())
{
DynErr(false,"VData sections not found", __FUNCTION__);
return false;
}
this->code.Add((uint32_t)this->DllHandler + CodeSection->VirtualAddress,CodeSection->Misc.VirtualSize,this);
rdata.Sort();
vdata.Sort();
#ifdef PARSE_IMPORT_EXPORT
if (NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size)
{
Msg(_T("IMAGE_DIRECTORY_ENTRY_IMPORT exist\n"));
}
if (NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size)
{
Msg(_T("IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT exist\n"));
}
if (NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size)
{
Msg(_T("IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT exist\n"));
}
CImportTable *ImpTab;
PIMAGE_IMPORT_DESCRIPTOR pImportDescriptor;
if(NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size != 0)/*if size of the table is 0 - Import Table does not exist */
{
pImportDescriptor = vtrt<PIMAGE_IMPORT_DESCRIPTOR>(NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
while(pImportDescriptor->Name)
{
ImpTab=new CImportTable;
if(ImpTab->ParseImportTable(DllHandler,pImportDescriptor, &rdata))
{
ImportData.push_back(ImpTab);
}
else
{
delete ImpTab;
}
pImportDescriptor++;
}
}
//#error http://www.deltann.ru/10/d-112007/p-169
/*
typedef struct _IMAGE_EXPORT_DIRECTORY {
DWORD Characteristics; //0x00
DWORD TimeDateStamp; //0x4
WORD MajorVersion; //0x8
WORD MinorVersion; //0xA
DWORD Name; //0xC nameRVA
DWORD Base; //0x10 ordinalBASE
DWORD NumberOfFunctions; //0x14 addressTableEntries
DWORD NumberOfNames; //0x18 numberOfNamePointers
DWORD AddressOfFunctions; //0x1C exportAddressTableRVA
DWORD AddressOfNames; //0x20 namePointerRVA
DWORD AddressOfNameOrdinals;//0x24 ordinalTableRVA
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;
*/
PIMAGE_EXPORT_DIRECTORY pExportDir;
char *name;
uint32_t f_index,f_address,ordinal ;
char *pForward;
//DebuggerBreak();
ExportData_t *ExpData;
uint32_t pAddr;
if(NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
{
pExportDir=vtrt<PIMAGE_EXPORT_DIRECTORY>(NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
for(uint32_t i=0;i<max(pExportDir->NumberOfFunctions,pExportDir->NumberOfNames);i++)
{
if (i < pExportDir->NumberOfNames)
{
name = vtrt<char*>(reinterpret_cast<uint32_t*>(vtrt<uint32_t*>(pExportDir->AddressOfNames)[i]));
f_index = vtrt<uint16_t*>(pExportDir->AddressOfNameOrdinals)[i];
}
else
{
name = "n/a"; f_index = i;
}
pAddr = static_cast<uint32_t>(vtrt<uint32_t*>(pExportDir->AddressOfFunctions)[f_index]);
//f_address = (uint32_t)vtr(vtrt<uint32_t*>(pExportDir->AddressOfFunctions)[f_index]);
f_address = (uint32_t)vtr(pAddr);
// ïîèñê "ðàçðûâîâ" â òàáëèöå àäðåñîâ
if (f_address == reinterpret_cast<uint32_t>(this->DllHandler))
{
// Msg("Hole! (i=%i)\n",i);
continue;
}
ordinal = f_index + pExportDir->Base;
if ((f_address > (uint32_t) pExportDir) && (f_address < (uint32_t) ((uint32_t) pExportDir + (uint32_t) NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)))
{
pForward = ( char *)f_address;
}
else
{
pForward = 0;
}
// Msg("%-30s [%03d/%03d] %08Xh %s \n",name, ordinal, i, f_address, (pForward)?pForward:"");
/*
ExpData = new ExportData_t;
ExpData->FuncName = name;
ExpData->FuncAddr = f_address;
ExpData->pVFuncAddr = pAddr;
ExportData.push_back(ExpData);
*/
}
}
#endif
this->DllBase = this->DllHandler;
this->DllSize = opt->SizeOfImage;
return true;
}
#else
bool CDynPatcher::ParseGenericDllData_ELF(void* FileData, uint32_t FileSize)
{
if(!this->DllBase)
{
DynErr(false,"DllBase not set");
return false;
}
if (FileSize < sizeof(Elf32_Ehdr))
{
DynErr(false,"bad library file (header)");
return false;
}
Elf32_Ehdr* ehdr = (Elf32_Ehdr*) FileData;
if (ehdr->e_ident[0] != 0x7F ||
ehdr->e_ident[1] != 'E' ||
ehdr->e_ident[2] != 'L' ||
ehdr->e_ident[3] != 'F') {
DynErr(false,"ELF Signature mismatch (got %.2X %.2X %.2X %.2X)\n", ehdr->e_ident[0], ehdr->e_ident[1], ehdr->e_ident[2], ehdr->e_ident[3]);
return false;
}
int i;
if (sizeof(Elf32_Phdr) > ehdr->e_phentsize)
return false;
if (sizeof(Elf32_Shdr) > ehdr->e_shentsize)
return false;
if (FileSize < (ehdr->e_phoff + ehdr->e_phentsize * ehdr->e_phnum)) {
DynErr(false,"bad library file (program headers)");
return false;
}
if (FileSize < (ehdr->e_shoff + ehdr->e_shentsize * ehdr->e_shnum)) {
DynErr(false,"bad library file (section headers)");
return false;
}
Elf32_Phdr* cpHdr = (Elf32_Phdr*)((size_t)FileData + ehdr->e_phoff);
for (i = 0; i < ehdr->e_phnum; i++)
{
rdata.Add((uint32_t)this->DllBase + cpHdr->p_vaddr,cpHdr->p_filesz,this);
vdata.Add((uint32_t)this->DllBase + cpHdr->p_vaddr,cpHdr->p_memsz,this);
cpHdr = (Elf32_Phdr*)((size_t)cpHdr + ehdr->e_phentsize);
}
//ALERT(at_logged, "[DPROTO]: %s: e_shstrndx = 0x%.8X; e_shoff=0x%.8X;\n", __FUNCTION__, ehdr->e_shstrndx, ehdr->e_shoff);
uint32_t StringSectionHdrOff = ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
if (FileSize < (StringSectionHdrOff + ehdr->e_shentsize)) {
DynErr(false,"bad library file (string section not found)");
return false;
}
Elf32_Shdr* shstrHdr = (Elf32_Shdr*) ((size_t)FileData + StringSectionHdrOff);
char* StringTable = (char*) ((size_t)FileData + shstrHdr->sh_offset);
this->GlobalsBase = 0;
Elf32_Shdr* csHdr = (Elf32_Shdr*)((size_t)FileData + ehdr->e_shoff);
for (i = 0; i < ehdr->e_shnum; i++)
{
const char* sname = StringTable + csHdr->sh_name;
//DynMsg("Seg[%d].name = 0x%.8X\n", i, csHdr->sh_name);
//DynMsg("Seg[%d].name = '%s'\n", i, sname);
if (!strcmp(sname, ".got"))
{
this->GlobalsBase = (uint32_t)this->DllBase + csHdr->sh_addr;
sect_got.Add((uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,this);
//DynMsg("Seg[%d].name = 0x%.8X\n", i, csHdr->sh_name);
DynMsg("Seg[%d].name = '%s' 0x%x 0x%x val=%i\n", i, sname,(uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,sect_got.IsValid());
}
else if (!strcmp(sname, ".text"))
{
code.Add((uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,this);
DynMsg("Seg[%d].name = '%s' 0x%x 0x%x val=%i\n", i, sname,(uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,code.IsValid());
}
else if (!strcmp(sname, ".plt"))
{
sect_plt.Add((uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,this);
DynMsg("Seg[%d].name = '%s' 0x%x 0x%x val=%i \n", i, sname,(uint32_t)this->DllBase + csHdr->sh_addr,csHdr->sh_size,sect_plt.IsValid());
}
csHdr = (Elf32_Shdr*)((size_t)csHdr + ehdr->e_shentsize);
}
if (GlobalsBase == 0)
{
DynErr(false,"bad library file (.got section not found)");
return false;
}
if (!code.IsValid())
{
DynErr(false,"bad library file (.text section not found)");
return false;
}
if (!sect_plt.IsValid())
{
DynErr(false,"bad library file (.plt section not found)");
return false;
}
DllSize=FileSize;
return true;
}
//char MBuffer[32768];
void* CDynPatcher::LocateLib(const char* libname)
{
char fname[128];
char linebuf[512];
char clib[256];
const char *clp;
FILE *fl;
int sl;
void* RegStart;
void* RegEnd;
Dl_info dli;
sprintf(fname, "/proc/%d/maps", getpid());
fl = fopen(fname, "r");
if (fl == NULL)
{
return NULL;
}
//setbuffer(fl, MBuffer, sizeof(MBuffer));
while (fgets(linebuf, sizeof(linebuf), fl))
{
sl = sscanf(linebuf, "%x-%x %s %s %s %s %s", &RegStart, &RegEnd, fname, fname, fname, fname, clib);
if (sl != 7)
{
continue;
}
if (dladdr(RegStart, &dli) == 0)
{
continue;
}
clp = CSectionData::GetFileName(dli.dli_fname);
if (strcmp(libname, clp) == 0)
{
fclose(fl);
return dli.dli_fbase;
}
}
fclose(fl);
return NULL;
}
uint32_t CDynPatcher::GetBaseLen(void *baseAddress)
{
pid_t pid = getpid();
char file[255];
char buffer[2048];
snprintf(file, sizeof(file)-1, "/proc/%d/maps", pid);
FILE *fp = fopen(file, "rt");
if (fp)
{
long length = 0;
void *start = NULL;
void *end = NULL;
while (!feof(fp))
{
if (fgets(buffer, sizeof(buffer) - 1, fp) == NULL)
return 0;
sscanf(buffer, "%lx-%lx", reinterpret_cast<long unsigned int *> (&start), reinterpret_cast<long unsigned int *> (&end));
if (start == baseAddress)
{
length = (unsigned long)end - (unsigned long)start;
char ignore[100];
int value;
while (!feof(fp))
{
if (fgets(buffer, sizeof(buffer) - 1, fp) == NULL)
return 0;
sscanf
(
buffer,
"%lx-%lx %*s %*s %*s %d",
reinterpret_cast<long unsigned int *> (&start),
reinterpret_cast<long unsigned int *> (&end),
&value
);
if (!value)
{
break;
}
else
{
length += (unsigned long)end - (unsigned long)start;
}
}
break;
}
}
fclose(fp);
return length;
}
return 0;
}
bool CDynPatcher::MProtect_Ex(void *addr, int npages)
{
void *paddr;
paddr = (void *)(((size_t)addr) & ~(PAGESIZE - 1));
return !mprotect(paddr, PAGESIZE*(npages + 1), PROT_READ | PROT_WRITE | PROT_EXEC);
}
#endif
bool CDynPatcher::LoadLib(const char *LibName, bool ForceLoad)
{
if(!LibName)
return false;
DynMsg("Loading library:%s%s",LibName,ForceLoad?" (Force)":"");
if(DllHandler)
{
DynErr(false,"Library \"%s\" already loaded",szLibName);
return false;
}
szLibName = new char[strlen(LibName) + 1];
//#ifdef _WIN32
strcpy(szLibName, LibName);
#ifdef LINUX
int Len=strlen(LibName) + 1;
V_StripExtension(LibName,szLibName,Len);
V_SetExtension( szLibName, ".so", Len);
#endif
const char *LibFileName = CSectionData::GetFileName(szLibName);
DynMsg("LibName=\"%s\"; LibFileName=\"%s\"",szLibName,LibFileName);
#ifdef _WIN32
DllHandler=GetModuleHandleA(LibFileName);
//DynMsg("GetModuleHandleA(%s)=0x%p",LibFileName,DllHandler);
if(DllHandler)
{
bSelfLoaded=false;
return true;
}
else if(ForceLoad)
{
//DynMsg("Force loading!");
DllHandler=LoadLibraryA(szLibName);
//DynMsg("LoadLibraryA(%s)=0x%p",LibName,DllHandler);
if(DllHandler)
{
bSelfLoaded=true;
return true;
}
}
#else
DllBase=LocateLib(LibFileName);
DynMsg("LocateLib(%s)=0x%p",LibFileName,DllBase);
if(DllBase)
{
DllHandler=dlopen(szLibName,RTLD_NOW);
DynMsg("dlopen(%s)=0x%p",szLibName,DllHandler);
dlclose(DllHandler);
DynMsg("DllHandler aftrer dlclose=0x%p",DllHandler);
if(DllHandler)
{
bSelfLoaded=false;
return true;
}
else
{
DllBase=0;
return false;
}
}
else if(ForceLoad)
{
DynMsg("Force loading!");
DllHandler=dlopen(szLibName, RTLD_NOW);
DynMsg("dlopen(%s)=0x%p",szLibName,DllHandler);
if(!DllHandler)
{
return false;
}
DllBase=LocateLib(LibFileName);
DynMsg("LocateLib(%s)=0x%p",LibFileName,DllBase);
if(!DllBase)
{
dlclose(DllHandler);
DllHandler=NULL;
return false;
}
bSelfLoaded=true;
return true;
}
#endif
return false;
}
bool CDynPatcher::CloseLib()
{
if(!DllHandler)
return false;
DynMsg("Closing \"%s\"",szLibName);
UnsetHooks();
#ifdef PARSE_IMPORT_EXPORT
DeleteImportData();
#endif
if (szLibName)
{
delete [] szLibName;
}
if(DllHandler)
{
if(bSelfLoaded)
{
#ifndef _WIN32
dlclose(DllHandler);
#else
FreeLibrary(reinterpret_cast<HMODULE>(DllHandler));
#endif
}
DllHandler=NULL;
return true;
}
DllHandler=NULL;
return false;
}
/*
bool CDynPatcher::FindSymbol(const char* sName, uint32_t* pSym)
{
if(!DllHandler)
{
return false;
}
uint32_t csym =
#ifdef WIN32
reinterpret_cast<uint32_t>(GetProcAddress(reinterpret_cast<HMODULE>(DllHandler), sName));
#else
reinterpret_cast<uint32_t>(dlsym(DllHandler, sName));
#endif
if (csym == 0)
{
DynErr(false,"Cant Resolve '%s'\n", sName);
return false;
}
if(pSym)
*pSym = csym;
return true;
}
*/
uint32_t CDynPatcher::FindString(uint32_t StartAddr, const char* str, bool FullMatch)
{
CSectionData* csect = NULL;
uint32_t cs;
if (StartAddr == 0)
{
cs = rdata.GetStart();
csect = &rdata;
}
else
{
cs = StartAddr + 1;
CSectionData *cur = &rdata;
while (cur)
{
if (cur->GetStart() >= StartAddr)
{
csect = cur;
break;
}
cur = cur->GetNext();
}
}
while (csect)
{
cs = csect->FindString(str, cs, FullMatch);
if (cs)
return cs;
csect = csect->GetNext();
if (csect)
cs = csect->GetStart();
}
return NULL;
}
uint32_t CDynPatcher::FindDataRef(uint32_t StartAddr, uint32_t RefAddr)
{
CSectionData* csect = NULL;
uint32_t cs;
if (StartAddr == 0)
{
cs = rdata.GetStart();
csect = &rdata;
}
else
{
cs = StartAddr + 1;
//we need to find ourself x_x
CSectionData *cur = &rdata;
while (cur)
{
if (cur->GetStart() >= StartAddr)
{
csect = cur;
break;
}
cur = cur->GetNext();
}
}
while (csect)
{
cs = csect->FindDataRef(RefAddr, cs);
if (cs)
return cs;
csect = csect->GetNext();
if (csect)
cs = csect->GetStart();
}
return NULL;
}
uint32_t CDynPatcher::ScanForTemplate_Backward(const unsigned char* Templ, const unsigned char *Mask, int TemplSize, uint32_t Code_Start, uint32_t Code_Size, CSectionData *pLookupSect)
{
uint8_t* Code_End = (uint8_t*) (Code_Start - Code_Size);
uint8_t* Code_Cur = (uint8_t*) (Code_Start - TemplSize);
CSectionData *LookupSect=pLookupSect;
if(!pLookupSect)
{
LookupSect=&code;
}
if ((uint32_t)Code_End < LookupSect->GetStart())
Code_End = (uint8_t*) LookupSect->GetStart();
size_t Result = 0;
int i;
bool not_match;
while (Code_Cur >= Code_End && !Result)
{
not_match = false;
for (i = 0; i < TemplSize; i++)
{
if ((Code_Cur[i] & Mask[i]) != (Templ[i] & Mask[i]))
{
not_match = true;
break;
}
}
if (!not_match)
{
Result = (uint32_t) Code_Cur;
}
Code_Cur--;
}
return Result;
}
uint32_t CDynPatcher::ScanForTemplate_Forward(const unsigned char* Templ, const unsigned char *Mask, int TemplSize, uint32_t Code_Start, uint32_t Code_Size, CSectionData *pLookupSect)
{
uint8_t* Code_End = (uint8_t*) (Code_Start + Code_Size);
uint8_t* Code_Cur = (uint8_t*) (Code_Start);
CSectionData *LookupSect=pLookupSect;
if(!pLookupSect)
{
LookupSect=&code;
}
if ((uint32_t)Code_End > LookupSect->GetEnd())
Code_End = (uint8_t*) LookupSect->GetEnd();
Code_End -= TemplSize;
size_t Result = 0;
int i;
bool not_match;
while (Code_Cur <= Code_End && !Result)
{
not_match = false;
for (i = 0; i < TemplSize; i++)
{
if ((Code_Cur[i] & Mask[i]) != (Templ[i] & Mask[i]))
{
not_match = true;
break;
}
}
if (!not_match)
{
Result = (size_t) Code_Cur;
}
Code_Cur++;
}
return Result;
}
uint32_t CDynPatcher::ScanForTemplate_Backward(const char* Templ, const char *Mask, int TemplSize, uint32_t Code_Start, uint32_t Code_Size, CSectionData *pLookupSect)
{
return ScanForTemplate_Backward(reinterpret_cast<const unsigned char*>(Templ), reinterpret_cast<const unsigned char*>(Mask), TemplSize, Code_Start, Code_Size, pLookupSect);
}
uint32_t CDynPatcher::ScanForTemplate_Forward(const char* Templ, const char *Mask, int TemplSize, uint32_t Code_Start, uint32_t Code_Size, CSectionData *pLookupSect)
{
return ScanForTemplate_Forward(reinterpret_cast<const unsigned char*>(Templ), reinterpret_cast<const unsigned char*>(Mask), TemplSize, Code_Start, Code_Size, pLookupSect);
}
uint32_t CDynPatcher::FindRef_Mov(uint32_t StartAddr, uint32_t RefAddress)
{
if(StartAddr<code.GetStart())
{
StartAddr=code.GetStart();
}
if(StartAddr>code.GetEnd())
{
DynErr(false,"!!StartAddr>code.GetEnd()!! (0x%x>0x%x)\n",StartAddr,code.GetEnd());
return 0;
}
/*
if(StartAddr<code.GetStart())