diff options
Diffstat (limited to 'snekbox.py')
-rw-r--r-- | snekbox.py | 28 |
1 files changed, 22 insertions, 6 deletions
@@ -1,33 +1,49 @@ -import subprocess import os +import subprocess import sys from flask import Flask, render_template, request, jsonify -class Snekbox(object): +class Snekbox: + """Core snekbox functionality, providing safe execution of Python code.""" + def __init__(self, nsjail_binary='nsjail', - python_binary=os.path.dirname(sys.executable)+os.sep+'python3.6'): + python_binary=os.path.dirname(sys.executable) + os.sep + 'python3.6'): self.nsjail_binary = nsjail_binary self.python_binary = python_binary - self.nsjail_workaround() + self._nsjail_workaround() env = { - 'PATH': '/snekbox/.venv/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + 'PATH': ( + '/snekbox/.venv/bin:/usr/local/bin:/usr/local/' + 'sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' + ), 'LANG': 'en_US.UTF-8', 'PYTHON_VERSION': '3.6.5', 'PYTHON_PIP_VERSION': '10.0.1', 'PYTHONDONTWRITEBYTECODE': '1', } - def nsjail_workaround(self): + def _nsjail_workaround(self): dirs = ['/sys/fs/cgroup/pids/NSJAIL', '/sys/fs/cgroup/memory/NSJAIL'] for d in dirs: if not os.path.exists(d): os.makedirs(d) def python3(self, cmd): + """ + Execute Python 3 code in a isolated environment. + + The value of ``cmd`` is passed using '-c' to a Python + interpreter that is started in a ``nsjail``, isolating it + from the rest of the system. + + Returns the output of executing the command (stdout) if + successful, or a error message if the execution failed. + """ + args = [self.nsjail_binary, '-Mo', '--rlimit_as', '700', '--chroot', '/', |