forked from erocarrera/pefile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pefile.py
8034 lines (6770 loc) · 295 KB
/
pefile.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
#!/usr/bin/python
"""pefile, Portable Executable reader module
All the PE file basic structures are available with their default names as
attributes of the instance returned.
Processed elements such as the import table are made available with lowercase
names, to differentiate them from the upper case basic structure names.
pefile has been tested against many edge cases such as corrupted and malformed
PEs as well as malware, which often attempts to abuse the format way beyond its
standard use. To the best of my knowledge most of the abuse is handled
gracefully.
Copyright (c) 2005-2024 Ero Carrera <[email protected]>
"""
__author__ = "Ero Carrera"
__version__ = "2024.8.26"
__contact__ = "[email protected]"
import codecs
import collections
import copy as copymod
import functools
import gc
import math
import mmap
import os
import string
import struct
import time
import uuid
from collections import Counter
from hashlib import md5, sha1, sha256, sha512
from typing import Union
import ordlookup
codecs.register_error("backslashreplace_", codecs.lookup_error("backslashreplace"))
long = int
# lru_cache with a shallow copy of the objects returned (list, dicts, ..)
# we don't use deepcopy as it's _really_ slow and the data we retrieved using
# this is enough with copy.copy taken from
# https://stackoverflow.com/questions/54909357
def lru_cache(maxsize=128, typed=False, copy=False):
if not copy:
return functools.lru_cache(maxsize, typed)
def decorator(f):
cached_func = functools.lru_cache(maxsize, typed)(f)
@functools.wraps(f)
def wrapper(*args, **kwargs):
# return copymod.deepcopy(cached_func(*args, **kwargs))
return copymod.copy(cached_func(*args, **kwargs))
return wrapper
return decorator
@lru_cache(maxsize=2048)
def cache_adjust_SectionAlignment(val, section_alignment, file_alignment):
if section_alignment < 0x1000: # page size
section_alignment = file_alignment
# 0x200 is the minimum valid FileAlignment according to the documentation
# although ntoskrnl.exe has an alignment of 0x80 in some Windows versions
#
# elif section_alignment < 0x80:
# section_alignment = 0x80
if section_alignment and val % section_alignment:
return section_alignment * (int(val / section_alignment))
return val
def count_zeroes(data):
return data.count(0)
fast_load = False
# This will set a maximum length of a string to be retrieved from the file.
# It's there to prevent loading massive amounts of data from memory mapped
# files. Strings longer than 1MB should be rather rare.
MAX_STRING_LENGTH = 0x100000 # 2^20
# Maximum number of imports to parse.
MAX_IMPORT_SYMBOLS = 0x2000
# Limit maximum length for specific string types separately
MAX_IMPORT_NAME_LENGTH = 0x200
MAX_DLL_LENGTH = 0x200
MAX_SYMBOL_NAME_LENGTH = 0x200
# Limit maximum number of sections before processing of sections will stop
MAX_SECTIONS = 0x800
# The global maximum number of resource entries to parse per file
MAX_RESOURCE_ENTRIES = 0x8000
# The maximum depth of nested resource tables
MAX_RESOURCE_DEPTH = 32
# Limit number of exported symbols
MAX_SYMBOL_EXPORT_COUNT = 0x2000
IMAGE_DOS_SIGNATURE = 0x5A4D
IMAGE_DOSZM_SIGNATURE = 0x4D5A
IMAGE_NE_SIGNATURE = 0x454E
IMAGE_LE_SIGNATURE = 0x454C
IMAGE_LX_SIGNATURE = 0x584C
IMAGE_TE_SIGNATURE = 0x5A56 # Terse Executables have a 'VZ' signature
IMAGE_NT_SIGNATURE = 0x00004550
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16
IMAGE_ORDINAL_FLAG = 0x80000000
IMAGE_ORDINAL_FLAG64 = 0x8000000000000000
OPTIONAL_HEADER_MAGIC_PE = 0x10B
OPTIONAL_HEADER_MAGIC_PE_PLUS = 0x20B
def two_way_dict(pairs):
return dict([(e[1], e[0]) for e in pairs] + pairs)
directory_entry_types = [
("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),
# Architecture on non-x86 platforms
("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),
("IMAGE_DIRECTORY_ENTRY_RESERVED", 15),
]
DIRECTORY_ENTRY = two_way_dict(directory_entry_types)
image_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),
]
IMAGE_CHARACTERISTICS = two_way_dict(image_characteristics)
section_characteristics = [
("IMAGE_SCN_TYPE_REG", 0x00000000), # reserved
("IMAGE_SCN_TYPE_DSECT", 0x00000001), # reserved
("IMAGE_SCN_TYPE_NOLOAD", 0x00000002), # reserved
("IMAGE_SCN_TYPE_GROUP", 0x00000004), # reserved
("IMAGE_SCN_TYPE_NO_PAD", 0x00000008), # reserved
("IMAGE_SCN_TYPE_COPY", 0x00000010), # reserved
("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_OVER", 0x00000400), # reserved
("IMAGE_SCN_LNK_REMOVE", 0x00000800),
("IMAGE_SCN_LNK_COMDAT", 0x00001000),
("IMAGE_SCN_MEM_PROTECTED", 0x00004000), # obsolete
("IMAGE_SCN_NO_DEFER_SPEC_EXC", 0x00004000),
("IMAGE_SCN_GPREL", 0x00008000),
("IMAGE_SCN_MEM_FARDATA", 0x00008000),
("IMAGE_SCN_MEM_SYSHEAP", 0x00010000), # obsolete
("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), # default alignment
("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),
]
SECTION_CHARACTERISTICS = two_way_dict(section_characteristics)
debug_types = [
("IMAGE_DEBUG_TYPE_UNKNOWN", 0),
("IMAGE_DEBUG_TYPE_COFF", 1),
("IMAGE_DEBUG_TYPE_CODEVIEW", 2),
("IMAGE_DEBUG_TYPE_FPO", 3),
("IMAGE_DEBUG_TYPE_MISC", 4),
("IMAGE_DEBUG_TYPE_EXCEPTION", 5),
("IMAGE_DEBUG_TYPE_FIXUP", 6),
("IMAGE_DEBUG_TYPE_OMAP_TO_SRC", 7),
("IMAGE_DEBUG_TYPE_OMAP_FROM_SRC", 8),
("IMAGE_DEBUG_TYPE_BORLAND", 9),
("IMAGE_DEBUG_TYPE_RESERVED10", 10),
("IMAGE_DEBUG_TYPE_CLSID", 11),
("IMAGE_DEBUG_TYPE_VC_FEATURE", 12),
("IMAGE_DEBUG_TYPE_POGO", 13),
("IMAGE_DEBUG_TYPE_ILTCG", 14),
("IMAGE_DEBUG_TYPE_MPX", 15),
("IMAGE_DEBUG_TYPE_REPRO", 16),
("IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS", 20),
]
DEBUG_TYPE = two_way_dict(debug_types)
subsystem_types = [
("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),
]
SUBSYSTEM_TYPE = two_way_dict(subsystem_types)
machine_types = [
("IMAGE_FILE_MACHINE_UNKNOWN", 0x0),
("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_ARMNT", 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_AXP64", 0x0284), # same
("IMAGE_FILE_MACHINE_MIPSFPU", 0x0366),
("IMAGE_FILE_MACHINE_MIPSFPU16", 0x0466),
("IMAGE_FILE_MACHINE_TRICORE", 0x0520),
("IMAGE_FILE_MACHINE_CEF", 0x0CEF),
("IMAGE_FILE_MACHINE_EBC", 0x0EBC),
("IMAGE_FILE_MACHINE_RISCV32", 0x5032),
("IMAGE_FILE_MACHINE_RISCV64", 0x5064),
("IMAGE_FILE_MACHINE_RISCV128", 0x5128),
("IMAGE_FILE_MACHINE_LOONGARCH32", 0x6232),
("IMAGE_FILE_MACHINE_LOONGARCH64", 0x6264),
("IMAGE_FILE_MACHINE_AMD64", 0x8664),
("IMAGE_FILE_MACHINE_M32R", 0x9041),
("IMAGE_FILE_MACHINE_ARM64", 0xAA64),
("IMAGE_FILE_MACHINE_CEE", 0xC0EE),
]
MACHINE_TYPE = two_way_dict(machine_types)
relocation_types = [
("IMAGE_REL_BASED_ABSOLUTE", 0),
("IMAGE_REL_BASED_HIGH", 1),
("IMAGE_REL_BASED_LOW", 2),
("IMAGE_REL_BASED_HIGHLOW", 3),
("IMAGE_REL_BASED_HIGHADJ", 4),
("IMAGE_REL_BASED_MIPS_JMPADDR", 5),
("IMAGE_REL_BASED_SECTION", 6),
("IMAGE_REL_BASED_REL", 7),
("IMAGE_REL_BASED_MIPS_JMPADDR16", 9),
("IMAGE_REL_BASED_IA64_IMM64", 9),
("IMAGE_REL_BASED_DIR64", 10),
("IMAGE_REL_BASED_HIGH3ADJ", 11),
]
RELOCATION_TYPE = two_way_dict(relocation_types)
dll_characteristics = [
("IMAGE_LIBRARY_PROCESS_INIT", 0x0001), # reserved
("IMAGE_LIBRARY_PROCESS_TERM", 0x0002), # reserved
("IMAGE_LIBRARY_THREAD_INIT", 0x0004), # reserved
("IMAGE_LIBRARY_THREAD_TERM", 0x0008), # reserved
("IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA", 0x0020),
("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_APPCONTAINER", 0x1000),
("IMAGE_DLLCHARACTERISTICS_WDM_DRIVER", 0x2000),
("IMAGE_DLLCHARACTERISTICS_GUARD_CF", 0x4000),
("IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE", 0x8000),
]
DLL_CHARACTERISTICS = two_way_dict(dll_characteristics)
ex_dll_characteristics = [
("IMAGE_DLLCHARACTERISTICS_EX_CET_COMPAT", 0x0001),
("IMAGE_DLLCHARACTERISTICS_EX_CET_COMPAT_STRICT_MODE", 0x0002),
("IMAGE_DLLCHARACTERISTICS_EX_CET_SET_CONTEXT_IP_VALIDATION_RELAXED_MODE", 0x0004),
("IMAGE_DLLCHARACTERISTICS_EX_CET_DYNAMIC_APIS_ALLOW_IN_PROC", 0x0008),
("IMAGE_DLLCHARACTERISTICS_EX_CET_RESERVED_1", 0x0010),
("IMAGE_DLLCHARACTERISTICS_EX_CET_RESERVED_2", 0x0020),
]
EX_DLL_CHARACTERISTICS = two_way_dict(ex_dll_characteristics)
MIN_VALID_FILE_ALIGNMENT = 0x200
SECTOR_SIZE = 0x200
# Unwind info-related enums
unwind_info_flags = [
("UNW_FLAG_EHANDLER", 0x01),
("UNW_FLAG_UHANDLER", 0x02),
("UNW_FLAG_CHAININFO", 0x04),
]
UNWIND_INFO_FLAGS = two_way_dict(unwind_info_flags)
registers = [
("RAX", 0),
("RCX", 1),
("RDX", 2),
("RBX", 3),
("RSP", 4),
("RBP", 5),
("RSI", 6),
("RDI", 7),
("R8", 8),
("R9", 9),
("R10", 10),
("R11", 11),
("R12", 12),
("R13", 13),
("R14", 14),
("R15", 15),
]
REGISTERS = two_way_dict(registers)
# enum _UNWIND_OP_CODES
UWOP_PUSH_NONVOL = 0
UWOP_ALLOC_LARGE = 1
UWOP_ALLOC_SMALL = 2
UWOP_SET_FPREG = 3
UWOP_SAVE_NONVOL = 4
UWOP_SAVE_NONVOL_FAR = 5
UWOP_EPILOG = 6
UWOP_SAVE_XMM128 = 8
UWOP_SAVE_XMM128_FAR = 9
UWOP_PUSH_MACHFRAME = 10
# Resource types
resource_type = [
("RT_CURSOR", 1),
("RT_BITMAP", 2),
("RT_ICON", 3),
("RT_MENU", 4),
("RT_DIALOG", 5),
("RT_STRING", 6),
("RT_FONTDIR", 7),
("RT_FONT", 8),
("RT_ACCELERATOR", 9),
("RT_RCDATA", 10),
("RT_MESSAGETABLE", 11),
("RT_GROUP_CURSOR", 12),
("RT_GROUP_ICON", 14),
("RT_VERSION", 16),
("RT_DLGINCLUDE", 17),
("RT_PLUGPLAY", 19),
("RT_VXD", 20),
("RT_ANICURSOR", 21),
("RT_ANIICON", 22),
("RT_HTML", 23),
("RT_MANIFEST", 24),
]
RESOURCE_TYPE = two_way_dict(resource_type)
# Language definitions
lang = [
("LANG_NEUTRAL", 0x00),
("LANG_INVARIANT", 0x7F),
("LANG_AFRIKAANS", 0x36),
("LANG_ALBANIAN", 0x1C),
("LANG_ARABIC", 0x01),
("LANG_ARMENIAN", 0x2B),
("LANG_ASSAMESE", 0x4D),
("LANG_AZERI", 0x2C),
("LANG_BASQUE", 0x2D),
("LANG_BELARUSIAN", 0x23),
("LANG_BENGALI", 0x45),
("LANG_BULGARIAN", 0x02),
("LANG_CATALAN", 0x03),
("LANG_CHINESE", 0x04),
("LANG_CROATIAN", 0x1A),
("LANG_CZECH", 0x05),
("LANG_DANISH", 0x06),
("LANG_DIVEHI", 0x65),
("LANG_DUTCH", 0x13),
("LANG_ENGLISH", 0x09),
("LANG_ESTONIAN", 0x25),
("LANG_FAEROESE", 0x38),
("LANG_FARSI", 0x29),
("LANG_FINNISH", 0x0B),
("LANG_FRENCH", 0x0C),
("LANG_GALICIAN", 0x56),
("LANG_GEORGIAN", 0x37),
("LANG_GERMAN", 0x07),
("LANG_GREEK", 0x08),
("LANG_GUJARATI", 0x47),
("LANG_HEBREW", 0x0D),
("LANG_HINDI", 0x39),
("LANG_HUNGARIAN", 0x0E),
("LANG_ICELANDIC", 0x0F),
("LANG_INDONESIAN", 0x21),
("LANG_ITALIAN", 0x10),
("LANG_JAPANESE", 0x11),
("LANG_KANNADA", 0x4B),
("LANG_KASHMIRI", 0x60),
("LANG_KAZAK", 0x3F),
("LANG_KONKANI", 0x57),
("LANG_KOREAN", 0x12),
("LANG_KYRGYZ", 0x40),
("LANG_LATVIAN", 0x26),
("LANG_LITHUANIAN", 0x27),
("LANG_MACEDONIAN", 0x2F),
("LANG_MALAY", 0x3E),
("LANG_MALAYALAM", 0x4C),
("LANG_MANIPURI", 0x58),
("LANG_MARATHI", 0x4E),
("LANG_MONGOLIAN", 0x50),
("LANG_NEPALI", 0x61),
("LANG_NORWEGIAN", 0x14),
("LANG_ORIYA", 0x48),
("LANG_POLISH", 0x15),
("LANG_PORTUGUESE", 0x16),
("LANG_PUNJABI", 0x46),
("LANG_ROMANIAN", 0x18),
("LANG_RUSSIAN", 0x19),
("LANG_SANSKRIT", 0x4F),
("LANG_SERBIAN", 0x1A),
("LANG_SINDHI", 0x59),
("LANG_SLOVAK", 0x1B),
("LANG_SLOVENIAN", 0x24),
("LANG_SPANISH", 0x0A),
("LANG_SWAHILI", 0x41),
("LANG_SWEDISH", 0x1D),
("LANG_SYRIAC", 0x5A),
("LANG_TAMIL", 0x49),
("LANG_TATAR", 0x44),
("LANG_TELUGU", 0x4A),
("LANG_THAI", 0x1E),
("LANG_TURKISH", 0x1F),
("LANG_UKRAINIAN", 0x22),
("LANG_URDU", 0x20),
("LANG_UZBEK", 0x43),
("LANG_VIETNAMESE", 0x2A),
("LANG_GAELIC", 0x3C),
("LANG_MALTESE", 0x3A),
("LANG_MAORI", 0x28),
("LANG_RHAETO_ROMANCE", 0x17),
("LANG_SAAMI", 0x3B),
("LANG_SORBIAN", 0x2E),
("LANG_SUTU", 0x30),
("LANG_TSONGA", 0x31),
("LANG_TSWANA", 0x32),
("LANG_VENDA", 0x33),
("LANG_XHOSA", 0x34),
("LANG_ZULU", 0x35),
("LANG_ESPERANTO", 0x8F),
("LANG_WALON", 0x90),
("LANG_CORNISH", 0x91),
("LANG_WELSH", 0x92),
("LANG_BRETON", 0x93),
]
LANG = two_way_dict(lang)
# Sublanguage definitions
sublang = [
("SUBLANG_NEUTRAL", 0x00),
("SUBLANG_DEFAULT", 0x01),
("SUBLANG_SYS_DEFAULT", 0x02),
("SUBLANG_ARABIC_SAUDI_ARABIA", 0x01),
("SUBLANG_ARABIC_IRAQ", 0x02),
("SUBLANG_ARABIC_EGYPT", 0x03),
("SUBLANG_ARABIC_LIBYA", 0x04),
("SUBLANG_ARABIC_ALGERIA", 0x05),
("SUBLANG_ARABIC_MOROCCO", 0x06),
("SUBLANG_ARABIC_TUNISIA", 0x07),
("SUBLANG_ARABIC_OMAN", 0x08),
("SUBLANG_ARABIC_YEMEN", 0x09),
("SUBLANG_ARABIC_SYRIA", 0x0A),
("SUBLANG_ARABIC_JORDAN", 0x0B),
("SUBLANG_ARABIC_LEBANON", 0x0C),
("SUBLANG_ARABIC_KUWAIT", 0x0D),
("SUBLANG_ARABIC_UAE", 0x0E),
("SUBLANG_ARABIC_BAHRAIN", 0x0F),
("SUBLANG_ARABIC_QATAR", 0x10),
("SUBLANG_AZERI_LATIN", 0x01),
("SUBLANG_AZERI_CYRILLIC", 0x02),
("SUBLANG_CHINESE_TRADITIONAL", 0x01),
("SUBLANG_CHINESE_SIMPLIFIED", 0x02),
("SUBLANG_CHINESE_HONGKONG", 0x03),
("SUBLANG_CHINESE_SINGAPORE", 0x04),
("SUBLANG_CHINESE_MACAU", 0x05),
("SUBLANG_DUTCH", 0x01),
("SUBLANG_DUTCH_BELGIAN", 0x02),
("SUBLANG_ENGLISH_US", 0x01),
("SUBLANG_ENGLISH_UK", 0x02),
("SUBLANG_ENGLISH_AUS", 0x03),
("SUBLANG_ENGLISH_CAN", 0x04),
("SUBLANG_ENGLISH_NZ", 0x05),
("SUBLANG_ENGLISH_EIRE", 0x06),
("SUBLANG_ENGLISH_SOUTH_AFRICA", 0x07),
("SUBLANG_ENGLISH_JAMAICA", 0x08),
("SUBLANG_ENGLISH_CARIBBEAN", 0x09),
("SUBLANG_ENGLISH_BELIZE", 0x0A),
("SUBLANG_ENGLISH_TRINIDAD", 0x0B),
("SUBLANG_ENGLISH_ZIMBABWE", 0x0C),
("SUBLANG_ENGLISH_PHILIPPINES", 0x0D),
("SUBLANG_FRENCH", 0x01),
("SUBLANG_FRENCH_BELGIAN", 0x02),
("SUBLANG_FRENCH_CANADIAN", 0x03),
("SUBLANG_FRENCH_SWISS", 0x04),
("SUBLANG_FRENCH_LUXEMBOURG", 0x05),
("SUBLANG_FRENCH_MONACO", 0x06),
("SUBLANG_GERMAN", 0x01),
("SUBLANG_GERMAN_SWISS", 0x02),
("SUBLANG_GERMAN_AUSTRIAN", 0x03),
("SUBLANG_GERMAN_LUXEMBOURG", 0x04),
("SUBLANG_GERMAN_LIECHTENSTEIN", 0x05),
("SUBLANG_ITALIAN", 0x01),
("SUBLANG_ITALIAN_SWISS", 0x02),
("SUBLANG_KASHMIRI_SASIA", 0x02),
("SUBLANG_KASHMIRI_INDIA", 0x02),
("SUBLANG_KOREAN", 0x01),
("SUBLANG_LITHUANIAN", 0x01),
("SUBLANG_MALAY_MALAYSIA", 0x01),
("SUBLANG_MALAY_BRUNEI_DARUSSALAM", 0x02),
("SUBLANG_NEPALI_INDIA", 0x02),
("SUBLANG_NORWEGIAN_BOKMAL", 0x01),
("SUBLANG_NORWEGIAN_NYNORSK", 0x02),
("SUBLANG_PORTUGUESE", 0x02),
("SUBLANG_PORTUGUESE_BRAZILIAN", 0x01),
("SUBLANG_SERBIAN_LATIN", 0x02),
("SUBLANG_SERBIAN_CYRILLIC", 0x03),
("SUBLANG_SPANISH", 0x01),
("SUBLANG_SPANISH_MEXICAN", 0x02),
("SUBLANG_SPANISH_MODERN", 0x03),
("SUBLANG_SPANISH_GUATEMALA", 0x04),
("SUBLANG_SPANISH_COSTA_RICA", 0x05),
("SUBLANG_SPANISH_PANAMA", 0x06),
("SUBLANG_SPANISH_DOMINICAN_REPUBLIC", 0x07),
("SUBLANG_SPANISH_VENEZUELA", 0x08),
("SUBLANG_SPANISH_COLOMBIA", 0x09),
("SUBLANG_SPANISH_PERU", 0x0A),
("SUBLANG_SPANISH_ARGENTINA", 0x0B),
("SUBLANG_SPANISH_ECUADOR", 0x0C),
("SUBLANG_SPANISH_CHILE", 0x0D),
("SUBLANG_SPANISH_URUGUAY", 0x0E),
("SUBLANG_SPANISH_PARAGUAY", 0x0F),
("SUBLANG_SPANISH_BOLIVIA", 0x10),
("SUBLANG_SPANISH_EL_SALVADOR", 0x11),
("SUBLANG_SPANISH_HONDURAS", 0x12),
("SUBLANG_SPANISH_NICARAGUA", 0x13),
("SUBLANG_SPANISH_PUERTO_RICO", 0x14),
("SUBLANG_SWEDISH", 0x01),
("SUBLANG_SWEDISH_FINLAND", 0x02),
("SUBLANG_URDU_PAKISTAN", 0x01),
("SUBLANG_URDU_INDIA", 0x02),
("SUBLANG_UZBEK_LATIN", 0x01),
("SUBLANG_UZBEK_CYRILLIC", 0x02),
("SUBLANG_DUTCH_SURINAM", 0x03),
("SUBLANG_ROMANIAN", 0x01),
("SUBLANG_ROMANIAN_MOLDAVIA", 0x02),
("SUBLANG_RUSSIAN", 0x01),
("SUBLANG_RUSSIAN_MOLDAVIA", 0x02),
("SUBLANG_CROATIAN", 0x01),
("SUBLANG_LITHUANIAN_CLASSIC", 0x02),
("SUBLANG_GAELIC", 0x01),
("SUBLANG_GAELIC_SCOTTISH", 0x02),
("SUBLANG_GAELIC_MANX", 0x03),
]
SUBLANG = two_way_dict(sublang)
# Initialize the dictionary with all the name->value pairs
SUBLANG = dict(sublang)
# Now add all the value->name information, handling duplicates appropriately
for sublang_name, sublang_value in sublang:
if sublang_value in SUBLANG:
SUBLANG[sublang_value].append(sublang_name)
else:
SUBLANG[sublang_value] = [sublang_name]
# Resolve a sublang name given the main lang name
#
def get_sublang_name_for_lang(lang_value, sublang_value):
lang_name = LANG.get(lang_value, "*unknown*")
for sublang_name in SUBLANG.get(sublang_value, []):
# if the main language is a substring of sublang's name, then
# return that
if lang_name in sublang_name:
return sublang_name
# otherwise return the first sublang name
return SUBLANG.get(sublang_value, ["*unknown*"])[0]
# Ange Albertini's code to process resources' strings
#
def parse_strings(data, counter, l):
i = 0
error_count = 0
while i < len(data):
data_slice = data[i : i + 2]
if len(data_slice) < 2:
break
len_ = struct.unpack("<h", data_slice)[0]
i += 2
if len_ != 0 and 0 <= len_ * 2 <= len(data):
try:
l[counter] = data[i : i + len_ * 2].decode("utf-16le")
except UnicodeDecodeError:
error_count += 1
if error_count >= 3:
break
i += len_ * 2
counter += 1
def retrieve_flags(flag_dict, flag_filter):
"""Read the flags from a dictionary and return them in a usable form.
Will return a list of (flag, value) for all flags in "flag_dict"
matching the filter "flag_filter".
"""
return [
(flag, flag_dict[flag])
for flag in flag_dict.keys()
if isinstance(flag, (str, bytes)) and flag.startswith(flag_filter)
]
def set_flags(obj, flag_field, flags):
"""Will process the flags and set attributes in the object accordingly.
The object "obj" will gain attributes named after the flags provided in
"flags" and valued True/False, matching the results of applying each
flag value from "flags" to flag_field.
"""
for flag, value in flags:
if value & flag_field:
obj.__dict__[flag] = True
else:
obj.__dict__[flag] = False
def power_of_two(val):
return val != 0 and (val & (val - 1)) == 0
class AddressSet(set):
def __init__(self):
super().__init__()
self.min = None
self.max = None
def add(self, value):
super().add(value)
self.min = value if self.min is None else min(self.min, value)
self.max = value if self.max is None else max(self.max, value)
def diff(self):
return 0 if self.min is None or self.max is None else self.max - self.min
class UnicodeStringWrapperPostProcessor:
"""This class attempts to help the process of identifying strings
that might be plain Unicode or Pascal. A list of strings will be
wrapped on it with the hope the overlappings will help make the
decision about their type."""
def __init__(self, pe, rva_ptr):
self.pe = pe
self.rva_ptr = rva_ptr
self.string = None
def get_rva(self):
"""Get the RVA of the string."""
return self.rva_ptr
def __str__(self):
"""Return the escaped UTF-8 representation of the string."""
return self.decode("utf-8", "backslashreplace_")
def decode(self, *args):
if not self.string:
return ""
return self.string.decode(*args)
def invalidate(self):
"""Make this instance None, to express it's no known string type."""
self = None
def render_pascal_16(self):
try:
self.string = self.pe.get_string_u_at_rva(
self.rva_ptr + 2, max_length=self.get_pascal_16_length()
)
except PEFormatError:
self.pe.get_warnings().append(
"Failed rendering pascal string, "
"attempting to read from RVA 0x{0:x}".format(self.rva_ptr + 2)
)
def get_pascal_16_length(self):
return self.__get_word_value_at_rva(self.rva_ptr)
def __get_word_value_at_rva(self, rva):
try:
data = self.pe.get_data(rva, 2)
except PEFormatError:
return False
if len(data) < 2:
return False
return struct.unpack("<H", data)[0]
def ask_unicode_16(self, next_rva_ptr):
"""The next RVA is taken to be the one immediately following this one.
Such RVA could indicate the natural end of the string and will be checked
to see if there's a Unicode NULL character there.
"""
if self.__get_word_value_at_rva(next_rva_ptr - 2) == 0:
self.length = next_rva_ptr - self.rva_ptr
return True
return False
def render_unicode_16(self):
try:
self.string = self.pe.get_string_u_at_rva(self.rva_ptr)
except PEFormatError:
self.pe.get_warnings().append(
"Failed rendering unicode string, "
"attempting to read from RVA 0x{0:x}".format(self.rva_ptr)
)
class PEFormatError(Exception):
"""Generic PE format error exception."""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Dump:
"""Convenience class for dumping the PE information."""
def __init__(self):
self.text = []
def add_lines(self, txt, indent=0):
"""Adds a list of lines.
The list can be indented with the optional argument 'indent'.
"""
for line in txt:
self.add_line(line, indent)
def add_line(self, txt, indent=0):
"""Adds a line.
The line can be indented with the optional argument 'indent'.
"""
self.add(txt + "\n", indent)
def add(self, txt, indent=0):
"""Adds some text, no newline will be appended.
The text can be indented with the optional argument 'indent'.
"""
self.text.append("{0}{1}".format(" " * indent, txt))
def add_header(self, txt):
"""Adds a header element."""
self.add_line("{0}{1}{0}\n".format("-" * 10, txt))
def add_newline(self):
"""Adds a newline."""
self.text.append("\n")
def get_text(self):
"""Get the text in its current state."""
return "".join("{0}".format(b) for b in self.text)
STRUCT_SIZEOF_TYPES = {
"x": 1,
"c": 1,
"b": 1,
"B": 1,
"h": 2,
"H": 2,
"i": 4,
"I": 4,
"l": 4,
"L": 4,
"f": 4,
"q": 8,
"Q": 8,
"d": 8,
"s": 1,
}
@lru_cache(maxsize=2048)
def sizeof_type(t):
count = 1
_t = t
if t[0] in string.digits:
# extract the count
count = int("".join([d for d in t if d in string.digits]))
_t = "".join([d for d in t if d not in string.digits])
return STRUCT_SIZEOF_TYPES[_t] * count
@lru_cache(maxsize=2048, copy=True)
def set_format(format):
__format_str__ = "<"
__unpacked_data_elms__ = []
__field_offsets__ = {}
__keys__ = []
__format_length__ = 0
offset = 0
for elm in format:
if "," in elm:
elm_type, elm_name = elm.split(",", 1)
__format_str__ += elm_type
__unpacked_data_elms__.append(None)
elm_names = elm_name.split(",")
names = []
for elm_name in elm_names:
if elm_name in __keys__:
search_list = [x[: len(elm_name)] for x in __keys__]
occ_count = search_list.count(elm_name)
elm_name = "{0}_{1:d}".format(elm_name, occ_count)
names.append(elm_name)
__field_offsets__[elm_name] = offset
offset += sizeof_type(elm_type)
# Some PE header structures have unions on them, so a certain
# value might have different names, so each key has a list of
# all the possible members referring to the data.
__keys__.append(names)
__format_length__ = struct.calcsize(__format_str__)
return (
__format_str__,
__unpacked_data_elms__,
__field_offsets__,
__keys__,
__format_length__,
)
class Structure:
"""Prepare structure object to extract members from data.
Format is a list containing definitions for the elements
of the structure.
"""
def __init__(self, format, name=None, file_offset=None):
# Format is forced little endian, for big endian non Intel platforms
self.__format_str__ = "<"
self.__keys__ = []
self.__format_length__ = 0
self.__field_offsets__ = {}
self.__unpacked_data_elms__ = []
d = format[1]
# need a tuple to be hashable in set_format using lru cache
if not isinstance(d, tuple):
d = tuple(d)
(
self.__format_str__,
self.__unpacked_data_elms__,
self.__field_offsets__,
self.__keys__,
self.__format_length__,
) = set_format(d)
self.__all_zeroes__ = False
self.__file_offset__ = file_offset
if name:
self.name = name
else:
self.name = format[0]
def __get_format__(self) -> str:
return self.__format_str__
def get_field_absolute_offset(self, field_name):
"""Return the offset within the field for the requested field in the structure."""
return self.__file_offset__ + self.__field_offsets__[field_name]
def get_field_relative_offset(self, field_name):
"""Return the offset within the structure for the requested field."""
return self.__field_offsets__[field_name]
def get_file_offset(self):
return self.__file_offset__
def set_file_offset(self, offset):
self.__file_offset__ = offset
def all_zeroes(self):
"""Returns true is the unpacked data is all zeros."""
return self.__all_zeroes__
def sizeof(self):