def run(self): from java.net import URL # Add new scope if self.opts.add_to_scope: self.burp.includeInScope(URL(self.opts.add_to_scope)) print("[--] Added new scope ...") # Send URL to spider if self.opts.send_to_spider: self.burp.sendToSpider(URL(self.opts.send_to_spider)) print("[--] Starting spider ...") # Start interactive jython console if self.opts.interactive: from java.util import Properties pre_properties = System.getProperties() pre_properties['python.console'] = 'org.python.util.ReadlineConsole' post_properties = Properties() PythonInterpreter.initialize(pre_properties, post_properties, []) # Attach threaded console to BurpExtender self.burp.console = console = JLineConsole() console.set('Burp', self.burp) try: self.burp.stdout.write('Launching interactive session...\n') except Exception: sys.stdout.write('Launching interactive session...\n') ConsoleThread(console).start()
def setCommandLineArgs(self, args): ''' This method is invoked immediately after the implementation's constructor to pass any command-line arguments that were passed to Burp Suite on startup. The following command-line options have been made available: -i, --interactive Run Burp in interactive mode (Jython Console) -f <FILE> Restore from burp state file upon startup -h ''' from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--interactive', action='store_true', help='Run Burp in interactive mode (Jython Console)') parser.add_option('-f', '--file', metavar='FILE', help='Restore Burp state from FILE on startup') parser.add_option('-P', '--python-path', default='', help='Set PYTHONPATH used by Jython') parser.add_option('--disable-reloading', action='store_true', help='Disable hot-reloading when a file is changed') opt, args = parser.parse_args(list(args)) if opt.interactive: from java.util import Properties pre_properties = System.getProperties() pre_properties['python.console'] = 'org.python.util.ReadlineConsole' post_properties = Properties() if opt.python_path: post_properties['python.path'] = opt.python_path PythonInterpreter.initialize(pre_properties, post_properties, sys.argv[1:]) self.console = JLineConsole() self.console.exec('import __builtin__ as __builtins__') self.console.exec('from gds.burp import HttpRequest, HttpResponse') self.console.set('Burp', self) sys.stderr.write('Launching interactive session...\n') ConsoleThread(self.console).start() self.opt, self.args = opt, args return
def function_context(): from org.python.core import Py from org.python.util import PythonInterpreter from org.python.core import PySystemState ps = PySystemState() pi = PythonInterpreter({}, ps) if not sharing: ps.shadow() ps.builtins = ps.builtins.copy() pi.exec(function.func_code)
def run_script(script, names): """Run the script and return a weak list of the values named""" pi = PythonInterpreter() pi.exec(script) if isinstance(names, str): names = (names, ) result = [] for n in names: obj = pi.getLocals()[n] result.append(weakref.ref(obj)) return result
def create_proxies(): pi = PythonInterpreter() pi.exec(""" from java.lang import Comparable class Dog(Comparable): def compareTo(self, o): return 0 def bark(self): return 'woof woof' Dog().bark() """)
def function_context(): from org.python.core import Py from org.python.util import PythonInterpreter from org.python.core import PySystemState ps = PySystemState() pi = PythonInterpreter({}, ps) if locals: pi.setLocals(locals) pi.setOut(out) pi.setErr(err) try: pi.exec(function.func_code) except: print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60
def printMessage(self,event): self.text = self.textField.getText() intrp = PythonInterpreter() self.interpreterOut = JythonOutputStream(self.outputText) try: intrp.setOut(self.interpreterOut) intrp.exec(self.text) except Exception, ex: print ex intrp.setErr(self.interpreterOut)
import org.python.core.*; public class get extends TagSupport{ public PythonInterpreter interp; public String cmd; protected PageContext pageContext; public get(){super();} public void setVar(String cmd){this.cmd=cmd;} public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } public int doEndTag() throws javax.servlet.jsp.JspTagException{ try{ if(pageContext.getAttribute("jythonInterp")==null){ interp = new PythonInterpreter(); pageContext.setAttribute("jythonInterp",interp,PageContext.PAGE_SCOPE); } else { interp=(PythonInterpreter)pageContext.getAttribute("jythonInterp"); } String res=interp.eval(cmd).toString(); pageContext.getOut().write(res); }catch(java.io.IOException e){ throw new JspTagException("IO Error: " + e.getMessage()); } return EVAL_PAGE; } }
def jython_execfile(argv): import org.python.util.PythonInterpreter as PythonInterpreter interpreter = PythonInterpreter() state = interpreter.getSystemState() state.argv = argv interpreter.execfile(argv[0])
# # Test for bug 1758838 # # execfile(<any file>) should not throw a NullPointerException # # The error only shows up in interactive interpretation (type "single" for the compilation). # But we cannot use InteractiveInterpreter here since it catches all Exceptions, # therefore we do the compilation 'by hand'. # from org.python.core import Py from org.python.core import PySystemState from org.python.util import PythonInterpreter PySystemState.initialize() interp = PythonInterpreter() code = Py.compile_command_flags("execfile('test401/to_be_executed.py')", "<input>", "single", None, 1) interp.exec(code)
def execScript(script): interpreter = PythonInterpreter() interpreter.exec(script)
def start_burp(options, *args): sys.path.extend([os.path.join('java', 'src'), options.burp]) from burp_extender import BurpExtender as MyBurpExtender, ConsoleThread from burp import StartBurp import BurpExtender from gds.burp.config import Configuration if options.debug: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.DEBUG) elif options.verbose: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.INFO) else: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.WARN) # Set the BurpExtender handler to the Pythonic BurpExtender Burp = MyBurpExtender() Burp.config = Configuration(os.path.abspath(opt.config)) Burp.opt = options Burp.args = args BurpExtender.setHandler(Burp) StartBurp.main(args) # In latest Burp, callbacks might not get registered immediately while not Burp.cb: time.sleep(0.1) # Disable Burp Proxy Interception on startup Burp.setProxyInterceptionEnabled(False) if options.interactive: from java.util import Properties pre_properties = System.getProperties() pre_properties['python.console'] = 'org.python.util.ReadlineConsole' post_properties = Properties() PythonInterpreter.initialize(pre_properties, post_properties, []) # Attach threaded console to BurpExtender Burp.console = console = JLineConsole() console.set('Burp', Burp) try: Burp.stdout.write('Launching interactive session...\n') except Exception: sys.stdout.write('Launching interactive session...\n') ConsoleThread(console).start()
def setCommandLineArgs(self, args): ''' This method is invoked immediately after the implementation's constructor to pass any command-line arguments that were passed to Burp Suite on startup. The following command-line options have been made available: -i, --interactive Run Burp in interactive mode (Jython Console) -f <FILE> Restore from burp state file upon startup -d, --debug Set log level to DEBUG -v, --verbose Set log level to INFO -C, --config Specify an alternate config (default: burp.ini) --disable-reloading Disable monitoring of plugins for changes -h ''' from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--interactive', action='store_true', help='Run Burp in interactive mode (Jython Console)') parser.add_option('-f', '--file', metavar='FILE', help='Restore Burp state from FILE on startup') parser.add_option('-d', '--debug', action='store_true', help='Set log level to DEBUG') parser.add_option('-v', '--verbose', action='store_true', help='Set log level to INFO') parser.add_option('-P', '--python-path', default='', help='Set PYTHONPATH used by Jython') parser.add_option('-C', '--config', default='burp.ini', help='Specify alternate jython-burp config file') parser.add_option('--disable-reloading', action='store_true', help='Disable hot-reloading when a file is changed') opt, args = parser.parse_args(list(args)) if opt.debug: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.DEBUG) elif opt.verbose: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.INFO) self.config = Configuration(os.path.abspath(opt.config)) if opt.interactive: from java.util import Properties pre_properties = System.getProperties() pre_properties['python.console'] = 'org.python.util.ReadlineConsole' post_properties = Properties() if opt.python_path: post_properties['python.path'] = opt.python_path PythonInterpreter.initialize( pre_properties, post_properties, sys.argv[1:]) self.console = JLineConsole() self.console.exec('import __builtin__ as __builtins__') self.console.exec('from gds.burp import HttpRequest, HttpResponse') self.console.set('Burp', self) sys.stderr.write('Launching interactive session...\n') ConsoleThread(self.console).start() self.opt, self.args = opt, args return
from org.python.util import PythonInterpreter print recurse pi = PythonInterpreter() pi.set("terminal", terminal) pi.set("recurse", recurse + 1) pi.execfile('/media/truecrypt1/code/java/Hakd/python/programs/recursive.py')
def doPost(self, request, response): c = NomjycContainer() # re-initialized container upon every request c.parameters = request.getParameterMap() log = open("/var/log/nomjyc/nomjyc.log","a") safelog = dict(c.parameters) if "pass" in safelog: safelog["pass"]=len(safelog["pass"]) log.write(("[[%s]] %s %s\n" % (request.getRemoteAddr(), datetime.utcnow(), self.yaml.dump(safelog))).encode("utf-8")) log.close() output = "<div class=\"infobox\"><span class=\"gh\">nomjyc 0.1</span>\n" c.session = {} if len(c.parameters)==0: output += "<pre>%s</pre>" % self.__doc__ output += "</div>" c.salt="dckx" try: c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.yaml")) except: output += self.explainException("Error while initiating game state - trying to load backup.") c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.bak")) # Print some debug information - for now. output += self.divHideCode("infobox", "Request", "reqi", self.dumpYaml(c.parameters), visible=True) output += self.divHideCode("infobox", "Data read", "dri", self.dumpYaml(c.data)) # If we have come so far, we assume that it is safe to write a backup. try: self.yaml.dump(c.data, FileWriter("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.bak")) except: output += self.explainException("Error while storing backup game state") # Execute all rules against the user input brain = PythonInterpreter() c.sandbox = False # a flag that tells that we are not in a sandbox checksum = hashlib.md5(self.yaml.dump(c.data)).hexdigest() for rule in c.data["rules"][:]: # we are going to modify the rules. a lot. this prevents concurrent modification. try: output += self.divHideCode("rulebox", "Executing rule '%s'" % rule["title"], "id"+str(random()), self.dumpPython(rule["code"]), openend=True) err = StringWriter() out = StringWriter() # Compile the rule into a jython/java class brain.set("self", c) # expose the container to the rules brain.setErr(err) brain.setOut(out) before = time.time() timeout (brain.exec,(rule["code"],),timeout_duration=30) runtime = int((time.time()-before) * 1000) newsum = hashlib.md5(self.yaml.dump(c.data)).hexdigest() changes = (checksum != newsum) checksum = newsum output += "<div class=\"ruleoutput\">" if changes: output += "<div class=\"erroroutput\">This rule changed the game data.</div>" if (err.getBuffer().length()): output += "<div class=\"erroroutput\">Err:<br />%s</div>" % self.dumpPythonTB(err.toString()) if (out.getBuffer().length()): output += "<div class=\"gu\">Out:</div>"+out.toString() output += "<div>(runtime: %sms)</div></div></div>" % runtime except Exception, ex: output += self.explainException("Execution failed") + "</div>"
from common import ScriptRunner from java.util import HashMap from org.python.core import PyDictionary from org.python.core import PySystemState from org.python.util import PythonInterpreter #set = ScriptRunner.methods.keySet() #for item in set: # print item # print ScriptRunner.methods.get(item) path = '/Users/miura/Desktop/test.py' #ScriptRunner.run(path, HashMap()) pystate = PySystemState() pystate.setClassLoader(IJ.getClassLoader()) pi = PythonInterpreter(PyDictionary(), pystate) pi.execfile(path)
def execution_context(): from org.python.core import Py from org.python.util import PythonInterpreter from org.python.core import PySystemState ps = PySystemState() pi = PythonInterpreter({}, ps) if locals is not None: pi.setLocals(locals) if inp is not None: pi.setIn(inp) if out is not None: pi.setOut(out) if err is not None: pi.setErr(err) try: if isinstance(source, types.FunctionType): # A function wrapping a compiled code block pi.exec(source.func_code) elif isinstance(source, java.io.InputStream): # A byte-oriented file-like input stream pi.execfile(source) elif isinstance(source, java.io.Reader): # A character-oriented file-like input stream code = pi.compile(source) pi.exec(code) else: # A str or unicode (see UnicodeSourceTest) pi.exec(source) except: print print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60
def doPost(self, request, response): c = NomjycContainer() c.parameters = request.getParameterMap() log = open("/var/log/nomjyc/sandbox.log","a") safelog = dict(c.parameters) if "pass" in safelog: safelog["pass"]=len(safelog["pass"]) log.write(("[[%s]] %s %s\n" % (request.getRemoteAddr(), datetime.utcnow(), self.yaml.dump(safelog))).encode("utf-8")) log.close() output = "<div class=\"infobox\"><span class=\"gh\">nomjyc 0.1</span>\n" c.session = {} if len(c.parameters)==0: output += "<pre>%s</pre>" % self.__doc__ output += "</div>" c.salt="dckx" try: c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.yaml")) except: output += self.explainException("Error while initiating game state") # Print some debug information - for now. output += self.divHideCode("infobox", "Request", "reqi", self.dumpYaml(c.parameters), visible=True) output += self.divHideCode("infobox", "Data read", "dri", self.dumpYaml(c.data)) # Add a final rule, if the test parameter is set if "test" in c.parameters: for code in c.parameters["test"]: c.data["rules"].add({"author":"impromptu", "code":code, "creation":datetime.utcnow(), "title":"test rule"}) cycles = 1 if "cycles" in c.parameters: try: cycles = int(c.parameters["cycles"][0]) except: pass if cycles<0 or cycles>3: cycles = 1 # Execute all rules against the user input brain = PythonInterpreter() c.sandbox = True # a flag that gives away that we are in a sandbox for i in range(cycles): c.cycle = i # a counter for the cycle we are in for rule in c.data["rules"][:]: # we are going to modify the rules. a lot. this prevents concurrent modification. try: output += self.divHideCode("rulebox", "Executing rule '%s'" % rule["title"], "id"+str(random()), self.dumpPython(rule["code"]), openend=True) err = StringWriter() out = StringWriter() checksum = hashlib.md5(self.yaml.dump(c.data)).hexdigest() brain.set("self", c) brain.setErr(err) brain.setOut(out) before = time.time() timeout (brain.exec,(rule["code"],),timeout_duration=30) runtime = int((time.time()-before) * 1000) changes = (checksum != hashlib.md5(self.yaml.dump(c.data)).hexdigest()) output += "<div class=\"ruleoutput\">" if changes: output += "<div class=\"erroroutput\">This rule changed the game data.</div>" if (err.getBuffer().length()): output += "<div class=\"erroroutput\">Err:<br />%s</div>" % self.dumpPythonTB(err.toString().strip()) if (out.getBuffer().length()): output += "<div class=\"gu\">Out:</div>"+out.toString().strip() output += "<div>(runtime: %sms)</div></div></div>" % runtime except Exception, ex: output += self.explainException("Execution failed") + "</div>"
def setCommandLineArgs(self, args): ''' This method is invoked immediately after the implementation's constructor to pass any command-line arguments that were passed to Burp Suite on startup. The following command-line options have been made available: -i, --interactive Run Burp in interactive mode (Jython Console) -f <FILE> Restore from burp state file upon startup -d, --debug Set log level to DEBUG -v, --verbose Set log level to INFO -C, --config Specify an alternate config (default: burp.ini) --disable-reloading Disable monitoring of plugins for changes -h ''' from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--interactive', action='store_true', help='Run Burp in interactive mode (Jython Console)') parser.add_option('-f', '--file', metavar='FILE', help='Restore Burp state from FILE on startup') parser.add_option('-d', '--debug', action='store_true', help='Set log level to DEBUG') parser.add_option('-v', '--verbose', action='store_true', help='Set log level to INFO') parser.add_option('-P', '--python-path', default='', help='Set PYTHONPATH used by Jython') parser.add_option('-C', '--config', default='burp.ini', help='Specify alternate jython-burp config file') parser.add_option('--disable-reloading', action='store_true', help='Disable hot-reloading when a file is changed') opt, args = parser.parse_args(list(args)) if opt.debug: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.DEBUG) elif opt.verbose: logging.basicConfig( filename='jython-burp.log', format='%(asctime)-15s - %(levelname)s - %(message)s', level=logging.INFO) self.config = Configuration(opt.config) if opt.interactive: from java.util import Properties pre_properties = System.getProperties() pre_properties['python.console'] = 'org.python.util.ReadlineConsole' post_properties = Properties() if opt.python_path: post_properties['python.path'] = opt.python_path PythonInterpreter.initialize( pre_properties, post_properties, sys.argv[1:]) self.console = JLineConsole() self.console.exec('import __builtin__ as __builtins__') self.console.exec('from gds.burp import HttpRequest, HttpResponse') self.console.set('Burp', self) sys.stderr.write('Launching interactive session...\n') ConsoleThread(self.console).start() self.opt, self.args = opt, args return
from common import ScriptRunner from java.util import HashMap from org.python.core import PyDictionary from org.python.core import PySystemState from org.python.util import PythonInterpreter #set = ScriptRunner.methods.keySet() #for item in set: # print item # print ScriptRunner.methods.get(item) path = '/Users/miura/Desktop/test.py' #ScriptRunner.run(path, HashMap()) pystate = PySystemState() pystate.setClassLoader(IJ.getClassLoader()) pi = PythonInterpreter(PyDictionary(), pystate) pi.execfile(path);
# import sys # sys.path += ["C:\\Users\\new\\Desktop\\java11.jar"] # # from com.roc.printtest import PrintTest # # PrintTest.printJava() # from ideal4j.source.util import DesEncrypt # DesEncrypt.main import org.python.util.PythonInterpreter; import org.python.core; from org.python.core import *; public class JythonTest { public static void main(String[] args) { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, brave new world"); interp.exec("import sys"); interp.exec("print sys"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye, cruel world!"); } }
def jython_start(ctx): from net.sf.chellow.billing import Contract from net.sf.chellow.monad import Hiber from org.python.util import PythonInterpreter from java.io import LineNumberReader, File, FileReader from org.python.core import PyString interp = PythonInterpreter() sys_state = interp.getSystemState() lib_path = ctx.getRealPath("/WEB-INF/lib-python") if lib_path is not None: lib_dir = File(lib_path) if lib_dir.exists(): sys_state.path.append(PyString(lib_path)) # Now check for .pth files in lib-python and process each one for lib_content in lib_dir.list(): if lib_content.endswith(".pth"): line_reader = None try: line_reader = LineNumberReader( FileReader(File(lib_path, lib_content))) line = line_reader.readLine() while line is not None: line = line.strip() if len(line) == 0: continue if line.startswith("#"): continue if line.startswith("import"): efunc = getattr(interp, 'exec') efunc(line) continue archive_file = File(lib_path, line) archive_real_path = archive_file.getAbsolutePath() sys_state.path.append(PyString(archive_real_path)) line = line_reader.readLine() finally: line_reader.close() for contract_name in LIBS: contract = Contract.getNonCoreContract(contract_name) nspace = LibDict() nspace['db_id'] = contract.id exec(contract.getChargeScript(), nspace) for k, v in nspace.iteritems(): if not hasattr(nspace, k): setattr(nspace, k, v) ctx.setAttribute("net.sf.chellow." + contract_name, nspace) Hiber.close()