Debian Codegraph @

jsbeautifier/unpackers/evalbased.py

raw
1 #
2 # Unpacker for eval() based packers, a part of javascript beautifier
3 # by Einar Lielmanis <[email protected]>
4 #
5 # written by Stefano Sanfilippo <[email protected]>
6 #
7 # usage:
8 #
9 # if detect(some_string):
10 # unpacked = unpack(some_string)
11 #
12
13 """Unpacker for eval() based packers: runs JS code and returns result.
14 Works only if a JS interpreter (e.g. Mozilla's Rhino) is installed and
15 properly set up on host."""
16
17 from subprocess import PIPE, Popen
18
19 PRIORITY = 3
20
21
22 def detect(source):
23 """Detects if source is likely to be eval() packed."""
24 return source.strip().lower().startswith("eval(function(")
25
26
27 def unpack(source):
28 """Runs source and return resulting code."""
29 return jseval("print %s;" % source[4:]) if detect(source) else source
30
31
32 # In case of failure, we'll just return the original, without crashing on user.
33
34
35 def jseval(script):
36 """Run code in the JS interpreter and return output."""
37 try:
38 interpreter = Popen(["js"], stdin=PIPE, stdout=PIPE)
39 except OSError:
40 return script
41 result, errors = interpreter.communicate(script)
42 if interpreter.poll() or errors:
43 return script
44 return result