-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSymExPorter.py
933 lines (785 loc) · 33.2 KB
/
SymExPorter.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
PLUG_NAME = "SymExPorter"
import os
import sys
from ctypes import *
from struct import unpack
USE_R2 = False
USE_IDA = False
USE_RIZIN = False
USE_CUTTER = False
TOOL = None
try:
import idaapi
USE_IDA = True
except:
try:
import cutter
USE_CUTTER = True
TOOL = cutter
except:
if "radare2" in os.getcwd().lower():
USE_R2 = True
elif "rizin" in os.getcwd().lower():
USE_RIZIN = True
else:
print("ERROR: The plugin must be run in IDA, radare2, rizin or cutter")
sys.exit(0)
SHN_UNDEF = 0
#counted from Symbol Binding(b) and Symbol Types(t) like that: (((b)<<4)+((t)&0xf)), for more info use: https://docs.oracle.com/cd/E19683-01/816-1386/chapter6-79797/index.html
STB_GLOBAL_VAR=0x11
STB_GLOBAL_FUNC = 0x12
class SHTypes:
SHT_NULL = 0
SHT_PROGBITS = 1
SHT_SYMTAB = 2
SHT_STRTAB = 3
SHT_RELA = 4
SHT_HASH = 5
SHT_DYNAMIC = 6
SHT_NOTE = 7
SHT_NOBITS = 8
SHT_REL = 9
SHT_SHLIB = 10
SHT_DYNSYM = 11
SHT_NUM = 12
SHT_LOPROC = 0x70000000
SHT_HIPROC = 0x7fffffff
SHT_LOUSER = 0x80000000
SHT_HIUSER = 0xffffffff
class ELFFlags:
ELFCLASS32 = 0x01
ELFCLASS64 = 0x02
EI_CLASS = 0x04
EI_DATA = 0x05
ELFDATA2LSB = 0x01
ELFDATA2MSB = 0x02
EM_386 = 0x03
EM_X86_64 = 0x3e
EM_ARM = 0x28
EM_MIPS = 0x08
EM_SPARCv8p = 0x12
EM_PowerPC = 0x14
EM_ARM64 = 0xb7
class SymFlags:
STB_LOCAL = 0
STB_GLOBAL = 1
STB_WEAK = 2
STT_NOTYPE = 0
STT_OBJECT = 1
STT_FUNC = 2
STT_SECTION = 3
STT_FILE = 4
STT_COMMON = 5
STT_TLS = 6
class Elf32_Ehdr_LSB(LittleEndianStructure):
_fields_ = [
("e_ident", c_ubyte * 16),
("e_type", c_ushort),
("e_machine", c_ushort),
("e_version", c_uint),
("e_entry", c_uint),
("e_phoff", c_uint),
("e_shoff", c_uint),
("e_flags", c_uint),
("e_ehsize", c_ushort),
("e_phentsize", c_ushort),
("e_phnum", c_ushort),
("e_shentsize", c_ushort),
("e_shnum", c_ushort),
("e_shstrndx", c_ushort)
]
class Elf64_Ehdr_LSB(LittleEndianStructure):
_fields_ = [
("e_ident", c_ubyte * 16),
("e_type", c_ushort),
("e_machine", c_ushort),
("e_version", c_uint),
("e_entry", c_ulonglong),
("e_phoff", c_ulonglong),
("e_shoff", c_ulonglong),
("e_flags", c_uint),
("e_ehsize", c_ushort),
("e_phentsize", c_ushort),
("e_phnum", c_ushort),
("e_shentsize", c_ushort),
("e_shnum", c_ushort),
("e_shstrndx", c_ushort)
]
class Elf32_Phdr_LSB(LittleEndianStructure):
_fields_ = [
("p_type", c_uint),
("p_offset", c_uint),
("p_vaddr", c_uint),
("p_paddr", c_uint),
("p_filesz", c_uint),
("p_memsz", c_uint),
("p_flags", c_uint),
("p_align", c_uint)
]
class Elf64_Phdr_LSB(LittleEndianStructure):
_fields_ = [
("p_type", c_uint),
("p_flags", c_uint),
("p_offset", c_ulonglong),
("p_vaddr", c_ulonglong),
("p_paddr", c_ulonglong),
("p_filesz", c_ulonglong),
("p_memsz", c_ulonglong),
("p_align", c_ulonglong)
]
class Elf32_Shdr_LSB(LittleEndianStructure):
_fields_ = [
("sh_name", c_uint),
("sh_type", c_uint),
("sh_flags", c_uint),
("sh_addr", c_uint),
("sh_offset", c_uint),
("sh_size", c_uint),
("sh_link", c_uint),
("sh_info", c_uint),
("sh_addralign", c_uint),
("sh_entsize", c_uint)
]
class Elf64_Shdr_LSB(LittleEndianStructure):
_fields_ = [
("sh_name", c_uint),
("sh_type", c_uint),
("sh_flags", c_ulonglong),
("sh_addr", c_ulonglong),
("sh_offset", c_ulonglong),
("sh_size", c_ulonglong),
("sh_link", c_uint),
("sh_info", c_uint),
("sh_addralign", c_ulonglong),
("sh_entsize", c_ulonglong)
]
class Elf32_Ehdr_MSB(BigEndianStructure):
_fields_ = [
("e_ident", c_ubyte * 16),
("e_type", c_ushort),
("e_machine", c_ushort),
("e_version", c_uint),
("e_entry", c_uint),
("e_phoff", c_uint),
("e_shoff", c_uint),
("e_flags", c_uint),
("e_ehsize", c_ushort),
("e_phentsize", c_ushort),
("e_phnum", c_ushort),
("e_shentsize", c_ushort),
("e_shnum", c_ushort),
("e_shstrndx", c_ushort)
]
class Elf64_Ehdr_MSB(BigEndianStructure):
_fields_ = [
("e_ident", c_ubyte * 16),
("e_type", c_ushort),
("e_machine", c_ushort),
("e_version", c_uint),
("e_entry", c_ulonglong),
("e_phoff", c_ulonglong),
("e_shoff", c_ulonglong),
("e_flags", c_uint),
("e_ehsize", c_ushort),
("e_phentsize", c_ushort),
("e_phnum", c_ushort),
("e_shentsize", c_ushort),
("e_shnum", c_ushort),
("e_shstrndx", c_ushort)
]
class Elf32_Phdr_MSB(BigEndianStructure):
_fields_ = [
("p_type", c_uint),
("p_offset", c_uint),
("p_vaddr", c_uint),
("p_paddr", c_uint),
("p_filesz", c_uint),
("p_memsz", c_uint),
("p_flags", c_uint),
("p_align", c_uint)
]
class Elf64_Phdr_MSB(BigEndianStructure):
_fields_ = [
("p_type", c_uint),
("p_flags", c_uint),
("p_offset", c_ulonglong),
("p_vaddr", c_ulonglong),
("p_paddr", c_ulonglong),
("p_filesz", c_ulonglong),
("p_memsz", c_ulonglong),
("p_align", c_ulonglong)
]
class Elf32_Shdr_MSB(BigEndianStructure):
_fields_ = [
("sh_name", c_uint),
("sh_type", c_uint),
("sh_flags", c_uint),
("sh_addr", c_uint),
("sh_offset", c_uint),
("sh_size", c_uint),
("sh_link", c_uint),
("sh_info", c_uint),
("sh_addralign", c_uint),
("sh_entsize", c_uint)
]
class Elf64_Shdr_MSB(BigEndianStructure):
_fields_ = [
("sh_name", c_uint),
("sh_type", c_uint),
("sh_flags", c_ulonglong),
("sh_addr", c_ulonglong),
("sh_offset", c_ulonglong),
("sh_size", c_ulonglong),
("sh_link", c_uint),
("sh_info", c_uint),
("sh_addralign", c_ulonglong),
("sh_entsize", c_ulonglong)
]
class Elf32_Sym_LSB(LittleEndianStructure):
_fields_ = [
("st_name", c_uint),
("st_value", c_uint),
("st_size", c_uint),
("st_info", c_ubyte),
("st_other", c_ubyte),
("st_shndx", c_ushort)
]
class Elf64_Sym_LSB(LittleEndianStructure):
_fields_ = [
("st_name", c_uint),
("st_info", c_ubyte),
("st_other", c_ubyte),
("st_shndx", c_ushort),
("st_value", c_ulonglong),
("st_size", c_ulonglong)
]
class Elf32_Sym_MSB(BigEndianStructure):
_fields_ = [
("st_name", c_uint),
("st_value", c_uint),
("st_size", c_uint),
("st_info", c_ubyte),
("st_other", c_ubyte),
("st_shndx", c_ushort)
]
class Elf64_Sym_MSB(BigEndianStructure):
_fields_ = [
("st_name", c_uint),
("st_info", c_ubyte),
("st_other", c_ubyte),
("st_shndx", c_ushort),
("st_value", c_ulonglong),
("st_size", c_ulonglong)
]
""" This class parses the ELF """
class ELF:
def __init__(self, binary):
self.binary = bytearray(binary)
self.ElfHeader = None
self.shdr_l = []
self.phdr_l = []
self.syms_l = []
self.e_ident = self.binary[:15]
self.ei_data = unpack("<B", self.e_ident[ELFFlags.EI_DATA:ELFFlags.EI_DATA+1])[0] # LSB/MSB
self.__setHeaderElf()
self.__setShdr()
self.__setPhdr()
def is_stripped(self):
if not self.get_symtab():
return True
if not self.get_strtab():
return True
return False
def strip_symbols(self):
sh2delete = 2
size2dec = 0
end_shdr = self.ElfHeader.e_shoff + (self.sizeof_sh() * self.ElfHeader.e_shnum)
symtab = self.get_symtab()
strtab = self.get_strtab()
if not symtab or not strtab:
return False
log("Stripping binary...")
if symtab.sh_offset < end_shdr:
size2dec += symtab.sh_size
if strtab.sh_offset < end_shdr:
size2dec += strtab.sh_size
self.ElfHeader.e_shoff -= size2dec
self.ElfHeader.e_shnum -= sh2delete
e_shnum = self.ElfHeader.e_shnum
e_shoff = self.ElfHeader.e_shoff
sz_striped = (e_shoff + (e_shnum * self.sizeof_sh()))
if strtab.sh_offset > symtab.sh_offset:
self.cut_at_offset(strtab.sh_offset, strtab.sh_size)
self.cut_at_offset(symtab.sh_offset, symtab.sh_size)
else:
self.cut_at_offset(symtab.sh_offset, symtab.sh_size)
self.cut_at_offset(strtab.sh_offset, strtab.sh_size)
self.binary = self.binary[0:sz_striped]
self.write(0, self.ElfHeader)
return True
def get_symtab(self):
shstrtab = bytes(self.get_shstrtab_data())
for sh in self.shdr_l:
sh_name = shstrtab[sh.sh_name:].split(b"\0")[0]
if sh.sh_type == SHTypes.SHT_SYMTAB and \
(sh.sh_name == SHN_UNDEF or sh_name == ".symtab"):
return sh
return None
def get_strtab(self):
shstrtab = bytes(self.get_shstrtab_data())
for sh in self.shdr_l:
sh_name = shstrtab[sh.sh_name:].split(b"\0")[0]
if sh.sh_type == SHTypes.SHT_STRTAB and \
(sh.sh_name == SHN_UNDEF or sh_name == ".strtab"):
return sh
return None
def getArchMode(self):
if self.ElfHeader.e_ident[ELFFlags.EI_CLASS] == ELFFlags.ELFCLASS32:
return 32
elif self.ElfHeader.e_ident[ELFFlags.EI_CLASS] == ELFFlags.ELFCLASS64:
return 64
else:
log("[Error] ELF.getArchMode() - Bad Arch size")
return None
""" Parse ELF header """
def __setHeaderElf(self):
e_ident = self.binary[:15]
ei_class = unpack("<B", e_ident[ELFFlags.EI_CLASS:ELFFlags.EI_CLASS+1])[0]
ei_data = unpack("<B", e_ident[ELFFlags.EI_DATA:ELFFlags.EI_DATA+1])[0]
if ei_class != ELFFlags.ELFCLASS32 and ei_class != ELFFlags.ELFCLASS64:
log("[Error] ELF.__setHeaderElf() - Bad Arch size")
return None
if ei_data != ELFFlags.ELFDATA2LSB and ei_data != ELFFlags.ELFDATA2MSB:
log("[Error] ELF.__setHeaderElf() - Bad architecture endian")
return None
if ei_class == ELFFlags.ELFCLASS32:
if ei_data == ELFFlags.ELFDATA2LSB: self.ElfHeader = Elf32_Ehdr_LSB.from_buffer_copy(self.binary)
elif ei_data == ELFFlags.ELFDATA2MSB: self.ElfHeader = Elf32_Ehdr_MSB.from_buffer_copy(self.binary)
elif ei_class == ELFFlags.ELFCLASS64:
if ei_data == ELFFlags.ELFDATA2LSB: self.ElfHeader = Elf64_Ehdr_LSB.from_buffer_copy(self.binary)
elif ei_data == ELFFlags.ELFDATA2MSB: self.ElfHeader = Elf64_Ehdr_MSB.from_buffer_copy(self.binary)
""" Write the section header to self.binary """
def write_shdr(self):
off = self.ElfHeader.e_shoff
for sh in self.shdr_l:
self.write(off, sh)
off += off + sizeof(sh)
""" Parse Section header """
def __setShdr(self):
shdr_num = self.ElfHeader.e_shnum
base = self.binary[self.ElfHeader.e_shoff:]
shdr_l = []
e_ident = self.binary[:15]
ei_data = unpack("<B", e_ident[ELFFlags.EI_DATA:ELFFlags.EI_DATA+1])[0]
for i in range(shdr_num):
if self.getArchMode() == 32:
if ei_data == ELFFlags.ELFDATA2LSB: shdr = Elf32_Shdr_LSB.from_buffer_copy(base)
elif ei_data == ELFFlags.ELFDATA2MSB: shdr = Elf32_Shdr_MSB.from_buffer_copy(base)
elif self.getArchMode() == 64:
if ei_data == ELFFlags.ELFDATA2LSB: shdr = Elf64_Shdr_LSB.from_buffer_copy(base)
elif ei_data == ELFFlags.ELFDATA2MSB: shdr = Elf64_Shdr_MSB.from_buffer_copy(base)
self.shdr_l.append(shdr)
base = base[self.ElfHeader.e_shentsize:]
string_table = self.binary[(self.shdr_l[self.ElfHeader.e_shstrndx].sh_offset):]
for i in range(shdr_num):
self.shdr_l[i].str_name = string_table[self.shdr_l[i].sh_name:].split(b'\0')[0]
""" Parse Program header """
def __setPhdr(self):
pdhr_num = self.ElfHeader.e_phnum
base = self.binary[self.ElfHeader.e_phoff:]
phdr_l = []
e_ident = self.binary[:15]
ei_data = unpack("<B", e_ident[ELFFlags.EI_DATA:ELFFlags.EI_DATA+1])[0]
for i in range(pdhr_num):
if self.getArchMode() == 32:
if ei_data == ELFFlags.ELFDATA2LSB: phdr = Elf32_Phdr_LSB.from_buffer_copy(base)
elif ei_data == ELFFlags.ELFDATA2MSB: phdr = Elf32_Phdr_MSB.from_buffer_copy(base)
elif self.getArchMode() == 64:
if ei_data == ELFFlags.ELFDATA2LSB: phdr = Elf64_Phdr_LSB.from_buffer_copy(base)
elif ei_data == ELFFlags.ELFDATA2MSB: phdr = Elf64_Phdr_MSB.from_buffer_copy(base)
self.phdr_l.append(phdr)
base = base[self.ElfHeader.e_phentsize:]
def get_section_id(self, sh_name):
for idx, sh in enumerate(self.shdr_l):
if sh.str_name == sh_name.encode('ascii'):
return idx
return None
def get_shstrtab_data(self):
sh = self.shdr_l[self.ElfHeader.e_shstrndx]
if sh.sh_type == SHTypes.SHT_STRTAB:
return self.binary[sh.sh_offset:sh.sh_offset+sh.sh_size]
return None
def get_sym_at_offset(self, off):
if self.getArchMode() == 32:
if ei_data == ELFFlags.ELFDATA2LSB: sym = Elf32_Sym_LSB.from_buffer_copy(self.binary[off:])
elif ei_data == ELFFlags.ELFDATA2MSB: sym = Elf32_Sym_MSB.from_buffer_copy(self.binary[off:])
elif self.getArchMode() == 64:
if ei_data == ELFFlags.ELFDATA2LSB: sym = Elf64_Sym_LSB.from_buffer_copy(self.binary[off:])
elif ei_data == ELFFlags.ELFDATA2MSB: sym = Elf64_Sym_MSB.from_buffer_copy(self.binaryGetInputFilePath[off:])
return sym
def get_entrypoint(self):
return self.e_entry
def sizeof_sh(self):
size = None
if self.getArchMode() == 32:
size = sizeof(Elf32_Shdr_LSB())
elif self.getArchMode() == 64:
size = sizeof(Elf64_Shdr_LSB())
return size
def sizeof_sym(self):
size = None
if self.getArchMode() == 32:
size = sizeof(Elf32_Sym_LSB)
elif self.getArchMode() == 64:
size = sizeof(Elf64_Sym_LSB)
return size
def append_section_header(self, section):
sh = None
if self.getArchMode() == 32:
if self.ei_data == ELFFlags.ELFDATA2LSB: sh = Elf32_Shdr_LSB()
elif self.ei_data == ELFFlags.ELFDATA2MSB: sh = Elf32_Shdr_MSB()
elif self.getArchMode() == 64:
if self.ei_data == ELFFlags.ELFDATA2LSB: sh = Elf64_Shdr_LSB()
elif self.ei_data == ELFFlags.ELFDATA2MSB: sh = Elf64_Shdr_MSB()
sh.sh_name = section["name"]
sh.sh_type = section["type"]
sh.sh_flags = section["flags"]
sh.sh_addr = section["addr"]
sh.sh_offset = section["offset"]
sh.sh_size = section["size"]
sh.sh_link = section["link"]
sh.sh_info = section["info"]
sh.sh_addralign = section["addralign"]
sh.sh_entsize = section["entsize"]
self.binary.extend(sh)
def append_symbol(self, symbol):
if self.getArchMode() == 32:
if self.ei_data == ELFFlags.ELFDATA2LSB: sym = Elf32_Sym_LSB()
elif self.ei_data == ELFFlags.ELFDATA2MSB: sym = Elf32_Sym_MSB()
elif self.getArchMode() == 64:
if self.ei_data == ELFFlags.ELFDATA2LSB: sym = Elf64_Sym_LSB()
elif self.ei_data == ELFFlags.ELFDATA2MSB: sym = Elf64_Sym_MSB()
sym.st_name = symbol["name"]
sym.st_value = symbol["value"]
sym.st_size = symbol["size"]
sym.st_info = symbol["info"]
sym.st_other = symbol["other"]
sym.st_shndx = symbol["shndx"]
self.binary.extend(sym)
def get_binary(self):
return self.binary
def write(self, offset, data):
self.binary[offset:offset+sizeof(data)] = data
def expand_at_offset(self, offset, data):
self.binary = self.binary[:offset] + data + self.binary[offset:]
def cut_at_offset(self, offset, size):
self.binary = self.binary[:offset] + self.binary[offset+size:]
def save(self, output):
with open(output, 'wb') as f:
f.write(self.binary)
class Symbol:
def __init__(self, name, info, value, size, shname, shndx=-1):
self.name = name
self.info = info
self.value = value
self.size = size
self.shname = shname
self.shndx = shndx
def __str__(self):
return "%s;%s;%s;%s;%s" % (self.name, self.value, self.size,
self.info, self.shname)
def log(msg=''):
print("[%s] %s" % (PLUG_NAME, msg))
def log_r2(msg=''):
print("%s" % msg)
def write_symbols(input_file, output_file, symbols):
try:
with open(input_file, 'rb') as f:
bin = ELF(f.read())
if len(symbols) < 1:
log("No symbols to export")
return
log("Exporting symbols to ELF...")
bin.strip_symbols()
# raw strtab
strtab_raw = b"\x00" + b"\x00".join([sym.name.encode('ascii') for sym in symbols]) + b"\x00"
symtab = {
"name" : SHN_UNDEF,
"type" : SHTypes.SHT_SYMTAB,
"flags" : 0,
"addr" : 0,
"offset" : len(bin.binary) + (bin.sizeof_sh() * (bin.ElfHeader.e_shnum + 2)),
"size" : (len(symbols) + 1) * bin.sizeof_sym(),
"link" : bin.ElfHeader.e_shnum + 1, # index of SHT_STRTAB
"info" : 1,
"addralign" : 4,
"entsize" : bin.sizeof_sym()
}
off_strtab = (len(bin.binary) + (bin.sizeof_sh() * (bin.ElfHeader.e_shnum + 2)) + (bin.sizeof_sym() * (len(symbols) + 1)))
strtab = {
"name" : SHN_UNDEF,
"type" : SHTypes.SHT_STRTAB,
"flags" : 0,
"addr" : 0,
"offset" : off_strtab,
"size" : len(strtab_raw),
"link" : 0,
"info" : 0,
"addralign" : 1,
"entsize" : 0
}
shdrs = bin.binary[bin.ElfHeader.e_shoff:bin.ElfHeader.e_shoff + (bin.sizeof_sh() * bin.ElfHeader.e_shnum)]
bin.ElfHeader.e_shnum += 2
bin.ElfHeader.e_shoff = len(bin.binary)
bin.write(0, bin.ElfHeader)
bin.binary.extend(shdrs)
base = bin.binary[bin.ElfHeader.e_shoff:]
_off = bin.ElfHeader.e_shoff
for i in range(bin.ElfHeader.e_shnum - 2):
if bin.getArchMode() == 32:
if bin.ei_data == ELFFlags.ELFDATA2LSB: shdr = Elf32_Shdr_LSB.from_buffer_copy(base)
elif bin.ei_data == ELFFlags.ELFDATA2MSB: shdr = Elf32_Shdr_MSB.from_buffer_copy(base)
elif bin.getArchMode() == 64:
if bin.ei_data == ELFFlags.ELFDATA2LSB: shdr = Elf64_Shdr_LSB.from_buffer_copy(base)
elif bin.ei_data == ELFFlags.ELFDATA2MSB: shdr = Elf64_Shdr_MSB.from_buffer_copy(base)
base = base[bin.ElfHeader.e_shentsize:]
bin.write(_off, shdr)
_off += bin.sizeof_sh()
bin.append_section_header(symtab)
bin.append_section_header(strtab)
# Local symbol - separator
sym = {
"name" : 0,
"value" : 0,
"size" : 0,
"info" : SymFlags.STB_LOCAL,
"other" : 0,
"shndx" : 0
}
bin.append_symbol(sym)
# add symbols
for s in symbols:
sh_idx = bin.get_section_id(s.shname)
if not sh_idx:
log("ERROR: Section ID for '%s' not found" % s.shname)
continue
sym = {
"name" : strtab_raw.index(s.name.encode('ascii')),
"value" : s.value,
"size" : s.size,
"info" : s.info,
"other" : 0,
"shndx" : sh_idx
}
#log("0x%08x - 0x%08x - %s - %d/%d - %d" % (s.value, s.size, s.name, strtab_raw.index(bytes(s.name.encode('ascii'))), len(strtab_raw), s.info))#Debug Mode
bin.append_symbol(sym)
# add symbol strings
bin.binary.extend(strtab_raw)
log("ELF saved to: %s" % output_file)
bin.save(output_file)
except:
import traceback
log(traceback.format_exc())
def ida_fcn_filter(func_ea):
if idc.get_segm_name(func_ea) not in ("extern", ".plt"):
return True
return False
def get_ida_functions():
functions = []
for f in filter(ida_fcn_filter, Functions()):
func = ida_funcs.get_func(f)
seg_name = idc.get_segm_name(f)
fn_name = idc.get_func_name(f)
functions.append(Symbol(fn_name, STB_GLOBAL_FUNC,
int(func.start_ea), int(func.size()), seg_name))
return functions
def get_ida_varnames():
names=[]
for n in Names():
if idc.get_segm_name(n[0]) in (".rodata", ".data", ".bss"):
var_name=n[1]
start=n[0]
size = get_item_size(start) #size of the global variable value or length of its name
if size==0:
size=len(var_name)
seg_name=idc.get_segm_name(n[0])
names.append(Symbol(var_name, STB_GLOBAL_VAR, int(start), int(size), seg_name))
return names
def get_section(addr):
for idx, s in enumerate(TOOL.cmdj("iSj")):
if s['vaddr'] <= addr < (s['vaddr'] + s['vsize']):
return (idx, s['name'])
return None, None
def fcn_filter(fcn):
if fcn['name'].startswith(("sym.imp", "loc.imp", "section")):
return False
return True
def get_functions():
functions = []
for fnc in filter(fcn_filter, TOOL.cmdj("aflj")):
sh_idx, sh_name = get_section(fnc['offset'])
fnc_name = fnc['name']
if fnc_name.startswith(("sym.","fcn.")):
fnc_name = fnc_name[4:]
if fnc_name.startswith("go."):
fnc_name = fnc_name[3:]
functions.append(Symbol(fnc_name, STB_GLOBAL_FUNC,
fnc['offset'], int(fnc['size']), sh_name))
return functions
def var_filter(var):
if var['name'].startswith(("data.", "segment.", "section.", "fcn.", "sym.", "entry", "main", "reloc.", "str.")):
return False
return True
def get_varnames():
names = []
if USE_RIZIN or USE_CUTTER:
for var in filter(var_filter, TOOL.cmdj("flj")):
sh_idx, sh_name = get_section(var['offset'])
if sh_name in (".data", ".rodata", ".bss"):
varname = var['name']
if varname.startswith(("obj.", "str.")):
varname = varname[4:]
names.append(Symbol(varname, STB_GLOBAL_VAR,
var['offset'], int(var['size']), sh_name))
elif USE_R2:
for var in filter(var_filter, TOOL.cmdj("fnj")):
sh_idx, sh_name = get_section(var['offset'])
if sh_name in (".data", ".rodata", ".bss"):
varname = var['name']
if varname.startswith(("obj.", "str.")):
varname = varname[4:]
names.append(Symbol(varname, STB_GLOBAL_VAR,
var['offset'], int(var['size']), sh_name))
return names
if USE_IDA:
import idc
import ida_nalt
import ida_kernwin
from idaapi import *
from idautils import *
class SymExPorter(Form):
def __init__(self):
Form.__init__(self, r"""SymExPorter
{formChangeCb}
<#Output file#Output ~f~ile:{txtFile}>
""", {
'formChangeCb' : Form.FormChangeCb(self.OnFormChange),
'txtFile' : Form.FileInput(save=True, swidth=50)
})
self.input_elf = ida_nalt.get_input_file_path()
def OnFormChange(self, fid):
if fid == self.txtFile.id:
o_file = self.GetControlValue(self.txtFile)
if os.path.exists(o_file):
s = "Output file already exists\n" \
"The output file already exists. " \
"Do you want to overwrite it?"
if bool(ida_kernwin.ask_form(s, "1")):
os.remove(o_file)
else:
self.SetControlValue(self.txtFile, '')
return 1
def Show(self):
if not self.Compiled():
self.Compile()
if "ELF" in get_file_type_name():
ok = self.Execute()
else:
warning("The input file is not an ELF executable!")
ok = 0
return ok
class SymExPorter_t(plugin_t):
flags = PLUGIN_UNL
comment = ""
help = ""
wanted_name = PLUG_NAME
wanted_hotkey = ""
def init(self):
return PLUGIN_OK
def run(self, arg=0):
f = SymExPorter()
if f.Show():
functions = get_ida_functions()
varnames = get_ida_varnames()
output_file = f.txtFile.value
write_symbols(f.input_elf, output_file, functions+varnames)
f.Free()
def term(self):
pass
def PLUGIN_ENTRY():
return SymExPorter_t()
elif USE_R2 or USE_RIZIN:
if USE_R2:
import r2pipe
TOOL = r2pipe.open()
elif USE_RIZIN:
import rzpipe
TOOL = rzpipe.open()
log = log_r2
if len(sys.argv) < 2:
log("Usage: #!pipe python ./SymExPorter.py <output_file>")
sys.exit(0)
file_info = TOOL.cmdj("ij").get("core")
if file_info['format'].lower() in ('elf','elf64'):
functions = get_functions()
varnames = get_varnames()
write_symbols(file_info['file'], sys.argv[1], functions+varnames)
else:
log("The input file is not an ELF executable!")
elif USE_CUTTER:
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QHBoxLayout, QLabel, QWidget, QSizePolicy, QPushButton, QLineEdit, QFileDialog
class SymExPorterWidget(cutter.CutterDockWidget):
def __init__(self, parent):
super(SymExPorterWidget, self).__init__(parent)
self.setObjectName("WidgetForSymExPorter")
self.setWindowTitle("SymExPorter")
content = QWidget()
self.setWidget(content)
layout = QHBoxLayout(content)
self.output_path = QLineEdit(content)
self.output_path.setPlaceholderText("Enter the filename")
self.output_path.setMinimumWidth(400)
layout.addWidget(self.output_path)
browse_button = QPushButton("...", content)
browse_button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
browse_button.setMaximumHeight(30)
browse_button.setMaximumWidth(40)
layout.addWidget(browse_button)
browse_button.clicked.connect(self.open_file_dialog)
export_button = QPushButton("Export", content)
export_button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
export_button.setMaximumHeight(30)
export_button.setMaximumWidth(70)
layout.addWidget(export_button)
export_button.clicked.connect(self.export_syms)
self.show()
def open_file_dialog(self):
filename, _ = QFileDialog.getSaveFileName(self, "SymExPorter", "", "All files (*)")
if filename:
self.output_path.setText(filename)
def export_syms(self):
file_info = cutter.cmdj("ij").get("core")
file_name = self.output_path.text()
if file_info['format'].lower() in ('elf','elf64'):
functions = get_functions()
varnames = get_varnames()
write_symbols(file_info['file'], file_name, functions+varnames)
else:
cutter.message("The input file is not an ELF executable!")
class CutterSymExPorterPlugin(cutter.CutterPlugin):
name = "SymExPorter"
description = "Export the symbols to the ELF symbol table."
version = "1.0"
author = "Kirill Magaskin"
def __init__(self):
super(CutterSymExPorterPlugin, self).__init__()
def setupPlugin(self):
pass
def setupInterface(self, main):
widget = SymExPorterWidget(main)
main.addPluginDockWidget(widget)
def terminate(self):
cutter.message("SymExPorter is shutting down")
def create_cutter_plugin():
return CutterSymExPorterPlugin()