Search code examples
dockersandboxinterpreter

Sandbox command execution with docker via Ajax


I'm looking For help in this matter, what options do I have if I want to sandbox the execution of commands that are typed in a website? I would like to create an online interpreter for a programming language.

I've been looking at docker, how would I use it? Is this the best option?


Solution

  • codecube.io does this. It's open source: https://github.com/hmarr/codecube

    The author wrote up his rationale and process. Here's how the system works:

    • A user types some code in to a box on the website, and specifies the language the code is written in
    • They click “Run”, the code is POSTed to the server
    • The server writes the code to a temporary directory, and boots a docker container with the temporary directory mounted
    • The container runs the code in the mounted directory (how it does this varies according to the code’s language)
    • The server tails the logs of the running container, and pushes them down to the browser via server-sent events
    • The code finishes running (or is killed if it runs for too long), and the server destroys the container

    The Docker container's entrypoint is entrypoint.sh, which inside a container runs:

    prog=$1
    <...create user and set permissions...>
    sudo -u codecube /bin/bash /run-code.sh $prog
    

    Then run-code.sh checks the extension and runs the relevant compiler or interpreter:

    extension="${prog##*.}"
    case "$extension" in
      "c")
        gcc $prog && ./a.out
        ;;
      "go")
        go run $prog
        ;;
    <...cut...>
    

    The server that accepts the code examples from the web, and orchestrates the Docker containers was written in Go. Go turned out to be a pretty good choice for this, as much of the server relied on concurrency (tailing logs to the browser, waiting for containers to die so cleanup could happen), which Go makes joyfully simple.

    The author also details how he implemented resource limiting, isolation and thoughts of security.