Flask

Flask is a lightweight WSGI (Web Server Gateway Interface) web application framework. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Flask offers suggestions, but doesn’t enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy.

Installation

sudo pip install Flask

Examples

app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"
sudo flask run

Web application accessible at http://127.0.0.1:5000.

Testing

HTML escaping

When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically.

app.py

from flask import Flask
from markupsafe import escape

app = Flask(__name__)

@app.route("/<name>")
def hello(name):
    return f"Hello, {name}!"

    # To escape dangerous characters
    #return f"Hello, {escape(name)}!"
sudo flask run

Without using the escape function, this application is vulnerable to XSS (will execute the alert function):

http://127.0.0.1:5000/john<img src=1 onerror=alert(1)>

When using the escape function, the application will display:

Hello, john<img src=1 onerror=alert(1)>!

“|safe” operator

Using the “|safe” operator is dangerous. It means that the data is trusted (“safe”) and no escaping will be done.

Vulnerable template example

[...]
{% for address in addresses %}
    <p>{{ address|safe }}</p>
{% endfor %}
[...]

With “| safe” Jinja2 will print symbols as they are in your variable, that means that it won’t translate “dangerous” symbols into html entities (that Jinja2 does by default to escape “dangerous” ones). Use this option if you trust variable’s content because in opposite case there can be vulnerabilities for example XSS.