-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathanalyze_backspace.py
executable file
·232 lines (183 loc) · 6.55 KB
/
analyze_backspace.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import pygrap
import pefile
def print_usage():
print("You need at least one argument: the (backspace) binary to analyze")
print("-v will output the generated graph patterns")
print("-h will print this message")
def main():
if len(sys.argv) <= 1:
print_usage()
sys.exit(1)
elif len(sys.argv) <= 2:
verbose = False
bin_path = sys.argv[1]
dot_path = sys.argv[1] + ".grapcfg"
else:
verbose = True
bin_path = sys.argv[2]
dot_path = sys.argv[2] + ".grapcfg"
if len(sys.argv) == 2 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
print_usage()
sys.exit(1)
if bin_path[-8:] == ".grapcfg":
print("The argument should be a binary and not a .grapcfg file")
sys.exit(1)
# use_existing specifies wether an existing dot file should be used unchanged or overwritten
pygrap.disassemble_file(bin_path=bin_path, dot_path=dot_path, use_existing=True)
test_graph = pygrap.getGraphFromPath(dot_path)
if verbose:
print("Analyzing", bin_path)
if not os.path.isfile(bin_path) or not os.path.isfile(dot_path):
print("Error: binary or dot file doesn't exist, exiting.")
sys.exit(1)
pattern_decrypt = "backspace_decrypt_algos.grapp"
matches_decrypt = pygrap.match_graph(pattern_decrypt, test_graph)
if len(matches_decrypt) >= 2:
print("Error: two or more decryption algorithms matched, exiting.")
sys.exit(1)
for algorithm_name in matches_decrypt:
if verbose:
print("Matched algorithm:", algorithm_name)
first_match = matches_decrypt[algorithm_name][0]
first_group = first_match["A"]
first_instruction = first_group[0]
description = first_instruction.info.inst_str
address = first_instruction.info.address
if verbose:
print("Found decryption pattern at address", hex(int(address)))
# Find the beginning of the function:
# It is a node with at least 5 fathers which address a fulfills: address - 30 <= a <= address
address_cond = "address >= " + str(hex(int(address - 30))) + " and address <= " + str(hex(int(address)))
entrypoint_pattern = """
digraph decrypt_fun_begin{
ep [label="ep", cond="nfathers >= 5 and FILL_ADDR_COND", getid="ep"]
}
""".replace("FILL_ADDR_COND", address_cond)
if verbose:
print("Looking for entrypoint with pattern:")
print(entrypoint_pattern)
matches_entrypoint = pygrap.match_graph(entrypoint_pattern, test_graph)
if len(matches_entrypoint) != 1 or len(matches_entrypoint["decrypt_fun_begin"]) != 1:
print("Error: Entrypoint not found, exiting")
sys.exit(1)
entrypoint = hex(int(matches_entrypoint["decrypt_fun_begin"][0]["ep"][0].info.address))
if verbose:
print("Found decryption function at", entrypoint)
push_call_pattern = """
digraph push_call_decrypt{
push [label="push", cond="opcode is push", repeat=2, getid=push]
call [label="call", cond="opcode is call"]
entrypoint [label="entrypoint", cond="address == FILL_ADDR"]
push -> call
call -> entrypoint [childnumber=2]
}
""".replace("FILL_ADDR", entrypoint)
if verbose:
print("Looking for calls to decrypt function with pattern:")
print(push_call_pattern)
matches_calls = pygrap.match_graph(push_call_pattern, test_graph)
if len(matches_calls) == 0:
print("error: No call found, exiting")
sys.exit(1)
if verbose:
print(len(matches_calls["push_call_decrypt"]), "calls to decrypt function found.")
str_tuple = []
for m in matches_calls["push_call_decrypt"]:
# Work on matches with immediate arguments such as:
# PUSH (between 2 and 5) with hex arguments (for instance: 9, 0x12 or 0x4012a3)
# CALL entrypoint
push1_arg_int = pygrap.parse_first_immediate(m["push"][-2].info.arg1)
push2_arg_int = pygrap.parse_first_immediate(m["push"][-1].info.arg1)
if push1_arg_int is not None and push2_arg_int is not None:
str_tuple.append((push1_arg_int, push2_arg_int))
decrypted_strings = decrypt_strings(algorithm_name, str_tuple, bin_path)
print("Decrypted strings in", bin_path + ":")
for d in decrypted_strings:
print(d)
print("")
pygrap.graph_free(test_graph, True)
def decrypt_xor_sub(s):
out = ""
for o in s:
o = o ^ 0x11
o = o - 0x25
out += chr(o % 0x100)
return out
def decrypt_sub_xor_sub(s):
out = ""
cl = 0
for o in s:
o -= cl
o = o ^ 0x0b
o = o - 0x12
out += chr(o % 0x100)
cl += 1
return out
def decrypt_sub_add(s):
out = ""
cl = 0
for o in s:
dl = 0xff
dl -= cl
o += dl
out += chr(o % 0x100)
cl += 1
return out
def decrypt_xor_sub_sub(s):
out = ""
i = 0
for o in s:
o = o ^ 0x17
o = o - i
o = o - 0x0b
out += chr(o % 0x100)
i += 1
return out
def decrypt_sub_xor_add(s):
out = ""
i = 0
for o in s:
o = o - i
o = o ^ 0x19
o = o + 0x13
out += chr(o % 0x100)
i += 1
return out
def decrypt_str(d, algo):
if algo == "decrypt_xor_sub":
return decrypt_xor_sub(d)
elif algo == "decrypt_sub_xor_sub":
return decrypt_sub_xor_sub(d)
elif algo == "decrypt_sub_add1":
return decrypt_sub_add(d)
elif algo == "decrypt_sub_add2":
return decrypt_sub_add(d)
elif algo == "decrypt_xor_sub_sub":
return decrypt_xor_sub_sub(d)
elif algo == "decrypt_sub_xor_add":
return decrypt_sub_xor_add(d)
else:
print("warning: unknown algo", algo)
return None
def decrypt_strings(algo, str_tuple, bin_path):
try:
data = open(bin_path, "rb").read()
pe = pefile.PE(data=data)
base_addr = pe.OPTIONAL_HEADER.ImageBase
except:
print("error: pefile")
sys.exit(1)
decrypted = []
for size, addr in str_tuple:
d = pe.get_data(addr - base_addr, size)
decrypted_str = decrypt_str(d, algo)
if decrypted_str is not None:
decrypted.append(decrypted_str)
return decrypted
if __name__ == '__main__':
main()
sys.exit(0)