-
Notifications
You must be signed in to change notification settings - Fork 6
/
peel.py
6385 lines (4764 loc) · 197 KB
/
peel.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
#!C:/Python27/python.exe
# lllllll
# l:::::l
# l:::::l
# l:::::l
# ppppp ppppppppp eeeeeeeeeeee eeeeeeeeeeee l::::l
# p::::ppp:::::::::p ee::::::::::::ee ee::::::::::::ee l::::l
# p:::::::::::::::::p e::::::eeeee:::::ee e::::::eeeee:::::eel::::l
# pp::::::ppppp::::::pe::::::e e:::::ee::::::e e:::::el::::l
# p:::::p p:::::pe:::::::eeeee::::::ee:::::::eeeee::::::el::::l
# p:::::p p:::::pe:::::::::::::::::e e:::::::::::::::::e l::::l
# p:::::p p:::::pe::::::eeeeeeeeeee e::::::eeeeeeeeeee l::::l
# p:::::p p::::::pe:::::::e e:::::::e l::::l
# p:::::ppppp:::::::pe::::::::e e::::::::e l::::::l
# p::::::::::::::::p e::::::::eeeeeeee e::::::::eeeeeeee l::::::l
# p::::::::::::::pp ee:::::::::::::e ee:::::::::::::e l::::::l
# p::::::pppppppp eeeeeeeeeeeeee eeeeeeeeeeeeee llllllll
# p:::::p
# p:::::p
# p:::::::p - the PE executable library! -
# p:::::::p
# p:::::::p (redunant like an ATM machine!)
# ppppppppp
#
# Copyright (C) 2011-2013, frank2 <frank2 [!] dc949 [:] org>
#
# Originally called "pestuff," PEEL is here to help you deal with PE files!
# Reading, writing-- whatever! It's all good!
#
# License pending. Open-source licensing is a clusterfuck. I dunno what I wanna
# do just yet. :(
#
# Thanks to Ero Carrera's pefile for a lot of guidance on how to properly parse
# PE files without getting bitten in the ass by malware!
# http://code.google.com/p/pefile/
#
# Also thanks to Alexander Sotirov's TinyPE research for helping with curious
# quirks of PE files.
# http://www.phreedom.org/research/tinype/
#
# Finally, thanks to the Corkami project for providing an exhaustive PE corpus
# of extremely odd quirks and other interesting PE file oddities for testing.
# http://code.google.com/p/corkami/
import binascii
import code
import ctypes
import hashlib
import math
import mmap
import os
import random
import re
import struct
import subprocess
import sys
import tempfile
import time
import zlib
# TODO add "set_$attr" functions where get/parse exist (mostly just for
# TODO cleaner-looking code)
###############################################################################
## PE defines
###############################################################################
try:
VirtualProtect = ctypes.windll.kernel32.VirtualProtect
GetProcAddress = ctypes.windll.kernel32.GetProcAddress
LoadLibraryA = ctypes.windll.kernel32.LoadLibraryA
LoadLibraryW = ctypes.windll.kernel32.LoadLibraryW
GetLastError = ctypes.windll.kernel32.GetLastError
GetModuleHandleW = ctypes.windll.kernel32.GetModuleHandleW
AddVectoredExceptionHandler = ctypes.windll.kernel32.AddVectoredExceptionHandler
RemoveVectoredExceptionHandler = ctypes.windll.kernel32.RemoveVectoredExceptionHandler
ExpandEnvironmentStringsA = ctypes.windll.kernel32.ExpandEnvironmentStringsA
WIN32_COMPATIBLE = 1
import ctypes.wintypes
except AttributeError:
VirtualProtect = None
GetProcAddress = None
LoadLibraryA = None
LoadLibraryW = None
GetLastError = None
GetModuleHandleW = None
AddVectoredExceptionHandler = None
RemoveVectoredExceptionHandler = None
ExpandEnvironmentStringsA = None
WIN32_COMPATIBLE = 0
# Various image signatures
IMAGE_DOS_SIGNATURE = 0x5A4D
IMAGE_OS2_SIGNATURE = 0x454E
IMAGE_OS2_SIGNATURE_LE = 0x454C
IMAGE_VXD_SIGNATURE = 0x454C
IMAGE_NT_SIGNATURE = 0x00004550
# Characteristics flags for IMAGE_FILE_HEADER.Characteristics
IMAGE_FILE_RELOCS_STRIPPED = 0x0001
IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002
IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004
IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008
IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010
IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020
IMAGE_FILE_16BIT_MACHINE = 0x0040
IMAGE_FILE_BYTES_REVERSED_LO = 0x0080
IMAGE_FILE_32BIT_MACHINE = 0x0100
IMAGE_FILE_DEBUG_STRIPPED = 0x0200
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400
IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800
IMAGE_FILE_SYSTEM = 0x1000
IMAGE_FILE_DLL = 0x2000
IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000
IMAGE_FILE_BYTES_REVERSED_HI = 0x8000
# Characteristics flags for IMAGE_SECTION_HEADER.Characteristics
IMAGE_SCN_CNT_CODE = 0x00000020
IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040
IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
IMAGE_SCN_LNK_OTHER = 0x00000100
IMAGE_SCN_LNK_INFO = 0x00000200
IMAGE_SCN_LNK_REMOVE = 0x00000800
IMAGE_SCN_LNK_COMDAT = 0x00001000
IMAGE_SCN_MEM_FARDATA = 0x00008000
IMAGE_SCN_MEM_PURGEABLE = 0x00020000
IMAGE_SCN_MEM_16BIT = 0x00020000
IMAGE_SCN_MEM_LOCKED = 0x00040000
IMAGE_SCN_MEM_PRELOAD = 0x00080000
IMAGE_SCN_ALIGN_1BYTES = 0x00100000
IMAGE_SCN_ALIGN_2BYTES = 0x00200000
IMAGE_SCN_ALIGN_4BYTES = 0x00300000
IMAGE_SCN_ALIGN_8BYTES = 0x00400000
IMAGE_SCN_ALIGN_16BYTES = 0x00500000
IMAGE_SCN_ALIGN_32BYTES = 0x00600000
IMAGE_SCN_ALIGN_64BYTES = 0x00700000
IMAGE_SCN_ALIGN_128BYTES = 0x00800000
IMAGE_SCN_ALIGN_256BYTES = 0x00900000
IMAGE_SCN_ALIGN_512BYTES = 0x00A00000
IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000
IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000
IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000
IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000
IMAGE_SCN_ALIGN_MASK = 0x00F00000
IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000
IMAGE_SCN_MEM_DISCARDABLE = 0x02000000
IMAGE_SCN_MEM_NOT_CACHED = 0x04000000
IMAGE_SCN_MEM_NOT_PAGED = 0x08000000
IMAGE_SCN_MEM_SHARED = 0x10000000
IMAGE_SCN_MEM_EXECUTE = 0x20000000
IMAGE_SCN_MEM_READ = 0x40000000
IMAGE_SCN_MEM_WRITE = 0x80000000
# defines for FileHeader.Machine
IMAGE_FILE_MACHINE_UNKNOWN = 0
IMAGE_FILE_MACHINE_I860 = 0x014d
IMAGE_FILE_MACHINE_I386 = 0x014c
IMAGE_FILE_MACHINE_R3000 = 0x0162
IMAGE_FILE_MACHINE_R4000 = 0x0166
IMAGE_FILE_MACHINE_R10000 = 0x0168
IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169
IMAGE_FILE_MACHINE_ALPHA = 0x0184
IMAGE_FILE_MACHINE_SH3 = 0x01a2
IMAGE_FILE_MACHINE_SH3DSP = 0x01a3
IMAGE_FILE_MACHINE_SH3E = 0x01a4
IMAGE_FILE_MACHINE_SH4 = 0x01a6
IMAGE_FILE_MACHINE_SH5 = 0x01a8
IMAGE_FILE_MACHINE_ARM = 0x01c0
IMAGE_FILE_MACHINE_THUMB = 0x01c2
IMAGE_FILE_MACHINE_ARMV7 = 0x01c4
IMAGE_FILE_MACHINE_AM33 = 0x01d3
IMAGE_FILE_MACHINE_POWERPC = 0x01f0
IMAGE_FILE_MACHINE_POWERPCFP = 0x01f1
IMAGE_FILE_MACHINE_IA64 = 0x0200
IMAGE_FILE_MACHINE_MIPS16 = 0x0266
IMAGE_FILE_MACHINE_ALPHA64 = 0x0284
IMAGE_FILE_MACHINE_MIPSFPU = 0x0366
IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466
IMAGE_FILE_MACHINE_AXP64 = IMAGE_FILE_MACHINE_ALPHA64
IMAGE_FILE_MACHINE_TRICORE = 0x0520
IMAGE_FILE_MACHINE_CEF = 0x0cef
IMAGE_FILE_MACHINE_EBC = 0x0ebc
IMAGE_FILE_MACHINE_AMD64 = 0x8664
IMAGE_FILE_MACHINE_M32R = 0x9041
IMAGE_FILE_MACHINE_CEE = 0xc0ee
# from Wine
IMAGE_FILE_MACHINE_SPARC = 0x2000
# Magic values
IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10B
IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20B
IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107
# DataDirectory indices
IMAGE_DIRECTORY_ENTRY_EXPORT = 0
IMAGE_DIRECTORY_ENTRY_IMPORT = 1
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2
IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3
IMAGE_DIRECTORY_ENTRY_SECURITY = 4
IMAGE_DIRECTORY_ENTRY_BASERELOC = 5
IMAGE_DIRECTORY_ENTRY_DEBUG = 6
IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7
IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8
IMAGE_DIRECTORY_ENTRY_TLS = 9
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11
IMAGE_DIRECTORY_ENTRY_IAT = 12
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
# DLL Characteristics
IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040
IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY = 0x0080
IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100
IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200
IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400
IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800
IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000
IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
# Subsystems
IMAGE_SUBSYSTEM_UNKNOWN = 0
IMAGE_SUBSYSTEM_NATIVE = 1
IMAGE_SUBSYSTEM_WINDOWS_GUI = 2
IMAGE_SUBSYSTEM_WINDOWS_CUI = 3
IMAGE_SUBSYSTEM_OS2_CUI = 5
IMAGE_SUBSYSTEM_POSIX_CUI = 7
IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8
IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9
IMAGE_SUBSYSTEM_EFI_APPLICATION = 10
IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11
IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12
IMAGE_SUBSYSTEM_EFI_ROM = 13
IMAGE_SUBSYSTEM_XBOX = 14
IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16
# Context record constants
SIZE_OF_80387_REGISTERS = 80
MAXIMUM_SUPPORTED_EXTENSION = 512
###############################################################################
## Debug stuff
###############################################################################
# debug logging verbosity (set_verbosity() to adjust)
VERBOSITY = 0
# some names for fancypants debugging
MILD_VERBOSITY = 1
MEDIUM_VERBOSITY = 2
SPICY_VERBOSITY = 3
XTREME_VERBOSITY = 4
def set_verbosity(verbosity):
global VERBOSITY
VERBOSITY = verbosity
def no_verbosity():
return set_verbosity(0)
def mild_verbosity():
return set_verbosity(MILD_VERBOSITY)
def medium_verbosity():
return set_verbosity(MEDIUM_VERBOSITY)
def spicy_verbosity():
return set_verbosity(SPICY_VERBOSITY)
def xtreme_verbosity():
return set_verbosity(XTREME_VERBOSITY)
def is_mild():
return get_verbosity() >= MILD_VERBOSITY
def is_medium():
return get_verbosity() >= MEDIUM_VERBOSITY
def is_spicy():
return get_verbosity() >= SPICY_VERBOSITY
def is_xtreme():
return get_verbosity() >= XTREME_VERBOSITY
def get_verbosity(): # so we don't have to type "global VERBOSITY" everywhere
global VERBOSITY
return VERBOSITY
def DEBUG(level, fmt, *args):
if level > get_verbosity():
return
return sys.stderr.write('[%.3f] [DEBUG=%d] %s\n' % (time.time(),level,fmt % tuple(args)))
def DBG1(fmt, *args):
return DEBUG(1, fmt, *args)
def DBG2(fmt, *args):
return DEBUG(2, fmt, *args)
def DBG3(fmt, *args):
return DEBUG(3, fmt, *args)
def DBG4(fmt, *args):
return DEBUG(4, fmt, *args)
###############################################################################
## Generic error stub just to have all the errors organized
###############################################################################
class PEELError(Exception):
pass
###############################################################################
## Address data
###############################################################################
class AddressError(PEELError): # TODO some contextual stuff
pass
class HeaderError(PEELError):
pass
# TODO this class should really get cleaned up a bit. it just feels gross.
class Address:
VALUE_VA = 0x0
VALUE_RVA = 0x1
VALUE_OFFSET = 0x2
VALUE_PVA = 0x4
VALUES = ['va','rva','offset','pva']
INVALID_ADDRESS = -1
def __init__(self, image, value, value_type):
self.image = image
self._value = int(value)
if value_type > len(Address.VALUES) or value_type < 0:
raise TypeError('bad value type')
self._value_type = value_type
if self._value_type == Address.VALUE_VA:
self._va = self._value
self._offset = Address.INVALID_ADDRESS
self._rva = Address.INVALID_ADDRESS
elif self._value_type == Address.VALUE_RVA:
self._rva = self._value
self._va = Address.INVALID_ADDRESS
self._offset = Address.INVALID_ADDRESS
elif self._value_type == Address.VALUE_OFFSET:
self._offset = self._value
self._va = Address.INVALID_ADDRESS
self._rva = Address.INVALID_ADDRESS
def rva(self):
if self._rva == Address.INVALID_ADDRESS:
self._rva = self.get_rva()
return self._rva
def va(self):
if self._va == Address.INVALID_ADDRESS:
self._va = self.get_va()
return self._va
def offset(self):
if self._offset == Address.INVALID_ADDRESS:
self._offset = self.get_offset()
return self._offset
# FIXME make PVAs an actual thing down the road.
def pva(self):
return self.rva() + self.image.virtual_base()
def get_rva(self):
if self.is_null():
return 0
if self._value_type == Address.VALUE_RVA:
return self._value
elif self._value_type == Address.VALUE_VA:
return self.image.va_to_rva(self._value)
else:
return self.image.offset_to_rva(self._value)
def get_va(self):
if self.is_null():
return 0
if self._value_type == Address.VALUE_RVA:
return self.image.rva_to_va(self._value)
elif self._value_type == Address.VALUE_VA:
return self._value
else:
return self.image.offset_to_va(self._value)
def get_offset(self):
if self.is_null():
return 0
if self._value_type == Address.VALUE_RVA:
return self.image.rva_to_offset(self._value)
elif self._value_type == Address.VALUE_VA:
return self.image.va_to_offset(self._value)
else:
return self._value
def as_rva(self):
rva = self.rva()
return self.image.rva(rva)
def as_va(self):
va = self.va()
return self.image.va(va)
def as_offset(self):
offset = self.offset()
return self.image.offset(offset)
def valid_rva(self):
# an rva can be null and valid
if self.is_null():
return 1
if not self._rva == Address.INVALID_ADDRESS:
value_check = self._rva
else:
try:
value_check = self.rva()
except (AddressError, HeaderError),e:
DBG3("got error converting value: %s", str(e))
return 0
if self.image.has_virtual_image():
return 0 < value_check < self.image.virtual_length()
elif self.image.has_optional_header():
size = int(self.image.IMAGE_OPTIONAL_HEADER.SizeOfImage)
return 0 < value_check < size
else:
raise ImageError("attempting to verify validity of an rva via SizeOfImage without an optional header present. see PEImage.section_by_offset as to why this error was raised.")
def valid_va(self):
optional = self.image.IMAGE_OPTIONAL_HEADER
size = int(optional.SizeOfImage)
base = int(optional.ImageBase)
# a va can be null and valid only if the image base is zero
if self.is_null() and size:
return 0
if not self._va == Address.INVALID_ADDRESS:
value_check = self._va
else:
try:
value_check = self.va()
except (AddressError, HeaderError),e:
DBG3("got error checking VA validity: %s", repr(e))
return 0
return base < value_check < (size+base)
def valid_offset(self):
# an offset can be null and valid
if self.is_null():
return 1
if not self._offset == Address.INVALID_ADDRESS:
value_check = self._offset
else:
try:
value_check = self.offset()
except (AddressError, HeaderError),e:
DBG3("got error checking offset validity: %s", repr(e))
return 0
size = len(self.image)
return 0 < value_check < size
def null(self):
return self.image.null()
def copy(self): # just something to look more pretty.
return self.address()
def address(self):
new_addr = Address(self.image, self._value, self._value_type)
new_addr._offset = self._offset
new_addr._rva = self._rva
new_addr._va = self._va
return new_addr
def is_null(self):
return self._value == 0
def is_orphan(self):
return self.image == None
def unpack_qword(self, signed=0):
return self.image.unpack_qword(self, signed)
def unpack_qword_raw(self, signed=0):
return self.image.unpack_qword_raw(self, signed)
def unpack_qword_virtual(self, signed=0):
return self.image.unpack_qword_virtual(self, signed)
def unpack_qwords(self, qwords, signed=0):
return self.image.unpack_qwords(self, qwords, signed)
def unpack_qwords_raw(self, qwords_raw, signed=0):
return self.image.unpack_qwords_raw(self, qwords_raw, signed)
def unpack_qwords_virtual(self, qwords_virtual, signed=0):
return self.image.unpack_qwords_virtual(self, qwords_virtual, signed)
def unpack_dword(self, signed=0):
return self.image.unpack_dword(self, signed)
def unpack_dword_raw(self, signed=0):
return self.image.unpack_dword_raw(self, signed)
def unpack_dword_virtual(self, signed=0):
return self.image.unpack_dword_virtual(self, signed)
def unpack_dwords(self, dwords, signed=0):
return self.image.unpack_dwords(self, dwords, signed)
def unpack_dwords_raw(self, dwords_raw, signed=0):
return self.image.unpack_dwords_raw(self, dwords_raw, signed)
def unpack_dwords_virtual(self, dwords_virtual, signed=0):
return self.image.unpack_dwords_virtual(self, dwords_virtual, signed)
def unpack_word(self, signed=0):
return self.image.unpack_word(self, signed)
def unpack_word_raw(self, signed=0):
return self.image.unpack_word_raw(self, signed)
def unpack_word_virtual(self, signed=0):
return self.image.unpack_word_virtual(self, signed)
def unpack_words(self, words, signed=0):
return self.image.unpack_words(self, words, signed)
def unpack_words_raw(self, words_raw, signed=0):
return self.image.unpack_words_raw(self, words_raw, signed)
def unpack_words_virtual(self, words_virtual, signed=0):
return self.image.unpack_words_virtual(self, words_virtual, signed)
def unpack_byte(self, signed=0):
return self.image.unpack_byte(self, signed)
def unpack_byte_raw(self, signed=0):
return self.image.unpack_byte_raw(self, signed)
def unpack_byte_virtual(self, signed=0):
return self.image.unpack_byte_virtual(self, signed)
def unpack_bytes(self, bytecount, signed=0):
return self.image.unpack_bytes(self, bytecount, signed)
def unpack_bytes_raw(self, bytes_raw, signed=0):
return self.image.unpack_bytes_raw(self, bytes_raw, signed)
def unpack_bytes_virtual(self, bytes_virtual, signed=0):
return self.image.unpack_bytes_virtual(self, bytes_virtual, signed)
def unpack_string_limit(self, limit):
return self.image.unpack_string_limit(self, limit)
def unpack_string_limit_raw(self, limit_raw):
return self.image.unpack_string_limit_raw(self, limit_raw)
def unpack_string_limit_virtual(self, limit_virtual):
return self.image.unpack_string_limit_virtual(self, limit_virtual)
def unpack_string(self):
return self.image.unpack_string(self)
def unpack_string_raw(self):
return self.image.unpack_string_raw(self)
def unpack_string_virtual(self):
return self.image.unpack_string_virtual(self)
def unpack_wide_string_limit(self, limit):
return self.image.unpack_wide_string_limit(self, limit)
def unpack_wide_string_limit_raw(self, limit_raw):
return self.image.unpack_wide_string_limit_raw(self, limit_raw)
def unpack_wide_string_limit_virtual(self, limit_virtual):
return self.image.unpack_wide_string_limit_virtual(self, limit_virtual)
def unpack_wide_string(self):
return self.image.unpack_wide_string(self)
def unpack_wide_string_raw(self):
return self.image.unpack_wide_string_raw(self)
def unpack_wide_string_virtual(self):
return self.image.unpack_wide_string_virtual(self)
def read(self, length=0):
return self.image.read(self, length)
def read_raw(self, length=0):
return self.image.read_raw(self, length)
def read_virtual(self, length=0):
return self.image.read_virtual(self, length)
def parse_pe(self):
return self.image.parse_image_at_address(self)
def pack_qword(self, qword, signed=0):
return self.image.pack_qword(self, qword, signed)
def pack_qword_raw(self, qword_raw, signed=0):
return self.image.pack_qword_raw(self, qword_raw, signed)
def pack_qword_virtual(self, qword_virtual, signed=0):
return self.image.pack_qword_virtual(self, qword_virtual, signed)
def pack_qwords(self, qwords, signed=0):
return self.image.pack_qwords(self, qwords, signed)
def pack_qwords_raw(self, qwords_raw, signed=0):
return self.image.pack_qwords_raw(self, qwords_raw, signed)
def pack_qwords_virtual(self, qwords_virtual, signed=0):
return self.image.pack_qwords_virtual(self, qwords_virtual, signed)
def pack_dword(self, dword, signed=0):
return self.image.pack_dword(self, dword, signed)
def pack_dword_raw(self, dword_raw, signed=0):
return self.image.pack_dword_raw(self, dword_raw, signed)
def pack_dword_virtual(self, dword_virtual, signed=0):
return self.image.pack_dword_virtual(self, dword_virtual, signed)
def pack_dwords(self, dwords, signed=0):
return self.image.pack_dwords(self, dwords, signed)
def pack_dwords_raw(self, dwords_raw, signed=0):
return self.image.pack_dwords_raw(self, dwords_raw, signed)
def pack_dwords_virtual(self, dwords_virtual, signed=0):
return self.image.pack_dwords_virtual(self, dwords_virtual, signed)
def pack_word(self, word, signed=0):
return self.image.pack_word(self, word, signed)
def pack_word_raw(self, word_raw, signed=0):
return self.image.pack_word_raw(self, word_raw, signed)
def pack_word_virtual(self, word_virtual, signed=0):
return self.image.pack_word_virtual(self, word_virtual, signed)
def pack_words(self, words, signed=0):
return self.image.pack_words(self, words, signed)
def pack_words_raw(self, words_raw, signed=0):
return self.image.pack_words_raw(self, words_raw, signed)
def pack_words_virtual(self, words_virtual, signed=0):
return self.image.pack_words_virtual(self, words_virtual, signed)
def pack_byte(self, byte, signed=0):
return self.image.pack_byte(self, byte, signed)
def pack_byte_raw(self, byte_raw, signed=0):
return self.image.pack_byte_raw(self, byte_raw, signed)
def pack_byte_virtual(self, byte_virtual, signed=0):
return self.image.pack_byte_virtual(self, byte_virtual, signed)
def pack_bytes(self, bytelist, signed=0):
return self.image.pack_bytes(self, bytelist, signed)
def pack_bytes_raw(self, bytes_raw, signed=0):
return self.image.pack_bytes_raw(self, bytes_raw, signed)
def pack_bytes_virtual(self, bytes_virtual, signed=0):
return self.image.pack_bytes_virtual(self, bytes_virtual, signed)
def pack_string(self, string):
return self.image.pack_string(self, string)
def pack_string_raw(self, string_raw):
return self.image.pack_string_raw(self, string_raw)
def pack_string_virtual(self, string_virtual):
return self.image.pack_string_virtual(self, string_virtual)
def pack_wide_string(self, string):
return self.image.pack_wide_string(self, string)
def write(self, raw):
return self.image.write(self, raw)
def write_raw(self, raw):
return self.image.write_raw(self, raw)
def write_virtual(self, raw):
return self.image.write_virtual(self, raw)
def section_by_offset(self):
return self.image.section_by_offset(self.offset())
def section_by_rva(self):
return self.image.section_by_rva(self.rva())
def create_function(self, function_class):
return self.image.create_function(self, function_class)
def relocate(self, target_base=None):
return self.image.relocate(self, target_base)
def relocate_raw(self, target_base=None):
return self.image.relocate_raw(self, target_base)
def relocate_virtual(self, target_base=None):
return self.image.relocate_virtual(self, target_base)
def __add__(self, val):
new_addr = Address(self.image, self._value+val, self._value_type)
if not self._offset == Address.INVALID_ADDRESS:
new_addr._offset = self._offset + val
if not self._rva == Address.INVALID_ADDRESS:
new_addr._rva = self._rva + val
if not self._va == Address.INVALID_ADDRESS:
new_addr._va = self._va + val
return new_addr
def __iadd__(self, val):
return self+val
def __sub__(self, val):
new_addr = Address(self.image, self._value-val, self._value_type)
if not self._offset == Address.INVALID_ADDRESS:
new_addr._offset = self._offset - val
if not self._rva == Address.INVALID_ADDRESS:
new_addr._rva = self._rva - val
if not self._va == Address.INVALID_ADDRESS:
new_addr._va = self._va - val
return new_addr
def __isub__(self, val):
return self-val
def __rsub__(self, val):
new_addr = Address(self.image, val-self._value, self._value_type)
if not self._offset == Address.INVALID_ADDRESS:
new_addr._offset = val - self._offset
if not self._rva == Address.INVALID_ADDRESS:
new_addr._rva = val - self._rva
if not self._va == Address.INVALID_ADDRESS:
new_addr._va = val - self._va
return new_addr
def __hash__(self):
return hash(self._value)
def __cmp__(self, addr):
if not isinstance(addr, Address):
raise AddressError("can't compare address object to non-address object")
DBG4("comparing %s to %s", repr(self), repr(addr))
if self._value_type == addr._value_type:
return cmp(self._value, addr._value)
if not self._offset == Address.INVALID_ADDRESS and not addr._offset == Address.INVALID_ADDRESS:
return cmp(self._offset, addr._offset)
if not self._rva == Address.INVALID_ADDRESS and not addr._rva == Address.INVALID_ADDRESS:
return cmp(self._rva, addr._rva)
if not self._va == Address.INVALID_ADDRESS and not addr._va == Address.INVALID_ADDRESS:
return cmp(self._va, addr._va)
# okay. now you're just being a dick. we HAVE to convert one of the addresses.
# the lowest hanging fruit is RVA -> VA. so if one is an RVA and another is a VA,
# we're in business.
if self._value_type == Address.VALUE_RVA and not addr._va == Address.INVALID_ADDRESS:
return cmp(self.va(), addr._va)
if not self._va == Address.INVALID_ADDRESS and addr._value_type == Address.VALUE_RVA:
return cmp(self._va, addr.va())
# the next lowest hanging fruit is VA -> RVA.
if self._value_type == Address.VALUE_RVA and not addr._va == Address.INVALID_ADDRESS:
return cmp(self._rva, addr.va())
if not self._va == Address.INVALID_ADDRESS and addr._value_type == Address.VALUE_RVA:
return cmp(self.rva(), addr._va)
# if we've gotten here, we have to do something nasty anyway. force them
# both into RVAs.
return cmp(self.rva(), addr.rva())
def __str__(self):
if self._value >= 0xFFFFFFFF: # we can't use architecture() for reasons
return '%s:0x%016X'%(self.VALUES[self._value_type].upper(),self._value)
else:
return '%s:0x%08X'%(self.VALUES[self._value_type].upper(),self._value)
def __repr__(self):
return '<Address [%s]>' % str(self)
def __int__(self):
return self._value
class PVA(Address):
def __init__(self, image, pva):
Address.__init__(self, image, pva, Address.VALUE_PVA)
@classmethod
def orphan(cls, value=0):
return PVA(None, value)
class RVA(Address):
def __init__(self, image, rva):
Address.__init__(self, image, rva, Address.VALUE_RVA)
@classmethod
def orphan(cls, value=0):
return RVA(None, value)
class VA(Address):
def __init__(self, image, va):
Address.__init__(self, image, va, Address.VALUE_VA)
@classmethod
def orphan(cls, value=0):
return VA(None, value)
class Offset(Address):
def __init__(self, image, offset):
Address.__init__(self, image, offset, Address.VALUE_OFFSET)
@classmethod
def orphan(cls, value=0):
return Offset(None, value)
###############################################################################
## Base data types
###############################################################################
# TODO endianness
class DataError(PEELError):
pass
def sizeof(cls):
return cls.sizeof()
class Data:
DEFAULT_VALUE = None
def __init__(self, **kwargs):
self.address = kwargs.setdefault('address', None)
self.copy = kwargs.setdefault('copy', 0)
self._data = None
if kwargs.setdefault('data', None):
self.set_data(kwargs['data'])
elif self.copy and self.address:
self.copy_data()
elif not self.address:
raise ValueError('cannot create a data object with no address or data')
if self.address:
self.address = self.address.address()
def checksum(self, seed=0):
#FIXME I really don't like using ''.join for this...
return zlib.crc32(''.join(self.read()), seed)
def set_data(self, data):
if not len(data) == sizeof(self.__class__):
raise ValueError('data size not equal to size of class')
for i in xrange(len(data)):
if not type(data[i]) is str or not len(data[i]) == 1:
raise TypeError('data argument must be a list of bytes')
if not type(data) is list:
data = list(data)
self._data = data[:]
def copy_data(self):
self._address_check()
self._data = self.address.read(sizeof(self.__class__))
def read(self):
if self._has_data():
return ''.join(self._data[:])
else:
self._address_check()
return self.address.read(sizeof(self.__class__))
def get_value(self):
pass
def set_value(self):
pass
def write(self):
if not self._has_data():
return # data should have been saved with set_value
self._address_check()
self.address.write(self._data)
def clear(self):
self._data = None
def size(self):
return sizeof(self.__class__)
def _address_check(self):
if not self.address:
raise ValueError("data object contains no address")
def _has_data(self):
return not self._data is None
def __len__(self):
return sizeof(self.__class__)
def __cmp__(self, other):
return cmp(self.read(),other.read())
def __repr__(self):
return '<Data: "%s">' % ''.join(self.read())
def __hash__(self):
return hash(self.read())
@classmethod
def sizeof(cls):
raise DataError('classmethod Data::sizeof undefined')
class DataArray:
BASE_CLASS = Data
def __init__(self, **kwargs):
self.address = kwargs.setdefault('address', None)
self.length = kwargs.setdefault('length', 0)
self._data = None
self.copy = kwargs.setdefault('copy', 0)
if kwargs.setdefault('data', None):
self.set_data(kwargs['data'])
elif self.copy and self.address:
self.copy_data()
elif kwargs.setdefault('elements', None):
self.set_elements(kwargs['elements'])
elif not self.address:
raise ValueError('cannot create a data reference with no address')
if self.address:
self.address = self.address.address()
def set_data(self, data):
cls = self.BASE_CLASS
size = sizeof(cls)
data_size = len(data)
if not data_size % size == 0:
raise ValueError('data size not a multiple of base class size')
if not type(data) is list:
raise TypeError('data argument not a list')
for byte in data:
if not type(byte) is str or not len(byte) == 1:
raise TypeError('data argument must be a list of bytes')
self._data = data[:]