-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcerebro-string-basic.py
436 lines (372 loc) · 17 KB
/
cerebro-string-basic.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
#!/usr/bin/env python
import binascii
from os import error
import sys, string, struct
from datetime import date
import argparse
import os.path
import itertools as it
import encodings
import fileinput
import re
import base64
'''
.d88b 8888 888b. 8888 888b. 888b. .d88b.
8P 8www 8 .8 8www 8wwwP 8 .8 8P Y8
8b 8 8wwK' 8 8 b 8wwK' 8b d8
`Y88P 8888 8 Yb 8888 888P' 8 Yb `Y88P'
This is Cerebro "String", a quick and simple script to take a single input string and spit out mutations in YARA friendly format.
If this doesn't work, because of your Python install and paths... make sure you've got everything in Python2 or Python3 as needed.
Example input: a string such as "VirtualAlloc"
Example output: a list of mutations of those strings such as $a01_VirtualAlloc = "hllochualAhVirt" nocase ascii wide
Usage:
python3 cerebro-string-basic.py -s kernel32.dll -m frenchstack
python3 cerebro-string-basic.py --str GetCurrentProcess --mut hex
python3 cerebro-string-basic.py -s IsDebuggerPresent --mut all
Thanks to contributions from: @notareverser, @bitsofbinary, @glesnewich
'''
#### frenchstack
# frenchstack stuff below courtesy of @notareverser https://gist.github.com/notareverser/4f6b9c644d4fe517889b3fbb0b4271ca
def strByByte(_strval):
strval = bytearray(_strval.encode())
for s in strval: yield s
def strByDword(_strval):
strval = bytearray(_strval.encode())
numDwords = int(len(strval) / 4)
remainder = len(strval) - (numDwords*4)
for x in range(numDwords):
yield struct.unpack_from("<L", strval, 4*x)[0]
if remainder != 0:
remainderVals = strval[4*numDwords:]
remainderVals.extend(bytearray([0]*(4-remainder)))
yield struct.unpack("<L", remainderVals)[0]
def hexlify(v): return '{:x}'.format(v)
def strToHex(strval): return ''.join(list(map(lambda k: '{:02x}'.format(ord(k)), strval)))
def bufToHex(bval): return ''.join(list(map(lambda k: '{:02x}'.format(k), bval)))
def doPrototype(proto, _strval):
strval = bytearray(_strval.encode())
v = []
for s in strval: v.append(proto.format(s))
return ' '.join(v)
def generateSmallStack(strval):
return ' $smallStack = {' + doPrototype('c6(45|4424)??{:02x}', strval) +'}'
def generateLargeStack(strval):
return ' $largeStack = {' + doPrototype('c7(45|85)[1-4]{:02x}000000', strval) + '}'
def generateRegister(strval):
return ' $register = {'+ doPrototype('b?{:02x}000000 6689????', strval) + '}'
def generateDword(_strval):
strval = bytearray(_strval.encode())
numDwords = int(len(strval)/4)
remainder = len(strval) - (numDwords*4)
values = []
for x in range(numDwords):
nextd = struct.unpack_from("<L", strval, 4*x)[0]
values.append('c7(45|85)[1-4]{:08x}'.format(nextd))
if remainder > 0:
if remainder == 3:
firstv, secondv = struct.unpack("<HB", strval[-remainder:])
print(firstv, secondv, "Oooops, something bad happened in generateDword, and yet we carry on:\n")
#print(firstv, secondv,file=sys.stderr)
values.append('[0-1]c7(45|85)[1-4]{:04x}'.format(firstv))
values.append('[0-1]c6(45|85)[1-4]{:02x}'.format(secondv))
elif remainder == 2:
firstv = struct.unpack("<H", strval[-remainder:])[0]
values.append('[0-1]c7(45|85)[1-4]{:04x}'.format(firstv))
elif remainder == 1:
values.append('[0-1]c6(45|85)[1-4]{:02x}'.format(strval[-1]))
return ' $dword = {'+(' '.join(values))+ '}'
def generatePushPop(strval):
return (' $pushpop = {'+
doPrototype('6a{:02x}5? ', strval[0]) +
doPrototype('6a{:02x} 6689????5?', strval[1:-1]) + '}')
def generateCallOverString(strval):
return (' $callOverString = {e8'+
bufToHex(struct.pack("<L", len(strval))) +
strToHex(strval) + '5? }')
def fixName(strval):
result = []
valid = string.ascii_letters + string.digits + '_'
for s in strval:
result.append('_' if s not in valid else s)
return ''.join(result)
def make_frenchstack_strings(strval):
nl = '\n'
clauses = []
clauses.append("rule ttp_mut_stack_french_{}".format(fixName(strval)))
clauses.append("{")
clauses.append("\tstrings:")
clauses.append(generateSmallStack(strval)+nl)
clauses.append(generateLargeStack(strval)+nl)
clauses.append(generateRegister(strval)+nl)
clauses.append(generateDword(strval)+nl)
clauses.append(generatePushPop(strval)+nl)
clauses.append(generateCallOverString(strval)+nl)
clauses.append("\tcondition:")
clauses.append("\t\tany of them")
clauses.append("}")
print(nl.join(clauses)+nl+nl)
#### bobstack
# bobstack stuff below courtesy of @bitsofbinary https://bitsofbinary.github.io/yara/2023/04/05/100daysofyara-day-95.html
def make_bobstack_strings(thing):
try:
if isinstance(thing,str):
api_name = thing
clean_str = re.sub('\W+','_',thing.strip())
one_byte_strs = []
two_byte_strs = []
four_byte_strs = []
for c in api_name:
### subbing in a '_' for any special characters into the string identifier
clean_char = re.sub('\W+','_',c.strip())
hex_str = f"$one_byte_mov_{clean_char}_stack = {{C6 44 24 ?? {format(ord(c), 'x')}}}"
if hex_str not in one_byte_strs:
one_byte_strs.append(hex_str)
for i in range(0, len(api_name)-1):
chars = api_name[i:i+2]
clean_chars = re.sub('\W+','_',chars.strip())
two_bytes = binascii.hexlify(chars.encode(), ' ').decode()
hex_str = f"$two_byte_mov_{clean_chars}_stack = {{66 C7 44 24 ?? {two_bytes}}}"
if hex_str not in two_byte_strs:
two_byte_strs.append(hex_str)
for i in range(0, len(api_name)-3):
chars = api_name[i:i+4]
clean_chars = re.sub('\W+','_',chars.strip())
four_bytes = binascii.hexlify(chars.encode(), ' ').decode()
hex_str = f"$four_byte_mov_{clean_chars}_stack = {{C7 44 24 ?? {four_bytes}}}"
if hex_str not in four_byte_strs:
four_byte_strs.append(hex_str)
print("rule ttp_mut_stack_bob_"+clean_str+" {")
print("\tstrings: ")
for string in one_byte_strs + two_byte_strs + four_byte_strs:
print("\t",string)
print('''
condition:
for any of ($four_byte_*) : (
any of ($one_byte_*, $two_byte_*) at @+8
)
}''')
except:
print("Uh oh, something bad happened in bobstack func")
####
def make_rot13_strings(thing):
try:
if isinstance(thing,str):
rot13 = str.maketrans(
'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
thing_rot13 = thing.translate(rot13)
return(thing_rot13)
# 'Uryyb Jbeyq!'
except:
print("Uh oh, something bad happened in rot13 func.")
def make_flipflop_strings(thing):
try:
if isinstance(thing,str):
str_len = len(thing)
s = thing
t = ""
thing_flip = t.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
return(thing_flip)
except:
print("Uh oh, something bad happened in flipflop func.")
def make_reverse_strings(thing):
try:
if isinstance(thing,str):
string_length = len(thing)
reversed_string = thing[string_length::-1]
return(reversed_string)
except:
print("Uh oh, something bad happened in reverse func.")
def make_hex_encoded_strings(thing):
# Hex encoding courtesy of @greglesnewich
try:
if isinstance(thing,str):
s = thing.encode('utf-8')
t = ""
thing_hex = t.join(s.hex())
return(thing_hex)
except:
print("Uh oh, something bad happened in hex encoding func.")
def make_dec_encoded_strings(thing):
try:
if isinstance(thing,str):
s = thing
t = " "
dec_list = []
for i in s:
dec_not = ord(i)
dec_list.append(dec_not)
stringed_list = t.join(str(e) for e in dec_list)
return(stringed_list)
except:
print("Uh oh, something bad happened in decimal encoding func.")
def make_fallchill_strings(thing):
# Lifted from https://lifars.com/wp-content/uploads/2021/09/Lazarus.pdf
try:
if isinstance(thing,str):
s = ''
for i in range (0, len(thing)):
b = hex(ord(thing[i]))
b = int(b,16)
if (b > 0x61) and (b < 0x7a):
c = int("0xdb",16) - b
s = s + str(bytearray.fromhex(str(hex(c))[2:]).decode())
else:
s = s + thing[i]
return(s)
except:
print("Is that a real string? Something bad happened in fallchill func.")
def make_stackpush_strings(thing):
try:
if isinstance(thing,str):
n = 4
out = [(thing[i:i+n]) for i in range(0, len(thing), n)]
out.reverse()
thing_stackpush=str('h'+'h'.join(map(str,out)))
return(thing_stackpush)
except:
print("Uh oh, something bad happened in stackpush func.")
def make_stackpush_nullterm(thing):
try:
if isinstance(thing,str):
n = 4
out = [(thing[i:i+n]) for i in range(0, len(thing), n)]
out.reverse()
thing_stackpush=str('h'+'h'.join(map(str,out)))
index = thing_stackpush.find('h',1)
final = thing_stackpush[:index] + "\\" + "x00" + thing_stackpush[index:]
return(final)
except:
print("Uh oh, something bad happened in stackpush_nullterm func.")
def make_stackpush_doublenullterm(thing):
try:
if isinstance(thing,str):
n = 4
out = [(thing[i:i+n]) for i in range(0, len(thing), n)]
out.reverse()
thing_stackpush=str('h'+'h'.join(map(str,out)))
index = thing_stackpush.find('h',1)
final = thing_stackpush[:index] + "\\" + "x00" + "\\" + "x00" + thing_stackpush[index:]
return(final)
except:
print("Uh oh, something bad happened in stackpush_nullterm func.")
def make_hex_mov_epb(thing):
try:
if isinstance(thing,str):
s = thing.encode('utf-8')
r = ""
thing_hex = r.join(s.hex())
t = "c645??"
movd = ""
for x in range(0, len(thing_hex),2):
movd += t
movd += thing_hex[x:x+2]
return(movd)
except:
print("Uh oh, something bad happened in mov epb func.")
# Add additional custom mutation functions ^ do things like reverse strings in diff formats, camel case, custom b64, b62, etc etc.
def assemble_output(clean_str,mut_type,mutated_str):
# Use this function to change how you prefer things to be formatted in the output.
# If you're feeling spunky maybe do a couple of versions, nocase ascii wide, xor, base64 base64 wide and so forth.
if "\\x00" in mutated_str:
print("\t$" + clean_str + mut_type + " = \"" + mutated_str + "\" nocase")
elif "_hex_" in mut_type and not "_hex_enc_str" in mut_type:
print("\t$" + clean_str + mut_type + " = {" + mutated_str + "}")
else:
#replace " with \"
yara_mutated_str1 = re.sub(r'\\',r'\\\\', mutated_str)
#replace \ with \\
yara_mutated_str2 = re.sub('"','\\"', yara_mutated_str1)
print("\t$" + clean_str + mut_type + " = \"" + yara_mutated_str2 + "\" nocase")
def main_active(args = sys.argv[1:]):
parser = argparse.ArgumentParser(prog = "cerebro-string-basic.py", description="Cerebro is a script for finding mutants. This takes a single string and dumps you out mutations of strings in YARA friendly formats. Beware, case sensitive inputs may yield less-than-optimal outputs.")
# File type input, but you could easily add a string input for oneoffs too.
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-s','--str', type=str, help='Single string to mutate.')
# Mutation selection choices.
parser.add_argument('-m','--mut','--mutation', choices=['flipflop','reverse','stackpush','stackpushnull','stackpushdoublenull','hex','decimal','movebp','rot13','fallchill','all','frenchstack','bobstack'], type=str, required=True)
args = parser.parse_args(args)
# Do stuff with arguments.
clean_str = re.sub('\W+','',args.str.strip())
in_string = args.str
mutation = args.mut
if args.str:
clean_str = re.sub('\W+','',args.str.strip())
in_string = args.str
mutation = args.mut
if args.mut:
print("\n")
if mutation == "flipflop":
mut_type = "_flipflop"
mutated_str = make_flipflop_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "stackpush":
mut_type = "_stackpush"
mutated_str = make_stackpush_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "stackpushnull":
mut_type = "_stackpushnull"
mutated_str = make_stackpush_nullterm(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "stackpushdoublenull":
mut_type = "_stackpushdoublenull"
mutated_str = make_stackpush_doublenullterm(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "reverse":
mut_type = "_reverse"
mutated_str = make_reverse_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "fallchill":
mut_type = "_fallchill"
mutated_str = make_fallchill_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "hex":
mut_type = "_hex_enc_str"
mutated_str = make_hex_encoded_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "decimal":
mut_type = "_decimal"
mutated_str = make_dec_encoded_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "movebp":
mut_type = "_hex_movebp"
mutated_str = make_hex_mov_epb(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "rot13":
mut_type = "_rot13"
mutated_str = make_rot13_strings(in_string)
assemble_output(clean_str,mut_type,mutated_str)
elif mutation == "bobstack":
make_bobstack_strings(in_string) #thank you @bitsofbinary!
elif mutation == "frenchstack":
make_frenchstack_strings(in_string) #thank you @notareverser!
elif mutation == "all": #everything *but* frenchstack / bobstack
funcs = [
make_flipflop_strings(in_string),
make_reverse_strings(in_string),
make_hex_encoded_strings(in_string),
make_dec_encoded_strings(in_string),
make_fallchill_strings(in_string),
make_stackpush_strings(in_string),
make_stackpush_nullterm(in_string),
make_stackpush_doublenullterm(in_string),
make_hex_mov_epb(in_string),
make_rot13_strings(in_string)
]
mut_types = ["_flipflop","_reverse","_hex_enc_str","_decimal","_fallchill","_stackpush","_stackpushnull","_stackpushdoublenull","_hex_movebp","_rot13"]
i = 0
for f in funcs:
mut_type = mut_types[i]
i+=1
mutated_str = f
assemble_output(clean_str,mut_type,mutated_str)
#make_frenchstack_strings(in_string)
#make_bobstack_strings(in_string)
else:
print("\nSomething bad happend with mutation selection.\n")
print("\n")
else:
print("\nError in mutations selection.\n")
#### main main
if __name__ == '__main__':
main_active()