def setUp(self): rt = spidermonkey.Runtime() self.cx = rt.create_context() class spam(object): def __init__(self): self.args = [] self.val = 42 self._private = u"no peeking" def foo(self, *args): self.args.append(args) def _private_method(self): assert False def __getitem__(self, key): assert isinstance(key, (types.IntType, types.LongType)) self.args.append(key) return self.val def __setitem__(self, key, value): assert isinstance(key, (types.IntType, types.LongType)) self.args.append((key, value)) self.val = value self.cx.install_class(spam) self.spam = spam() self.cx.bind(u"bs", self.spam)
def main(self, aArgs): # Verify parameters. if len(aArgs) == 0: print( "usage: python TeXZillaParser.py aTeX [aDisplay] [aRTL] [aThrowExceptionOnError]" ) sys.exit(1) tex = aArgs[0] display = len(aArgs) >= 2 and aArgs[1] == "true" rtl = len(aArgs) >= 3 and aArgs[2] == "true" throwException = len(aArgs) >= 4 and aArgs[3] == "true" # Prepare the SpiderMonkey Javascript engine. rt = spidermonkey.Runtime() cx = rt.new_context() # Load TeXZilla.js and execute TeXZilla.toMathMLString with the # specified arguments. cx.execute("var window = {}") f = open(self.TEXZILLA_JS, "r") cx.execute(f.read()) f.close() TeXZilla = cx.execute("window.TeXZilla") try: print(TeXZilla.toMathMLString(tex, display, rtl, throwException)) except Exception, e: print(str(e)) sys.exit(1)
def Scan_JS(jscode): rt = spidermonkey.Runtime() cx = rt.new_context() A = app() cx.add_global("app",A) result = cx.execute(code) return result
def get_infoHash(self): # get_hash sm = spidermonkey.Runtime() file_js = open("api/infoHash.js", "r") cx = sm.new_context() get_hash = cx.execute(file_js.read()) self.info_hash = get_hash(self.username, self.ptwebqq) print 'info_hash:', self.info_hash
def execute_function(just_function_lines): # Snip the top to make it an anonymous function anonymized_function_lines = ['function () {'] + just_function_lines[1:] # pass it into SpiderMonkey... rt = spidermonkey.Runtime() cx = rt.new_context() func = cx.execute('\n'.join(anonymized_function_lines)) value = func() return value
def main(): rt = spidermonkey.Runtime() cx = rt.new_context() fp=file("mal.js",'rb') code = fp.read() print "Testing Spider \n" A = app() #cx.add_global("app",A) #result = cx.execute(code) Scan_JS_V8(code)
def main(): rt = spidermonkey.Runtime() cx = rt.new_context() fp=file("/home/sandeep/data",'rb') code = fp.read() print "Testing Spider \n" A = app() print A cx.add_global("app",A) result = cx.execute(code)
def __init__(self, filename): def loadfile(filename): fp = open(filename) content = fp.read() fp.close() return content self.rt = spidermonkey.Runtime() self.cx = self.rt.new_context() self.cx.add_global("loadfile", loadfile) self.fname = filename
def __init__(self, file_name, md5): self.filename = file_name self.md5 = md5 self.fun = ['String', 'eval'] self.rt = spidermonkey.Runtime() self.cx = self.rt.new_context() with open("report/"+self.md5+"/"+self.filename) as file1: self.data1 = file1.readlines() with open('data/string_sig/malware_js') as malware: self.mal=malware.read().splitlines()
def js10113(): # getp sm = spidermonkey.Runtime() file_js = open("wxagent/loginMd5.js", "r") cx = sm.new_context() getp = cx.execute(file_js.read()) username = '' password = '' code1 = '' username = sys.argv[2] password = sys.argv[3] code1 = sys.argv[4] print('js10113', username, password, code1) p = getp(username, password, code1) print 'resp:', p
def init(): rt = spidermonkey.Runtime() cx = rt.new_context() cx.bind_class(ConsoleClass) cx.bind_object('console', console) directory, fn = os.path.split(__file__) jsdir = os.path.join(directory, '../js/') chFile = os.path.join(jsdir, 'cryptoHelpers.js') f = open(chFile) chScript = f.read() f.close() aesFile = os.path.join(jsdir, 'aes.js') f = open(aesFile) aesScript = f.read() f.close() cx.eval_script(chScript) cx.eval_script(aesScript) return cx
def infoHash(): sm = spidermonkey.Runtime() file_js = open("wxagent/hash.js", "r") cx = sm.new_context() fulljs = 'function(username, ptwebqq) {' + \ file_js.read() + \ 'return P2(username, ptwebqq);}' # getp = cx.execute(file_js.read()) getp = cx.execute(fulljs) # getp = cx.execute('function(val) {return "whoosh: " + val;}') username = sys.argv[2] ptwebqq = sys.argv[3] print('infohash', username, ptwebqq) iusername = int(username) p = getp(username, ptwebqq) print 'resphash:', p
def init_js(self): self.js_runtime = spidermonkey.Runtime() self.js_context = ctx = self.js_runtime.new_context() ctx.execute(''' window = this; dummy = function() { return {}; } document = {getElementById: dummy, createElement: dummy} navigator = {userAgent: 'Chrome'}; location = {}; g_href = ''; document.loginform = {}; ''') ctx.execute('g_appid = %s' % self.appid) mq_comm = requests.get( "https://ui.ptlogin2.qq.com/js/10114/mq_comm.js").content # mq_comm = open('/dev/shm/a.js').read() ctx.execute(mq_comm) ctx.execute(''' ptui_checkVC = ptuiCB = function() { return [].slice.call(arguments); }; ''')
def js10120(): # getp sm = spidermonkey.Runtime() file_js = open("wxagent/encrypt.js", "r") cx = sm.new_context() fulljs = 'function(password, salt, vcode) {' + \ file_js.read() + \ 'return encryption(password, salt, vcode);}' # getp = cx.execute(file_js.read()) getp = cx.execute(fulljs) # getp = cx.execute('function(val) {return "whoosh: " + val;}') password = '' salt = '' code1 = '' password = sys.argv[2] salt = sys.argv[3] code1 = sys.argv[4] print('js10120', password, salt, code1) p = getp(password, salt, code1) print 'resp:', p
def __init__(self, dAPI): self._context = spidermonkey.Runtime().new_context() self._context.bind_callable("getAttr", dAPI._getAttr) self._context.bind_callable("hasAttr", dAPI._hasAttr) self._context.bind_callable("setAttr", dAPI._setAttr) self._context.bind_callable("getAllNodes", dAPI._getAllNodes) self._context.bind_callable("getNeighbors", dAPI._getNeighbors) self._context.bind_callable("isConnectionType", dAPI._isConnectionType) self._context.bind_callable("httpReq", dAPI._httpReq) self._context.bind_callable("print", dAPI._print) self._context.bind_callable("printToDevCon", dAPI._printToDevCon) self._context.bind_callable("session_get", dAPI._session_get) self._context.bind_callable("session_put", dAPI._session_put) self._context.bind_callable("sys_call", dAPI._sys_call) self._context.bind_callable("sys_mkdir", dAPI._sys_mkdir) self._context.bind_callable("sys_readf", dAPI._sys_readf) self._context.bind_callable("sys_writef", dAPI._sys_writef) self._context.bind_callable("pauseTransformation", dAPI._pauseTransformation) self._context.bind_callable("resumeTransformation", dAPI._resumeTransformation) self._context.bind_callable("stopTransformation", dAPI._stopTransformation)
def args(self): rt = spidermonkey.Runtime() cx = rt.new_context() cx.add_global(self.name, self.value) return (cx, self.value)
def login_on(self): try: # getp sm = spidermonkey.Runtime() file_js = open("api/loginMd5.js", "r") cx = sm.new_context() getp = cx.execute(file_js.read()) self.p = getp(self.username, self.password, self.code1) print 'p:', self.p # login 1 if self.check == '1': ck = dict((c.name, c.value) for c in self.cookies) self.pt_verifysession_v1 = ck['verifysession'] login_on_url = 'https://ssl.ptlogin2.qq.com/login?u=' + self.username + '&p=' + self.p + '&verifycode=' + self.code1 + \ '&webqq_type=10&remember_uin=1&login2qq=1&aid=501004106&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-16-56797&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10113&login_sig=' + self.login_sig + '&pt_randsalt=0&pt_vcode_v1=0&pt_vcode_v1=0&pt_verifysession_v1=' + \ self.pt_verifysession_v1 req = urllib2.Request(login_on_url) data = urllib2.urlopen(req).read() print 'login 1' # login 2 arg = re.search(r"'.','.','(.*?)'", data) req = urllib2.Request(arg.group(1)) data = urllib2.urlopen(req).read() ck = dict((c.name, c.value) for c in self.cookies) if ck['ptwebqq']: # print 'ptwebqq:', ck['ptwebqq'] self.ptwebqq = ck['ptwebqq'] print 'ptwebqq:', self.ptwebqq print 'login 2' # login 3 url_vf = 'http://s.web2.qq.com/api/getvfwebqq?ptwebqq=' + \ self.ptwebqq + '&clientid=53999199&psessionid=&t=1424324701030' req = urllib2.Request(url_vf) req.add_header( 'Referer', 'http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1' ) data = json.load(urllib2.urlopen(req)) self.newvfwebqq = data['result']['vfwebqq'] print 'newvfwebqq:', self.newvfwebqq print 'login 3' # login post url_post = 'http://d.web2.qq.com/channel/login2' data_post = { 'r': '{"ptwebqq":"' + self.ptwebqq + '","clientid":53999199,"psessionid":"","status":"online"}' } req = urllib2.Request(url_post, data=urllib.urlencode(data_post)) req.add_header( 'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2' ) data = json.load(urllib2.urlopen(req)) print 'login post' ''' {"retcode":0, "result":{"uin":28762822, "cip":3062847601, "index":1075, "port":49069, "status":"online", "vfwebqq":"3a479360aa6e9f45b0d6a990bb53a296666c3bff30b78bc58ee4d992899680848deadb94a4689df8", "psessionid":"8368046764001d636f6e6e7365727665725f77656271714031302e3133392e372e31363000000b43000006af016201b6e2c66d0000000a403251345a4f675a506a6d000000283a479360aa6e9f45b0d6a990bb53a296666c3bff30b78bc58ee4d992899680848deadb94a4689df8", "user_state":0, "f":0 } } ''' self.psessionid = data['result']['psessionid'] print 'psessionid:', self.psessionid if data['retcode'] == 0: return True except Exception, e: print e return False
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+ mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}} if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;} rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');} return str('',{'':value});};} if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}} return reviver.call(holder,key,value);} text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+ ('0000'+a.charCodeAt(0).toString(16)).slice(-4);});} if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;} throw new SyntaxError('JSON.parse');};}}()); """ LIST_INIT = "var packlist = Array();packlist.packs = Array();" rt = spidermonkey.Runtime() cx = rt.new_context() cx.execute(JSON_INCLUDE) def get_packs(server, search): print server print search res = urllib.urlopen("%s/search.php?%s" % (server.rstrip('/'), urllib.urlencode({'t': search}))) cx.execute(LIST_INIT) cx.execute(res.read()) text = cx.execute("JSON.stringify(packlist.packs);") packs = json.loads(text)
import doctest import manuel.capture import manuel.doctest import manuel.testing import os import re import spidermonkey import sys import time import unittest import zope.testing.module import zope.testing.setupstack baseUrl = None # Set by test runner. run_time = spidermonkey.Runtime() class DocTestPyParser(doctest.DocTestParser): _EXAMPLE_RE = re.compile( r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P<source> (?:^(?P<indent> [ ]*) py> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P<want> (?:(?![ ]*$) # Not a blank line (?![ ]*py>) # Not a line starting with PS1 .*$\n? # But any other line
def getCookie(id, password): f = urllib.urlopen('http://static.nid.naver.com/enclogin/keys.nhn') keystring = f.read() f.close() # login JavaScript from 'https://nid.naver.com/login/js/login.long.js' js_path = os.path.join(os.path.dirname(__file__), 'login.long.js') f = file(js_path, 'r') js = f.read() f.close() rt = spidermonkey.Runtime() cx = rt.new_context() cx.execute(js) cx.execute(''' keystr = '%s'; rsa = new RSAKey(); keySplit(); rsa.setPublic(evalue, nvalue); uid = '%s'; upw = '%s'; encrypted = rsa.encrypt(getLenChar(sessionkey)+sessionkey\ +getLenChar(uid)+uid+getLenChar(upw)+upw); ''' % (keystring, id, password)) keyname, encpw = str(cx.execute('keyname')), str(cx.execute('encrypted')) params = dict(enctp='1', encnm=keyname, svctype='0', enc_url='http0X0.0000000000001P-10220.\ 0000000.000000www.naver.com', url='www.naver.com', smart_level='1', encpw=encpw) params = urllib.urlencode(params) headers = { 'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain' } conn = httplib.HTTPSConnection('nid.naver.com') conn.request('POST', '/nidlogin.login', params, headers) response = conn.getresponse() data = response.read() conn.close() cookie = response.getheader('set-cookie') while True: headers = {'Accept': 'text/plain', 'Cookie': cookie} if response.status == 302: location = response.getheader('location') host, url = re.match(r'http:\/\/([\w+\.]*)(.*)', location).groups() elif response.status == 200: host, url = re.search(r'"(?:http:\/\/)?([\w+\.]*)(.*)"', data).groups() conn = httplib.HTTPConnection(host) conn.request('GET', url, '', headers) response = conn.getresponse() data = response.read() if response.status == 302: cookie = response.getheader('set-cookie').replace(';, ', '; ') conn.close() if host == 'www.naver.com': break cookies = [c.split('=', 1) for c in cookie.split(';')] cookie = {} for c in cookies: try: key = c[0].strip() value = c[1].strip() cookie[key] = value except: continue # do nothing return cookie
def args(self): return (spidermonkey.Runtime(), )
def args(self): rt = spidermonkey.Runtime() cx = rt.new_context() echo = cx.execute("function(arg) {return arg;}") return (echo, )
def args(self): rt = spidermonkey.Runtime() return (rt.new_context(), )
def main(): global file_name parser = OptionParser(usage = usage) pyjs.add_compile_options(parser) parser.add_option("-o", "--output", dest="output", help="File to which the generated javascript should be written") parser.add_option("-i", "--input", dest="input", help="File from which the generated javascript should be read") parser.set_defaults(\ output = None, input = None, ) (options, args) = parser.parse_args() file_name = args[0] if len(args) > 1: module_name = args[1] else: module_name = None debug = 0 if options.input: txt = open(options.input, 'r').read() else: parser = pyjs.PlatformParser("platform", verbose=False) parser.setPlatform("pysm") if file_name.endswith(".py"): file_name = file_name[:-3] app_translator = pyjs.AppTranslator( app_library_dirs, parser, verbose = False, debug = options.debug, print_statements = options.print_statements, function_argument_checking = options.function_argument_checking, attribute_checking = options.attribute_checking, source_tracking = options.source_tracking, line_tracking = options.line_tracking, store_source = options.store_source, ) app_libs, txt = app_translator.translate(file_name, debug=debug, library_modules=['_pyjs.js', 'sys', 'pyjslib']) template = """ var $pyjs = new Object(); $pyjs.modules = {}; $pyjs.modules_hash = {}; $pyjs.options = new Object(); $pyjs.options.set_all = function (v) { $pyjs.options.arg_ignore = v; $pyjs.options.arg_count = v; $pyjs.options.arg_is_instance = v; $pyjs.options.arg_instance_type = v; $pyjs.options.arg_kwarg_dup = v; $pyjs.options.arg_kwarg_unexpected_keyword = v; $pyjs.options.arg_kwarg_multiple_values = v; } $pyjs.options.set_all(true); $pyjs.trackstack = []; $pyjs.track = {module:'__main__', lineno: 1}; $pyjs.trackstack.push($pyjs.track); %(app_libs)s %(module)s """ txt = template % {'app_libs': app_libs, 'module_name': file_name, 'module': txt} txt += "sys();\n" txt += "pyjslib();\n" txt += "%s();\n" % file_name if options.output: fp = open(options.output, 'w') fp.write(txt) fp.close() rt = spidermonkey.Runtime() global cx cx = rt.new_context() cx.add_global("pysm_print_fn", pysm_print_fn) cx.add_global("pysm_import_module", pysm_import_module) cx.execute(txt)
def execute_template(source_file, support_files, tests_file): tests = [] used_envs = set() for l in open(tests_file): l = l.strip() if not l or l[0] == '#': continue lang = 'any' if l.startswith('js>'): l = l[3:].strip() lang = 'js' elif l.startswith('py>'): l = l[3:].strip() lang = 'py' env_names = ['default', 'noescape'] for en in ENVIRONMENTS.keys(): if not l.startswith(en + '>'): continue env_names = [en] l = l[len(en) + 1:].strip() break used_envs.update(env_names) args_start_pos = l.find('(') args_end_pos = l.rfind(')') macro_name = l[:args_start_pos] args_str = l[args_start_pos:args_end_pos + 1] args_json = '[' + args_str[1:-1] + ']' if lang == 'any': args = json.loads(args_json) tests.append([macro_name, args, args_str, env_names]) elif lang == 'js': if tests and tests[-1][0] == macro_name: tests[-1][2] = args_str else: tests.append([macro_name, None, args_str, env_names]) elif lang == 'py': args = eval(args_json) if tests and tests[-1][0] == macro_name: tests[-1][1] = args else: tests.append([macro_name, args, None, env_names]) sm_runtime = spidermonkey.Runtime() j2_templates = {} js_contexts = {} js_sources = {} for env_name in used_envs: env = ENVIRONMENTS[env_name] j2_templates[env_name] = env.get_template(source_file) js_source = jscompiler.generate(env, None, source_file) print(js_source) cx = sm_runtime.new_context() window = {} cx.add_global('window', window) for sf in support_files: support_js = open(sf).read() cx.execute(support_js) cx.add_global('jinja2support', window['jinja2support']) cx.execute(js_source) js_contexts[env_name] = cx js_sources[env_name] = js_source for macro, args_py, args_js, env_names in tests: for e in env_names: expected = getattr(j2_templates[e].module, macro)(*args_py) js_command = 'window.jinja2js.' + macro + args_js result = js_contexts[e].execute(js_command).strip() if result != expected: print(tests) print(js_sources[e]) print("Test:", e, macro, args_py, args_js) print("Expected:") print(expected) print("Result:") print(result) assert False, "Test failed"