Package: securepy
SecurePySecurePy is a project which aims to allow very secure unknown python code execution without worries.FunctionalitySecurePy has 2 ways of restricting your executions:securepy.Restrictorthis is a way to execute python code directly, usingexecin a protected way. It tries to remove as many potentially harmful builtin classes and functions as it can, in order to run the given code safely.securepy.Sandboxthis is only available for Linux based devices and currently requires a privilege escalation (must be run as root). This is because it usesnsjailto create an isolated environment for the python script to run. This option is much safer but it's currently unfinished and it can't be used in production. (It's being developed in thensjailbranch)Critical noteEven though this library is able to safely execute most unknown python source codes, you should still be very careful with granting someone access to random code execution as it is hard to cover everything.You should also take note that this library is still relatively new and the development is still in progress, although the basic implementation is working and is relatively secure.UsageIn order to use this library, you must first download it from PyPi:pip install securepyRestrictorimportsecurepyrestrictor=securepy.Restrictor(max_exec_time=3,restriction_scope=2)stdout,exc=restrictor.execute("""[your python code here]""")max_exec_timeparameter is a way to specify the maximum amount of seconds the code will be allowed to run for until interruption.restriction_scopeparameter is a way to specify how restricted the code should be. These are the currently available scopes:0: No restriction (regular exec)1: Restricted globals (removed some unsafe globals)2(RECOMMENDED): Secure globals (only using relatively safe globals)3: No globals (very limiting but quite safe)stdoutandexcvariables will hold the outputs from your code.excwill hold the exception if there is some (otherwise it will beNone).stdoutwill hold the simple standard output (print output).Sandbox (NsJail)This is only available innsjailbranch and it isn't production ready, only use it for testing purposes until it's finished.You'll need to run your script as root user (or usingsudo) because nsjail requires mounting privileges and some more file/floder management permissions, this is not a security issue as the script inside ofnsjailis completely isolated and it can't touch the main system even with root privileges.You'll also have to havensjailinstalled and manually create a directory/securepywhich will be used as the working directory for nsjail.frompathlibimportPathimportsecurepysandbox=securepy.Sandbox(nsjail_path=Path("/usr/sbin/nsjail"),# This is path to nsjail binary (not necessary if left default)python_path=Path("/usr/bin/python"),# This is path to python binary (not necessary if left default)allowed_memory=64_000_000,# Maximum allowed memory: 64 MBmax_stdout=1_000_000,# Maximum of 1MB of stdout/stderr dataread_chunk_size=10_000,# Read from stdout/stderr by chunks of 10KBtime_limit=6,# Set maximum execution time to 6 seconds)Maximum time limitingSecurePy has the ability to stop given function if it takes over certain given maximum execution time.fromtimeimportsleepimportsecurepy# Decorator@securepy.TimedFunction(3)# Limit this function to 3 secondsdeffoo():sleep(5)# Function will take 5 seconds (> 3s limit)return2foo()# <-- this will raise `TimeoutError` after 3 second limit and the execution of the function will be automatically stopped.# Wrappertimed_func=securepy.TimedFunction(3)deffoo():sleep(1)return2timed_foo=timed_func(foo)timed_foo()# <-- this will return `2` after 1 second, since it didn't reach the given limit# Exceptions@securepy.TimedFunction(3)# Limit this function to 3 secondsdeffoo():raiseTypeError("example exception")foo()# <-- this will raise `securepy.TimedFunctionError` and the original exception will be stored in `TimedFunctionError.inner_exception`Important note:Running timed functions requires running them as separate processes in order to be able to terminate them after time limit was reached. This means that you might encounter some issues if you want to access/change certain variables because they'll exist in separate process. If you need to obtain some extra variables, the best approach would be to subclassTimedFunctionand override_capture_returnand_value_returnfunctions to your needs.STDOUT/STDERR CapturingSecurePy has the ability to run a function in a STD capturing mode which will redirect STDOUT/STDERR and store it internally so that it can be accessed later on as a string.importsecurepycaptured_std=securepy.StdCapture(auto_reset=True,memory_limit=100_000)# Context Manager:withcaptured_std:print("hello")# Wrapper:deffoo(*args,**kwargs):print("hello")captured_std.capture(foo,args=None,kwargs=None)# Decorator:@captured_stddeffoo(*args,**kwargs):print("hello")foo(*args,**kwargs)# Getting STDOUTcaptured_std.stdout# <-- will contain the captured STDOUT (str): "hello\n"# Getting STDERRcaptured_std.stderr# <-- will contain the captured STDERR (str): ""auto_resetparameter passed intoStdCaptureis a bool which guides whether stored stdout should keep being added to or if it should reset itself once function ends. Default value isTrue. Note that if you set this toFalseyou'll have to reset manually withStdCapture.reset().memory_limitparameter passed intoStdCaptureis a maximum amount of memory in bytes which will be stored, if the amount of stored memory gets higher, raisesecurepy.MemoryOverflowCapturing STDOUT/STDERR with Time LimitingIf you need to capture STDOUT/STDERR for a function which you also want to time-limit, you can useCapturingTimedFunctionwhich works very similarly toTimedFunctionbut apart from max time, it also takes theStdCaptureclassimportsecurepystd_capture=securepy.StdCapture()@securepy.TimedFunction(time_limit=2,std_capture=std_capture)deffoo(value):print("hello")returnvaluefoo(2)# <-- will return `value` (2)std_capture.stdout# <-- will hold the captured stdout string: "hello\n"