Search code examples
htmlflaskflask-wtforms

Can someone clarify csrf protection and an empty flask-wtforms forms?


I have a question about csrf Cross-site Request Forgery Attacks in flask.

I found a good youtube video. Basically, in the video:

  • someone updated someone's email when logged in through a login path/function that updates the email when logged in.
  • then someone updates the email when the csrf token isn't there and ends up inserting data from using an HTML file.

In the video, they only show it is needed for logged-in routes.

Do I need it when I am not logged in? Also, do I need csrf protection for a get request? I assume not because nothing is being submitted.

Also, can I have an empty WTForms, and will the code below work?

Example of emptyforms:

forms.py

class EmptyForm(FlaskForm):
    pass

routes.py

@app.route('/random_route')
def some_route_function()
    if request.method == 'GET' :     
       form = EmptyForm()
       return render_template ( 'random_route.html', form=form )

random_route.html

 <form validate="" id="random_route" method="GET"> 
     <!-- Make the secret key work -->
     {{form.csrf_token}}
     <h1>Random message this is the only thing the form does. </h1>
</form>  
I also have a layout.hmtl which contains the html.

Solution

  • Cross site requests work like this: An attacker sends a malicious link to a user which then does stuff the user did not intend to do. An example:

    Let's say you have a URL in your flask app that allows the user to update their email. The URL is https://mygreatapp.com/[email protected].

    Now I (the attacker) trick your user into clicking the following link: https://mygreatapp.com/[email protected]. Since you are logged into your app, this will work and reset your email to the attackers email, who can then request a password reset.

    If you were using CSRF protection, the form/link requires an additional csrf token which is generated freshly each time the form is generated for a user.

    So if your user wants to change their email, they request the emailChangeForm from you, and you send it to them with a randomly generated csrf token 'abcdefg'. Now when the user sends back the form, it has to contain not only the updated email address, but also the exact csrf token that you sent with it. If it doesn't, you know it wasn't the user who filled out that form.