2
# Unpacker for Dean Edward's p.a.c.k.e.r, a part of javascript beautifier
3
# by Einar Lielmanis <einar@jsbeautifier.org>
5
# written by Stefano Sanfilippo <a.little.coder@gmail.com>
9
# if detect(some_string):
10
# unpacked = unpack(some_string)
13
"""Unpacker for Dean Edward's p.a.c.k.e.r"""
17
from jsbeautifier.unpackers import UnpackingError
22
"""Detects whether `source` is P.A.C.K.E.R. coded."""
23
return source.replace(' ', '').startswith('eval(function(p,a,c,k,e,r')
26
"""Unpacks P.A.C.K.E.R. packed js code."""
27
payload, symtab, radix, count = _filterargs(source)
29
if count != len(symtab):
30
raise UnpackingError('Malformed p.a.c.k.e.r. symtab.')
33
unbase = Unbaser(radix)
35
raise UnpackingError('Unknown p.a.c.k.e.r. encoding.')
38
"""Look up symbols in the synthetic symtab."""
40
return symtab[unbase(word)] or word
42
source = re.sub(r'\b\w+\b', lookup, payload)
43
return _replacestrings(source)
45
def _filterargs(source):
46
"""Juice from a source file the four args needed by decoder."""
47
argsregex = (r"}\('(.*)', *(\d+), *(\d+), *'(.*)'\."
48
r"split\('\|'\), *(\d+), *(.*)\)\)")
49
args = re.search(argsregex, source, re.DOTALL).groups()
52
return args[0], args[3].split('|'), int(args[1]), int(args[2])
54
raise UnpackingError('Corrupted p.a.c.k.e.r. data.')
56
def _replacestrings(source):
57
"""Strip string lookup table (list) and replace values in source."""
58
match = re.search(r'var *(_\w+)\=\["(.*?)"\];', source, re.DOTALL)
61
varname, strings = match.groups()
62
startpoint = len(match.group(0))
63
lookup = strings.split('","')
64
variable = '%s[%%d]' % varname
65
for index, value in enumerate(lookup):
66
source = source.replace(variable % index, '"%s"' % value)
67
return source[startpoint:]
71
class Unbaser(object):
72
"""Functor for a given base. Will efficiently convert
73
strings to natural numbers."""
75
62 : '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
76
95 : (' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ'
77
'[\]^_`abcdefghijklmnopqrstuvwxyz{|}~')
80
def __init__(self, base):
83
# If base can be handled by int() builtin, let it do it for us
85
self.unbase = lambda string: int(string, base)
87
# Build conversion dictionary cache
89
self.dictionary = dict((cipher, index) for
90
index, cipher in enumerate(self.ALPHABET[base]))
92
raise TypeError('Unsupported base encoding.')
94
self.unbase = self._dictunbaser
96
def __call__(self, string):
97
return self.unbase(string)
99
def _dictunbaser(self, string):
100
"""Decodes a value to an integer."""
102
for index, cipher in enumerate(string[::-1]):
103
ret += (self.base ** index) * self.dictionary[cipher]