-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjsjaws.py
executable file
·4677 lines (4109 loc) · 218 KB
/
jsjaws.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 re
import tempfile
from base64 import b64decode
from binascii import Error as BinasciiError
from glob import glob
from hashlib import sha256
from inspect import getmembers, isclass
from io import BytesIO
from json import JSONDecodeError, dumps, load, loads
from os import environ, listdir, mkdir, path
from pkgutil import iter_modules
from subprocess import PIPE, Popen, TimeoutExpired
from sys import modules
from threading import Thread
from time import sleep, time
from typing import Any, Dict, List, Optional, Set, Tuple
from urllib.parse import urlparse
from assemblyline.common import forge
from assemblyline.common.digests import get_sha256_for_file
from assemblyline.common.entropy import calculate_partition_entropy
from assemblyline.common.hexdump import load as hexload
from assemblyline.common.identify import CUSTOM_BATCH_ID, CUSTOM_PS1_ID
from assemblyline.common.str_utils import safe_str, truncate
from assemblyline.common.uid import get_id_from_data
from assemblyline_service_utilities.common.dynamic_service_helper import (
COMMON_FP_DOMAINS,
OntologyResults,
extract_iocs_from_text_blob,
)
from assemblyline_service_utilities.common.extractor.base64 import BASE64_RE
from assemblyline_service_utilities.common.safelist_helper import is_tag_safelisted
from assemblyline_service_utilities.common.tag_helper import add_tag
from assemblyline_v4_service.common.api import ServiceAPIError
from assemblyline_v4_service.common.base import ServiceBase
from assemblyline_v4_service.common.request import ServiceRequest
from assemblyline_v4_service.common.result import (
Heuristic,
KVSectionBody,
Result,
ResultGraphSection,
ResultMultiSection,
ResultSection,
ResultTableSection,
ResultTextSection,
TableRow,
TextSectionBody,
)
from assemblyline_v4_service.common.utils import PASSWORD_WORDS, extract_passwords
from bs4 import BeautifulSoup
from bs4.element import Comment, ResultSet, Tag
from dateutil.parser import parse as dtparse
from multidecoder.decoders.network import find_urls, is_domain, is_url
from multidecoder.decoders.shell import find_powershell_strings, get_powershell_command
from requests import get
from tinycss2 import parse_stylesheet
from yaml import safe_load as yaml_safe_load
import signatures
from signatures.abstracts import Signature
from tools import tinycss2_helper
from tools.gootloader.run import run as gootloader_run
from yara import Error as YARAError
from yara import compile as yara_compile
# Execution constants
# Default value for the maximum number of files found in the "payload" folder that MalwareJail creates, to be extracted
MAX_PAYLOAD_FILES_EXTRACTED = 50
# The SHA256 representation of the "Resource Not Found" response from MalwareJail that occurs
# when we pass the --h404 arg
RESOURCE_NOT_FOUND_SHA256 = "85658525ce99a2b0887f16b8a88d7acf4ae84649fa05217caf026859721ba04a"
# The SHA256 representation when MalwareJail creates a fake file when _download is set to "No"
FAKE_FILE_CONTENT = "5110232a47fc52354ed061b5e29979f4497ab2d3a3a402ad74f194acedfddad0"
# The string used in file contents to separate code dynamically created by JsJaws and the original script
DIVIDING_COMMENT = "// This comment was created by JsJaws"
# Static path to the system safelist file
SAFELIST_PATH = "al_config/system_safelist.yaml"
# We do not want to dynamically add these attributes to HTML elements
SAFELISTED_ATTRS_TO_POP = {
"link": ["href"],
"svg": ["xmlns"],
}
# Signature score translations
TRANSLATED_SCORE = {
0: 10, # Informational (0-24% hit rate)
1: 100, # On the road to being suspicious (25-34% hit rate)
2: 250, # Wow this file could be suspicious (35-44% hit rate)
3: 500, # Definitely Suspicious (45-50% hit rate)
4: 750, # Highly Suspicious, on the road to being malware (51-94% hit rate)
5: 1000, # Malware (95-100% hit rate)
}
# Default cap of 10k lines of stdout from tools, usually only applied to MalwareJail
STDOUT_LIMIT = 10000
# Strings indicative of a PE
PE_INDICATORS = [b"MZ", b"This program cannot be run in DOS mode"]
# Strings related to Character Data delimiters in markup languages
CDATA_START = "<![CDATA["
CDATA_END = "]]>"
# Variations of PowerShell found in WScript Shell commands
POWERSHELL_VARIATIONS = ["pwsh", "powershell"]
# Variations of Command Prompt found in WScript Shell commands
COMMAND_VARIATIONS = ["cmd"]
# Variations of cURL found in WScript Shell commands
CURL_VARIATIONS = ["curl"]
# Variations of bitsadmin found in WScript Shell commands
BITSADMIN_VARIATIONS = ["bitsadmin"]
# WshShell is a protected term because it is used as a module class name in MalwareJail
WSHSHELL = "WshShell"
# HTMLScriptElement/HTMLIFrameElement-related constants that will be used for seeking output in MalwareJail
HTMLSCRIPTELEMENT = "HTMLScriptElement"
HTMLIFRAMEELEMENT = "HTMLIFrameElement"
HTMLELEMENT_SRC_SET_TO_URI = ".src was set to a URI:"
# These characters are cannot be included in a variable name
INVALID_VARNAME_CHARS = ["-", " ", ":", ",", ";"]
# Enumerations
OBFUSCATOR_IO = "obfuscator.io"
MALWARE_JAIL = "MalwareJail"
JS_X_RAY = "JS-X-Ray"
BOX_JS = "Box.js"
SYNCHRONY = "Synchrony"
EXITED_DUE_TO_STDOUT_LIMIT = "EXITED_DUE_TO_STDOUT_LIMIT"
TEMP_JS_FILENAME = "temp_javascript.js"
GOOTLOADERAUTOJSDECODER = "GootLoaderAutoJsDecode"
# Default value for the maximum number of times the gauntlet should be run
# This usually gets exceeded when a script writes randomly generated content to the DOM
MAXIMUM_GAUNTLET_RUNS = 30
# When looking at HTML files, these are common terms found in phishing files
PHISHING_TITLE_TERMS = [
# Classic phishing terms for file names
"payment",
"statement",
"invoice",
"notice",
"download",
"transfer",
# These file-type specific terms of suspicious because this is an HTML file!
"\.xls",
"\.doc",
"\.ppt",
"\.one",
"\.pdf",
"microsoft",
"adobe",
"excel",
"word",
"powerpoint",
"onenote",
"pdf",
# https://github.com/CAPESandbox/community/blob/815e21980f4b234cf84e78749447f262af2beef9/modules/signatures/secure_login_phish.py
"secure login",
"google doc",
"dropbox",
"google drive",
"outlook",
# https://github.com/CAPESandbox/community/blob/d010d2c8a8343a37e176133edb26e901c2c8ced9/modules/signatures/suspicious_html.py
"please wait",
"redirecting",
"remittence",
"remittance",
"voicemail",
# Other
"paypal",
"instagram",
"facebook",
"secure",
"security",
"sign",
"bank",
"ether",
"coin",
"files",
"challenge",
"card",
"remember",
"forgot",
"verify",
"confirm",
]
# There is a signature called "phishing_terms" which is used for detecting terms commonly associated with phishing
# in the JavaScript code / emulation output
# These values will be used for this signature, as well as looking for "input" elements in the HTML that use these.
PHISHING_INPUTS = [
"email",
"account",
"phone",
"skype",
"e-mail",
"authentication",
"login",
"username",
"usrn",
"psrd",
"pswd",
"passwd",
"identity",
"card",
"mail",
"challenge",
]
# Regular Expressions
# Examples:
# WScript.Shell[99].Run(do the thing)
# Shell.Application[99].ShellExecute(do the thing)
WSCRIPT_SHELL_REGEX = r"(?:WScript\.Shell|Shell\.Application)\[\d+\]\.(?:Run|ShellExecute|Exec)\((.*)\)"
# Example:
# /*!
# * jQuery JavaScript Library v1.5
JQUERY_VERSION_REGEX = r"\/\*\!\n \* jQuery JavaScript Library v([\d\.]+(?:-[a-z0-9.]+)?)\n"
# Example:
# /**
# * Maplace.js
# *
# * Copyright (c) 2013 Daniele Moraschi
# * Licensed under the MIT license
# * For all details and documentation:
# * http://maplacejs.com
# *
# * @version 0.2.7
MAPLACE_REGEX = r"\/\*\*\n\* Maplace\.js\n[\n\r*\sa-zA-Z0-9\(\):\/\.@]+?@version ([\d\.]+)\n"
# Example:
# /*
# Copyright (c) 2011 Sencha Inc. - Author: Nicolas Garcia Belmonte (http://philogb.github.com/)
COMBO_REGEX = (
r"\/\*\nCopyright \(c\) 2011 Sencha Inc\. \- Author: Nicolas Garcia Belmonte \(http:\/\/philogb\.github\.com\/\)"
)
# Example:
# // Underscore.js 1.13.6
UNDERSCORE_REGEX = r"\/\/ Underscore.js ([\d\.]+)\n"
# Example:
# (function(){d3 = {version: "1.29.5"}; // semver
D3_REGEX = r"\(function\(\)\{d3 = \{version: \"(1.29.5)\"\}; \/\/ semver"
# Example:
# /**
# * @license
# * Lodash <https://lodash.com/>
# * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
# * Released under MIT license <https://lodash.com/license>
# * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
# * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
# */
# ;(function() {
# /** Used as a safe reference for `undefined` in pre-ES5 environments. */
# var undefined;
# /** Used as the semantic version number. */
# var VERSION = '4.17.21';
LODASH_REGEX = (
r"\/\*\*\n \* @license\n \* Lodash <https:\/\/lodash\.com\/>[\n\s*\w<:\/.>,&;(){}`\-=+]+var VERSION = '([\d.]+)';"
)
# Example:
#
# /*
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements. See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership. The ASF licenses this file
# * to you 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.
# */
#
# (function (global, factory) {
# typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
# typeof define === 'function' && define.amd ? define(['exports'], factory) :
# (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
# }(this, (function (exports) { 'use strict';
CHARTVIEW_REGEX = (
r"\s*\/\*[\s\S]+?\*\/\s*\(function\s+\(global,\s*factory\)\s*\{\s*typeof\s+exports\s*===\s*'object'"
r"\s*&&\s*typeof\s*module\s*!==\s*'undefined'\s*\?\s*factory\(exports\)\s*:\s*typeof\s+define\s*==="
r"\s*'function'\s*&&\s*define\.amd\s*\?\s*define\(\['exports'\],\s*factory\)\s*:\s*\(global\s*=\s*"
r"typeof\s+globalThis\s*!==\s*'undefined'\s*\?\s*globalThis\s*:\s*global\s*\|\|\s*self,\s*factory"
r"\(global\.echarts\s*=\s*\{\}\)\);\s*\}\(this,\s*\(function\s*\(exports\)\s*\{\s*'use\s+strict';"
)
# Example:
# ;(function() {
# "use strict";
# /**
# * @license
# * Copyright 2015 Google Inc. 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.
# */
# /**
# * A component handler interface using the revealing module design pattern.
MDL_REGEX = r";\(function\(\)\s*\{\s*\"use\sstrict\";\s*\/\*\*[\s\S]+?\*\/[\s\S]*\/\*\*\s*\*\s*A component handler interface using the revealing module design pattern\."
# Example:
# [2023-02-07T14:08:19.018Z] mailware-jail, a malware sandbox ver. 0.20\n
MALWARE_JAIL_TIME_STAMP = "\[([\dTZ:\-.]+)\] "
# Example:
# data:image/png;base64,iVBORw0KGgoAAAAN
APPENDCHILD_BASE64_REGEX = re.compile("data:(?:[^;]+;)+base64,([\s\S]*)")
# Example:
# const element99_jsjaws =
ELEMENT_INDEX_REGEX = re.compile(b"const element(\d+)\w*_jsjaws = ")
# Example:
# wscript_shell_object_env("test") = "Hello World!";
VBSCRIPT_ENV_SETTING_REGEX = (
b"[^;]\((?P<property_name>[\w\s()'\"+\\\\]{2,1000})\)\s*=\s*(?P<property_value>[^>=;\.]+?[^>=;]+);"
)
# Example:
# Exception occurred in aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: object blahblah:123
# badinputhere
# SyntaxError: Unexpected end of input
INVALID_END_OF_INPUT_REGEX = (
b"Exception occurred in [a-zA-Z0-9]{64}: object .+:\d+\n(.+)\nSyntaxError: Unexpected end of input"
)
# Example:
# Exception occurred in aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: object blahblah:123
# missingfunction()
# ReferenceError: missingfunction is not defined
REFERENCE_NOT_DEFINED_REGEX = (
b"Exception occurred in [a-zA-Z0-9]{64}: object .+:\d+\\n.+\\n\^\\nReferenceError: (.+) is not defined"
)
# JScript conditional comments
# Inspired by https://github.com/HynekPetrak/malware-jail/blob/master/jailme.js#L310:L315
# Example:
# /*@cc_on
AT_CC_ON_REGEX = b"\/\*@cc_on\s*"
# Example:
# @*/
AT_REGEX = b"@\*\/"
# Example:
# /*@if (@_jscript_version >= 7)
AT_IF_REGEX = b"\/\*@if\s*\(@_jscript_version\s[>=<]=\s\d\)\s*"
# Example:
# @elif (@_jscript_version >= 7)
AT_ELIF_REGEX = b"@elif\s*\(@_jscript_version\s[>=<]=\s\d\)\s*"
# Example:
# @else
AT_ELSE_REGEX = b"@else\s*"
# Example:
# /*@end
AT_END_REGEX = b"\/\*@end\s*"
JSCRIPT_REGEXES = [AT_CC_ON_REGEX, AT_REGEX, AT_IF_REGEX, AT_ELIF_REGEX, AT_ELSE_REGEX, AT_END_REGEX]
# Time-waster method structure, commonly found in Gootloader
# Examples:
# function blah1(blah2, blah3, blah4, blah5) {
# blah6=blah7;
# while(blah6<(blah2*blah8)) {
# blah6 = blah6 + blah7;
# }
# }
# or
# function blah1(blah2, blah3, blah4) {
# blah5=blah6;
# blah7=blah8;
# while(blah7<(blah2*(blah9))) {
# blah7++;
# }
# }
WHILE_TIME_WASTER_REGEX = b"function\s*\w{2,15}\s*\((?:\w{2,15}(?:,\s*)?){1,5}\)\s*{(?:\s*\w{2,15}\s*=\s*\w{2,15};)+\s*while\s*\(\w{2,15}\s*<\s*\(\w{2,15}\s*\*\s*\(?\w{2,15}\)?\)\)\s*{\s*(?:\w{2,15}\s*=\s*\w{2,15}\s*\+\s*\w{2,15}\s*|\w{2,15}\+\+);\s*}\s*}"
# Examples:
# function blah1() {
# blah2(blah3);
# blah4 = blah5;
# while(blah6 = blah7) {
# try{
# blah8[blah9](blah9);
# } catch(blah10){
# blah8[1272242] = blah11;
# }
# blah9++
# }
# }
# or
# function blah1() {
# blah2(blah3);
# blah4 = blah5;
# while(blah6) {
# try{
# blah7=blah8[blah9](blah9);
# } catch(blah10){
# blah11=1272242;
# blah8[blah11] = blah12;
# }
# blah9++
# }
# }
# or
# function blah1(blah2, blah3, blah4, blah5) {
# blah6(blah7);
# blah8 = blah9;
# while (blah10) {
# blah11++;
# blah11 = blah11;
# try {
# blah12 = (blah13[blah11](blah11));
# } catch (blah14) {
# blah15 = 1272242;
# blah13[(blah15)] = blah16;
# }
# }
# }
WHILE_TRY_CATCH_TIME_WASTER_REGEX = b"function\s+\w{2,15}\((?:\w{2,15}(?:,\s*)?){0,5}\)\s*{\s*\w{2,15}\(\w{2,15}\);\s*\w{2,15}\s*=\s*\w{2,15};\s*while\s*\(\w{2,15}\s*(?:=\s*\w{2,15})?\)\s*{\s*(?:\w{2,15}\[\w{2,15}\]\s*=\s*\w{2,15};\s*|\w{2,15}\s*=\s*\w{2,15};\s*|\w{2,15}\+\+;\s*)*try\s*{\s*(?:\w{2,15}\s*=\s*)?\(?\w{2,15}\[\w{2,15}\]\(\w{2,15}\)\)?;\s*}\s*catch\s*\(\w{2,15}\)\s*{\s*(?:\w{2,15}\[\(?\w{2,15}\)?\]\s*=\s*\w{2,15};|\w{2,15}\s*=\s*\w{2,15};\s*)+\s*}\s*(?:\w{2,15}\+\+;?)?\s*}\s*}"
TIME_WASTER_REGEXES = [WHILE_TIME_WASTER_REGEX, WHILE_TRY_CATCH_TIME_WASTER_REGEX]
# These regular are used for converting simple VBScript to JavaScript so that we can run it all in JsJaws
# Example:
# blah = "blahblah"
VBS_GRAB_VARS_REGEX = "(?P<variable_name>\w{2,10})\s*=\s*(?P<variable_value>[\"'].+[\"'])"
# Examples:
# Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
# or
# Dim blah
# Set blah = CreateObject("wscript.shell")
VBS_WSCRIPT_SHELL_REGEX = (
"Dim\s+(?P<varname>\w+)\s+:?\s*Set\s+(?P=varname)\s*=\s*CreateObject\([\"']wscript\.shell[\"']\)"
)
# Example:
# WshShell.RegWrite "blah\blah\blah\blah\blah", varname, "REG_SZ"
VBS_WSCRIPT_REG_WRITE_REGEX = (
"%s\.RegWrite\s+(?P<key>[\w\"'\\\\]+),\s*(?P<content>[\w\"'.()]+),\s*(?P<type>[\w\"'.()]+)"
)
# Examples:
# blah "http://blah.com/evil.exe"
# or
# Call blah(varname)
VBS_FUNCTION_CALL = "(?:Call\s*)?%s\(?\s*(?P<func_args>[\w'\":\/.-]+)\s*\)?"
# Examples:
# var blah = Function("blah", varname);
# or
# var blah = new Function("blah", varnamey);
# or
# function blah(thing1, thing2)
# {
# return(new Function(thing1, thing2));
# }
JS_NEW_FUNCTION_REGEX = "(?:(var|function))\s+(?P<function_varname>\w+)(?:(\s*=\s*|\((?:\w{2,10}(?:,\s*)?)+\)\s*{\s*return\s*\())(?:new)?\s+Function\((?P<function_name>[\w\"']+),\s*(?P<args>[\w.()\"'\/&,\s]+)\)\)?;(\s*})?"
# Example:
# var new_blah = blah("blah", thing2);
JS_NEW_FUNCTION_REASSIGN_REGEX = "(?P<new_name>\w+)\s*=\s*%s"
# Example:
# document.write(unescape("blah"))
DOM_WRITE_UNESCAPE_REGEX = "(document\.write\(unescape\(.+\))"
# Example:
# document.write(atob(val));
DOM_WRITE_ATOB_REGEX = "(document\.write\((window\.)?atob\(.+\))"
# Example:
# HTMLScriptElement[9].src was set to a URI 'http://blah.com'
HTMLELEMENT_SRC_REGEX = f"(?:{HTMLSCRIPTELEMENT}|{HTMLIFRAMEELEMENT})\[[0-9]+\]{HTMLELEMENT_SRC_SET_TO_URI} '(.+)'"
# Example:
# <!-- HTML Encryption provided by www.blah.com -->
FULL_HTML_COMMENT_IN_JS = b"(^|\n)\s*(\<\!\-\-[\s\S]+?\-\-\>)\s*;?\n"
# Example:
# function a0nnnnoo() {
# var fmicaiaimxeof = ['bunch', 'of', 'nonsense'];
# a0nnnnoo = function() {
# return fmicaiaimxeof;
# };
# return a0nnnnoo();
# };
FUNCTION_INCEPTION = b"function\s+(?P<function_name>\w+)\(\)\s*\{\s*var\s+(?P<variable_name>\w+)\s*=\s*\[[\s\S]+?\];\s*(?P=function_name)\s*=\s*function\(\)\s*\{\s*return\s+(?P=variable_name);\s*\};\s*return\s+(?P=function_name)\(\);\s*\};"
# Example:
# adc4bc7c-8f35-4a85-91e9-dc822b07f60d
BOX_JS_PAYLOAD_FILE_NAME = "[a-z0-9]{8}\-(?:[a-z0-9]{4}\-){3}[a-z0-9]{12}"
# Example:
# 'adc4bc7c-8f35-4a85-91e9-dc822b07f60d.js'
SNIPPET_FILE_NAME = BOX_JS_PAYLOAD_FILE_NAME + "\.js"
# Examples:
# <!DOCTYPE html>
# or
# <html>
HTML_START = b"(^|\n|\>)[ \t]*(?P<html_start><!doctype html>|<html)"
# Example:
# atob was seen decoding a URI: 'http://blah.com'
ATOB_URI_REGEX = "atob was seen decoding a URI: '(.+)'"
# Example:
# Payment.xls
# or
# Invoice.pdf
PHISHING_TITLE_TERMS_REGEX = r"\b(" + "|".join(PHISHING_TITLE_TERMS) + r")\b"
def is_vb_script(script: Tag) -> bool:
return script.get("language", "").lower() == "vbscript" or script.get("type", "").lower() == "text/vbscript"
def is_js_script(script: Tag) -> bool:
"""Checks if script is javascript or jscript"""
if "type" in script:
return script["type"].lower() in ("", "text/javascript", "text/jscript")
if "language" in script:
return script["language"].lower() in ("", "javascript", "jscript")
return True # default is text/javascript if there is no type/language
class JsJaws(ServiceBase):
def __init__(self, config: Optional[Dict] = None) -> None:
super(JsJaws, self).__init__(config)
self.artifact_list: Optional[List[Dict[str, str]]] = None
self.malware_jail_payload_extraction_dir: Optional[str] = None
self.malware_jail_sandbox_env_dump: Optional[str] = None
self.malware_jail_sandbox_env_dir: Optional[str] = None
self.malware_jail_sandbox_env_dump_path: Optional[str] = None
self.path_to_jailme_js: Optional[str] = None
self.path_to_boxjs: Optional[str] = None
self.path_to_boxjs_boilerplate: Optional[str] = None
self.path_to_jsxray: Optional[str] = None
self.path_to_synchrony: Optional[str] = None
self.boxjs_urls_json_path: Optional[str] = None
self.malware_jail_urls_json_path: Optional[str] = None
self.wscript_only_config: Optional[str] = None
self.extracted_wscript_batch: Optional[str] = None
self.extracted_wscript_ps1: Optional[str] = None
self.extracted_wscript_batch_path: Optional[str] = None
self.extracted_wscript_ps1_path: Optional[str] = None
self.boxjs_batch: Optional[str] = None
self.boxjs_batch_path: Optional[str] = None
self.boxjs_ps1: Optional[str] = None
self.boxjs_ps1_path: Optional[str] = None
self.malware_jail_output: Optional[str] = None
self.malware_jail_output_path: Optional[str] = None
self.boxjs_output_dir: Optional[str] = None
self.boxjs_iocs: Optional[str] = None
self.boxjs_resources: Optional[str] = None
self.boxjs_analysis_log: Optional[str] = None
self.boxjs_snippets: Optional[str] = None
self.cleaned_with_synchrony: Optional[str] = None
self.cleaned_with_synchrony_path: Optional[str] = None
self.stdout_limit: Optional[int] = None
self.identify = forge.get_identify(use_cache=environ.get("PRIVILEGED", "false").lower() == "true")
self.safelist: Dict[str, Dict[str, List[str]]] = {}
self.doc_write_hashes: Optional[Set[str]] = None
self.gauntlet_runs: Optional[int] = None
# Used for maintaining the sample type as manipulations occur in the service per execution
self.sample_type: Optional[str] = None
# Script sources that are NOT programatically created
# (or at least, written to the DOM via code)
self.initial_script_sources: Optional[Set[str]] = None
# Script sources that ARE programatically created
# (or at least, written to the DOM via code)
self.subsequent_script_sources: Optional[Set[str]] = None
self.script_with_source_and_no_body: Optional[bool] = None
self.scripts: Set[str] = set()
self.malformed_javascript: Optional[bool] = None
self.function_inception: Optional[bool] = None
self.ignore_stdout_limit: Optional[bool] = None
# Flag that the sample was embedded within a third party library
self.embedded_code_in_lib: Optional[str] = None
# List of malicious domains detected from a gootloader sample
self.gootloader_uris: Optional[List[str]] = None
# Persistence data from a gootloader sample
self.gootloader_persistence: Optional[Dict[str, str]] = None
# Flag that the sample contains a single script that writes unescaped values to the DOM
self.single_script_with_unescape: Optional[bool] = None
# Flag that the sample contains multiple scripts that write unescaped values to the DOM
self.multiple_scripts_with_unescape: Optional[bool] = None
# Flag that the sample contains leading garbage
self.leading_garbage: Optional[bool] = None
# Flag that the split_reverse_join signature was raised
self.split_reverse_join: Optional[bool] = None
# Flag that the file is phishing
self.is_phishing: Optional[bool] = None
# Flag that the file sets long base64-encoded strings to weird attributes, like innerText or input:value
self.weird_base64_value_set: Optional[bool] = None
# List of marks to indicate if a base64-encoded URL was base64-decoded
self.base64_encoded_urls: List[str] = []
# URL is seen in the same execution as a "SaveToFile", "WritesExecutable" and "RunsShell"
self.url_used_for_suspicious_exec: Optional[bool] = None
# Used for heuristic 22
self.low_body_elements: Optional[bool] = None
# Used for heuristic 23
self.html_document_write: Optional[bool] = None
# Used for heuristic 24
self.html_phishing_title: Set[str] = set()
# Used for heuristic 25
self.phishing_inputs: Set[str] = set()
# Used for heuristic 26
self.password_input_and_no_form_action: Optional[bool] = None
# List of URLs found in suspicious forms, used for heuristic 27
self.sus_form_actions: Set[str] = set()
# Map of scripts found and their corresponding entropies
self.script_entropies: Dict[str, Any] = dict()
# The number of web bugs/beacons found in an HTML document
self.num_of_web_bugs = 0
# Used for heuristic 25, to show that a form exists and that there are a small amount of input elements
self.short_form = False
self.log.debug("JsJaws service initialized")
def start(self) -> None:
try:
self.safelist = self.get_api_interface().get_safelist()
except ServiceAPIError as e:
self.log.warning(f"Couldn't retrieve safelist from service: {e}. Continuing without it..")
if not self.safelist:
with open(SAFELIST_PATH, "r") as f:
self.safelist = yaml_safe_load(f)
self.stdout_limit = self.config.get("total_stdout_limit", STDOUT_LIMIT)
def _reset_execution_variables(self) -> None:
"""
This method resets variables that are expected to return to their default values when a new sample is received.
:return: None
"""
# Reset per sample
self.doc_write_hashes = set()
self.embedded_code_in_lib = None
self.gootloader_uris = list()
self.gootloader_persistence = dict()
self.single_script_with_unescape = False
self.multiple_scripts_with_unescape = False
self.gauntlet_runs = 0
self.initial_script_sources = set()
self.subsequent_script_sources = set()
self.scripts = set()
self.script_with_source_and_no_body = False
self.malformed_javascript = False
self.function_inception = False
self.leading_garbage = False
self.split_reverse_join = False
self.is_phishing = False
self.weird_base64_value_set = False
self.url_used_for_suspicious_exec = False
self.low_body_elements = False
self.html_document_write = False
self.password_input_and_no_form_action = False
self.base64_encoded_urls = []
self.html_phishing_title = set()
self.phishing_inputs = set()
self.sus_form_actions = set()
self.script_entropies = dict()
self.num_of_web_bugs = 0
self.short_form = False
def _reset_gauntlet_variables(self, request: ServiceRequest) -> None:
"""
This method resets variables that are expected to return to their default values when a gauntlet run begins.
:param request: The ServiceRequest object
:return: None
"""
# Reset per gauntlet run
self.artifact_list = []
request.result = Result()
self.script_with_source_and_no_body = False
def _handle_filtered_code(self, file_path: str, file_content: bytes) -> Tuple[str, bytes]:
"""
This method handles filtering code from third-party libraries, or not!
:param file_path: The path of the file
:param file_content: The content of the file
:return: A tuple of the file path and the file content
"""
# Let's try using the Gootloader-decoder lib first
gootloader_config = gootloader_run(
file_path,
unsafe_uris=True,
# The only reason we pass these variables is so that task cleanup is done
payload_path=path.join(self.working_directory, "DecodedJsPayload.js_"),
stage2_path=path.join(self.working_directory, "GootLoader3Stage2.js_"),
log=self.log.debug,
)
# If we have a hit
if gootloader_config and gootloader_config.urls:
for uri in gootloader_config.urls:
stripped_uri = uri.strip()
# URI should exist, URI should actually be a URI, or URI is actually a domain
if not stripped_uri or (not is_url(stripped_uri.encode()) and not is_domain(stripped_uri.encode())):
continue
self.gootloader_uris.append(stripped_uri)
if self.gootloader_uris:
self.log.debug(f"Extracted malicious URIs from a GOOTLOADER sample using {GOOTLOADERAUTOJSDECODER}")
self.embedded_code_in_lib = f"Unknown. We used {GOOTLOADERAUTOJSDECODER} to decode."
if gootloader_config.persistence:
self.gootloader_persistence = gootloader_config.persistence.__dict__
if gootloader_config.code:
return gootloader_config.final_stage_path, gootloader_config.code.encode()
# Looks like the Gootloader-decoder did not work (at least for extracting the malicious code from the common
# library). Let's try to use the libraries we manually extracted.
try:
filtered_file_path, filtered_file_content, lib_path = self._extract_filtered_code(file_content)
if filtered_file_path and filtered_file_content:
self.log.debug(f"Extracted malicious code from a third-party library: {lib_path}")
file_path = filtered_file_path
file_content = filtered_file_content
self.embedded_code_in_lib = lib_path
except UnicodeDecodeError:
pass
return file_path, file_content
def _remove_leading_garbage_from_html(
self, request: ServiceRequest, file_path: str, file_content: bytes
) -> Tuple[str, bytes]:
"""
This method removes garbage text from HTML files that have been mis-identified
:param request: The ServiceRequest object
:param file_path: The path of the file
:param file_content: The content of the file
:return: A tuple of the file path and the file content
"""
if request.file_type not in ["code/html", "code/hta", "code/svg"]:
# First check to see there is an obvious <html> tag somewhere
html_start = re.search(HTML_START, file_content)
html_comment = None
if not html_start:
# If no obvious <html> tag, check if there are HTML/XML comments
html_comment = re.search(FULL_HTML_COMMENT_IN_JS, file_content)
if html_start or html_comment:
# Setup some defaults for leading garbage and the script we want
garbage = b""
script_we_want = b""
if html_start:
idx = file_content.index(html_start.group("html_start"))
# If the index is 0, then there is no leading garbage
if idx > 0:
garbage = file_content[:idx]
script_we_want = file_content[idx:]
elif html_comment and len(html_comment.regs) > 2:
start_idx, end_idx = html_comment.regs[2]
# If the index is 0, then there is no leading garbage
if start_idx > 0:
garbage = file_content[start_idx:end_idx]
script_we_want = file_content[:start_idx] + file_content[end_idx:]
# If there is leading garbage, write to disk and identify
if garbage != b"":
with tempfile.NamedTemporaryFile(dir=self.working_directory, delete=False, mode="wb") as t:
t.write(garbage)
garbage_path = t.name
garbage_info = self.identify.fileinfo(garbage_path, generate_hashes=False)
with tempfile.NamedTemporaryFile(dir=self.working_directory, delete=False, mode="wb") as t:
t.write(script_we_want)
script_we_want_path = t.name
script_we_want_info = self.identify.fileinfo(script_we_want_path, generate_hashes=False)
else:
# Otherwise, return!
return file_path, file_content
if garbage_info["type"] not in [
"code/javascript",
"code/html",
"code/hta",
"code/jscript",
"code/wsf",
"code/wsc",
] and script_we_want_info["type"] in ["code/html", "code/hta", "image/svg"]:
self.log.debug("Removed garbage from the file...")
self.sample_type = script_we_want_info["type"]
return script_we_want_path, script_we_want
else:
# If there is more than one HTML comment, recursively remove
html_comment = re.search(FULL_HTML_COMMENT_IN_JS, script_we_want)
if html_comment:
try:
return self._remove_leading_garbage_from_html(request, script_we_want_path, script_we_want)
except RecursionError as e:
self.log.debug(f"Exiting _remove_leading_garbage_from_html due to '{e}'")
return file_path, file_content
def _handle_vbscript_env_variables(self, file_path: str, file_content: bytes) -> Tuple[str, bytes]:
"""
This is a VBScript method of setting an environment variable:
var wscript_shell_object = CreateObject("WScript.Shell")
var wscript_shell_object_env = wscript_shell_object.Environment("USER")
wscript_shell_object_env("test") = "Hello World!";
The above code is also valid in JavaScript when we are not intercepting the
WScript.Shell object. However, since we are doing so, the act of
setting the environment variable using round brackets is not possible and will
result in an "ReferenceError: Invalid left-hand side in assignment"
error.
Therefore we are going to hunt for instances of this, and replace
it with an accurate JavaScript technique for setting variables.
:param file_path: The path of the file
:param file_content: The content of the file
:return: A tuple of the file path and the file content
"""
def log_and_replace(match) -> bytes:
"""
This nested method looks for matches of the VBSCRIPT_ENV_SETTING_REGEX regular
expression, logs the match for debugging purposes, then replaces it
:param match: The regular expression match
:return: The value to replace the match
"""
if len(match.regs) != 3:
return
property_name = match.group("property_name").decode()
# We only want the last property assigned \(.+\), despite the regex capturing consecutive \(.+\)+
if ")(" in property_name:
# Therefore split
split_property_name = match.group(0).split(b")(")[-1]
another_match = re.search(VBSCRIPT_ENV_SETTING_REGEX, b"test(" + split_property_name)
if another_match:
property_name = another_match.group("property_name").decode()
property_value = another_match.group("property_value").decode()
try:
property_value = match.group("property_value").decode()
except UnicodeDecodeError:
return
self.log.debug(f"Replaced VBScript Env variable: ({truncate(property_name)}) = {truncate(property_value)};")
# Since we are looking for the character prior to this assignment, we need to add it again
leading_char_index = match.regs[0][0]
try:
decoded_match_string = match.string.decode()
except UnicodeDecodeError:
return
if leading_char_index > len(decoded_match_string):
return
leading_char = decoded_match_string[leading_char_index]
return f"{leading_char}[{property_name}] = {property_value};".encode()
new_content = re.sub(VBSCRIPT_ENV_SETTING_REGEX, log_and_replace, file_content)
if new_content != file_content:
with tempfile.NamedTemporaryFile(dir=self.working_directory, delete=False, mode="wb") as f:
file_content = new_content
f.write(file_content)
file_path = f.name
return file_path, file_content
def execute(self, request: ServiceRequest) -> None:
file_path = request.file_path
file_content = request.file_contents
self.sample_type = request.file_type
# Initial setup per sample
self._reset_execution_variables()
self.ignore_stdout_limit = request.get_param("ignore_stdout_limit")
# Handle UTF-16 Encoding with BOM
if file_content[:2] in (b"\xFF\xFE", b"\xFE\xFF"):
file_content = file_content.decode("utf-16").encode("utf-8")
with tempfile.NamedTemporaryFile(dir=self.working_directory, delete=False, mode="wb") as f:
f.write(file_content)
file_path = f.name
original_contents = file_content
if self.sample_type in ["code/javascript", "code/jscript"]:
file_path, file_content = self._handle_filtered_code(file_path, file_content)
file_path, file_content_with_no_leading_garbage = self._remove_leading_garbage_from_html(
request, file_path, file_content
)
if file_content_with_no_leading_garbage != file_content:
file_content = file_content_with_no_leading_garbage
self.leading_garbage = True
# There are always false positive hits in embedded code for VBScript env variables, so let's avoid that
if not self.embedded_code_in_lib:
file_path, file_content = self._handle_vbscript_env_variables(file_path, file_content)
# File constants
self.malware_jail_payload_extraction_dir = path.join(self.working_directory, "payload/")
self.malware_jail_sandbox_env_dump = "sandbox_dump.json"
self.malware_jail_sandbox_env_dir = path.join(self.working_directory, "sandbox_env")
self.malware_jail_sandbox_env_dump_path = path.join(
self.malware_jail_sandbox_env_dir, self.malware_jail_sandbox_env_dump
)
root_dir = path.dirname(path.abspath(__file__))
self.path_to_jailme_js = path.join(root_dir, "tools/malwarejail/jailme.js")
self.path_to_boxjs = path.join(root_dir, "tools/node_modules/box-js/run.js")
self.path_to_boxjs_boilerplate = path.join(root_dir, "tools/node_modules/box-js/boilerplate.js")
self.path_to_jsxray = path.join(root_dir, "tools/js-x-ray-run.js")
self.path_to_synchrony = path.join(root_dir, "tools/node_modules/.bin/synchrony")
self.malware_jail_urls_json_path = path.join(self.malware_jail_payload_extraction_dir, "urls.json")
self.wscript_only_config = path.join(root_dir, "tools/malwarejail/config/config_wscript_only.json")
self.extracted_wscript_batch = "extracted_wscript.bat"
self.extracted_wscript_batch_path = path.join(
self.malware_jail_payload_extraction_dir, self.extracted_wscript_batch
)
self.extracted_wscript_ps1 = "extracted_wscript.ps1"
self.extracted_wscript_ps1_path = path.join(
self.malware_jail_payload_extraction_dir, self.extracted_wscript_ps1
)
self.boxjs_batch = "boxjs_cmds.bat"
self.boxjs_batch_path = path.join(self.malware_jail_payload_extraction_dir, self.boxjs_batch)
self.boxjs_ps1 = "boxjs_cmds.ps1"
self.boxjs_ps1_path = path.join(self.malware_jail_payload_extraction_dir, self.boxjs_ps1)
self.malware_jail_output = "output.txt"
self.malware_jail_output_path = path.join(self.working_directory, self.malware_jail_output)
# Box.js creates an output directory in the working level directory with the name <file_name>.results
# We must use globs to find the specific file paths
self.boxjs_output_dir = path.join(self.working_directory, "*.results")
self.boxjs_urls_json_path = path.join(self.boxjs_output_dir, "urls.json")
self.boxjs_iocs = path.join(self.boxjs_output_dir, "IOC.json")
self.boxjs_resources = path.join(self.boxjs_output_dir, "resources.json")
self.boxjs_analysis_log = path.join(self.boxjs_output_dir, "analysis.log")
self.boxjs_snippets = path.join(self.boxjs_output_dir, "snippets.json")
self.cleaned_with_synchrony = f"{request.sha256}.cleaned"
self.cleaned_with_synchrony_path = path.join(self.working_directory, self.cleaned_with_synchrony)
# Setup directory structure
if not path.exists(self.malware_jail_payload_extraction_dir):
mkdir(self.malware_jail_payload_extraction_dir)
if not path.exists(self.malware_jail_sandbox_env_dir):
mkdir(self.malware_jail_sandbox_env_dir)
self._run_the_gauntlet(request, file_path, file_content, original_contents)
if path.exists(self.cleaned_with_synchrony_path):
# Set this to avoid a loop of Synchrony extractions
request.temp_submission_data["cleaned_by_synchrony"] = True