12

I'm writing my application backend with Python Flask. As part of the registration process, I have a form that sends the new user's information to my backend and then adds it to my MongoDB database.

I'm pretty new in this world and never wrote something that has to be secured..

My Python code looks like that:

from flask import Flask, request

app = Flask(__name__)


@app.route('/register', methods=['POST'])
def register():
    username = request.form['username']
    password = request.form['password']

Is there a Python library that sanitizes the request.form['username'] and request.form['password'] field for me? Something that make me safe from XSS and data leaks?

Thanks ahead!

GMe
  • 1,091
  • 3
  • 13
  • 24
  • 1
    If you want to prevent cross site request forgery you can either include code snippets e.g.: http://flask.pocoo.org/snippets/3/ or use a library like FlaskWTF which is a nice Flask wrapper for WTForms https://flask-wtf.readthedocs.io/en/stable/. As for XSS Flask just escapes everything by default so you should be okay: http://flask.pocoo.org/docs/0.12/security/#cross-site-scripting-xss – Jack Evans May 11 '17 at 21:10
  • 1
    @JackEvans Thanks! I will try to use session tokens in my code – GMe May 11 '17 at 21:24
  • 3
    You can use **escape** example `from flask import escape` then `username = escape(request.form['username'])` – jirarium May 27 '19 at 00:49
  • @jirarium `escape` is depreciated and it is not recommended to use anymore – Piyush Srivastava Jan 05 '22 at 13:34
  • @PiyushSrivastava sure , things keep developing , and one should be always up to date. – jirarium Jan 20 '22 at 14:15

2 Answers2

1

I have used python bleach in the past. https://github.com/mozilla/bleach

I think it might be useful for your case.

1

One of the best way to avoid injections is to use ORM and avoid raw queries. For MongoDB it can be flask_mongoengine or motor. Both of them provide escaping out of the box (except for some cases).

But you should take care of variable types that you pass to queries.

For example,

query = Model.objects.filter(field=value)

Everything is fine while value is str or int, but what if it looks like {'$gte': ''}?

So flask-wtf or marshmallow are strong recommended to avoid such problems.

akdev
  • 586
  • 2
  • 6
  • 18