-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGootLoaderAutoJsDecode.py
More file actions
713 lines (538 loc) · 25.5 KB
/
GootLoaderAutoJsDecode.py
File metadata and controls
713 lines (538 loc) · 25.5 KB
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
#!/usr/bin/env python
# filename : GootLoaderAutoJsDecode.py
# description : GootLoader automatic static JS decoder
# author : @andy2002a - Andy Morales
# author : @g0vandS - Govand Sinjari
# date : 2023-01-13
# updated : 2025-11-05
# version : 3.8.1
# usage : python GootLoaderAutoJsDecode.py malicious.js
# output : DecodedJsPayload.js_ and GootLoader3Stage2.js_
# py version : 3
#
# Note: To make JS files readable, you can use CyberChef JavaScript or
# Generic Code Beautify
#
############################
#
# Legal Notice
#
# Copyright 2023 Mandiant. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
############################
# pylint: disable=g-line-too-long
# pylint: disable=invalid-name
# pylint: disable=bad-indentation
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
import argparse
import re
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('jsFilePath', help='Path to the GOOTLOADER JS file.')
args = parser.parse_args()
goot3detected = False
def defang(input_str):
if not input_str.strip():
return input_str
# most domains/ip/url have a dot, match anything not already in brackets ([^\[])\.([^\]])
start = input_str
end = ''
ignoreNext = False
for i, _ in enumerate(input_str):
if ignoreNext:
ignoreNext = False
continue
# if input_str has a single slash, not a double slash, split it at the first one and just escape the first half.
# this avoids escaping the domains' URI dots, which are always after the first single slash
if input_str[i] == '/':
if (i + 1) < len(input_str) and input_str[i + 1] == '/':
ignoreNext = True
continue
start = input_str[:i]
end = input_str[i:]
break
result = re.compile("([^\\[])\\.([^\\]])").sub(r'''\1[.]\2''', start) + end
# but not all! http://0x7f000001 ([^\[]):([^\]])
# result = result.replaceAll(new RegExp("([^\\[]):([^\\]])", 'g'), "$1[:]$2");
result = re.compile(r'''([^\\[]):([^\\]])''').sub(r'''\1[:]\2''', result)
if result.lower().startswith('http'):
result = result.replace('https', 'hxxps')
result = result.replace('http', 'hxxp')
return result
def ConvertVarsToDict(inArray):
# Converts variables to a dict
# Adds the first 2 items only since the rest is not part of the match
varDict = {}
for arItem in inArray:
varDict.update({arItem[0]: arItem[1]})
return varDict
def convertConcatToString(inputConcatMatches, inputVarsDict, noEquals=False):
# Joins multiple concat operations into a string
# V3 matches do not have an equal sign so add some dummy text
if noEquals:
dummyEquals = 'dummy='+inputConcatMatches.replace('(', '').replace(')', '')
inputConcatMatches = [dummyEquals]
for index, concatItem in enumerate(inputConcatMatches):
# Remove any unwanted characters and split on '='
splitItem = re.sub(r'[;\s\(\)]', '', concatItem).split('=')
currentLineString = ''
for additionItem in splitItem[1].split('+'):
try:
# look up the items in the dict and join them together
currentLineString += inputVarsDict[additionItem]
except:
# probably a junk match
continue
if index != len(inputConcatMatches) - 1:
# add the items back into the dict so that they can be referenced later in the loop
inputVarsDict.update({splitItem[0]: currentLineString})
else:
# This is the last item in the list
# return the full encoded line fixing escaped chars
return currentLineString.encode('raw_unicode_escape').decode('unicode_escape')
def decodeString(scripttext):
# Gootloader decode function
ans = ''
for i in range(0, len(scripttext)):
if i % 2 == 1:
ans += scripttext[i]
else:
ans = scripttext[i] + ans
return ans
def rotateSplitText(string, count):
for i in range(count+1):
string = string[1:]+string[0]
return str(string)
# V3 Decoding scripts converted from their JS versions
def remainder(v1, v2, v3):
# The 3 and the 1 could possibly change in the future
if(v3 % (3-1)):
rtn = v1+v2
else:
rtn = v2+v1
return rtn
def rtrSub(inputStr, idx1):
# use this odd format of substring so that it matches the way JS works
return inputStr[idx1:(idx1+1)]
def workFunc(inputStr):
outputStr = ''
for i in range(len(inputStr)):
var1 = rtrSub(inputStr, i)
outputStr = remainder(outputStr, var1, i)
return outputStr
def findFileInStr(fileExtension, stringToSearch):
fileExtensionPattern = re.compile(r'''["']([a-zA-Z0-9_\-\s]+\.''' + fileExtension + r''')["']''') ## Find: "Example Engineering.log"
regexMatch = fileExtensionPattern.search(stringToSearch)
if (regexMatch):
dataFound = regexMatch.group(1)
else:
dataFound = 'NOT FOUND'
return dataFound
def getGootVersion(topFileData):
goot3linesRegex = 'GOOT3'
goot3linesPattern = re.compile(goot3linesRegex, re.MULTILINE)
gloader3sample = False
gloader21sample = False
if re.search(r'jQuery JavaScript Library v\d{1,}\.\d{1,}\.\d{1,}$', topFileData):
print('\nGootLoader Obfuscation Variant 2.0 detected')
gloader21sample = False
elif goot3linesPattern.match(topFileData):
print('\nGootLoader Obfuscation Variant 3.0 detected\n\nIf this fails try using CyberChef "JavaScript Beautify" against the file first.')
gloader3sample = True
# 3 and 2 have some overlap so enabling both flags for simplicity
gloader21sample = True
else:
print('\nGootLoader Obfuscation Variant 2.1 or higher detected')
gloader21sample = True
return gloader21sample, gloader3sample
def separateFileAndTaskString(regexPattern, delimiter, inputString):
# searches and returns text that has been joined together with a delimiter
splitTextPattern = re.compile(regexPattern)
splitTextResult = splitTextPattern.search(inputString)
if splitTextResult:
splitTextArray = splitTextResult.group(1).split(delimiter)
return splitTextArray
else:
return None
def getFileandTaskData(inputString):
s2FirstFileName = s2JsFileName = persistenceItemName = persistenceType = 'N/A'
splitTextArray = None
# Check to see if the code has been reversed, and reverse it back to normal if so
if 'noitcnuf' in inputString:
inputString = inputString[::-1]
# New samples like b20162ee69b06184d87dc2f5665f5c80 have added another character replacement
charReplacementRegex = re.compile(r'''\.replace\(\/(.)\/g,\s?['"](.)['"]\)''') # Find: .replace(/!/g, 'e')
charReplacementResult = charReplacementRegex.search(inputString)
# Replace the chars in the input strings with those from the regex result
if charReplacementResult:
inputString = inputString.replace(charReplacementResult.group(1), charReplacementResult.group(2))
# Find the string that has been joined together with a delimiter (usually by |)
# some new samples are using @ as a separator rather than | : MD5: d5e60e0941ebcef5436406a7ecf1d0f1
regexPatternAndDelimiter = [
# [r'''(?<=\=)\s?"((?:.{3,30}?\|.{3,30}){5,})";''', '|'], # Find: "text|text2|text3";
# [r'''(?<=\=)\s?"((?:.{3,30}?\@.{3,30}){5,})";''', '@'] # Find: "text@text2@text3";
# The previous patters would sometimes causes the regex to hang. Testing this one out to see if it is better.
[r'''(?<=\=)\s?"([\w~\.\s%]+(?:\|[\w~\.\s%]+)+)";''', '|'], # Find: "text|text2|text3";
[r'''(?<=\=)\s?"([\w~\.\s%]+(?:\@[\w~\.\s%]+)+)";''', '@'] # Find: "text@text2@text3";
]
for patternDelim in regexPatternAndDelimiter:
separationResult = separateFileAndTaskString(patternDelim[0], patternDelim[1], inputString)
if separationResult:
splitTextArray = separationResult
# exit the loop if we get a hit
break
if patternDelim == regexPatternAndDelimiter[-1]:
# hit the last delimiter without getting a hit.
return None
# un-rotate the strings
fixedStrings = []
for i in range(len(splitTextArray)):
fixedStrings.append(rotateSplitText(splitTextArray[i], i))
# Find the file names in the array
for fixedString in fixedStrings:
if fixedString.endswith(('.log', '.dat', '.txt', '.xml')):
s2FirstFileName = fixedString
elif fixedString.endswith('.js'):
s2JsFileName = fixedString
# In some instances the .log/.js file was outside of the "|" separated string. Try to find it outside
if 's2FirstFileName' not in locals():
s2FirstFileName = findFileInStr('(?:log|dat)', inputString)
if 's2JsFileName' not in locals():
s2JsFileName = findFileInStr('js', inputString)
# Find the offset of the scheduled task name
taskCreationRegexPattern = re.compile(
r'''\((\w+),\s?(\w+),\s?6,\s['"]{2}\s?,\s?['"]{2}\s?,\s?3\s?\)''' # Find: (str1, str2, 6, "" , "" , 3)
)
taskCreationResult = taskCreationRegexPattern.search(inputString)
# Newer variants use an LNK file
lnkPersistencePattern = re.compile(
r'''\(\w+,\s?\w+\s?\+\s?['"]\\\\['"]\s?\+\s?(\w+)\s?\+\s?\w\(\d{1,3}\)\)''' # Find (BBBB, CCCC + '\\' + AAAAAA + f(40)) ## Where AAAAAAA is the variable we want
)
lnkPersistenceResult = lnkPersistencePattern.search(inputString)
persistenceVariableName = ''
if taskCreationResult:
persistenceVariableName = taskCreationResult.group(1)
persistenceType = 'Scheduled Task'
elif lnkPersistenceResult:
persistenceVariableName = lnkPersistenceResult.group(1)
persistenceType = 'LNK File'
if persistenceVariableName:
persistenceOffsetPattern = re.compile(
r'''\}''' + persistenceVariableName + r'''\s?=\s\w{1,2}\((\d{1,3})\);''' # Find: }str1 = Z(41);
)
persistenceOffsetMatch = persistenceOffsetPattern.search(inputString)
if persistenceOffsetMatch:
persistenceOffset = int(persistenceOffsetMatch.group(1))
persistenceItemName = fixedStrings[persistenceOffset]
if lnkPersistenceResult:
persistenceItemName += '.lnk'
else:
# MD5 9565187442f857bd47c8ab0859009752 had the task name in plain text
persistenceStrPattern = re.compile(
r'''\}''' + persistenceVariableName + r'''\s?=\s"(.{10,232})";''' # Find: }str1 = "Task Name";
)
persistenceStrMatch = persistenceStrPattern.search(inputString)
if persistenceStrMatch:
persistenceItemName = persistenceStrMatch.group(1)
# Get hotkey combination
hotkeyPattern = re.compile(
r'''\.hotkey=["'](\w+(?:\+\w+)+)["']''', # Find .Hotkey="CTRL+RR+E"
flags=re.IGNORECASE
)
hotkeyResult = hotkeyPattern.search(inputString)
if hotkeyResult:
hotkeyCombination = hotkeyResult.group(1)
else:
hotkeyCombination = 'N/A'
Stage2Data = 'File and Persistence data:\n'
FilePersistenceFileName = 'FileAndPersistenceData.txt'
Stage2Data += '\nFirst File Name: ' + s2FirstFileName
Stage2Data += '\nJS File Name: ' + s2JsFileName
Stage2Data += '\nPersistence Item Name: ' + persistenceItemName
Stage2Data += '\nPersistence Type: ' + persistenceType
Stage2Data += '\nHotkey: ' + hotkeyCombination
with open(FilePersistenceFileName, mode='w') as file:
file.write(Stage2Data)
Stage2Data += '\n\nData Saved to: ' + FilePersistenceFileName
print('\n'+Stage2Data+'\n')
def invokeStage2Decode(inputString, inputVarsDict):
# Get all the relevant variables from the sample
v3workFuncVarsPattern = re.compile(
r'''(?:\((?:[a-zA-Z0-9_]{1,}\s{0,}\+\s{0,}){1,}[a-zA-Z0-9_]{1,}\s{0,}\))''' # Find: (var1+var2+var3)
)
v3WorkFuncVars = v3workFuncVarsPattern.search(inputString)[0]
stage2JavaScript = workFunc(convertConcatToString(v3WorkFuncVars, inputVarsDict, True))
# Get all the string variables on their own line
strVarPattern = re.compile(
r'''([a-zA-Z0-9_]{1,}\s{0,}=(["'])((?:\\\2|(?:(?!\2)).)*)(\2);)(?=([a-zA-Z0-9_]{1,}\s{0,}=)|function)''' # Find: var='xxxxx';[var2=|function]
)
strVarsNewLine = re.sub(strVarPattern, r'\n\1\n', stage2JavaScript)
# Get all the var concat on their own line
strConcPattern = re.compile(
r'''([a-zA-Z0-9_]{1,}\s{0,}=\s{0,}(?:[a-zA-Z0-9_]{1,}\s{0,}\+\s{0,}){1,}[a-zA-Z0-9_]{1,}\s{0,};)''' # Find: var1 = var2+var3
)
strConcatNewLine = re.sub(strConcPattern, r'\n\1\n', strVarsNewLine)
# Attempt to find the last variable and add a tab in front of it. This search is imperfect since the line could be shorter than what this regex picks up.
finalStrConcPattern = re.compile(
r'''([a-zA-Z0-9_]{1,}\s{0,}=\s{0,}(?:[a-zA-Z0-9_]{1,}\s{0,}\+\s{0,}){5,}[a-zA-Z0-9_]{1,}\s{0,};)''' # Find: var0 = var1+var2+var3+var4+var5+var6
)
finalStrConcNewLine = re.sub(finalStrConcPattern, r'\n\t\1\n', strConcatNewLine)
# put 1:1 variables on their own lines
strVar1to1Pattern = re.compile(
r'''((?:\n|^)[a-zA-Z0-9_]{1,}\s{0,}=\s{0,}[a-zA-Z0-9_]{1,};)''' # Find: var = var2;
)
str1to1NewLine = re.sub(strVar1to1Pattern, r'\n\1\n', finalStrConcNewLine)
# put long digits on their own lines
strLongDigitPattern = re.compile(
r''';(\d{15,};)''' # Find: ;216541846845465456465121312313221456456465;
)
finalRegexStr = re.sub(strLongDigitPattern, r';\n\1\n', str1to1NewLine)
outputString = []
for line in finalRegexStr.splitlines():
# clean up the empty lines
if line.strip():
outputString.append(line)
outputString = '\n'.join(outputString)
return outputString
def findCodeMatchInRound1Result(inputStr):
# Find code text in the result of the first decode round
findCodeinQuotePattern = re.compile(
r"(?<!\\)(?:\\\\)*'([^'\\]*(?:\\.[^'\\]*)*)'"
)
outputStr = max(findCodeinQuotePattern.findall(inputStr), key=len) # Return the longest string since that is the one that will contain the data
return outputStr
def getVariableAndConcatPatterns(isGloader21Sample):
if isGloader21Sample:
# 2.1 sample
# Regex Group 1 = variable name
# Regex Group 2 = string
varPattern = re.compile(
r'''(?:^([a-zA-Z0-9_]{1,})\s{0,}=\s{0,}'(.*)'\s{0,};)|''' # Find: var='str';
r'''(?:^([a-zA-Z0-9_]{1,})\s{0,}=\s{0,}"(.*)"\s{0,};)|''' # Find: var = "str";
r'''(?:^([a-zA-Z0-9_]{1,})\s{0,}=\s{0,}(\d{1,});)''' # Find: var = 1234;
, re.MULTILINE
)
concPattern = re.compile(
r'''(?:^[a-zA-Z0-9_]{1,}\s{0,}=\s{0,}(?:\(?[a-zA-Z0-9_]{1,}\)?\s{0,}(?:\+|\-)\s{0,}){1,}\(?[a-zA-Z0-9_]{1,}\)?\s{0,};)|''' # Find: var1 = var2+var3+(var4);
r'''(?:^[a-zA-Z0-9_]{1,}\s{0,}=\s{0,}[a-zA-Z0-9_]{1,}\s{0,};)''' # Find: var1 = var2;
, re.MULTILINE
)
else:
# pre-2.1 sample
# Find the obfuscated code line
varPattern = re.compile(
r'''(?:([a-zA-Z0-9_]{1,})\s{0,}=\s{0,}'(.+?)'\s{0,};)|''' # Find: var = 'str';
r'''(?:([a-zA-Z0-9_]{1,})\s{0,}=\s{0,}"(.+?)"\s{0,};)''' # Find: var = "str";
, re.MULTILINE
)
concPattern = re.compile(
r'''(?:[a-zA-Z0-9_]{1,}\s{0,}=\s{0,}(?:[a-zA-Z0-9_]{1,}\s{0,}\+\s{0,}){1,}[a-zA-Z0-9_]{1,}\s{0,};)|''' # Find: var1 = var2+var3+var4;
r'''(?:[a-zA-Z0-9_]{1,}\s{0,}=\s{0,}[a-zA-Z0-9_]{1,}\s{0,};)''' # Find: var1 = var2;
, re.MULTILINE
)
return varPattern, concPattern
def getDataToDecode(isGloader21Sample, inputData):
if isGloader21Sample:
outputData = inputData
else:
findObfuscatedPattern = re.compile(
r'''((?<=\t)|(?<=\;))(.{800,})(\n.*\=.*\+.*)*'''
)
outputData = findObfuscatedPattern.search(inputData)[0].replace('\n', ' ').replace('\r', ' ')
return outputData
def parseRound2Data(round2InputStr, round1InputStr, variablesDict, isGootloader3sample):
if round2InputStr.startswith('function'):
print('GootLoader Obfuscation Variant 3.0 sample detected.')
# File Names and scheduled task
try:
getFileandTaskData(decodeString(round1InputStr.encode('raw_unicode_escape').decode('unicode_escape')))
except:
print('Unable to parse Scheduled Task and Second Stage File Names')
global goot3detected
goot3detected = True
outputCode = 'GOOT3\n' + invokeStage2Decode(round2InputStr, variablesDict)
outputFileName = 'GootLoader3Stage2.js_'
print('\nScript output Saved to: %s\n' % outputFileName)
print('\nThe script will new attempt to deobfuscate the %s file.' % outputFileName)
else:
if isGootloader3sample:
outputCode = round2InputStr.replace("'+'", '').replace("')+('", '').replace('+()+', '').replace('?+?', '')
# new samples have added this character replacement, might be worth doing this programmatically in the future
outputCode = outputCode.replace('~+~', '')
# Check to see if the code has been reversed, and reverse it back to normal if so
# Sample MD5: 2e6e43e846c5de3ecafdc5f416b72897
if 'sptth' in outputCode:
outputCode = outputCode[::-1]
powershell_cookie_identifier = extract_cookie_identifier(outputCode)
cookie_identifier_string = 'Cookie Identifier: %s' % powershell_cookie_identifier
print('\n' + cookie_identifier_string)
user_agent = extract_user_agent(outputCode)
user_agent_string = 'User Agent: %s' % user_agent
print(user_agent_string)
# Write output file
with open('PowerShell_Network_IOCs.txt', mode='w') as file:
file.write(cookie_identifier_string+'\n'+user_agent_string)
v3DomainRegex = re.compile(
r'''(?:(?:https?):\/\/)[^\[|^\]|^\/|^\\|\s]*\.[^'"]+'''
)
maliciousDomains = re.findall(v3DomainRegex, outputCode)
else:
outputCode = round2InputStr
v2DomainRegex = re.compile(
r'(.*)(\[\".*?\"\])(.*)'
)
domainsMatch = v2DomainRegex.search(round2InputStr)[2]
maliciousDomains = domainsMatch.replace('[', '').replace(']', '').replace('"', '').replace('+(', '').replace(')+', '').split(',')
outputFileName = 'DecodedJsPayload.js_'
# Print to screen
print('\nScript output Saved to: %s\n' % outputFileName)
outputDomains = ''
for dom in maliciousDomains:
outputDomains += defang(dom) + '\n'
print('\nMalicious Domains: \n\n%s' % outputDomains)
return outputCode, outputFileName
def extract_obfuscated_ps_array(input_str):
# Extracts an array of obfuscated arrays from the larger PowerShell code
powershell_string_array_regex = re.compile(
# this regex will probably need updating when payloads start changing
r'''(?<=join\(\()"(.+?)"\|%{''' # Find: join(("str","str","str"|%{
# The capture group purposely excludes the first and last quote. This makes the .split() operation easier
)
powershell_string_match = powershell_string_array_regex.search(input_str)
if (powershell_string_match):
powershell_string = powershell_string_match.group(1)
else:
powershell_string = ''
output_array = powershell_string.split('","')
return output_array
def decode_powershell_array(input_array, index_num):
# Decodes a string that has been split across several arrays
# Sample input:
#
# 'ne!he'
# 'wOb!ll'
# 'ject|o'
#
# Output:
#
# func(0) = newObject
# func(1) = hello
split_delimiter = '!' # This is what current payloads are using.
new_2d_array = []
output_string = ''
for i in range(len(input_array)):
new_2d_array.insert(i, input_array[i].split(split_delimiter))
# This can probably be part of the previous loop but separating to make debugging easier later
for i in range(len(new_2d_array)):
output_string += new_2d_array[i][index_num]
return output_string
def extract_cookie_identifier(input_str):
# The cookie variable is in a code arrea that looks like:
# $tRuUcQ=$JXTLNoRq;
# $tRuUcQ`1=$bTDNv;
# $tRuUcQ`2=$Uivf;
# $tRuUcQ`3=$MVbnBAb;
# $tRuUcQ`4=$fPZxM");
cookie_identifier = 'N/A'
cookie_variable_regex = re.compile(
r'''(?<=\$)(\w+?)(?=`1)''' # Find: $str`1
)
cookie_variable_match = cookie_variable_regex.search(input_str)
if cookie_variable_match:
cookie_variable_name = cookie_variable_match.group(1)
else:
# match failed, return N/A
return cookie_identifier
cookie_offset_regex = re.compile(
# looks for the variable name being set as a result of a function exec. Where 18 is the cookie offset
(r'''(?<=\$''' + cookie_variable_name + r'''=\(\w\s)\d{1,2}''') # Find: $str=(N 18)
)
cookie_offset_match = cookie_offset_regex.search(input_str)
if cookie_offset_match:
cookie_offset = int(cookie_offset_match.group(0))
else:
# match failed, return N/A
return cookie_identifier
powershell_ofuscated_array = extract_obfuscated_ps_array(input_str)
cookie_identifier = decode_powershell_array(powershell_ofuscated_array, cookie_offset)
return cookie_identifier
def extract_user_agent(input_str):
output_string = 'N/A'
user_agent_concat_regex = re.compile(
r'''(?<=useragent=)\(\w\s\d{1,2}\)(\+\(\w\s\d{1,2}\))+''', # Find: .USeraGeNt=(Y 14)+(Y 25)+(Y 4)+(Y 8)
re.IGNORECASE
)
user_agent_concat_match = user_agent_concat_regex.search(input_str)
if user_agent_concat_match:
user_agent_concat = user_agent_concat_match.group(0)
else:
# match failed, return an empty string
return output_string
all_user_agent_index_regex = re.compile(
r'''\d{1,2}''' # Find: (Y 14)
)
all_user_agent_index_match = all_user_agent_index_regex.findall(user_agent_concat)
if all_user_agent_index_match:
output_string = ''
powershell_ofuscated_array = extract_obfuscated_ps_array(input_str)
for i in all_user_agent_index_match:
output_string += decode_powershell_array(powershell_ofuscated_array, int(i))
return output_string
else:
# match failed, return an empty string
return output_string
def gootDecode(path):
# Open File
with open(path, mode="r", encoding="utf-8") as file:
# Check for the GootLoader obfuscation variant
fileTopLines = ''.join(file.readlines(5))
gootloader21sample, gootloader3sample = getGootVersion(fileTopLines)
# reset cursor to read again
file.seek(0)
fileData = file.read()
# Extract the relevant data that will be decoded
dataToDecode = getDataToDecode(gootloader21sample, fileData)
# Get the regex patterns that will be used to find variables and concat lines
variablesPattern, concatPattern = getVariableAndConcatPatterns(gootloader21sample)
# Find all the variables
variablesAllmatches = variablesPattern.findall(dataToDecode)
VarsDict = ConvertVarsToDict(variablesAllmatches)
# Find all the concat functions
concatAllmatches = concatPattern.findall(dataToDecode)
if gootloader21sample:
# Some variants have the final variable in the middle of the code. Search for it separately so that it shows up last.
lastConcatPattern = re.compile(
# This is split into 2 regex because the lookbehind must be a fixed length
r"""(?:(?<=\t)\s*\w+\s*=\s*\(?\w+(?:\s?\+\s?\w+)+\)?;)|""" # Find: [tab]var1 = var2+var3+var4+var5+var6+var7;
r"""(?:(?<=\)\{)\s*\w+\s*=\s*\(?\w+(?:\s?\+\s?\w+)+\)?;)""" # Find: ){var1 = var2+var3+var4+var5+var6+var7;
# Find: ){var1 = (var2+var3+var4+var5+var6+var7);
, re.MULTILINE
)
concatAllmatches += list(sorted(lastConcatPattern.findall(fileData), key=len))
Obfuscated1Text = convertConcatToString(concatAllmatches, VarsDict)
# run the decoder
round1Result = decodeString(Obfuscated1Text)
# Find code text in the result of the first decode round
CodeMatch = findCodeMatchInRound1Result(round1Result)
# run the decode function against the previous result
round2Result = decodeString(CodeMatch.encode('raw_unicode_escape').decode('unicode_escape'))
round2Code, round2FileName = parseRound2Data(round2Result, round1Result, VarsDict, gootloader3sample)
# Write output file
with open(round2FileName, mode='w') as file:
file.write(round2Code)
gootDecode(args.jsFilePath)
if goot3detected:
gootDecode('GootLoader3Stage2.js_')