-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpolar.py
3540 lines (2998 loc) · 111 KB
/
polar.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
import warnings
warnings.filterwarnings("ignore")
import io
import os
import re
import abc
import cmd
import sys
import json
import lldb
import stat
import uuid
import fcntl
import shlex
import string
import struct
import openai
import hashlib
import fnmatch
import pathlib
import sqlite3
import termios
import capstone
import optparse
import platform
import functools
import subprocess
import textwrap
from pprint import pformat
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers.c_cpp import CLexer
from functools import lru_cache
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.embeddings import LocalAIEmbeddings
from langchain.embeddings import LlamaCppEmbeddings
from langchain.llms import Ollama
from openai import OpenAI
# Set your API key in the OPENAI_API_KEY environment variable.
api_key = os.getenv("OPENAI_API_KEY") or "sk-"
# Set your API key in the OPENAI_API_KEY environment variable to use speak.
speak = os.getenv("LISA_SPEAK") or "false"
if speak == "true":
openai.api_key = api_key
speak = True
else:
speak = False
# choose between local or openai
channel = os.getenv("LISA_CHANNEL") or "ollama" # "openai" or "local" or "ollama"
localAiModel = "gpt4all-j"
ollamaModel = os.getenv("LISA_OLLAMA_MODEL") or "codellama" #"llama2"
# Prompt
decompile_prompt = """\
This is a AI powered debugger working with a security engineer reverse engineering and malware analysis. You can decompile and provide pseudo C-code for the given disassembly ARM64, X86_64 architecuteres. Do not provide explanation for the decompiled pseudo code. Try and decompile as much as possible and bring to a higher level C-language.\
User: Hello, please decompile this {architecture} binary for me.\ Here's the disassembly: {disassembly}\
"""
disassembly_explanation_prompt = """\
This is a AI powered debugger working with a security engineer reverse engineering and malware analysis. You can decompile and provide pseudo C-code for the given disassembly ARM64, X86_64 architecuteres. Do not provide explanation for the decompiled pseudo code. Try and decompile as much as possible and bring to a higher level C-language. Keep it to 400 words max.\
User: Hello, please explain this disassembly from a {architecture} binary for me. Here's the disassembly: {disassembly}\
"""
function_name_suggestion_prompt = """\
This is a AI powered debugger working with a security engineer reverse engineering and malware analysis. You can read the provided disassembly and suggest a function name that suits what the given disassembly does. This disassembly could be in ARM64, X86_64 architecuteres. Please provide a valid reason why you suggested the function name using atmost 100 words. \
User: Hello, please suggest a function name for disassembly from a {architecture} binary for me. Here's the disassembly: {disassembly}\
"""
BLK = "\033[30m"
BLU = "\033[34m"
CYN = "\033[36m"
GRN = "\033[32m"
MAG = "\033[35m"
RED = "\033[31m"
RST = "\033[0m"
YEL = "\033[33m"
WHT = "\033[37m"
BASE00 = '#657b83'
VERTICAL_LINE = "\u2502"
HORIZONTAL_LINE = "\u2500"
__prompt__ = f"'(lisa:>) '"
# from CW
MINIMUM_RECURSION_LENGTH = 300
NO_CHANGE = 0
CHANGE_TO_EXPLOITABLE = 1
CHANGE_TO_NOT_EXPLOITABLE = 2
# cpu types
CPU_TYPE_I386 = 7
CPU_ARCH_ABI64 = 0x1000000
CPU_TYPE_X86_64 = CPU_TYPE_I386 | CPU_ARCH_ABI64
CPU_TYPE_ARM = 12
CPU_TYPE_ARM64 = CPU_TYPE_ARM | CPU_ARCH_ABI64
dlog = lambda msg: print(f"{GRN}{msg}{RST}")
warnlog = lambda msg: print(f"{YEL}{msg}{RST}")
errlog = lambda msg: print(f"{RED}{msg}{RST}")
try:
tty_rows, tty_columns = struct.unpack("hh", fcntl.ioctl(1, termios.TIOCGWINSZ, "1234"))
except:
tty_rows, tty_columns = 120, 120
def context_title(m):
line_color= YEL
msg_color = GRN
if not m:
print(f"{line_color}{HORIZONTAL_LINE * tty_columns} {line_color}{RST}")
return
trail_len = len(m) + 8
title = ""
title += line_color+" {:{padd}<{width}} ".format("", width=max(tty_columns - trail_len, 0), padd=HORIZONTAL_LINE)+RST
title += f"{msg_color}{m}{RST}"
title += line_color+" {:{padd}<4}".format("", padd=HORIZONTAL_LINE)+RST
print(title)
def get_host_pagesize():
host_machine = get_host_machine()
target_arch = get_target_triple().split('-')[0]
page_size = 0
if host_machine == target_arch:
page_size = run_shell_command('getconf PAGE_SIZE').stdout.rstrip()
elif host_machine=="arm64" and target_arch=="x86_64":
page_size = run_shell_command('arch -x86_64 getconf PAGE_SIZE').stdout.rstrip()
else:
errlog("get_host_pagesize failed")
return 16384
return int(page_size)
def get_host_machine():
return platform.machine()
def get_host_arch():
if get_host_machine() == "arm64":
return CPU_TYPE_ARM64
elif get_host_machine() == "x86_64":
return CPU_TYPE_X86_64
def cpu_to_string(cpu):
if cpu == CPU_TYPE_X86_64:
return "x86_64"
elif cpu == CPU_TYPE_ARM64:
return "arm64"
def get_target_triple():
return lldb.debugger.GetSelectedTarget().triple
def get_target_arch():
arch = lldb.debugger.GetSelectedTarget().triple.split('-')[0]
if arch == "arm64" or arch=="arm64e":
return AARCH64()
elif arch == "x86_64":
return X8664()
else:
errlog(f"Architecture {arch} not supported")
def run_shell_command(command, shell=True):
return subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)
def make_run_command(command):
def runCommand(debugger, input, exe_ctx, result, _):
command.result = result
command.context = exe_ctx
splitInput = command.lex(input)
# OptionParser will throw in the case where you want just one
# big long argument and no options and you enter something
# that starts with '-' in the argument. e.g.:
# somecommand -[SomeClass someSelector:]
# This solves that problem by prepending a '--' so that
# OptionParser does the right thing.
options = command.options()
if len(options) == 0:
if "--" not in splitInput:
splitInput.insert(0, "--")
parser = option_parser_for_command(command)
(options, args) = parser.parse_args(splitInput)
# When there are more args than the command has declared, assume
# the initial args form an expression and combine them into a single arg.
if len(args) > len(command.args()):
overhead = len(args) - len(command.args())
head = args[: overhead + 1] # Take N+1 and reduce to 1.
args = [" ".join(head)] + args[-overhead:]
if validate_args_for_command(args, command):
command.run(args, options)
runCommand.__doc__ = help_for_command(command)
return runCommand
def load_command(module, command, filename):
func = make_run_command(command)
name = command.name()
key = filename + "_" + name
helpText = (
command.description().strip().splitlines()[0]
) # first line of description
module._loadedFunctions[key] = func
functionName = "__" + key
lldb.debugger.HandleCommand(
"script "
+ functionName
+ " = sys.modules['"
+ module.__name__
+ "']._loadedFunctions['"
+ key
+ "']"
)
lldb.debugger.HandleCommand(
'command script add --help "{help}" --function {function} {name}'.format(
help=helpText.replace('"', '\\"'), # escape quotes
function=functionName,
name=name,
)
)
def validate_args_for_command(args, command):
if len(args) < len(command.args()):
defaultArgs = [arg.default for arg in command.args()]
defaultArgsToAppend = defaultArgs[len(args) :]
index = len(args)
for defaultArg in defaultArgsToAppend:
if defaultArg:
arg = command.args()[index]
print("Whoops! You are missing the <" + arg.argName + "> argument.")
print("\nUsage: " + usage_for_command(command))
return
index += 1
args.extend(defaultArgsToAppend)
return True
def option_parser_for_command(command):
parser = optparse.OptionParser()
for argument in command.options():
if argument.boolean:
parser.add_option(
argument.shortName,
argument.longName,
dest=argument.argName,
help=argument.help,
action=("store_false" if argument.default else "store_true"),
)
else:
parser.add_option(
argument.shortName,
argument.longName,
dest=argument.argName,
help=argument.help,
default=argument.default,
)
return parser
def help_for_command(command):
help = command.description()
argSyntax = ""
optionSyntax = ""
if command.args():
help += "\n\nArguments:"
for arg in command.args():
help += "\n <" + arg.argName + ">; "
if arg.argType:
help += "Type: " + arg.argType + "; "
help += arg.help
argSyntax += " <" + arg.argName + ">"
if command.options():
help += "\n\nOptions:"
for option in command.options():
if option.longName and option.shortName:
optionFlag = option.longName + "/" + option.shortName
elif option.longName:
optionFlag = option.longName
else:
optionFlag = option.shortName
help += "\n " + optionFlag + " "
if not option.boolean:
help += "<" + option.argName + ">; Type: " + option.argType
help += "; " + option.help
optionSyntax += " [{name}{arg}]".format(
name=(option.longName or option.shortName),
arg=("" if option.boolean else ("=" + option.argName)),
)
help += "\n\nSyntax: " + command.name() + optionSyntax + argSyntax
help += "\n\nThis command is implemented as %s" % (
command.__class__.__name__,
)
return help
def usage_for_command(command):
usage = command.name()
for arg in command.args():
if arg.default:
usage += " [" + arg.argName + "]"
else:
usage += " " + arg.argName
return usage
class CommandArgument: # noqa B903
def __init__(
self, short="", long="", arg="", type="", help="", default="", boolean=False):
self.shortName = short
self.longName = long
self.argName = arg
self.argType = type
self.help = help
self.default = default
self.boolean = boolean
class LLDBCommand:
def name(self):
return None
def options(self):
return []
def args(self):
return []
def description(self):
return ""
def lex(self, commandLine):
return shlex.split(commandLine)
def run(self, arguments, option):
pass
#################################################################################
############################ Utilities #########################################
#################################################################################
colormap = [
0x000000, 0x560000, 0x640000, 0x750000, 0x870000, 0x9b0000, 0xb00000, 0xc60000, 0xdd0000, 0xf50000, 0xff0f0f, 0xff2828, 0xff4343, 0xff5e5e, 0xff7979, 0xfe9595,
0x4c1600, 0x561900, 0x641e00, 0x752300, 0x872800, 0x9b2e00, 0xb03400, 0xc63b00, 0xdd4200, 0xf54900, 0xff570f, 0xff6928, 0xff7b43, 0xff8e5e, 0xffa179, 0xfeb595,
0x4c3900, 0x564000, 0x644b00, 0x755700, 0x876500, 0x9b7400, 0xb08400, 0xc69400, 0xdda600, 0xf5b800, 0xffc30f, 0xffc928, 0xffd043, 0xffd65e, 0xffdd79, 0xfee495,
0x4c4c00, 0x565600, 0x646400, 0x757500, 0x878700, 0x9b9b00, 0xb0b000, 0xc6c600, 0xdddd00, 0xf5f500, 0xffff0f, 0xffff28, 0xffff43, 0xffff5e, 0xffff79, 0xfffe95,
0x324c00, 0x395600, 0x426400, 0x4e7500, 0x5a8700, 0x679b00, 0x75b000, 0x84c600, 0x93dd00, 0xa3f500, 0xafff0f, 0xb7ff28, 0xc0ff43, 0xc9ff5e, 0xd2ff79, 0xdbfe95,
0x1f4c00, 0x235600, 0x296400, 0x307500, 0x388700, 0x409b00, 0x49b000, 0x52c600, 0x5cdd00, 0x66f500, 0x73ff0f, 0x82ff28, 0x91ff43, 0xa1ff5e, 0xb1ff79, 0xc1fe95,
0x004c00, 0x005600, 0x006400, 0x007500, 0x008700, 0x009b00, 0x00b000, 0x00c600, 0x00dd00, 0x00f500, 0x0fff0f, 0x28ff28, 0x43ff43, 0x5eff5e, 0x79ff79, 0x95fe95,
0x004c19, 0x00561c, 0x006421, 0x007527, 0x00872d, 0x009b33, 0x00b03a, 0x00c642, 0x00dd49, 0x00f551, 0x0fff5f, 0x28ff70, 0x43ff81, 0x5eff93, 0x79ffa6, 0x95feb8,
0x004c4c, 0x005656, 0x006464, 0x007575, 0x008787, 0x009b9b, 0x00b0b0, 0x00c6c6, 0x00dddd, 0x00f5f5, 0x0ffffe, 0x28fffe, 0x43fffe, 0x5efffe, 0x79ffff, 0x95fffe,
0x00394c, 0x004056, 0x004b64, 0x005775, 0x006587, 0x00749b, 0x0084b0, 0x0094c6, 0x00a6dd, 0x00b8f5, 0x0fc3ff, 0x28c9ff, 0x43d0ff, 0x5ed6ff, 0x79ddff, 0x95e4fe,
0x00264c, 0x002b56, 0x003264, 0x003a75, 0x004387, 0x004d9b, 0x0058b0, 0x0063c6, 0x006edd, 0x007af5, 0x0f87ff, 0x2893ff, 0x43a1ff, 0x5eaeff, 0x79bcff, 0x95cafe,
0x00134c, 0x001556, 0x001964, 0x001d75, 0x002187, 0x00269b, 0x002cb0, 0x0031c6, 0x0037dd, 0x003df5, 0x0f4bff, 0x285eff, 0x4372ff, 0x5e86ff, 0x799aff, 0x95b0fe,
0x19004c, 0x1c0056, 0x210064, 0x270075, 0x2d0087, 0x33009b, 0x3a00b0, 0x4200c6, 0x4900dd, 0x5100f5, 0x5f0fff, 0x7028ff, 0x8143ff, 0x935eff, 0xa679ff, 0xb895fe,
0x33004c, 0x390056, 0x420064, 0x4e0075, 0x5a0087, 0x67009b, 0x7500b0, 0x8400c6, 0x9300dd, 0xa300f5, 0xaf0fff, 0xb728ff, 0xc043ff, 0xc95eff, 0xd279ff, 0xdb95fe,
0x4c004c, 0x560056, 0x640064, 0x750075, 0x870087, 0x9b009b, 0xb000b0, 0xc600c6, 0xdd00dd, 0xf500f5, 0xfe0fff, 0xfe28ff, 0xfe43ff, 0xfe5eff, 0xfe79ff, 0xfe95fe,
0x4c0032, 0x560039, 0x640042, 0x75004e, 0x87005a, 0x9b0067, 0xb00075, 0xc60084, 0xdd0093, 0xf500a3, 0xff0faf, 0xff28b7, 0xff43c0, 0xff5ec9, 0xff79d2, 0xffffff,
]
def expand(v):
"""Split a 24 bit integer into 3 bytes
>>> expand(0xff2001)
(255, 32, 1)
"""
return ( ((v)>>16 & 0xFF), ((v)>>8 & 0xFF), ((v)>>0 & 0xFF) )
def format_offset(offset):
"""Return a right-aligned hexadecimal representation of offset.
>>> format_offset(128)
' 0080'
>>> format_offset(3735928559)
'deadbeef'
"""
return '0x%5x%03x' % (offset >> 12, offset & 0xFFF)
def visual_hexdump(buffer, start=0, end=None, columns=64):
"""Print a colorful representation of binary data using terminal ESC codes
"""
count = (end or -1) - start
read = 0
while read != count:
if end == None:
to_read = io.DEFAULT_BUFFER_SIZE
else:
to_read = min(count - read, io.DEFAULT_BUFFER_SIZE)
buf = buffer[read:read+to_read]
for i in range(0, len(buf), columns*2):
offset = start + read + i
print(format_offset(offset), end=' ')
for j in range(0, columns):
if i + j >= len(buf):
break
elif i + j + columns >= len(buf):
print('\x1B[0m\x1B[38;2;%d;%d;%dm▀' % expand(colormap[buf[i + j]]), end='')
else:
print('\x1B[38;2;%d;%d;%dm\x1B[48;2;%d;%d;%dm▀' % (expand(colormap[buf[i + j]]) + expand(colormap[buf[i + j + columns]])), end='')
print('\x1B[m')
read += len(buf)
HEADER = '┌────────────────┬─────────────────────────┬─────────────────────────┬────────┬────────┐'
FOOTER = RST+'└────────────────┴─────────────────────────┴─────────────────────────┴────────┴────────┘'
LINE_FORMATTER = '│' + '' + '{:016x}' + '│ {}' + '│{}' + '│' + RST
def hexmod(b: int) -> str:
'''10 -> "0xa" -> "0a"'''
return hex(b)[2:].rjust(2, '0')
def colored(b: int) -> (str, str):
ch = chr(b)
hx = hexmod(b)
if '\x00' == ch:
return RST + hx , RST + "."
elif ch in string.ascii_letters + string.digits + string.punctuation:
return CYN + hx, CYN + ch
elif ch in string.whitespace:
return GRN + hx, ' ' if ' ' == ch else GRN + '_'
return YEL + hx, YEL + '.'
def hexdump(buf, address):
cache = {hexmod(b): colored(b) for b in range(256)} #0x00 - 0xff
cache[' '] = (' ', ' ')
print(HEADER)
cur = 0
row = address
line = buf[cur:cur+16]
while line:
line_hex = line.hex().ljust(32)
hexbytes = ''
printable = ''
for i in range(0, len(line_hex), 2):
hbyte, abyte = cache[line_hex[i:i+2]]
hexbytes += hbyte + ' ' if i != 14 else hbyte + ' ┊ '
printable += abyte if i != 14 else abyte + '┊'
print(LINE_FORMATTER.format(row, hexbytes, printable))
row += 0x10
cur += 0x10
line = buf[cur:cur+16]
print(FOOTER)
def swap_unpack_char():
"""Returns the unpack prefix that will for non-native endian-ness."""
if struct.pack('H', 1).startswith("\x00"):
return '<'
return '>'
def dump_hex_bytes(addr, s, bytes_per_line=8):
i = 0
line = ''
for ch in s:
if (i % bytes_per_line) == 0:
if line:
print(line)
line = '%#8.8x: ' % (addr + i)
line += "%02x " % ch
i += 1
print(line)
def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16):
i = 0
line = ''
a_len = len(a)
b_len = len(b)
if a_len < b_len:
max_len = b_len
else:
max_len = a_len
tty_colors = TerminalColors(True)
for i in range(max_len):
ch = None
if i < a_len:
ch_a = a[i]
ch = ch_a
else:
ch_a = None
if i < b_len:
ch_b = b[i]
if not ch:
ch = ch_b
else:
ch_b = None
mismatch = ch_a != ch_b
if (i % bytes_per_line) == 0:
if line:
print(line)
line = '%#8.8x: ' % (addr + i)
if mismatch:
line += RED
line += "%02X " % ord(ch)
if mismatch:
line += RST
i += 1
print(line)
def evaluateInputExpression(expression, printErrors=True):
# HACK
frame = (
lldb.debugger.GetSelectedTarget()
.GetProcess()
.GetSelectedThread()
.GetSelectedFrame()
)
options = lldb.SBExpressionOptions()
options.SetTrapExceptions(False)
value = frame.EvaluateExpression(expression, options)
error = value.GetError()
if printErrors and error.Fail():
errlog(error)
return value
class FileExtract:
'''Decode binary data from a file'''
def __init__(self, f, b='='):
'''Initialize with an open binary file and optional byte order'''
self.file = f
self.byte_order = b
self.offsets = list()
def set_byte_order(self, b):
'''Set the byte order, valid values are "big", "little", "swap", "native", "<", ">", "@", "="'''
if b == 'big':
self.byte_order = '>'
elif b == 'little':
self.byte_order = '<'
elif b == 'swap':
# swap what ever the current byte order is
self.byte_order = swap_unpack_char()
elif b == 'native':
self.byte_order = '='
elif b == '<' or b == '>' or b == '@' or b == '=':
self.byte_order = b
else:
print("error: invalid byte order specified: '%s'" % b)
def is_in_memory(self):
return False
def seek(self, offset, whence=0):
if self.file:
return self.file.seek(offset, whence)
raise ValueError
def tell(self):
if self.file:
return self.file.tell()
raise ValueError
def read_size(self, byte_size):
s = self.file.read(byte_size)
if len(s) != byte_size:
return None
return s
def push_offset_and_seek(self, offset):
'''Push the current file offset and seek to "offset"'''
self.offsets.append(self.file.tell())
self.file.seek(offset, 0)
def pop_offset_and_seek(self):
'''Pop a previously pushed file offset, or do nothing if there were no previously pushed offsets'''
if len(self.offsets) > 0:
self.file.seek(self.offsets.pop())
def get_sint8(self, fail_value=0):
'''Extract a single int8_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(1)
if s:
v, = struct.unpack(self.byte_order + 'b', s)
return v
else:
return fail_value
def get_uint8(self, fail_value=0):
'''Extract a single uint8_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(1)
if s:
v, = struct.unpack(self.byte_order + 'B', s)
return v
else:
return fail_value
def get_sint16(self, fail_value=0):
'''Extract a single int16_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(2)
if s:
v, = struct.unpack(self.byte_order + 'h', s)
return v
else:
return fail_value
def get_uint16(self, fail_value=0):
'''Extract a single uint16_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(2)
if s:
v, = struct.unpack(self.byte_order + 'H', s)
return v
else:
return fail_value
def get_sint32(self, fail_value=0):
'''Extract a single int32_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(4)
if s:
v, = struct.unpack(self.byte_order + 'i', s)
return v
else:
return fail_value
def get_uint32(self, fail_value=0):
'''Extract a single uint32_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(4)
if s:
v, = struct.unpack(self.byte_order + 'I', s)
return v
else:
return fail_value
def get_sint64(self, fail_value=0):
'''Extract a single int64_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(8)
if s:
v, = struct.unpack(self.byte_order + 'q', s)
return v
else:
return fail_value
def get_uint64(self, fail_value=0):
'''Extract a single uint64_t from the binary file at the current file position, returns a single integer'''
s = self.read_size(8)
if s:
v, = struct.unpack(self.byte_order + 'Q', s)
return v
else:
return fail_value
def get_fixed_length_c_string(
self,
n,
fail_value='',
isprint_only_with_space_padding=False):
'''Extract a single fixed length C string from the binary file at the current file position, returns a single C string'''
s = self.read_size(n)
if s:
cstr, = struct.unpack(self.byte_order + ("%i" % n) + 's', s)
# Strip trialing NULLs
cstr = cstr.decode()
cstr = cstr.strip("\0")
if isprint_only_with_space_padding:
for c in cstr:
if c in string.printable or ord(c) == 0:
continue
return fail_value
return cstr
else:
return fail_value
def get_c_string(self):
'''Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string'''
cstr = ''
byte = self.get_uint8()
while byte != 0:
cstr += "%c" % byte
byte = self.get_uint8()
return cstr
def get_n_sint8(self, n, fail_value=0):
'''Extract "n" int8_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'b', s)
else:
return (fail_value,) * n
def get_n_uint8(self, n, fail_value=0):
'''Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'B', s)
else:
return (fail_value,) * n
def get_n_sint16(self, n, fail_value=0):
'''Extract "n" int16_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(2 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'h', s)
else:
return (fail_value,) * n
def get_n_uint16(self, n, fail_value=0):
'''Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(2 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'H', s)
else:
return (fail_value,) * n
def get_n_sint32(self, n, fail_value=0):
'''Extract "n" int32_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(4 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'i', s)
else:
return (fail_value,) * n
def get_n_uint32(self, n, fail_value=0):
'''Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(4 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'I', s)
else:
return (fail_value,) * n
def get_n_sint64(self, n, fail_value=0):
'''Extract "n" int64_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(8 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'q', s)
else:
return (fail_value,) * n
def get_n_uint64(self, n, fail_value=0):
'''Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(8 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'Q', s)
else:
return (fail_value,) * n
class LookupDictionary(dict):
"""
a dictionary which can lookup value by key, or keys by value
"""
def __init__(self, items=[]):
"""items can be a list of pair_lists or a dictionary"""
dict.__init__(self, items)
def get_keys_for_value(self, value, fail_value=None):
"""find the key(s) as a list given a value"""
list_result = [item[0] for item in self.items() if item[1] == value]
if len(list_result) > 0:
return list_result
return fail_value
def get_first_key_for_value(self, value, fail_value=None):
"""return the first key of this dictionary given the value"""
list_result = [item[0] for item in self.items() if item[1] == value]
if len(list_result) > 0:
return list_result[0]
return fail_value
def get_value(self, key, fail_value=None):
"""find the value given a key"""
if key in self:
return self[key]
return fail_value
class Enum(LookupDictionary):
def __init__(self, initial_value=0, items=[]):
"""items can be a list of pair_lists or a dictionary"""
LookupDictionary.__init__(self, items)
self.value = initial_value
def set_value(self, v):
v_typename = typeof(v).__name__
if v_typename == 'str':
if str in self:
v = self[v]
else:
v = 0
else:
self.value = v
def get_enum_value(self):
return self.value
def get_enum_name(self):
return self.__str__()
def __str__(self):
s = self.get_first_key_for_value(self.value, None)
if s is None:
s = "%#8.8x" % self.value
return s
def __repr__(self):
return self.__str__()
#################################################################################
############################ Mach-O Parser ######################################
#################################################################################
# Mach header "magic" constants
MH_MAGIC = 0xfeedface
MH_CIGAM = 0xcefaedfe
MH_MAGIC_64 = 0xfeedfacf
MH_CIGAM_64 = 0xcffaedfe
FAT_MAGIC = 0xcafebabe
FAT_CIGAM = 0xbebafeca
# Mach haeder "filetype" constants
MH_OBJECT = 0x00000001
MH_EXECUTE = 0x00000002
MH_FVMLIB = 0x00000003
MH_CORE = 0x00000004
MH_PRELOAD = 0x00000005
MH_DYLIB = 0x00000006
MH_DYLINKER = 0x00000007
MH_BUNDLE = 0x00000008
MH_DYLIB_STUB = 0x00000009
MH_DSYM = 0x0000000a
MH_KEXT_BUNDLE = 0x0000000b
# Mach haeder "flag" constant bits
MH_NOUNDEFS = 0x00000001
MH_INCRLINK = 0x00000002
MH_DYLDLINK = 0x00000004
MH_BINDATLOAD = 0x00000008
MH_PREBOUND = 0x00000010
MH_SPLIT_SEGS = 0x00000020
MH_LAZY_INIT = 0x00000040
MH_TWOLEVEL = 0x00000080
MH_FORCE_FLAT = 0x00000100
MH_NOMULTIDEFS = 0x00000200
MH_NOFIXPREBINDING = 0x00000400
MH_PREBINDABLE = 0x00000800
MH_ALLMODSBOUND = 0x00001000
MH_SUBSECTIONS_VIA_SYMBOLS = 0x00002000
MH_CANONICAL = 0x00004000
MH_WEAK_DEFINES = 0x00008000
MH_BINDS_TO_WEAK = 0x00010000
MH_ALLOW_STACK_EXECUTION = 0x00020000
MH_ROOT_SAFE = 0x00040000
MH_SETUID_SAFE = 0x00080000
MH_NO_REEXPORTED_DYLIBS = 0x00100000
MH_PIE = 0x00200000
MH_DEAD_STRIPPABLE_DYLIB = 0x00400000
MH_HAS_TLV_DESCRIPTORS = 0x00800000
MH_NO_HEAP_EXECUTION = 0x01000000
# Mach load command constants
LC_REQ_DYLD = 0x80000000
LC_SEGMENT = 0x00000001
LC_SYMTAB = 0x00000002
LC_SYMSEG = 0x00000003
LC_THREAD = 0x00000004
LC_UNIXTHREAD = 0x00000005
LC_LOADFVMLIB = 0x00000006
LC_IDFVMLIB = 0x00000007
LC_IDENT = 0x00000008
LC_FVMFILE = 0x00000009
LC_PREPAGE = 0x0000000a
LC_DYSYMTAB = 0x0000000b
LC_LOAD_DYLIB = 0x0000000c
LC_ID_DYLIB = 0x0000000d
LC_LOAD_DYLINKER = 0x0000000e
LC_ID_DYLINKER = 0x0000000f
LC_PREBOUND_DYLIB = 0x00000010
LC_ROUTINES = 0x00000011
LC_SUB_FRAMEWORK = 0x00000012
LC_SUB_UMBRELLA = 0x00000013
LC_SUB_CLIENT = 0x00000014
LC_SUB_LIBRARY = 0x00000015
LC_TWOLEVEL_HINTS = 0x00000016
LC_PREBIND_CKSUM = 0x00000017
LC_LOAD_WEAK_DYLIB = 0x00000018 | LC_REQ_DYLD
LC_SEGMENT_64 = 0x00000019
LC_ROUTINES_64 = 0x0000001a
LC_UUID = 0x0000001b
LC_RPATH = 0x0000001c | LC_REQ_DYLD
LC_CODE_SIGNATURE = 0x0000001d
LC_SEGMENT_SPLIT_INFO = 0x0000001e
LC_REEXPORT_DYLIB = 0x0000001f | LC_REQ_DYLD
LC_LAZY_LOAD_DYLIB = 0x00000020
LC_ENCRYPTION_INFO = 0x00000021
LC_DYLD_INFO = 0x00000022
LC_DYLD_INFO_ONLY = 0x00000022 | LC_REQ_DYLD
LC_LOAD_UPWARD_DYLIB = 0x00000023 | LC_REQ_DYLD
LC_VERSION_MIN_MACOSX = 0x00000024
LC_VERSION_MIN_IPHONEOS = 0x00000025
LC_FUNCTION_STARTS = 0x00000026
LC_DYLD_ENVIRONMENT = 0x00000027
# Mach CPU constants
CPU_ARCH_MASK = 0xff000000
CPU_ARCH_ABI64 = 0x01000000
CPU_TYPE_ANY = 0xffffffff
CPU_TYPE_VAX = 1
CPU_TYPE_MC680x0 = 6
CPU_TYPE_I386 = 7
CPU_TYPE_X86_64 = CPU_TYPE_I386 | CPU_ARCH_ABI64
CPU_TYPE_ARM = 12
CPU_TYPE_ARM64 = CPU_TYPE_ARM | CPU_ARCH_ABI64
# VM protection constants
VM_PROT_READ = 1
VM_PROT_WRITE = 2
VM_PROT_EXECUTE = 4
# VM protection constants
N_STAB = 0xe0
N_PEXT = 0x10
N_TYPE = 0x0e
N_EXT = 0x01
# Values for nlist N_TYPE bits of the "Mach.NList.type" field.
N_UNDF = 0x0
N_ABS = 0x2
N_SECT = 0xe
N_PBUD = 0xc
N_INDR = 0xa
# Section indexes for the "Mach.NList.sect_idx" fields
NO_SECT = 0
MAX_SECT = 255
# Stab defines
N_GSYM = 0x20
N_FNAME = 0x22
N_FUN = 0x24
N_STSYM = 0x26
N_LCSYM = 0x28
N_BNSYM = 0x2e
N_OPT = 0x3c
N_RSYM = 0x40
N_SLINE = 0x44
N_ENSYM = 0x4e
N_SSYM = 0x60
N_SO = 0x64
N_OSO = 0x66
N_LSYM = 0x80
N_BINCL = 0x82
N_SOL = 0x84
N_PARAMS = 0x86
N_VERSION = 0x88
N_OLEVEL = 0x8A
N_PSYM = 0xa0
N_EINCL = 0xa2
N_ENTRY = 0xa4