| 1 |
"""Compress and obfuscate JavaScript code. |
| 2 |
|
| 3 |
It includes classes and methods for parsing, encoding, and packing JavaScript |
| 4 |
scripts to reduce their size and improve performance. |
| 5 |
|
| 6 |
ParseMaster, version 1.0 (pre-release) (2005/05/12) x6 |
| 7 |
Copyright 2005, Dean Edwards |
| 8 |
Web: http://dean.edwards.name/ |
| 9 |
|
| 10 |
This software is licensed under the CC-GNU LGPL |
| 11 |
Web: http://creativecommons.org/licenses/LGPL/2.1/ |
| 12 |
|
| 13 |
Ported to Python by Florian Schulze |
| 14 |
|
| 15 |
""" |
| 16 |
|
| 17 |
from __future__ import annotations |
| 18 |
|
| 19 |
import functools |
| 20 |
import re |
| 21 |
from typing import Callable |
| 22 |
|
| 23 |
|
| 24 |
class Pattern: |
| 25 |
"""A multi-pattern parser. |
| 26 |
|
| 27 |
Args: |
| 28 |
expression (str): The regular expression pattern to match. |
| 29 |
replacement (str | Callable): The replacement string or function. |
| 30 |
If None, the pattern will be deleted. |
| 31 |
length (int): The number of sub-expressions in the pattern. |
| 32 |
""" |
| 33 |
|
| 34 |
def __init__( |
| 35 |
self, expression: str, replacement: str | Callable, length: int |
| 36 |
) -> None: |
| 37 |
self.expression = expression |
| 38 |
self.replacement = replacement |
| 39 |
self.length = length |
| 40 |
|
| 41 |
def __str__(self) -> str: |
| 42 |
"""Return the string representation of the pattern. |
| 43 |
|
| 44 |
Returns: |
| 45 |
str: The string representation of the pattern. |
| 46 |
""" |
| 47 |
return f"({self.expression})" |
| 48 |
|
| 49 |
|
| 50 |
class Patterns(list): |
| 51 |
"""A collection of patterns.""" |
| 52 |
|
| 53 |
def __str__(self) -> str: |
| 54 |
"""Return the string representation of the patterns. |
| 55 |
|
| 56 |
Returns: |
| 57 |
str: The string representation of the patterns. |
| 58 |
""" |
| 59 |
return "|".join([str(e) for e in self]) |
| 60 |
|
| 61 |
|
| 62 |
class ParseMaster: |
| 63 |
"""ParseMaster is a class for parsing and replacing patterns in strings.""" |
| 64 |
|
| 65 |
# constants |
| 66 |
EXPRESSION = 0 |
| 67 |
REPLACEMENT = 1 |
| 68 |
LENGTH = 2 |
| 69 |
GROUPS = re.compile(r"\(", re.M) # g |
| 70 |
SUB_REPLACE = re.compile(r"\$\d", re.M) |
| 71 |
INDEXED = re.compile(r"^\$\d+$", re.M) |
| 72 |
TRIM = re.compile(r"""(['"])\1\+(.*)\+\1\1$""", re.M) |
| 73 |
ESCAPE = re.compile(r"\\.", re.M) # g |
| 74 |
# QUOTE = re.compile(r"'", re.M) |
| 75 |
DELETED = re.compile(r"\x01[^\x01]*\x01", re.M) # g |
| 76 |
|
| 77 |
def __init__(self) -> None: |
| 78 |
self._patterns = Patterns() # patterns stored by index |
| 79 |
self._escaped = [] |
| 80 |
self.ignoreCase = False |
| 81 |
self.escapeChar = None |
| 82 |
|
| 83 |
def delete(self, match: re.Match, offset: int) -> str: |
| 84 |
"""Replacement function for deleting matched patterns. |
| 85 |
|
| 86 |
Args: |
| 87 |
match (re.Match): The match object containing the matched patterns. |
| 88 |
offset (int): The offset for the match groups. |
| 89 |
|
| 90 |
Returns: |
| 91 |
str: A string indicating that the matched pattern should be deleted. |
| 92 |
""" |
| 93 |
return "\x01" + match.group(offset) + "\x01" |
| 94 |
|
| 95 |
def _repl(self, a: re.Match, o: int, r: str, i: int) -> str: |
| 96 |
"""Replacement function for complex replacements. |
| 97 |
|
| 98 |
Args: |
| 99 |
a (re.Match): The match object containing the matched patterns. |
| 100 |
o (int): The offset for the match groups. |
| 101 |
r (str): The replacement string. |
| 102 |
i (int): The number of sub-expressions in the pattern. |
| 103 |
|
| 104 |
Returns: |
| 105 |
str: The processed replacement string with matched patterns |
| 106 |
replaced. |
| 107 |
""" |
| 108 |
while i: |
| 109 |
m = a.group(o + i - 1) |
| 110 |
s = "" if m is None else m |
| 111 |
r = r.replace("$" + str(i), s) |
| 112 |
i = i - 1 |
| 113 |
return ParseMaster.TRIM.sub("$1", r) |
| 114 |
|
| 115 |
def add( |
| 116 |
self, expression: str = "^$", replacement: None | str | Callable = None |
| 117 |
) -> None: |
| 118 |
"""Add a pattern to the parser. |
| 119 |
|
| 120 |
Args: |
| 121 |
expression (str, optional): The regular expression pattern to |
| 122 |
match. |
| 123 |
replacement (None | str | Callable, optional): The replacement |
| 124 |
string or function. If None, the pattern will be deleted. |
| 125 |
""" |
| 126 |
if replacement is None: |
| 127 |
replacement = self.delete |
| 128 |
# count the number of sub-expressions |
| 129 |
# - add one because each pattern is itself a sub-expression |
| 130 |
length = ( |
| 131 |
len(ParseMaster.GROUPS.findall(self._internal_escape(str(expression)))) + 1 |
| 132 |
) |
| 133 |
# does the pattern deal with sub-expressions? |
| 134 |
if isinstance(replacement, str) and ParseMaster.SUB_REPLACE.match(replacement): |
| 135 |
# a simple lookup? (e.g. "$2") |
| 136 |
if ParseMaster.INDEXED.match(replacement): |
| 137 |
# store the index (used for fast retrieval of matched strings) |
| 138 |
replacement = int(replacement[1:]) - 1 |
| 139 |
else: # a complicated lookup (e.g. "Hello $2 $1") |
| 140 |
# build a function to do the lookup |
| 141 |
i = length |
| 142 |
r = replacement |
| 143 |
|
| 144 |
def replacement(a: re.Match, o: int) -> str: |
| 145 |
"""Replacement function for complex replacements. |
| 146 |
|
| 147 |
Args: |
| 148 |
a (re.Match): The match object containing the matched |
| 149 |
patterns. |
| 150 |
o (int): The offset for the match groups. |
| 151 |
|
| 152 |
Returns: |
| 153 |
str: The processed replacement string. |
| 154 |
""" |
| 155 |
return self._repl(a, o, r, i) |
| 156 |
|
| 157 |
# pass the modified arguments |
| 158 |
self._patterns.append(Pattern(expression, replacement, length)) |
| 159 |
|
| 160 |
def execute(self, string: str) -> str: |
| 161 |
"""Execute the global replacement on the given string. |
| 162 |
|
| 163 |
Args: |
| 164 |
string (str): The string to process. |
| 165 |
|
| 166 |
Returns: |
| 167 |
str: The processed string with patterns replaced. |
| 168 |
""" |
| 169 |
if self.ignoreCase: |
| 170 |
r = re.compile(str(self._patterns), re.I | re.M) |
| 171 |
else: |
| 172 |
r = re.compile(str(self._patterns), re.M) |
| 173 |
string = self._escape(string, self.escapeChar) |
| 174 |
string = r.sub(self._replacement, string) |
| 175 |
string = self._unescape(string, self.escapeChar) |
| 176 |
string = ParseMaster.DELETED.sub("", string) |
| 177 |
return string # noqa: RET504 |
| 178 |
|
| 179 |
def reset(self) -> None: |
| 180 |
"""Reset the patterns collection to an empty state. |
| 181 |
|
| 182 |
Clear the patterns collections so that this object may be re-used. |
| 183 |
""" |
| 184 |
self._patterns = Patterns() |
| 185 |
|
| 186 |
def _replacement(self, match: re.Match) -> str: |
| 187 |
"""Replace matched patterns with their corresponding replacements. |
| 188 |
|
| 189 |
This is the global replace function (it's quite complicated). |
| 190 |
|
| 191 |
Args: |
| 192 |
match (re.Match): The match object containing the matched patterns. |
| 193 |
|
| 194 |
Returns: |
| 195 |
str: The replacement string based on the matched patterns. |
| 196 |
""" |
| 197 |
i = 1 |
| 198 |
# loop through the patterns |
| 199 |
for pattern in self._patterns: |
| 200 |
if match.group(i) is not None: |
| 201 |
replacement = pattern.replacement |
| 202 |
if callable(replacement): |
| 203 |
return replacement(match, i) |
| 204 |
if isinstance(replacement, int): |
| 205 |
return match.group(replacement + i) |
| 206 |
return replacement |
| 207 |
i = i + pattern.length |
| 208 |
|
| 209 |
return None |
| 210 |
|
| 211 |
def _escape(self, string: str, escape_char: None | str = None) -> str: |
| 212 |
"""Encode escaped characters. |
| 213 |
|
| 214 |
Args: |
| 215 |
string (str): The string to escape. |
| 216 |
escape_char (None | str, optional): The character used for escaping. |
| 217 |
Defaults to None. |
| 218 |
""" |
| 219 |
|
| 220 |
def repl(match: re.Match) -> str: |
| 221 |
"""Replacement function for escaping characters. |
| 222 |
|
| 223 |
Args: |
| 224 |
match (re.Match): The match object containing the matched |
| 225 |
patterns. |
| 226 |
|
| 227 |
Returns: |
| 228 |
str: The escaped character or the escape character if no match |
| 229 |
is found. |
| 230 |
""" |
| 231 |
char = match.group(1) |
| 232 |
self._escaped.append(char) |
| 233 |
return escape_char |
| 234 |
|
| 235 |
if escape_char is None: |
| 236 |
return string |
| 237 |
|
| 238 |
r = re.compile(r"\\" + escape_char + r"(.)", re.M) |
| 239 |
return r.sub(repl, string) |
| 240 |
|
| 241 |
def _unescape(self, string: str, escape_char: None | str = None) -> str: |
| 242 |
"""Decode escaped characters. |
| 243 |
|
| 244 |
Args: |
| 245 |
string (str): The string to unescape. |
| 246 |
escape_char (None | str, optional): The character used for |
| 247 |
escaping. Defaults to None. |
| 248 |
|
| 249 |
Returns: |
| 250 |
str: The unescaped string. |
| 251 |
""" |
| 252 |
|
| 253 |
def repl(match: re.Match) -> str: |
| 254 |
"""Replacement function for unescaping characters. |
| 255 |
|
| 256 |
Args: |
| 257 |
match (re.Match): The match object containing the matched |
| 258 |
patterns. |
| 259 |
|
| 260 |
Returns: |
| 261 |
str: The unescaped character or the escape character if no |
| 262 |
match is found. |
| 263 |
""" |
| 264 |
try: |
| 265 |
# result = eval("'"+escapeChar + self._escaped.pop(0)+"'") |
| 266 |
return escape_char + self._escaped.pop(0) |
| 267 |
except IndexError: |
| 268 |
return escape_char |
| 269 |
|
| 270 |
if escape_char is None: |
| 271 |
return string |
| 272 |
r = re.compile(r"\\" + escape_char, re.M) |
| 273 |
return r.sub(repl, string) |
| 274 |
|
| 275 |
def _internal_escape(self, string: str) -> str: |
| 276 |
"""Escape special characters in the string for internal processing. |
| 277 |
|
| 278 |
Args: |
| 279 |
string (str): The string to escape. |
| 280 |
|
| 281 |
Returns: |
| 282 |
str: The escaped string with special characters removed. |
| 283 |
""" |
| 284 |
return ParseMaster.ESCAPE.sub("", string) |
| 285 |
|
| 286 |
|
| 287 |
class JavaScriptPacker: |
| 288 |
"""JavaScriptPacker is a class for compressing and obfuscating JavaScript code. |
| 289 |
|
| 290 |
packer, version 2.0 (2005/04/20) |
| 291 |
Copyright 2004-2005, Dean Edwards |
| 292 |
License: http://creativecommons.org/licenses/LGPL/2.1/ |
| 293 |
|
| 294 |
Ported to Python by Florian Schulze |
| 295 |
|
| 296 |
http://dean.edwards.name/packer/ |
| 297 |
|
| 298 |
""" |
| 299 |
|
| 300 |
def basic_compression(self, script: str) -> str: |
| 301 |
"""Get a ParseMaster to compress JavaScript code. |
| 302 |
|
| 303 |
Args: |
| 304 |
script (str): The JavaScript code to compress. |
| 305 |
|
| 306 |
Returns: |
| 307 |
str: The compressed JavaScript code without special character |
| 308 |
encoding. |
| 309 |
""" |
| 310 |
return self.get_compression_parse_master(False, script) |
| 311 |
|
| 312 |
def special_compression(self, script: str) -> str: |
| 313 |
"""Get a ParseMaster to compress JavaScript code with special characters. |
| 314 |
|
| 315 |
Args: |
| 316 |
script (str): The JavaScript code to compress. |
| 317 |
|
| 318 |
Returns: |
| 319 |
str: The compressed JavaScript code with special characters |
| 320 |
encoded. |
| 321 |
""" |
| 322 |
return self.get_compression_parse_master(True, script) |
| 323 |
|
| 324 |
def get_compression_parse_master(self, special_chars: bool, script: str) -> str: |
| 325 |
"""Get a ParseMaster instance for compressing JavaScript code. |
| 326 |
|
| 327 |
Args: |
| 328 |
special_chars (bool): Whether to include special character encoding. |
| 329 |
script (str): The JavaScript code to compress. |
| 330 |
|
| 331 |
Returns: |
| 332 |
str: The compressed JavaScript code. |
| 333 |
""" |
| 334 |
ignore = "$1" |
| 335 |
parser = ParseMaster() |
| 336 |
parser.escapeChar = r"\\" |
| 337 |
# protect strings |
| 338 |
parser.add(r"""'[^'\n\r]*'""", ignore) |
| 339 |
parser.add(r'"[^"\n\r]*"', ignore) |
| 340 |
# remove comments |
| 341 |
parser.add(r"""//[^\n\r]*[\n\r]""") |
| 342 |
parser.add(r"""/\*[^*]*\*+([^/][^*]*\*+)*/""") |
| 343 |
# protect regular expressions |
| 344 |
parser.add(r"""\s+(\/[^\/\n\r\*][^\/\n\r]*\/g?i?)""", "$2") |
| 345 |
parser.add(r"""[^\w\$\/'"*)\?:]\/[^\/\n\r\*][^\/\n\r]*\/g?i?""", ignore) |
| 346 |
# remove: ;;; doSomething(); |
| 347 |
if special_chars: |
| 348 |
parser.add(""";;;[^\n\r]+[\n\r]""") |
| 349 |
# remove redundant semi-colons |
| 350 |
parser.add(r"""\(;;\)""", "$2") # protect for (;;) loops |
| 351 |
parser.add(r""";+\s*([};])""", "$2") |
| 352 |
# apply the above |
| 353 |
script = parser.execute(script) |
| 354 |
|
| 355 |
# remove white-space |
| 356 |
parser.add(r"""(\b|\$)\s+(\b|\$)""", "$2 $3") |
| 357 |
parser.add(r"""([+\-])\s+([+\-])""", "$2 $3") |
| 358 |
parser.add(r"""\s+""", "") |
| 359 |
return parser.execute(script) |
| 360 |
|
| 361 |
def get_encoder(self, ascii_: int) -> Callable: |
| 362 |
"""Get the encoding function based on the ASCII value. |
| 363 |
|
| 364 |
Args: |
| 365 |
ascii_ (int): The ASCII value to determine the encoding function. |
| 366 |
|
| 367 |
Returns: |
| 368 |
Callable: The encoding function based on the ASCII value. |
| 369 |
""" |
| 370 |
mapping = {} |
| 371 |
base = ord("0") |
| 372 |
mapping.update({i: chr(i + base) for i in range(10)}) |
| 373 |
base = ord("a") |
| 374 |
mapping.update({i + 10: chr(i + base) for i in range(26)}) |
| 375 |
base = ord("A") |
| 376 |
mapping.update({i + 36: chr(i + base) for i in range(26)}) |
| 377 |
base = 161 |
| 378 |
mapping.update({i + 62: chr(i + base) for i in range(95)}) |
| 379 |
|
| 380 |
def encode10(char_code: int) -> str: |
| 381 |
"""Encode using base10 characters. |
| 382 |
|
| 383 |
zero encoding |
| 384 |
characters: 0123456789 |
| 385 |
|
| 386 |
Args: |
| 387 |
char_code (int): The character code to encode. |
| 388 |
|
| 389 |
Returns: |
| 390 |
str: The encoded character code as a string. |
| 391 |
""" |
| 392 |
return str(char_code) |
| 393 |
|
| 394 |
def encode36(char_code: int) -> str: |
| 395 |
"""Encode using base36 characters. |
| 396 |
|
| 397 |
inherent base36 support |
| 398 |
characters: 0123456789abcdefghijklmnopqrstuvwxyz |
| 399 |
|
| 400 |
Args: |
| 401 |
char_code (int): The character code to encode. |
| 402 |
|
| 403 |
Returns: |
| 404 |
str: The encoded character code as a string. |
| 405 |
""" |
| 406 |
l = [] |
| 407 |
remainder = char_code |
| 408 |
while 1: |
| 409 |
result, remainder = divmod(remainder, 36) |
| 410 |
l.append(mapping[remainder]) |
| 411 |
if not result: |
| 412 |
break |
| 413 |
remainder = result |
| 414 |
l.reverse() |
| 415 |
return "".join(l) |
| 416 |
|
| 417 |
def encode62(char_code: int) -> str: |
| 418 |
"""Encode using base62 characters. |
| 419 |
|
| 420 |
hitch a ride on base36 and add the upper case alpha characters |
| 421 |
characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ |
| 422 |
|
| 423 |
Args: |
| 424 |
char_code (int): The character code to encode. |
| 425 |
|
| 426 |
Returns: |
| 427 |
str: The encoded character code as a string. |
| 428 |
""" |
| 429 |
l = [] |
| 430 |
remainder = char_code |
| 431 |
while 1: |
| 432 |
result, remainder = divmod(remainder, 62) |
| 433 |
l.append(mapping[remainder]) |
| 434 |
if not result: |
| 435 |
break |
| 436 |
remainder = result |
| 437 |
l.reverse() |
| 438 |
return "".join(l) |
| 439 |
|
| 440 |
def encode95(char_code: int) -> str: |
| 441 |
"""Encode using high-ascii characters. |
| 442 |
|
| 443 |
Args: |
| 444 |
char_code (int): The character code to encode. |
| 445 |
|
| 446 |
Returns: |
| 447 |
str: The encoded character code as a string. |
| 448 |
""" |
| 449 |
l = [] |
| 450 |
remainder = char_code |
| 451 |
while 1: |
| 452 |
result, remainder = divmod(remainder, 95) |
| 453 |
l.append(mapping[remainder + 62]) |
| 454 |
if not result: |
| 455 |
break |
| 456 |
remainder = result |
| 457 |
l.reverse() |
| 458 |
return "".join(l) |
| 459 |
|
| 460 |
return ( |
| 461 |
encode10 |
| 462 |
if ascii_ <= 10 |
| 463 |
else encode36 |
| 464 |
if ascii_ <= 36 |
| 465 |
else encode62 |
| 466 |
if ascii_ <= 62 |
| 467 |
else encode95 |
| 468 |
) |
| 469 |
|
| 470 |
def escape(self, script: str) -> str: |
| 471 |
"""Escape the script for safe embedding in a string. |
| 472 |
|
| 473 |
Args: |
| 474 |
script (str): The JavaScript code to escape. |
| 475 |
|
| 476 |
Returns: |
| 477 |
str: The escaped JavaScript code. |
| 478 |
""" |
| 479 |
return script.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n") |
| 480 |
# return re.sub(r"""([\\'](?!\n))""", "\\$1", script) |
| 481 |
|
| 482 |
def escape95(self, script: str) -> str: |
| 483 |
"""Escape high-ascii characters in the script. |
| 484 |
|
| 485 |
Args: |
| 486 |
script (str): The JavaScript code to escape. |
| 487 |
|
| 488 |
Returns: |
| 489 |
str: The escaped JavaScript code. |
| 490 |
""" |
| 491 |
result = [] |
| 492 |
for x in script: |
| 493 |
if x > "\xa1": |
| 494 |
x = f"\\x{ord(x):0x}" |
| 495 |
result.append(x) |
| 496 |
return "".join(result) |
| 497 |
|
| 498 |
def encode_keywords( |
| 499 |
self, |
| 500 |
script: str, |
| 501 |
encoding: int, |
| 502 |
fast_decode: bool, |
| 503 |
) -> str: |
| 504 |
"""Encode keywords in the JavaScript code. |
| 505 |
|
| 506 |
Args: |
| 507 |
script (str): The JavaScript code to encode. |
| 508 |
encoding (int): The encoding level (0-95). |
| 509 |
fast_decode (bool): Whether to use fast decoding. |
| 510 |
|
| 511 |
Returns: |
| 512 |
str: The encoded JavaScript code. |
| 513 |
""" |
| 514 |
# escape high-ascii values already in the script (i.e. in strings) |
| 515 |
if encoding > 62: |
| 516 |
script = self.escape95(script) |
| 517 |
# create the parser |
| 518 |
parser = ParseMaster() |
| 519 |
encode = self.get_encoder(encoding) |
| 520 |
# for high-ascii, don't encode single character low-ascii |
| 521 |
regexp = r"""\w\w+""" if encoding > 62 else r"""\w+""" |
| 522 |
# build the word list |
| 523 |
keywords = self.analyze(script, regexp, encode) |
| 524 |
encoded = keywords["encoded"] |
| 525 |
# encode |
| 526 |
|
| 527 |
def repl(match: re.Match, offset: int) -> str: |
| 528 |
"""Replacement function for encoding keywords. |
| 529 |
|
| 530 |
Args: |
| 531 |
match (re.Match): The match object containing the matched |
| 532 |
patterns. |
| 533 |
offset (int): The offset for the match groups. |
| 534 |
|
| 535 |
Returns: |
| 536 |
str: The encoded string for the matched pattern. |
| 537 |
""" |
| 538 |
return encoded.get(match.group(offset), "") |
| 539 |
|
| 540 |
parser.add(regexp, repl) |
| 541 |
# if encoded, wrap the script in a decoding function |
| 542 |
script = parser.execute(script) |
| 543 |
return self.boot_strap(script, keywords, encoding, fast_decode) |
| 544 |
|
| 545 |
def analyze(self, script: str, regexp: str, encode: Callable) -> dict: |
| 546 |
"""Analyse the script to find keywords and their frequencies. |
| 547 |
|
| 548 |
Args: |
| 549 |
script (str): The JavaScript code to analyse. |
| 550 |
regexp (str): The regular expression to match keywords. |
| 551 |
encode (Callable): The encoding function to use for keywords. |
| 552 |
|
| 553 |
Returns: |
| 554 |
dict: A dictionary containing sorted keywords, their encodings, and |
| 555 |
protected words. |
| 556 |
""" |
| 557 |
# analyse |
| 558 |
# retrieve all words in the script |
| 559 |
regexp = re.compile(regexp, re.M) |
| 560 |
all_words = regexp.findall(script) |
| 561 |
sorted_ = [] # list of words sorted by frequency |
| 562 |
encoded = {} # dictionary of word->encoding |
| 563 |
protected = {} # instances of "protected" words |
| 564 |
if not all_words: |
| 565 |
return {"sorted": sorted_, "encoded": encoded, "protected": protected} |
| 566 |
|
| 567 |
unsorted = [] |
| 568 |
_protected = {} |
| 569 |
values = {} |
| 570 |
count = {} |
| 571 |
all_words.reverse() |
| 572 |
for word in all_words: |
| 573 |
word = f"${word}" |
| 574 |
if word not in count: |
| 575 |
count[word] = 0 |
| 576 |
j = len(unsorted) |
| 577 |
unsorted.append(word) |
| 578 |
# make a dictionary of all of the protected words in this script |
| 579 |
# these are words that might be mistaken for encoding |
| 580 |
values[j] = encode(j) |
| 581 |
_protected["$" + values[j]] = j |
| 582 |
count[word] = count[word] + 1 |
| 583 |
# prepare to sort the word list, first we must protect |
| 584 |
# words that are also used as codes. we assign them a code |
| 585 |
# equivalent to the word itself. |
| 586 |
# e.g. if "do" falls within our encoding range |
| 587 |
# then we store keywords["do"] = "do"; |
| 588 |
# this avoids problems when decoding |
| 589 |
sorted_ = [None] * len(unsorted) |
| 590 |
for word in unsorted: |
| 591 |
if word in _protected and isinstance(_protected[word], int): |
| 592 |
sorted_[_protected[word]] = word[1:] |
| 593 |
protected[_protected[word]] = True |
| 594 |
count[word] = 0 |
| 595 |
# unsorted.sort(lambda a, b: count[b]-count[a]) |
| 596 |
unsorted = sorted( |
| 597 |
unsorted, key=functools.cmp_to_key(lambda a, b: count[b] - count[a]) |
| 598 |
) |
| 599 |
j = 0 |
| 600 |
for i in range(len(sorted_)): |
| 601 |
if sorted_[i] is None: |
| 602 |
sorted_[i] = unsorted[j][1:] |
| 603 |
j = j + 1 |
| 604 |
encoded[sorted_[i]] = values[i] |
| 605 |
return {"sorted": sorted_, "encoded": encoded, "protected": protected} |
| 606 |
|
| 607 |
def encode_private(self, char_code: int) -> str: |
| 608 |
"""Encode private variables (those starting with an underscore). |
| 609 |
|
| 610 |
Args: |
| 611 |
char_code (int): The character code to encode. |
| 612 |
|
| 613 |
Returns: |
| 614 |
str: The encoded character code as a string. |
| 615 |
""" |
| 616 |
return f"_{char_code}" |
| 617 |
|
| 618 |
def encode_special_chars(self, script: str) -> str: |
| 619 |
"""Encode special characters in the script. |
| 620 |
|
| 621 |
Args: |
| 622 |
script (str): The JavaScript code to encode. |
| 623 |
|
| 624 |
Returns: |
| 625 |
str: The encoded JavaScript code. |
| 626 |
""" |
| 627 |
parser = ParseMaster() |
| 628 |
# replace: $name -> n, $$name -> $$na |
| 629 |
|
| 630 |
def repl(match: re.Match, offset: int) -> str: |
| 631 |
"""Replacement function for encoding special characters. |
| 632 |
|
| 633 |
Args: |
| 634 |
match (re.Match): The match object containing the matched |
| 635 |
patterns. |
| 636 |
offset (int): The offset for the match groups. |
| 637 |
|
| 638 |
Returns: |
| 639 |
str: The encoded string for the matched pattern. |
| 640 |
""" |
| 641 |
# print offset, match.groups() |
| 642 |
length = len(match.group(offset + 2)) |
| 643 |
start = length - max(length - len(match.group(offset + 3)), 0) |
| 644 |
return match.group(offset + 1)[start : start + length] + match.group( |
| 645 |
offset + 4 |
| 646 |
) |
| 647 |
|
| 648 |
parser.add(r"""((\$+)([a-zA-Z\$_]+))(\d*)""", repl) |
| 649 |
# replace: _name -> _0, double-underscore (__name) is ignored |
| 650 |
regexp = r"""\b_[A-Za-z\d]\w*""" |
| 651 |
# build the word list |
| 652 |
keywords = self.analyze(script, regexp, self.encode_private) |
| 653 |
# quick ref |
| 654 |
encoded = keywords["encoded"] |
| 655 |
|
| 656 |
def repl(match: re.Match, offset: int) -> str: |
| 657 |
"""Replacement function for encoding special characters. |
| 658 |
|
| 659 |
Args: |
| 660 |
match (re.Match): The match object containing the matched |
| 661 |
patterns. |
| 662 |
offset (int): The offset for the match groups. |
| 663 |
|
| 664 |
Returns: |
| 665 |
str: The encoded string for the matched pattern. |
| 666 |
""" |
| 667 |
return encoded.get(match.group(offset), "") |
| 668 |
|
| 669 |
parser.add(regexp, repl) |
| 670 |
return parser.execute(script) |
| 671 |
|
| 672 |
def boot_strap( |
| 673 |
self, |
| 674 |
packed: str, |
| 675 |
keywords: dict, |
| 676 |
encoding: int, |
| 677 |
fast_decode: bool, |
| 678 |
) -> str: |
| 679 |
"""Build the boot function used for loading and decoding the packed script. |
| 680 |
|
| 681 |
Args: |
| 682 |
packed (str): The packed JavaScript code. |
| 683 |
keywords (dict): A dictionary containing the sorted keywords and |
| 684 |
their encodings. |
| 685 |
encoding (int): The encoding level (0-95). |
| 686 |
fast_decode (bool): Whether to use fast decoding. |
| 687 |
|
| 688 |
Returns: |
| 689 |
str: The bootstrapped JavaScript code. |
| 690 |
""" |
| 691 |
encode_regex = re.compile(r"""\$encode\(\$count\)""") |
| 692 |
# $packed: the packed script |
| 693 |
# packed = self.escape(packed) |
| 694 |
# packed = [packed[x*10000:(x+1)*10000] for x in range((len(packed)/10000)+1)] |
| 695 |
# packed = "'" + "'+\n'".join(packed) + "'\n" |
| 696 |
packed = "'" + self.escape(packed) + "'" |
| 697 |
|
| 698 |
# $count: number of words contained in the script |
| 699 |
count = len(keywords["sorted"]) |
| 700 |
|
| 701 |
# $ascii: base for encoding |
| 702 |
ascii_value = min(count, encoding) or 1 |
| 703 |
|
| 704 |
# $keywords: list of words contained in the script |
| 705 |
for i in keywords["protected"]: |
| 706 |
keywords["sorted"][i] = "" |
| 707 |
# convert from a string to an array |
| 708 |
keywords = "'" + "|".join(keywords["sorted"]) + "'.split('|')" |
| 709 |
|
| 710 |
encoding_functions = { |
| 711 |
10: """ function($charCode) {return $charCode;}""", |
| 712 |
36: """ function($charCode) {return $charCode.toString(36);}""", |
| 713 |
62: """ function($charCode) { |
| 714 |
return ($charCode < _encoding ? "" : |
| 715 |
arguments.callee(parseInt($charCode / _encoding))) + |
| 716 |
(($charCode = $charCode % _encoding) > 35 ? |
| 717 |
String.fromCharCode($charCode + 29) : $charCode.toString(36)); |
| 718 |
}""", |
| 719 |
95: """ function($charCode) { |
| 720 |
return ($charCode < _encoding ? "" : arguments.callee($charCode / _encoding)) + |
| 721 |
String.fromCharCode($charCode % _encoding + 161); |
| 722 |
}""", |
| 723 |
} |
| 724 |
|
| 725 |
# $encode: encoding function (used for decoding the script) |
| 726 |
encode = encoding_functions[encoding] |
| 727 |
encode = encode.replace("_encoding", "$ascii") |
| 728 |
encode = encode.replace("arguments.callee", "$encode") |
| 729 |
inline = "$count.toString($ascii)" if ascii_value > 10 else "$count" |
| 730 |
# $decode: code snippet to speed up decoding |
| 731 |
if fast_decode: |
| 732 |
# create the decoder |
| 733 |
decode = r"""// does the browser support String.replace where the |
| 734 |
// replacement value is a function? |
| 735 |
if (!''.replace(/^/, String)) { |
| 736 |
// decode all the values we need |
| 737 |
while ($count--) { |
| 738 |
$decode[$encode($count)] = $keywords[$count] || $encode($count); |
| 739 |
} |
| 740 |
// global replacement function |
| 741 |
$keywords = [function($encoded){return $decode[$encoded]}]; |
| 742 |
// generic match |
| 743 |
$encode = function(){return'\\w+'}; |
| 744 |
// reset the loop counter - we are now doing a global replace |
| 745 |
$count = 1; |
| 746 |
}""" |
| 747 |
if encoding > 62: |
| 748 |
decode = decode.replace("\\\\w", "[\\xa1-\\xff]") |
| 749 |
# perform the encoding inline for lower ascii values |
| 750 |
elif ascii_value < 36: |
| 751 |
decode = encode_regex.sub(inline, decode) |
| 752 |
# special case: when $count==0 there ar no keywords. i want to keep |
| 753 |
# the basic shape of the unpacking function so i'll frig the code... |
| 754 |
if not count: |
| 755 |
raise NotImplementedError |
| 756 |
# ) $decode = $decode.replace(/(\$count)\s*=\s*1/, "$1=0"); |
| 757 |
|
| 758 |
# boot function |
| 759 |
unpack = r"""function($packed, $ascii, $count, $keywords, $encode, $decode) { |
| 760 |
while ($count--) { |
| 761 |
if ($keywords[$count]) { |
| 762 |
$packed = $packed.replace( |
| 763 |
new RegExp("\\b" + $encode($count) + "\\b", "g"), $keywords[$count] |
| 764 |
); |
| 765 |
} |
| 766 |
} |
| 767 |
return $packed; |
| 768 |
}""" |
| 769 |
if fast_decode: |
| 770 |
# insert the decoder |
| 771 |
# unpack = re.sub(r"""\{""", "{" + decode + ";", unpack) |
| 772 |
unpack = unpack.replace("{", "{" + decode + ";", 1) |
| 773 |
|
| 774 |
if encoding > 62: # high-ascii |
| 775 |
# get rid of the word-boundaries for regexp matches |
| 776 |
unpack = re.sub(r"""'\\\\b'\s*\+|\+\s*'\\\\b'""", "", unpack) |
| 777 |
if ascii_value > 36 or encoding > 62 or fast_decode: |
| 778 |
# insert the encode function |
| 779 |
# unpack = re.sub(r"""\{""", "{$encode=" + encode + ";", unpack) |
| 780 |
unpack = unpack.replace("{", "{$encode=" + encode + ";", 1) |
| 781 |
else: |
| 782 |
# perform the encoding inline |
| 783 |
unpack = encode_regex.sub(inline, unpack) |
| 784 |
# pack the boot function too |
| 785 |
unpack = self.pack(unpack, 0, False, True) |
| 786 |
|
| 787 |
# arguments |
| 788 |
params = [packed, str(ascii_value), str(count), keywords] |
| 789 |
if fast_decode: |
| 790 |
# insert placeholders for the decoder |
| 791 |
params.extend(["0", "{}"]) |
| 792 |
|
| 793 |
# the whole thing |
| 794 |
return "eval(" + unpack + "(" + ",".join(params) + "))\n" |
| 795 |
|
| 796 |
def pack( |
| 797 |
self, |
| 798 |
script: str, |
| 799 |
encoding: int = 0, |
| 800 |
fast_decode: bool = False, |
| 801 |
special_chars: bool = False, |
| 802 |
compaction: bool = True, |
| 803 |
) -> str: |
| 804 |
"""Pack the given JavaScript script. |
| 805 |
|
| 806 |
Args: |
| 807 |
script (str): The JavaScript code to pack. |
| 808 |
encoding (int, optional): The encoding level (0-95). Defaults to 0. |
| 809 |
fast_decode (bool, optional): Whether to use fast decoding. Defaults |
| 810 |
to False. |
| 811 |
special_chars (bool, optional): Whether to encode special |
| 812 |
characters. Defaults to False. |
| 813 |
compaction (bool, optional): Whether to apply basic compression. |
| 814 |
Defaults to True. |
| 815 |
|
| 816 |
Returns: |
| 817 |
str: The packed JavaScript code. |
| 818 |
""" |
| 819 |
script = script + "\n" |
| 820 |
self._encoding = encoding |
| 821 |
self._fastDecode = fast_decode |
| 822 |
if special_chars: |
| 823 |
script = self.special_compression(script) |
| 824 |
script = self.encode_special_chars(script) |
| 825 |
elif compaction: |
| 826 |
script = self.basic_compression(script) |
| 827 |
if encoding: |
| 828 |
script = self.encode_keywords(script, encoding, fast_decode) |
| 829 |
return script |