-
Notifications
You must be signed in to change notification settings - Fork 1
/
downgrade_elf.py
1765 lines (1318 loc) · 57 KB
/
downgrade_elf.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/env python2.7
# (c) flatz
import string
import sys, os, struct
import argparse
import shutil
import struct
import distutils.dir_util
#
# #
# # #
# # # # downgrade elf
# # #
# #
#
from hexdump import hexdump
from pprint import pprint
import math
def align_up(x, alignment):
return (x + (alignment - 1)) & ~(alignment - 1)
def align_down(x, alignment):
return x & ~(alignment - 1)
def is_intervals_overlap(p1, p2):
return p1[0] <= p2[1] and p1[1] <= p2[0]
def check_file_magic(f, expected_magic):
old_offset = f.tell()
try:
magic = f.read(len(expected_magic))
except:
return False
finally:
f.seek(old_offset)
return magic == expected_magic
def check_sdk_version(sdk_version):
if len(sdk_version) != 10:
return False
parts = sdk_version.split('.', 2)
if len(parts) != 3:
return False
try:
lengths = [2, 3, 3]
for i, n in enumerate(parts):
if len(n) != lengths[i]:
return False
n = int(n, 10)
except:
return False
return True
# SDK version have 001 in "patch" field
def parse_sdk_version(sdk_version):
major, minor, patch = sdk_version >> 24, (sdk_version >> 12) & 0xFFF, sdk_version & 0xFFF
return major, minor, patch
def stringify_sdk_version(major, minor, patch):
return '{0:02x}.{1:03x}.{2:03x}'.format(major, minor, patch)
def unstringify_sdk_version(sdk_version):
major, minor, patch = map(lambda x: int(x, 16), sdk_version.split('.', 2))
return major, minor, patch
def build_sdk_version(major, minor, patch):
sdk_version = ((major & 0xFF) << 24) | ((minor & 0xFFF) << 12) | (patch & 0xFFF)
return sdk_version
# Tag for SCE string table size
DT_SCE_JMPREL = 0x61000029
DT_SCE_PLTRELSZ = 0x6100002D
DT_SCE_RELASZ = 0x61000031
DT_SCE_SYMTAB = 0x61000039
DT_SCE_SYMENT = 0x6100003B
DT_SCE_HASHSZ = 0x6100003D
DT_SCE_SYMTABSZ = 0x6100003F
ENUM_RELA_TYPES = dict(
R_AMD64_NONE = 0x00000000,
R_AMD64_64 = 0x00000001,
R_AMD64_PC32 = 0x00000002,
R_AMD64_GOT32 = 0x00000003,
R_AMD64_PLT32 = 0x00000004,
R_AMD64_COPY = 0x00000005,
R_AMD64_GLOB_DAT = 0x00000006,
R_AMD64_JUMP_SLOT = 0x00000007,
R_AMD64_RELATIVE = 0x00000008,
R_AMD64_GOTPCREL = 0x00000009,
R_AMD64_32 = 0x0000000A,
R_AMD64_32S = 0x0000000B,
R_AMD64_16 = 0x0000000C,
R_AMD64_PC16 = 0x0000000D,
R_AMD64_8 = 0x0000000E,
R_AMD64_PC8 = 0x0000000F,
R_AMD64_DTPMOD64 = 0x00000010,
R_AMD64_DTPOFF64 = 0x00000011,
R_AMD64_TPOFF64 = 0x00000012,
R_AMD64_TLSGD = 0x00000013,
R_AMD64_TLSLD = 0x00000014,
R_AMD64_DTPOFF32 = 0x00000015,
R_AMD64_GOTTPOFF = 0x00000016,
R_AMD64_TPOFF32 = 0x00000017,
R_AMD64_PC64 = 0x00000018,
R_AMD64_GOTOFF64 = 0x00000019,
R_AMD64_GOTPC32 = 0x0000001A,
)
ENUM_SYMTAB_BINDS = dict(
STB_LOCAL = 0x00000000,
STB_GLOBAL = 0x00000001,
STB_WEAK = 0x00000002,
)
ENUM_SYMTAB_TYPES = dict(
STT_NOTYPE = 0x00000000,
STT_OBJECT = 0x00000001,
STT_FUNC = 0x00000002,
STT_SECTION = 0x00000003,
STT_FILE = 0x00000004,
STT_COMMON = 0x00000005,
STT_TLS = 0x00000006,
)
class ElfProgramHeader(object):
FMT = '<2I6Q'
PT_NULL = 0x0
PT_LOAD = 0x1
PT_DYNAMIC = 0x2
PT_INTERP = 0x3
PT_TLS = 0x7
PT_SCE_DYNLIBDATA = 0x61000000
PT_SCE_PROCPARAM = 0x61000001
PT_SCE_MODULE_PARAM = 0x61000002
PT_SCE_RELRO = 0x61000010
PT_SCE_COMMENT = 0x6FFFFF00
PT_SCE_VERSION = 0x6FFFFF01
PT_GNU_EH_FRAME = 0x6474E550
PF_X = 0x1
PF_W = 0x2
PF_R = 0x4
PF_RX = PF_R | PF_X
PF_RW = PF_R | PF_W
def __init__(self):
self.type = None
self.offset = None
self.vaddr = None
self.paddr = None
self.file_size = None
self.mem_size = None
self.flags = None
self.align = None
def load(self, f):
data = f.read(struct.calcsize(ElfProgramHeader.FMT))
if len(data) != struct.calcsize(ElfProgramHeader.FMT):
return False
self.type, self.flags, self.offset, self.vaddr, self.paddr, self.file_size, self.mem_size, self.align = struct.unpack(ElfProgramHeader.FMT, data)
return True
def save(self, f):
data = struct.pack(ElfProgramHeader.FMT, self.type, self.flags, self.offset, self.vaddr, self.paddr, self.file_size, self.mem_size, self.align)
if len(data) != struct.calcsize(ElfProgramHeader.FMT):
return False
if args.dry_run is False:
f.write(data)
return True
class ElfSectionHeader(object):
FMT = '<2I4Q2I2Q'
def __init__(self, fmt):
self.name = None
self.type = None
self.flags = None
self.addr = None
self.offset = None
self.size = None
self.link = None
self.info = None
self.align = None
self.entry_size = None
def load(self, f):
data = f.read(struct.calcsize(ElfProgramHeader.FMT))
if len(data) != struct.calcsize(ElfProgramHeader.FMT):
return False
self.name, self.type, self.flags, self.addr, self.offset, self.size, self.link, self.info, self.align, self.entry_size = struct.unpack(ElfProgramHeader.FMT, data)
return True
def save(self, f):
data = struct.pack(ElfProgramHeader.FMT, self.name, self.type, self.flags, self.addr, self.offset, self.size, self.link, self.info, self.align, self.entry_size)
if len(data) != struct.calcsize(ElfProgramHeader.FMT):
return False
if args.dry_run is False:
f.write(data)
return True
class ElfFile(object):
MAGIC = '\x7FELF'
FMT = '<4s5B6xB2HI3QI6H'
CLASS_NONE = 0
CLASS_64 = 2
DATA_NONE = 0
DATA_LSB = 1
VERSION_CURRENT = 1
MACHINE_X86_64 = 0x3E
TYPE_EXEC = 0x2
TYPE_SCE_EXEC = 0xFE00
TYPE_SCE_EXEC_ASLR = 0xFE10
TYPE_SCE_DYNAMIC = 0xFE18
def __init__(self):
self.magic = None
self.cls = None
self.encoding = None
self.version = None
self.os_abi = None
self.abi_version = None
self.nident_size = None
self.type = None
self.machine = None
self.version = None
self.entry = None
self.phdr_offset = None
self.shdr_offset = None
self.flags = None
self.ehdr_size = None
self.phdr_size = None
self.phdr_count = None
self.shdr_size = None
self.shdr_count = None
self.shdr_strtable_idx = None
self.phdrs = None
self.shdrs = None
def check(self, f):
old_offset = f.tell()
try:
result = check_file_magic(f, ElfFile.MAGIC)
except:
return False
finally:
f.seek(old_offset)
return result
def load(self, f):
data = f.read(struct.calcsize(ElfFile.FMT))
if len(data) != struct.calcsize(ElfFile.FMT):
print('error: unable to read header')
return False
self.magic, self.cls, self.encoding, self.legacy_version, self.os_abi, self.abi_version, self.nident_size, self.type, self.machine, self.version, self.entry, self.phdr_offset, self.shdr_offset, self.flags, self.ehdr_size, self.phdr_size, self.phdr_count, self.shdr_size, self.shdr_count, self.shdr_strtable_idx = struct.unpack(ElfFile.FMT, data)
if self.magic != ElfFile.MAGIC:
print('error: invalid magic: 0x{0:08X}'.format(self.magic))
return False
if self.encoding != ElfFile.DATA_LSB:
print('error: unsupported encoding: 0x{0:02X}'.format(self.encoding))
return False
if self.legacy_version != ElfFile.VERSION_CURRENT:
raise Exception('Unsupported version: 0x{0:x}'.format(self.version))
if self.cls != ElfFile.CLASS_64:
print('error: unsupported class: 0x{0:02X}'.format(self.cls))
return False
if self.type not in [ElfFile.TYPE_SCE_EXEC, ElfFile.TYPE_SCE_EXEC_ASLR, ElfFile.TYPE_SCE_DYNAMIC]:
print('error: unsupported type: 0x{0:04X}'.format(self.type))
return False
if self.machine != ElfFile.MACHINE_X86_64:
print('error: unexpected machine: 0x{0:X}'.format(self.machine))
return False
if self.ehdr_size != struct.calcsize(ElfFile.FMT):
print('error: invalid elf header size: 0x{0:X}'.format(self.ehdr_size))
return False
if self.phdr_size > 0 and self.phdr_size != struct.calcsize(ElfProgramHeader.FMT):
print('error: invalid program header size: 0x{0:X}'.format(self.phdr_size))
return False
if self.shdr_size > 0 and self.shdr_size != struct.calcsize(ElfSectionHeader.FMT):
print('error: invalid section header size: 0x{0:X}'.format(self.shdr_size))
return False
self.phdrs = []
for i in xrange(self.phdr_count):
phdr = ElfProgramHeader()
f.seek(self.phdr_offset + i * self.phdr_size)
if not phdr.load(f):
print('error: unable to load program header #{0}'.format(i))
return False
self.phdrs.append(phdr)
self.shdrs = []
#if self.shdr_size > 0:
# for i in xrange(self.shdr_count):
# shdr = ElfSectionHeader()
# f.seek(self.shdr_offset + i * self.shdr_size)
# if not shdr.load(f):
# print('error: unable to load section header #{0}'.format(i))
# return False
# self.shdrs.append(shdr)
return True
def save_hdr(self, f):
data = struct.pack(ElfFile.FMT, self.magic, self.cls, self.encoding, self.legacy_version, self.os_abi, self.abi_version, self.nident_size, self.type, self.machine, self.version, self.entry, self.phdr_offset, self.shdr_offset, self.flags, self.ehdr_size, self.phdr_size, self.phdr_count, self.shdr_size, self.shdr_count, self.shdr_strtable_idx)
if len(data) != struct.calcsize(ElfFile.FMT):
print('error: unable to save header')
return False
if args.dry_run is False:
f.write(data)
for i, phdr in enumerate(self.phdrs):
f.seek(self.phdr_offset + i * self.phdr_size)
if not phdr.save(f):
print('error: unable to save program header #{0}'.format(i))
return False
for i, shdr in enumerate(self.shdrs):
f.seek(self.shdr_offset + i * self.shdr_size)
if not shdr.save(f):
print('error: unable to save section header #{0}'.format(i))
return False
return True
def get_phdr_by_type(self, type):
for i, phdr in enumerate(elf.phdrs):
if phdr.type == type:
return phdr
return None
class MyParser(argparse.ArgumentParser):
def error(self, message):
self.print_help()
sys.stderr.write('\nerror: {0}\n'.format(message))
sys.exit(2)
def CheckHexText(source, length, add_0x): # returns the hex text
source_hex = str(hex(source)[2:])
source_hex_length = len(source_hex)
source_hex_index = None
source_hex_cell = None
for source_hex_index in range(0, source_hex_length):
source_hex_cell = source_hex[source_hex_index]
if (source_hex_cell in string.hexdigits) is False:
source_hex = source_hex[:source_hex_index]
break
result = str(source_hex.zfill(length))
if add_0x is True:
result = "0x" + result
return result
def add_replacement(old_value, new_value, struct_fmt):
result = None
replacement_old_value = old_value
replacement_old_value_bytes = struct.pack(struct_fmt, old_value)
replacement_new_value = new_value
replacement_new_value_bytes = struct.pack(struct_fmt, new_value)
replacement_value_size = struct.calcsize(struct_fmt)
replacement_min_segments_index = 0
replacement = (
[
replacement_old_value
, replacement_old_value_bytes
, replacement_new_value
, replacement_new_value_bytes
, replacement_value_size
, replacement_min_segments_index
]
)
result = replacement
return result
def remove_replacements_duplicates(replacements):
result = None
current_result = None
replacement = None
replacement_old_value = None
# replacement_old_value_bytes = None
# replacement_new_value = None
# replacement_new_value_bytes = None
# replacement_value_size = None
# replacement_min_segments_index = None
replacements_old_value_list = []
for replacement in replacements:
replacement_old_value = replacement[0]
# replacement_old_value_bytes = replacement[1]
# replacement_new_value = replacementA[2]
# replacement_new_value_bytes = replacement[3]
# replacement_value_size = replacement[4]
# replacement_min_segments_index = replacement[5]
if replacement_old_value not in replacements_old_value_list:
if current_result is None:
current_result = []
current_result.append(replacement)
replacements_old_value_list.append(replacement_old_value)
result = current_result
return result
def print_patch_memhole_references_help():
print("patch memhole references options:")
print(
"00x:" + '\t' + "0 - don't patch memory hole segments bytes"
+ "\n" + '\t' + "1 - patch memory hole segments bytes"
+ "\n" + "0x0:" + '\t' + "0 - don't patch memory hole segments bytes that the bits from their end up to the replacement value bytes amount aren't 0"
+ "\n" + '\t' + "1 - patch memory hole segments bytes that the bits from their end up to the replacement value bytes amount aren't 0"
+ "\n" + "x00:" + '\t' + "0 - don't patch memory hole segments bytes with addresses that aren't a multiply of 8"
+ "\n" + '\t' + "1 - patch memory hole segments bytes with addresses that aren't a multiply of 8"
)
Debug = False
parser = MyParser(description='elf downgrader tool')
if Debug is False:
parser.add_argument('--input', required=False, type=str, help='old file')
parser.add_argument('--output', required=False, default="", type=str, help='new file')
parser.add_argument('--dry-run', required=False, default=False, action='store_true', help='if inserted then nothing will be written to the output file')
parser.add_argument('--verbose', required=False, default=False, action='store_true', help='detailed printing')
parser.add_argument('--overwrite', required=False, default=False, action='store_true')
parser.add_argument('--sdk-version', required=False, default="0", type=str, help='wanted sdk version, leave empty for no patching')# 05.050.001 is the one usually used when converting sdk version
parser.add_argument('--add-modded-to-output', required=False, default=False, action='store_true', help='if true then adds _modded to the output file name')
parser.add_argument('--patch-memhole', required=False, default="1", type=str, help="0 - don't patch, 1 - extend the memory size of the segment to fill the memhole, 2 - move the segments after the memhole backwards")
parser.add_argument('--patch-memhole-references', required=False, default="001", type=str, help=("use --patch-memhole-references-help in order to see usage"))
parser.add_argument('--patch-memhole-references-help', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-program-headers', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-dynamic-section', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-relocation-section', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-symbol-table', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-elf-header', required=False, default=False, action='store_true')
if len(sys.argv) == 1:
parser.print_usage()
sys.exit(1)
else:
parser.add_argument('--input', required=False, default="C:/somefolder/somefile.elf", type=str, help='old file')
parser.add_argument('--output', required=False, default="", type=str, help='new file')
parser.add_argument('--dry-run', required=False, default=False, action='store_true', help='if inserted then nothing will be written to the output file')
parser.add_argument('--verbose', required=False, default=False, action='store_true', help='detailed printing')
parser.add_argument('--overwrite', required=False, default=False, action='store_true')
parser.add_argument('--sdk-version', required=False, default="0", type=str, help='wanted sdk version, leave empty for no patching')# 05.050.001 is the one usually used when converting sdk version
parser.add_argument('--add-modded-to-output', required=False, default=False, action='store_true', help='if true then adds _modded to the output file name')
parser.add_argument('--patch-memhole', required=False, default="1", type=str, help="0 - don't patch, 1 - extend the memory size of the segment to fill the memhole, 2 - move the segments after the memhole backwards")
parser.add_argument('--patch-memhole-references', required=False, default="001", type=str, help=("use --patch-memhole-references-help in order to see usage"))
parser.add_argument('--patch-memhole-references-help', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-program-headers', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-dynamic-section', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-relocation-section', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-symbol-table', required=False, default=False, action='store_true')
parser.add_argument('--not-patch-elf-header', required=False, default=False, action='store_true')
args = parser.parse_args()
if args.patch_memhole_references_help is True:
print_patch_memhole_references_help()
sys.exit(1)
input_file_path = os.path.abspath(args.input).replace('\\','/')
if not os.path.isfile(input_file_path):
parser.error('invalid input file: {0}'.format(input_file_path))
input_folder_path = os.path.dirname(input_file_path).replace('\\','/')
if input_folder_path[len(input_folder_path) - 1] == '/':
input_folder_path = input_folder_path[:-1]
if args.output == "":
input_file_name = os.path.basename(input_file_path)
input_file_name_length = len(input_file_name)
input_file_name_splitted = input_file_name.split(".")
input_file_name_splitted_amount = len(input_file_name_splitted)
input_file_name_extension = input_file_name_splitted[input_file_name_splitted_amount - 1]
input_file_name_extension_length = len(input_file_name_extension)
input_file_name_without_extension = input_file_name[:input_file_name_length - input_file_name_extension_length - 1]
output_file_name_without_extension = input_file_name_without_extension
if args.add_modded_to_output is True:
output_file_name_without_extension += "_modded"
output_file_name = output_file_name_without_extension + '.' + input_file_name_extension
if args.overwrite is True:
output_folder_path = input_folder_path + "/backup"
output_file_path = output_folder_path + "/" + output_file_name
else:
output_folder_path = input_folder_path
if args.add_modded_to_output is False:
output_folder_path += "/output"
output_file_path = output_folder_path + "/" + output_file_name
else:
output_file_path = os.path.abspath(args.output).replace('\\','/')
output_folder_path = os.path.dirname(output_file_path).replace('\\','/')
if args.dry_run is False:
distutils.dir_util.mkpath(output_folder_path)
if os.path.exists(output_file_path) and not os.path.isfile(output_file_path):
parser.error('invalid output file: {0}'.format(output_file_path))
if args.dry_run is False:
shutil.copyfile(input_file_path, output_file_path)
if args.overwrite is True:
output_file_path = input_file_path
if args.dry_run is True:
output_file_path_fixed = input_file_path
else:
output_file_path_fixed = output_file_path
print(
"Input:" + ' ' + input_file_path + "\n"
+ "Output:" + ' ' + output_file_path + "\n"
+ "Dry Run:" + ' ' + ("True" if args.dry_run is True else "False") + "\n"
+ "Verbose:" + ' ' + ("True" if args.verbose is True else "False") + "\n"
+ "Overwrite:" + ' ' + ("True" if args.overwrite is True else "False") + "\n"
+ "Sdk Version:" + ' ' + ("Not Patching" if args.sdk_version == "0" else args.sdk_version) + "\n"
+ "Add _modded to Output:" + ' ' + ("True" if args.add_modded_to_output is True else "False") + "\n"
+ "Patch Memory Hole:" + ' ' + args.patch_memhole + "\n"
+ "Patch Memory Hole References:" + ' ' + args.patch_memhole_references + "\n"
+ "Patch Memory Hole References Help:" + ' ' + ("True" if args.patch_memhole_references_help is True else "False") + "\n"
+ "Patch Program Headers:" + ' ' + ("False" if args.not_patch_program_headers is True else "True") + "\n"
+ "Patch Dynamic Section:" + ' ' + ("False" if args.not_patch_dynamic_section is True else "True") + "\n"
+ "Patch Relocation Section:" + ' ' + ("False" if args.not_patch_relocation_section is True else "True") + "\n"
+ "Patch Symbol Table:" + ' ' + ("False" if args.not_patch_symbol_table is True else "True") + "\n"
+ "Patch Elf Header:" + ' ' + ("False" if args.not_patch_elf_header is True else "True")
)
print("")
print('processing elf file: {0}'.format(output_file_path))
with open(output_file_path_fixed, 'r+b') as f:
elf = ElfFile()
Headers = None
Fields = None
FieldsIndex = None
AddressesLength = 8#16
MemorySizeLength = 8#16
SymbolsSizeLength = 4
SymbolsLength = 8
TagsLength = 8
TypesLength = 8
ValuesLength = 8#16
struct_fmt = None
struct_size = None
method_found = False
error_found = False
has_changes = False
selfutil_detected = False
if not elf.check(f):
print('error: invalid elf file format')
sys.exit(1)
if not elf.load(f):
print('error: unable to load elf file')
sys.exit(1)
#
# Patching proc/module param structure.
#
if elf.type in [ElfFile.TYPE_SCE_EXEC, ElfFile.TYPE_SCE_EXEC_ASLR]:
needed_type = ElfProgramHeader.PT_SCE_PROCPARAM
param_magic = 'ORBI'
print("")
print('executable file detected')
elif elf.type == ElfFile.TYPE_SCE_DYNAMIC:
needed_type = ElfProgramHeader.PT_SCE_MODULE_PARAM
param_magic = '\xBF\xF4\x13\x3C'
print("")
print('module file detected')
else:
print('error: unsupported elf type')
sys.exit(1)
if args.sdk_version == "0":
new_sdk_version = 0
else:
major, minor, patch = unstringify_sdk_version(args.sdk_version)
new_sdk_version = build_sdk_version(major, minor, patch)
new_sdk_version_str = stringify_sdk_version(major, minor, patch)
print('wanted sdk version: {0}'.format(new_sdk_version_str))
print("")
print('searching for {0} param segment'.format('proc' if needed_type == ElfProgramHeader.PT_SCE_PROCPARAM else 'module'))
phdr = elf.get_phdr_by_type(needed_type)
if phdr is not None:
print('found param segment, parsing param structure')
struct_fmt = '<I'
f.seek(phdr.offset)
data = f.read(phdr.file_size)
if len(data) != phdr.file_size:
print('error: insufficient data read')
sys.exit(1)
param_size, = struct.unpack(struct_fmt, data[0x0:0x4])
if param_size < 0x14:
print('error: param structure is too small')
sys.exit(1)
data = data[:param_size]
if data[0x8:0xC] != param_magic:
print('error: unexpected param structure format')
sys.exit(1)
old_sdk_version, = struct.unpack(struct_fmt, data[0x10:0x14])
major, minor, patch = parse_sdk_version(old_sdk_version)
old_sdk_version_str = stringify_sdk_version(major, minor, patch)
print('sdk version: {0}'.format(old_sdk_version_str))
if old_sdk_version > new_sdk_version:
print("")
print('patching param structure')
if args.dry_run is False:
f.seek(phdr.offset + 0x10)
f.write(struct.pack(struct_fmt, new_sdk_version))
print('patched param structure')
print('parsed param structure')
else:
print('warning: param segment not found (elf from old sdk?)')
#
# Removing memory holes in PHDRs.
# Prevents error on old kernel versions: uncountigous RELRO and DATA segments
#
if new_sdk_version < 0x06000000: # less than 6.00 fw
segments = []
segments_length = None
segments_index = 1
segments_indexA = None
segments_indexB = None
segment = None
previous_segment = None
next_segment = None
dynamicPH = None
dynlibDataPH = None
DynamicTableEntriesAmount = None
DynamicTableEntriesIndex = None
DynamicTable_addr = None
RelaTableSize = 0
RelaTableEntriesAmount = None
RelaTableEntriesIndex = None
RelaTable_addr = None
SymTableSize = 0
SymTableEntriesAmount = None
SymTableEntriesIndex = None
SymTable_addr = None
FirstSegment_VirtualAddress = None
SegmentBeforeMemHole_VirtualAddress = None
SegmentAfterMemHole_Unmapped_VirtualAddress = None
SegmentAfterMemHole_Mapped_VirtualAddress = None
SegmentAfterMemHole_FileSize = None
SegmentAfterMemHole_MemorySize = None
paddr_mem_size = None
paddr_file_size = None
paddr_start = None
paddr_end = None
paddr_diff = None
vaddr_mem_size = None# ida shows virtual address
vaddr_file_size = None
vaddr_start = None
vaddr_end = None
vaddr_diff = None
old_mem_size = None
new_mem_size = None
old_paddr = None
old_vaddr = None
new_paddr = None
new_vaddr = None
mem_size_aligned = None
faddr = None
old_struct_data = None
old_struct_unpacked = None
new_struct_data_list = None
new_struct_data = None
new_struct_unpacked = None
d_tag = None
old_d_val = None
new_d_val = None
d_val_replacements = None
d_val_replacements_use = True # suggested not to use, doesn't appear to be necessary
old_r_addr = None
r_info = None
r_sym = None
old_r_addend = None
new_r_addr = None
new_r_addend = None
r_addr_replacements = None
r_addr_replacements_use = True # suggested not to use, not tested enough, but appears to just cause problems and be not needed
r_addend_replacements = None
r_addend_replacements_use = True
r_type = None
st_name = None
st_info = None
st_other = None
st_shndx = None
old_st_value = None
st_size = None
new_st_value = None
st_value_replacements = None
st_value_replacements_use = True
st_type = None
st_bind = None
patch_memhole_references_value = int(args.patch_memhole_references, 2)
patch_memhole_references_enable = ((patch_memhole_references_value & int("001", 2)) > 0)
patch_memhole_references_patch_rest_bytes_not_zeroes = ((patch_memhole_references_value & int("010", 2)) > 0)
patch_memhole_references_patch_not_8_multiply = ((patch_memhole_references_value & int("100", 2)) > 0)
safe_min_bytes_size = None
safe_min_bytes_amount = None
safe_min_bytes_estimated_amount = None
safe_max_bytes_size = None
safe_max_bytes_amount = None
safe_max_bytes_estimated_amount = None
replacements = None
replacements_amount = None
replacements_min_value = None
replacements_max_value = None
replacement = None
replacement_old_value = None
replacement_old_value_bytes = None
replacement_new_value = None
replacement_new_value_bytes = None
replacement_value_size = None
old_replacement_min_segments_index = None
new_replacement_min_segments_index = None
SegmentsIndex = 0
current_value = None
current_value_size_index = None
bytes_estimated_index = None
bytes_index = None
for phdrs_index, phdr in enumerate(elf.phdrs):
if phdr.type not in [ElfProgramHeader.PT_LOAD, ElfProgramHeader.PT_SCE_RELRO]:
continue
if phdr.type == ElfProgramHeader.PT_LOAD and phdr.flags == ElfProgramHeader.PF_RX:
#print('skipping text segment')
continue
#print('type:0x{0:X} vaddr:0x{1:X} paddr:0x{2:X} file_size:0x{3:X} mem_size:0x{4:X} align:0x{5:X}'.format(phdr.type, phdr.vaddr, phdr.paddr, phdr.file_size, phdr.mem_size, phdr.align))
segments.append(phdr)
for phdrs_index, phdr in enumerate(elf.phdrs):
for segment in segments:
if segment == phdr:
method_found=True
break
if method_found is True:
method_found = False
else:
for segment in segments:
if segment.paddr == phdr.paddr:
method_found=True
break
if method_found is False:
for segment in segments:
if segment.vaddr == phdr.vaddr:
method_found=True
break
if method_found is True:
method_found = False
segments.append(phdr)
#for i, phdr in enumerate(segs):
# print('vaddr:0x{0:X} mem_size:0x{1:X}'.format(phdr.vaddr, phdr.mem_size))
segments_length = len(segments)
segments.sort(key=lambda x: (x.vaddr, -(x.vaddr + x.mem_size)))
while segments_index < segments_length:
segment = segments[segments_index]
previous_segment = segments[segments_index - 1]
if (
segment.vaddr >= previous_segment.vaddr
and (segment.vaddr + segment.mem_size <= previous_segment.vaddr + previous_segment.mem_size)
and segment.type == previous_segment.type
):
#print('removing seg vaddr:0x{0:X} mem_size:0x{1:X}'.format(segs[i].vaddr, segs[i].mem_size))
#print(' previous seg vaddr:0x{0:X} mem_size:0x{1:X}'.format(segs[i - 1].vaddr, segs[i - 1].mem_size))
segments = segments[:segments_index] + segments[segments_index + 1:]
segments_length -= 1
else:
segments_index += 1
if (
args.not_patch_dynamic_section is False
or args.not_patch_relocation_section is False
or args.not_patch_symbol_table is False
) and args.patch_memhole == "2":
# Find the dynamic segment
for phdrs_index, phdr in enumerate(elf.phdrs):
if phdr.type == ElfProgramHeader.PT_DYNAMIC:
dynamicPH = phdr
elif phdr.type == ElfProgramHeader.PT_SCE_DYNLIBDATA:
dynlibDataPH = phdr
if dynamicPH is None:
print("An error occurred, as the ELF is not a valid OELF!")
sys.exit(1)
struct_fmt = '<QQ'
struct_size = struct.calcsize(struct_fmt)
DynamicTableEntriesAmount = int(dynamicPH.mem_size / struct_size)
DynamicTable_addr = dynamicPH.offset
RelaTable_addr = dynlibDataPH.offset
SymTable_addr = dynlibDataPH.offset
FirstSegment_VirtualAddress = elf.phdrs[0].vaddr
if (
args.not_patch_relocation_section is False
or args.not_patch_symbol_table is False
) and args.patch_memhole == "2":
for DynamicTableEntriesIndex in range(0, DynamicTableEntriesAmount):
struct_fmt = '<QQ'
struct_size = struct.calcsize(struct_fmt)
f.seek(dynamicPH.offset + (DynamicTableEntriesIndex * struct_size))
d_tag, d_val = struct.unpack(struct_fmt, f.read(struct_size))
if d_tag == DT_SCE_JMPREL:
RelaTable_addr += d_val
elif d_tag == DT_SCE_PLTRELSZ:
RelaTableSize += d_val
elif d_tag == DT_SCE_RELASZ:
RelaTableSize += d_val
elif d_tag == DT_SCE_SYMTAB:
SymTable_addr += d_val
elif d_tag == DT_SCE_SYMTABSZ:
SymTableSize += d_val
struct_fmt = '<QLLq'
struct_size = struct.calcsize(struct_fmt)
RelaTableEntriesAmount = int(RelaTableSize / struct_size)
struct_fmt = '<IBBHQQ'
struct_size = struct.calcsize(struct_fmt)
SymTableEntriesAmount = int(SymTableSize / struct_size)
#print('')
#for i, phdr in enumerate(segs):
# #print('type:0x{0:X} vaddr:0x{1:X} paddr:0x{2:X} file_size:0x{3:X} mem_size:0x{4:X} align:0x{5:X}'.format(phdr.type, phdr.vaddr, phdr.paddr, phdr.file_size, phdr.mem_size, phdr.align))
# print('vaddr:0x{0:X} mem_size:0x{1:X} end_vaddr:0x{2:X}'.format(phdr.vaddr, phdr.mem_size, phdr.vaddr + phdr.mem_size))
if segments_length > 1:
for segments_indexA in range(0, segments_length - 1):
segment = segments[segments_indexA]
next_segment = segments[segments_indexA + 1]
mem_size_aligned = align_up(segment.mem_size, 0x4000)
if (segment.vaddr + mem_size_aligned) < next_segment.vaddr:
print("")
print(
"found a memhole between:"
+ ' ' + CheckHexText(segment.vaddr + mem_size_aligned, AddressesLength, True)
+ ' ' + '-' + ' ' + CheckHexText(next_segment.vaddr, AddressesLength, True)
+ ' ' + "(not including the last address)"
)
old_mem_size = segment.mem_size
old_paddr = next_segment.paddr
old_vaddr = next_segment.vaddr
paddr_mem_size = next_segment.mem_size