|
| 1 | +# Based on https://github.com/beautifier/js-beautify/blob/main/python/jsbeautifier/unpackers/packer.py |
| 2 | +from re import compile, DOTALL, ASCII |
| 3 | + |
| 4 | +class UnpackingError(Exception): |
| 5 | + pass |
| 6 | + |
| 7 | +DETECT_PATTERN = compile( |
| 8 | + r"eval[ ]*\([ ]*function[ ]*\([ ]*p[ ]*,[ ]*a[ ]*,[ ]*c[ ]*,[ ]*k[ ]*,[ ]*e[ ]*,[ ]*" |
| 9 | +) |
| 10 | +FILTERARGS_PATTERNS = [ |
| 11 | + compile(r"}\('(.*)', *(\d+|\[\]), *(\d+), *'(.*)'\.split\('\|'\), *(\d+), *(.*)\)\)", DOTALL), |
| 12 | + compile(r"}\('(.*)', *(\d+|\[\]), *(\d+), *'(.*)'\.split\('\|'\)", DOTALL), |
| 13 | +] |
| 14 | +WORD_PATTERN = compile(r"\b\w+\b", ASCII) |
| 15 | +REPLACESTRINGS_PATTERN = compile(r'var *(_\w+)\=\["(.*?)"\];', DOTALL) |
| 16 | + |
| 17 | +def detect(source: str) -> tuple[bool, str, str]: |
| 18 | + """Detects whether `source` is P.A.C.K.E.R. coded.""" |
| 19 | + beginstr = "" |
| 20 | + endstr = "" |
| 21 | + begin_offset = -1 |
| 22 | + mystr = DETECT_PATTERN.search(source) |
| 23 | + if mystr: |
| 24 | + begin_offset = mystr.start() |
| 25 | + beginstr = source[:begin_offset] |
| 26 | + if begin_offset != -1: |
| 27 | + source_end = source[begin_offset:] |
| 28 | + if source_end.split("')))", 1)[0] == source_end: |
| 29 | + try: |
| 30 | + endstr = source_end.split("}))", 1)[1] |
| 31 | + except IndexError: |
| 32 | + endstr = "" |
| 33 | + else: |
| 34 | + endstr = source_end.split("')))", 1)[1] |
| 35 | + return mystr is not None, beginstr, endstr |
| 36 | + |
| 37 | +def unpack(source: str, beginstr: str = "", endstr: str = "") -> str: |
| 38 | + """Unpacks P.A.C.K.E.R. packed js code.""" |
| 39 | + payload, symtab, radix, count = _filterargs(source) |
| 40 | + |
| 41 | + if count != len(symtab): |
| 42 | + raise UnpackingError("Malformed p.a.c.k.e.r. symtab.") |
| 43 | + |
| 44 | + try: |
| 45 | + unbase = Unbaser(radix) |
| 46 | + except TypeError: |
| 47 | + raise UnpackingError("Unknown p.a.c.k.e.r. encoding.") |
| 48 | + |
| 49 | + def lookup(match) -> str: |
| 50 | + """Look up symbols in the synthetic symtab.""" |
| 51 | + word = match.group(0) |
| 52 | + return symtab[unbase(word)] or word |
| 53 | + |
| 54 | + payload = payload.replace("\\\\", "\\").replace("\\'", "'") |
| 55 | + source = WORD_PATTERN.sub(lookup, payload) |
| 56 | + return _replacestrings(source, beginstr, endstr) |
| 57 | + |
| 58 | +def _filterargs(source: str) -> tuple[str, list[str], int, int]: |
| 59 | + """Juice from a source file the four args needed by decoder.""" |
| 60 | + for juicer in FILTERARGS_PATTERNS: |
| 61 | + args = juicer.search(source) |
| 62 | + if args: |
| 63 | + a = args.groups() |
| 64 | + if a[1] == "[]": |
| 65 | + a = list(a) |
| 66 | + a[1] = 62 |
| 67 | + a = tuple(a) |
| 68 | + try: |
| 69 | + return a[0], a[3].split("|"), int(a[1]), int(a[2]) |
| 70 | + except ValueError: |
| 71 | + raise UnpackingError("Corrupted p.a.c.k.e.r. data.") |
| 72 | + raise UnpackingError("Could not make sense of p.a.c.k.e.r data (unexpected code structure)") |
| 73 | + |
| 74 | +def _replacestrings(source: str, beginstr: str = "", endstr: str = "") -> str: |
| 75 | + """Strip string lookup table (list) and replace values in source.""" |
| 76 | + match = REPLACESTRINGS_PATTERN.search(source) |
| 77 | + if match: |
| 78 | + varname, strings = match.groups() |
| 79 | + startpoint = len(match.group(0)) |
| 80 | + lookup = strings.split('","') |
| 81 | + variable = "%s[%%d]" % varname |
| 82 | + for index, value in enumerate(lookup): |
| 83 | + source = source.replace(variable % index, '"%s"' % value) |
| 84 | + return source[startpoint:] |
| 85 | + return beginstr + source + endstr |
| 86 | + |
| 87 | +class Unbaser: |
| 88 | + """Functor for a given base. Will efficiently convert strings to natural numbers.""" |
| 89 | + ALPHABET = { |
| 90 | + 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", |
| 91 | + 95: ( |
| 92 | + " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 93 | + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" |
| 94 | + ), |
| 95 | + } |
| 96 | + |
| 97 | + def __init__(self, base: int): |
| 98 | + self.base = base |
| 99 | + |
| 100 | + if 36 < base < 62: |
| 101 | + if base not in self.ALPHABET: |
| 102 | + self.ALPHABET[base] = self.ALPHABET[62][:base] |
| 103 | + |
| 104 | + if 2 <= base <= 36: |
| 105 | + self.unbase = lambda string: int(string, base) |
| 106 | + else: |
| 107 | + try: |
| 108 | + self.dictionary = {cipher: index for index, cipher in enumerate(self.ALPHABET[base])} |
| 109 | + except KeyError: |
| 110 | + raise TypeError("Unsupported base encoding.") |
| 111 | + |
| 112 | + self.unbase = self._dictunbaser |
| 113 | + |
| 114 | + def __call__(self, string: str) -> int: |
| 115 | + return self.unbase(string) |
| 116 | + |
| 117 | + def _dictunbaser(self, string: str) -> int: |
| 118 | + """Decodes a value to an integer.""" |
| 119 | + ret = 0 |
| 120 | + for index, cipher in enumerate(string[::-1]): |
| 121 | + ret += (self.base**index) * self.dictionary[cipher] |
| 122 | + return ret |
0 commit comments