{"id":13416213,"url":"https://github.com/openedx/codejail","last_synced_at":"2025-05-14T09:11:05.379Z","repository":{"id":8255522,"uuid":"9703957","full_name":"openedx/codejail","owner":"openedx","description":"Secure code execution","archived":false,"fork":false,"pushed_at":"2025-05-08T18:36:14.000Z","size":386,"stargazers_count":438,"open_issues_count":20,"forks_count":78,"subscribers_count":149,"default_branch":"master","last_synced_at":"2025-05-08T19:40:09.384Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openedx.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2013-04-26T20:48:06.000Z","updated_at":"2025-05-08T18:36:16.000Z","dependencies_parsed_at":"2023-11-13T23:23:11.239Z","dependency_job_id":"b3d364c6-3b6d-447f-b9a7-5251dbcf2e9b","html_url":"https://github.com/openedx/codejail","commit_stats":{"total_commits":177,"total_committers":31,"mean_commits":5.709677419354839,"dds":0.4576271186440678,"last_synced_commit":"46e4319f25f8082c271a5de69e03160b4f580906"},"previous_names":["edx/codejail"],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openedx%2Fcodejail","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openedx%2Fcodejail/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openedx%2Fcodejail/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openedx%2Fcodejail/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openedx","download_url":"https://codeload.github.com/openedx/codejail/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254110374,"owners_count":22016391,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T21:00:55.537Z","updated_at":"2025-05-14T09:11:05.328Z","avatar_url":"https://github.com/openedx.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"CodeJail\n========\n\nCodeJail manages execution of untrusted code in secure sandboxes. It is\ndesigned primarily for Python execution, but can be used for other languages as\nwell.\n\nSecurity is enforced with AppArmor.  If your operating system doesn't support\nAppArmor, then CodeJail won't protect the execution.\n\nCodeJail is designed to be configurable, and will auto-configure itself for\nPython execution if you install it properly.  The configuration is designed to\nbe flexible: it can run in safe mode or unsafe mode.  This helps support large\ndevelopment groups where only some of the developers are involved enough with\nsecure execution to configure AppArmor on their development machines.\n\nIf CodeJail is not configured for safe execution, it will execution Python\nusing the same API, but will not guard against malicious code.  This allows the\nsame code to be used on safe-configured or non-safe-configured developer's\nmachines.\n\nA CodeJail sandbox consists of several pieces:\n\n#) Sandbox environment. For a Python setup, this would be Python and\n   associated core packages. This is denoted throughout this document\n   as **\u003cSANDENV\u003e**. This is read-only.\n\n#) Sandbox packages. These are additional packages needed for a given\n   run. For example, this might be a grader written by an instructor\n   to run over a student's code, or data that a student's code might\n   need to access. This is denoted throughout this document as\n   **\u003cSANDPACK\u003e**. This is read-only.\n\n#) Untrusted packages. This is typically the code submitted by the\n   student to be tested on the server, as well as any data the code\n   may need to modify. This is denoted throughout this document as\n   **\u003cUNTRUSTED_PACK\u003e**. This is currently read-only, but may need to\n   be read-write for some applications.\n\n#) OS packages. These are standard system libraries needed to run\n   Python (e.g. things in /lib). This is denoted throughout this\n   document as **\u003cOSPACK\u003e**. This is read-only, and is specified by\n   Ubuntu's AppArmor profile.\n\nTo run, CodeJail requires two user accounts. One account is the main\naccount under which the code runs, which has access to create\nsandboxes. This will be referred to as **\u003cSANDBOX_CALLER\u003e**. The\nsecond account is the account under which the sandbox runs. This is\ntypically the account 'sandbox.'\n\nSupported Versions\n------------------\n\nThis library currently is tested to work with the following versions\n\nPython:\n\n* 3.11\n\nUbuntu:\n\n* 22.04\n* 24.04\n\nInstallation\n------------\n\nThese instructions detail how to configure your operating system so that\nCodeJail can execute Python code safely.  You can run CodeJail without these\nsteps, and you will have an unsafe CodeJail.  This is fine for developers'\nmachines who are unconcerned with security, and simplifies the integration of\nCodeJail into your project.\n\nTo secure Python execution, you'll be creating a new virtualenv.  This means\nyou'll have two: the main virtualenv for your project, and the new one for\nsandboxed Python code.\n\nChoose a place for the new virtualenv, call it **\u003cSANDENV\u003e**.  It will be\nautomatically detected and used if you put it right alongside your existing\nvirtualenv, but with ``-sandbox`` appended.  So if your existing virtualenv is in\n``/home/chris/ve/myproj``, make **\u003cSANDENV\u003e** be ``/home/chris/ve/myproj-sandbox``.\n\nThe user running the LMS is **\u003cSANDBOX_CALLER\u003e**, for example, you on\nyour dev machine, or ``www-data`` on a server.\n\nOther details here that depend on your configuration:\n\n1. Create the new virtualenv, using ``--copies`` so that there's a distinct Python executable to limit::\n\n    $ sudo python3.11 -m venv --copies \u003cSANDENV\u003e\n\n   By default, the virtualenv would just symlink against the system Python, and apparmor's default configuration on some operating systems may prevent confinement from being appled to that.\n\n2. (Optional) If you have particular packages you want available to your\n   sandboxed code, install them by activating the sandbox virtual env, and\n   using pip to install them::\n\n    $ \u003cSANDENV\u003e/bin/pip install -r requirements/sandbox.txt\n\n3. Add a sandbox user::\n\n    $ sudo addgroup sandbox\n    $ sudo adduser --disabled-login sandbox --ingroup sandbox\n\n4. Let the web server run the sandboxed Python as sandbox.  Create the file\n   ``/etc/sudoers.d/01-sandbox``::\n\n    $ sudo visudo -f /etc/sudoers.d/01-sandbox\n\n    \u003cSANDBOX_CALLER\u003e ALL=(sandbox) SETENV:NOPASSWD:\u003cSANDENV\u003e/bin/python\n    \u003cSANDBOX_CALLER\u003e ALL=(sandbox) SETENV:NOPASSWD:/usr/bin/find\n    \u003cSANDBOX_CALLER\u003e ALL=(ALL) NOPASSWD:/usr/bin/pkill\n\n   (Note that the ``find`` binary can run arbitrary code, so this is not a safe sudoers file for non-codejail purposes.)\n\n5. Edit an AppArmor profile.  This is a text file specifying the limits on the\n   sandboxed Python executable.  The file must be in ``/etc/apparmor.d`` and must\n   be named based on the executable, with slashes replaced by dots.  For\n   example, if your sandboxed Python is at ``/home/chris/ve/myproj-sandbox/bin/python``,\n   then your AppArmor profile must be ``/etc/apparmor.d/home.chris.ve.myproj-sandbox.bin.python``::\n\n    $ sudo vim /etc/apparmor.d/home.chris.ve.myproj-sandbox.bin.python\n\n    #include \u003ctunables/global\u003e\n\n    \u003cSANDENV\u003e/bin/python {\n        #include \u003cabstractions/base\u003e\n        #include \u003cabstractions/python\u003e\n\n        \u003cCODEJAIL_CHECKOUT\u003e/** mr,\n        \u003cSANDENV\u003e/** mr,\n        # If you have code that the sandbox must be able to access, add lines\n        # pointing to those directories:\n        /the/path/to/your/sandbox-packages/** r,\n\n        /tmp/codejail-*/ rix,\n        /tmp/codejail-*/** wrix,\n    }\n\n   Depending on your OS and AppArmor version you may need to specify a policy\n   ABI to ensure the restrictions are being correctly applied. Modern ubuntu\n   versions using AppArmor V3 should use the 3.0 ABI in order to enable\n   network confinment rules. A profile using the ABI 3.0 would look as\n   follows::\n\n     $ sudo vim /etc/apparmor.d/home.chris.ve.myproj-sandbox.bin.python\n\n     abi \u003cabi/3.0\u003e,\n     #include \u003ctunables/global\u003e\n\n     \u003cSANDENV\u003e/bin/python {\n         #include \u003cabstractions/base\u003e\n         #include \u003cabstractions/python\u003e\n\n         \u003cCODEJAIL_CHECKOUT\u003e/** mr,\n         \u003cSANDENV\u003e/** mr,\n         # If you have code that the sandbox must be able to access, add lines\n         # pointing to those directories:\n         /the/path/to/your/sandbox-packages/** r,\n\n         /tmp/codejail-*/ rix,\n         /tmp/codejail-*/** wrix,\n     }\n\n   You can also look at the\n   ``apparmor-profiles/home.sandbox.codejail_sandbox-python3.bin.python-abi3``\n   file which is used for testing for a full profile example.\n\n6. Parse the profiles::\n\n    $ sudo apparmor_parser \u003cAPPARMOR_FILE\u003e\n\n7. Reactivate your project's main virtualenv again.\n\n8. Disable using PAM to set rlimits::\n\n    sed -i '/pam_limits.so/d' /etc/pam.d/sudo\n\nUsing CodeJail\n--------------\n\nIf your CodeJail is properly configured to use safe_exec, try these\ncommands at your Python terminal::\n\n    import codejail.jail_code\n    codejail.jail_code.configure('python', '\u003cSANDENV\u003e/bin/python', user='sandbox')\n    import codejail.safe_exec\n    jailed_globals = {}\n    codejail.safe_exec.safe_exec(\"output=open('/etc/passwd').read()\", jailed_globals)\n    print(jailed_globals)  # should be unreachable if codejail is working properly\n\nThis should fail with an exception.\n\nIf you need to change the packages installed into your sandbox's virtualenv,\nyou'll need to disable AppArmor, because your sandboxed Python doesn't have\nthe rights to modify the files in its site-packages directory.\n\n1. Disable AppArmor for your sandbox::\n\n    $ sudo apt-get install apparmor-utils  # if you haven't already\n    $ sudo aa-complain /etc/apparmor.d/home.chris.ve.myproj-sandbox.bin.python\n\n2. Install or otherwise change the packages installed::\n\n    $ pip install -r requirements/sandbox.txt\n\n3. Re-enable AppArmor for your sandbox::\n\n    $ sudo aa-enforce /etc/apparmor.d/home.chris.ve.myproj-sandbox.bin.python\n\n\nTests\n-----\n\nIn order to target the sandboxed Python environment(s) you have created on your\nsystem, you must set the following environment variables for testing::\n\n    $ export CODEJAIL_TEST_USER=\u003cowner of sandbox (usually 'sandbox')\u003e\n    $ export CODEJAIL_TEST_VENV=\u003cSANDENV\u003e\n\nRun the tests with the Makefile::\n\n    $ make tests\n\nIf CodeJail is running unsafely, many of the tests will be automatically\nskipped, or will fail, depending on whether CodeJail thinks it should be in\nsafe mode or not.\n\n\nDesign\n------\n\nCodeJail is general-purpose enough that it can be used in a variety of projects\nto run untrusted code.  It provides two layers:\n\n* ``jail_code.py`` offers secure execution of subprocesses.  It does this by\n  running the program in a subprocess managed by AppArmor.\n\n* ``safe_exec.py`` offers specialized handling of Python execution, using\n  jail_code to provide the semantics of Python's exec statement.\n\nCodeJail runs programs under AppArmor.  AppArmor is an OS-provided feature to\nlimit the resources programs can access. To run Python code with limited access\nto resources, we make a new virtualenv, then name that Python executable in an\nAppArmor profile, and restrict resources in that profile.  CodeJail will\nexecute the provided Python program with that executable, and AppArmor will\nautomatically limit the resources it can access.  CodeJail also uses setrlimit\nto limit the amount of CPU time and/or memory available to the process.\n\n``CodeJail.jail_code`` takes a program to run, files to copy into its\nenvironment, command-line arguments, and a stdin stream.  It creates a\ntemporary directory, creates or copies the needed files, spawns a subprocess to\nrun the code, and returns the output and exit status of the process.\n\n``CodeJail.safe_exec`` emulates Python's exec statement.  It takes a chunk of\nPython code, and runs it using jail_code, modifying the globals dictionary as a\nside-effect.  safe_exec does this by serializing the globals into and out of\nthe subprocess as JSON.\n\nLimitations\n-----------\n\n* If codejail or AppArmor is not configured properly, codejail will default to\n  running code insecurely (no sandboxing). It is not secure by default.\n* Sandbox isolation is achieved via AppArmor confinement. Codejail facilitates\n  this, but cannot isolate execution without the use of AppArmor.\n* Resource limits can only be constrained using the mechanisms that Linux's\n  rlimit makes available. Some notable deficiencies:\n\n  * While rlimit's ``FSIZE`` can limit the size of any one file that\n    a process can create, and can limit the number of files it has open at any\n    one time, it cannot limit the total number of files written, and therefore\n    cannot limit the total number of bytes written across *all* files.\n    A partial mitigation is to constrain the max execution time. (All files\n    written in the sandbox will be deleted at end of execution, in any case.)\n  * The ``NPROC`` limit constrains the ability of the *current* process to\n    create new threads and processes, but the usage count (how many processes\n    already exist) is the sum across *all* processes with the same UID, even in\n    other containers on the same host where the UID may be mapped to a different\n    username. This constraint also applies to the app user due to how the\n    rlimits are applied. Even if a UIDs are chosen so they aren't used by other\n    software on the host, multiple codejail sandbox processes on the same host\n    will share this usage pool and can reduce each other's ability to create\n    processes. In this situation, ``NPROC`` will need to be set higher than it\n    would be for a single codejail instance taking a single request at a time.\n\n* Sandboxes do not have strong isolation from each other. Under proper\n  configuration, untrusted code should not be able to discover other actively\n  running code executions, but if this assumption is violated then one sandbox\n  could theoretically interfere with another one.\n\nReporting Security Issues\n-------------------------\n\nPlease do not report security issues in public. Please email security@openedx.org.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenedx%2Fcodejail","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenedx%2Fcodejail","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenedx%2Fcodejail/lists"}