Jack022
Jack022

Reputation: 1277

Securing a POST request on Flask

I built a simple Flask application that receives a POST request and performs some actions after receiving it. Here is my simple code:

@app.route('/<user>/', methods=['POST'])
def Receiver(user):
    Query = User.query.filter_by(token=user)
    Content = request.data.decode('UTF-8')
    Data = {'Content': Content, 'Username': Query.Username, 'UserID': Query.UserID}
    return jsonify(Data)

I would like to make this code as safe as possible, but i'm just getting started to Flask and security in general. What dangers can i run using this code? I'm using the variable user to make a query to my database, can it be harmful if that variable gets set to an SQL query, for example? What other threats should i consider in this case?

Upvotes: 3

Views: 2380

Answers (2)

Lewis Farnworth
Lewis Farnworth

Reputation: 297

Just to add to what Marek said, would also recommend changing to a GET... As long as there's no sensitive information being passed along in the URL. This link nicely explains the differences. It might be a good idea to look at encrypting the URL token string too, so that any parameters aren't passed over in plain text, as this leaves room for vulnerability.

Alongside this, if the site is to be made live- definitely ensure to use SSL encryption.

In terms of SQL validation, you'll need to sanitize the input before it ever reaches the database. You can do this in Flask, simply by using the HTML escape special chars... But Flask provides their own function. This link might help in that regard.

In terms of error handling, I found this tutorial mighty useful. That whole series of blog posts walks you right the way through.

Upvotes: 3

Marek Puchalski
Marek Puchalski

Reputation: 3659

Here some of my thoughts to your question:

  1. Why is this a POST request and not a GET request? POST requests are meant to change data, GETs are for queries.
  2. You don't validate input data. What happens, if the user sends you e.g. a 100kB long user name? How will the database handle it? Will it have impact on performance? Will it allow a DOS attack on server/database?
  3. Yes, SQL injection too. Everywhere where relational databases are concerned.
  4. What if the user ID does not exist? Should we not return 404?
  5. What is actually security? What is safety? The two terms are not interchangeable. Safety is when the code does not harm the world. Security is when the world does not harm the code.
  6. There is a wide variety of things to consider that could impact your code security (meaning providing confidentiality, integrity and accessibility of the data the code touches), that are unrelated to your code like: communication channel protection, server misconfigurations, DDOS attacks... Even if your code is perfect, the system holding it might still be insecure.

Upvotes: 4

Related Questions