Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely executing user-submitted python code on the server

I am looking into starting a project which involves executing python code that the user enters via a HTML form. I know this can be potentially lethal (exec), but I have seen it done successfully in at least one instance.

I sent an email off to the developers of the Python Challenge and I was told they are using a solution they came up with themselves, and they only let on that they are using "security features provided by the operating system" and that "the operating system [Linux] provides most of the security you need if you know how to use it."

Would anyone know how a safe and secure way to go about doing this? I thought about spawning a new VM for every submission, but that would have way too much overhead and be pert-near impossible to implement efficiently.

like image 572
Josh Hunt Avatar asked Nov 15 '09 13:11

Josh Hunt


People also ask

How can I run my Python code on server?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .

How can I protect my Python code but still make it available to run?

The best solution to this vulnerability is to encrypt Python source code. Encrypting Python source code is a method of “Python obfuscation,” which has the purpose of storing the original source code in a form that is unreadable to humans.

What are the 2 ways to execute Python program?

It can run a Python code in two ways: As a Script or Module. As a piece of code written in an interactive session.


1 Answers

On a modern Linux in addition to chroot(2) you can restrict process further by using clone(2) instead of fork(2). There are several interesting clone(2) flags:

CLONE_NEWIPC (new namespace for semaphores, shared memory, message queues)
CLONE_NEWNET (new network namespace - nice one)
CLONE_NEWNS (new set of mountpoints)
CLONE_NEWPID (new set of process identifiers)
CLONE_NEWUTS (new hostname, domainname, etc)

Previously this functionality was implemented in OpenVZ and merged then upstream, so there is no need for patched kernel anymore.

like image 159
dottedmag Avatar answered Oct 20 '22 17:10

dottedmag