Ethan Chiu My personal blog

Hacked With Python

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:

from os import open
with open('./templates/index.html', 'w') as f:
   f.write('<img ...'>

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:

import sys

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
  • Simpleeval
    • 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 found your pythonbuddy page earlier when you posted it and saw that it was defaced. I was curious how the person did it so I tried it myself. You probably discovered the Hacker gif I left you. I meant no harm. :) 

I even tried to mark the as readonly so others can't change it again.

I see you tried to fix the issue but It is still vulnerable btw. I used the open() command to overwrite the index.html

I recommend RestrictedPython or Sculpt the Javascript version you tried out.
Hope you didn't mind the harmless prank. I'm a student like you. Gl."

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.

Additional Resources:

Side Notes:

  • 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.