def main(options): #prepare network interfaces if options.verbose: print >> sys.stderr, "Preparing networking interfaces %s" % options.interface prepare_interfaces(options.interface) #move file to tmp dir and chown it to executing user if options.verbose: print >> sys.stderr, "Reading program from %s" % options.program try: fp = open(options.program) usercode = fp.read() finally: fp.close() #build usercontext if options.verbose: print >> sys.stderr, "Building script context" import time, nonportable nonportable.getruntime = time.time #change getruntime to time.time to gain preformance build_context(options.quiet) #change directory to directory of safe_check.py os.chdir(os.path.dirname(os.path.realpath(sys.argv[0]))) #drop privileges if not options.runasroot: if options.verbose: print >> sys.stderr, "Dropping privileges (%s)" % options.runas drop_privileges(options.runas_uid, options.runas_gid) else: if options.verbose: print >> sys.stderr, "Not dropping privileges !!!" #run script try: if options.verbose: print >> sys.stderr, "Checking script %s" % options.program namespace = virtual_namespace.VirtualNamespace(usercode, options.program) usercode = None # allow the (potentially large) code string to be garbage collected if options.verbose: print >> sys.stderr, "Initializing resource restrictions %s" % options.resources repy.initialize_nanny(options.resources) if options.verbose: print >> sys.stderr, "Running script %s, arguments = %s" % ( options.program, options.arguments) context = repy.get_safe_context(options.arguments) repy.execute_namespace_until_completion(namespace, context) except KeyboardInterrupt: return except SystemExit: pass except: tracebackrepy.handle_exception() try: import time while True: time.sleep(1.0) except KeyboardInterrupt: return
def main(): # JAC: This function should be kept as stable if possible. Others who # extend Repy may be doing essentially the same thing in their main and # your changes may not be reflected there! # Armon: The CMD line path to repy is the first argument repy_location = sys.argv[0] # Get the directory repy is in repy_directory = os.path.dirname(repy_location) init_repy_location(repy_directory) ### PARSE OPTIONS. These are command line in our case, but could be from ### anywhere if this is repurposed... usage = "USAGE: repy.py [options] resource_file program_to_run.repy [program args]" parser = optparse.OptionParser(usage=usage) add_repy_options(parser) options, args = parser.parse_args() if len(args) < 2: print "Repy requires a resource file and the program to run!" parser.print_help() sys.exit(1) resourcefn = args[0] progname = args[1] progargs = args[2:] # Do a huge amount of initialization. parse_options(options) ### start resource restrictions, etc. for the nanny initialize_nanny(resourcefn) # Read the user code from the file try: filehandle = open(progname) usercode = filehandle.read() filehandle.close() except: print "FATAL ERROR: Unable to read the specified program file: '%s'" % (progname) sys.exit(1) # create the namespace... try: newnamespace = virtual_namespace.VirtualNamespace(usercode, progname) except CodeUnsafeError, e: print "Specified repy program is unsafe!" print "Static-code analysis failed with error: "+str(e) harshexit.harshexit(5)
def run_unrestricted_repy_code(filename, args_list=[]): """ <Purpose> This function allows an user to run a repy file without using any restrictions like a normal repy program. <Arguments> filename - The filename of the repy file you want to run. args_list - a list of arguments that need to be passed in to the repy file. <Exceptions> Exception raised if args_list provided is not in the list form. Any exception raised by the repy file will be raised. Error may be raised if the code in the repy file is not safe. <Return> None """ if not isinstance(args_list, list): raise Exception("args_list must be of list type!") # Initialize the safe module before building the context. _initialize_safe_module() # Prepare the callargs list callargs_list = [filename] callargs_list.extend(args_list) # Prepare the context. context = {} namespace.wrap_and_insert_api_functions(context) context = safe.SafeDict(context) context["_context"] = context context[ "createvirtualnamespace"] = virtual_namespace.createvirtualnamespace context["getlasterror"] = emulmisc.getlasterror context['callfunc'] = 'initialize' context['callargs'] = callargs_list code = open("dylink.repy").read() virt = virtual_namespace.VirtualNamespace(code, name="dylink_code") result = virt.evaluate(context)
# Might be an interrupted system call, if so retry... (#840) if 'nterrupred system call' in str(e): continue print "Failed to read the specified file: '"+program+"'" raise except: print "Failed to read the specified file: '"+program+"'" raise else: print "Failed to read the specified file with multiple attempts: '"+program+"'" # Armon: Create the main namespace main_namespace = virtual_namespace.VirtualNamespace(usercode, program) # Let the code string get GC'ed usercode = None # Insert program log separator and execution information if displayexecinfo: print '=' * 40 print "Running program:", program if simpleexec: print "(Simple execution mode)" else: print "Arguments:", args print '=' * 40 # If we are in "simple execution" mode, execute and exit
def init_namespace(resourcefn, program, args): global idlethreadcount, event_id # Armon: Initialize the circular logger before starting the nanny if logfile: # time to set up the circular logger loggerfo = loggingrepy.circular_logger(logfile) # and redirect err and out there... sys.stdout = loggerfo sys.stderr = loggerfo else: # let's make it so that the output (via print) is always flushed sys.stdout = loggingrepy.flush_logger(sys.stdout) # start the nanny up and read the resource file. nanny.start_resource_nanny(resourcefn) # now, let's fire up the cpu / disk / memory monitor... # nonportable.monitor_cpu_disk_and_mem() # Armon: Update our IP cache emulcomm.update_ip_cache() # These will be the functions and variables in the user's namespace (along # with the builtins allowed by the safe module). usercontext = {'mycontext': {}} # Add to the user's namespace wrapped versions of the API functions we make # available to the untrusted user code. namespace.wrap_and_insert_api_functions(usercontext) # Convert the usercontext from a dict to a SafeDict usercontext = safe.SafeDict(usercontext) # Allow some introspection by providing a reference to the context usercontext["_context"] = usercontext # BAD:REMOVE all API imports usercontext["getresources"] = nonportable.get_resources usercontext["mycontext"]["wallclocktime"] = time.time #usercontext["openfile"] = emulfile.emulated_open #usercontext["listfiles"] = emulfile.listfiles #usercontext["removefile"] = emulfile.removefile #usercontext["exitall"] = emulmisc.exitall #usercontext["createlock"] = emulmisc.createlock #usercontext["getruntime"] = emulmisc.getruntime #usercontext["randombytes"] = emulmisc.randombytes #usercontext["createthread"] = emultimer.createthread #usercontext["sleep"] = emultimer.sleep #usercontext["getthreadname"] = emulmisc.getthreadname usercontext[ "createvirtualnamespace"] = virtual_namespace.createvirtualnamespace usercontext["getlasterror"] = emulmisc.getlasterror # grab the user code from the file try: usercode = file(program).read() except: print "Failed to read the specified file: '" + program + "'" raise # Armon: Create the main namespace try: main_namespace = virtual_namespace.VirtualNamespace(usercode, program) except CodeUnsafeError, e: print "Specified repy program is unsafe!" print "Static-code analysis failed with error: " + str(e) harshexit.harshexit(5)
def main(): repy_location = sys.argv[0] repy_directory = os.path.dirname(repy_location) init_repy_location(repy_directory) usage = "USAGE: repy.py [options] program_to_run.r2py [program args]" parser = optparse.OptionParser(usage=usage) parser.disable_interspersed_args() add_repy_options(parser) options, args = parser.parse_args() if len(args) < 1: print("Repy requires a program to run!") parser.print_help() sys.exit(1) #resourcefn = args[0] progname = args[0] progargs = args[1:] parse_options(options) nmstatusinterface.launch(None) try: filehandle = open(progname) usercode = filehandle.read() filehandle.close() except: print( f"FATAL ERROR: Unable to read the specified program file: {progname}" ) sys.exit(1) try: newnamespace = virtual_namespace.VirtualNamespace(usercode, progname) except CodeUnsafeError as e: print("Specified repy program is unsafe!") print("Static-code analysis failed with error: " + str(e)) harshexit.harshexit(5) del usercode if options.execinfo: print("=" * 40) print("Running program: " + progname) print("Arguments: " + progargs) print("=" * 40) newcontext = get_safe_context(progargs) try: newnamespace.evaluate(newcontext) except SystemExit: raise except: tracebackrepy.handle_exception() harshexit.harshexit(6) harshexit.harshexit(0)