Hacked With Python05 Mar 2017
A few days ago, my project PythonBuddy was hacked. The hacker hacked my server and replaced my whole site with a gif by running python code in the editor that used the open Python function. Here is what the code could have possibly looked like:
This hack was quite a wake up call. I had naively implemented PythonBuddy without any sandboxing.
After this incident, I scoured the web searching for a solution to prevent a hack like this from happening again. I wanted a quick fix.
Eventually, I came up with a quick solution to prevent people from using dangerous imports such as os:
This basically just blacklisted certain imports like “sys” or “os”.
While researching a fix for my program, I discovered some sandboxes that didn’t quite work out for me:
- Pypy sandbox
- Required me to use the PyPy interpreter which would slow down my program
- Created by a Python coredeveloper
- Not flexible enough.
- If I used this, I would have to parse through the document each time using regex to identify the functions being defined.
- Also, it was quite limited and didn’t support enough functions.
- Edx’s codejail
- Was really aimed towards the edx platform and I couldn’t really figure how to manipulate it for my own program.
Funnily enough, the person who hacked me contacted me via Reddit today and told me about the vulnerabilities in my site and how he was trying to help secure my site:
So, I created a different version of PythonBuddy which used RestrictedPython: PythonBuddy’s Restricted Python Branch . Unfortunately, this version doesn’t allow a lot of python functions and operators to work like “yield”.
Overall, the main takeaway here is that we should always safely execute unknown code via a protected environment such as a sandbox.
- Later today, I watched an amazing video from Pycon 2014 about Python sandboxing which made me realized if I were to create my own full-fledge sandbox, I would include functions that blacklist certain keywords, make builtins read in only, etc. But, right now, I hope to implement something more secure and well estabilshed like Pypy’s sandbox.