Vuln-Code 3 {Python}

This code is one of the challenges intigriti posts on twitter. Source below

code

from flask import Flask, request
from jinja2 import Environment

app = Flask(__name__)

Jinja2 = Environment()

@app.route("/email/unsubscribe")
def page():
    email = request.values.get('email')
    output = Jinja2.from_string('<h1>Are you sure you want the mail: '+email+' to unsubscribe?</h1>'+'<button onclick="unsubsUser()">BYE!</button>'+'<a href="/">Reconsider</a>').render()
    return output

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=80)

Source for the code , the original post on twitter.

Vulnerability

The code seems to be vulnerable to the two vulnerabilities:

Client side Vulnerability

Cross-Site-Scripting attack can be used on the application's front-end due to the *email* parameter that is being fetched at line 10 without and being used without any sanitization. Making it to embed malicious javascript.

Server Side Vulnerability

The application allows imposes risk of RCE due to the same *email* parameter being vulnerable and used without sanitization , the vulnerability that leads to such scenario is Server-Side-Template-Injection. Even a small payload like: {{5*5}} would result in evaluating that.

Remedy

  • Proper sanitization will help in doing so , but how:

Avoid directly injecting user input into your templates. Instead, use Flask's built-in mechanisms to handle user input safely:

we could use render_template method to change:

from flask import Flask, render_template, request, Markup

app = Flask(__name__)

@app.route("/email/unsubscribe")
def page():
    email = request.values.get('email')
    
    # Use Flask's render_template to render a template safely
    return render_template('unsubscribe.html', email=email)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

and the template may look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Email Unsubscribe</title>
</head>
<body>
    <h1>Are you sure you want the mail: {{ email }} to unsubscribe?</h1>
    <button onclick="unsubsUser()">BYE!</button>
    <a href="/">Reconsider</a>
</body>
</html>

Last updated