Sunday, 21 December 2014

Remote code execution on misconfigured systems using Werkzeug

One of the most popular WSGI utility frameworks for Python is Werkzeug. It simplifies the handling of HTTP connections within your Python application but also provides a powerful debugger that permits one to execute code from within the browser.

While the provided link warns those to not enable the debugger on anything production, it is often ignored or forgotten about and ends up being enabled in the first place. It is possible to search for systems on the Internet that have the debugger enabled and execute Python code remotely.

It should be noted that this affects both the Flask and Django frameworks mainly but could be used elsewhere.

Revealing and using the debugger

Getting the debugger to reveal itself is fairly simple: cause an exception. This can be achieved by writing some faulty code or by simply making it happen yourself such as in this code example using the Flask framework:
from flask import Flask

app = Flask(__name__)

def main():
All you need to do is execute the above as a Python script and the following should be outputted:
$ python
 * Running on
 * Restarting with reloader...
Now view the page via the URL it provides and you'll have access to the debugger as follows:

And as you can see it is pretty straightforward too:
You can view the code by highlighting over the code on the right.

Python code can be executed as if you were running the interpreter locally.

Finding affected hosts

Finding hosts is trivial using a search engine such as Google or a service like Shodan.

At the time of this writing, using Google does not net any results but previously during some research on this matter it did. It appears that any services that are indexed are being taken down fairly quickly.

If you wanted to try a Google search for the future, this search may provide a result:
intitle:"Werkzeug Debugger" "You can execute arbitrary Python code in the stack frames"
However, Shodan makes it easier to find servers that specifically run Werkzeug.

Finding servers that error out is fairly simple.
Some fine-tuning is required to find hosts that can have the code executed but they are there.

It should be noted that the debugger can be activated even without executing the HTTP server internally. Documentation exists that allows one to enable the debugger via Apache if you so dare.

It goes without saying that you should not execute any code if you run across a machine that has the debug mode enabled.

Preventing your application from being vulnerable

If you're developing an application that makes use of Werkzeug, you should avoid hard-coding a debug mode into it.

My suggestion is to try something like this:
import sys
if __name__ == '__main__':
    debug = 'debug' in sys.argv
This should require you to add 'debug' to the command line arguments when running the code, allowing you to just leave it to local development.