| 1 |
# |
| 2 |
# simple unpacker/deobfuscator for scripts messed up with |
| 3 |
# javascriptobfuscator.com |
| 4 |
# |
| 5 |
# written by Einar Lielmanis <[email protected]> |
| 6 |
# rewritten in Python by Stefano Sanfilippo <[email protected]> |
| 7 |
# |
| 8 |
# Will always return valid javascript: if `detect()` is false, `code` is |
| 9 |
# returned, unmodified. |
| 10 |
# |
| 11 |
# usage: |
| 12 |
# |
| 13 |
# if javascriptobfuscator.detect(some_string): |
| 14 |
# some_string = javascriptobfuscator.unpack(some_string) |
| 15 |
# |
| 16 |
|
| 17 |
"""deobfuscator for scripts messed up with JavascriptObfuscator.com""" |
| 18 |
|
| 19 |
import re |
| 20 |
|
| 21 |
PRIORITY = 1 |
| 22 |
|
| 23 |
|
| 24 |
def smartsplit(code): |
| 25 |
"""Split `code` at " symbol, only if it is not escaped.""" |
| 26 |
strings = [] |
| 27 |
pos = 0 |
| 28 |
while pos < len(code): |
| 29 |
if code[pos] == '"': |
| 30 |
word = "" # new word |
| 31 |
pos += 1 |
| 32 |
while pos < len(code): |
| 33 |
if code[pos] == '"': |
| 34 |
break |
| 35 |
if code[pos] == "\\": |
| 36 |
word += "\\" |
| 37 |
pos += 1 |
| 38 |
word += code[pos] |
| 39 |
pos += 1 |
| 40 |
strings.append('"%s"' % word) |
| 41 |
pos += 1 |
| 42 |
return strings |
| 43 |
|
| 44 |
|
| 45 |
def detect(code): |
| 46 |
"""Detects if `code` is JavascriptObfuscator.com packed.""" |
| 47 |
# prefer `is not` idiom, so that a true boolean is returned |
| 48 |
return re.search(r"^var _0x[a-f0-9]+ ?\= ?\[", code) is not None |
| 49 |
|
| 50 |
|
| 51 |
def unpack(code): |
| 52 |
"""Unpacks JavascriptObfuscator.com packed code.""" |
| 53 |
if detect(code): |
| 54 |
matches = re.search(r"var (_0x[a-f\d]+) ?\= ?\[(.*?)\];", code) |
| 55 |
if matches: |
| 56 |
variable = matches.group(1) |
| 57 |
dictionary = smartsplit(matches.group(2)) |
| 58 |
code = code[len(matches.group(0)) :] |
| 59 |
for key, value in enumerate(dictionary): |
| 60 |
code = code.replace(r"%s[%s]" % (variable, key), value) |
| 61 |
return code |