Sea Surf

Do you have a moment to talk about our lord and savior, csrfmiddlewaretoken?

yellowriver81 posted 2 months ago

Hi guys. I recently learned a bit about cross-site request forgery (CSRF). It's a vulnerability in which an attacker can make an authorized user perform something that he didn't want to. For instance, suppose I wanted to make Jacob post some content in the blog that I choose. Conceivably, I could craft a malicious form to try to trick him into posting something, like the following, which automatically submits a post:

<body onload = "document.forms[0].submit">
<form action = "" method = "POST">
<input type = "hidden" name = "title" value = "Goober">
<input type = "hidden" name = "image" value = "">
<input type = "hidden" name = "caption" value = "Look at all those chickens!">
<input type = "hidden" name = "content" value = "yellowriver81 was here">

and it would actually work because when Jacob makes a request to his blog, the browser *automatically* sends his cookie information (remember that http is stateless).

This seems really really scary, so what's preventing this from happening? It turns out that it's this single line of input included in the html called "csrfmiddlewaretoken". Its value is a cryptographically-random 64-character string generated by the server and put on the page, and there's no way for my malicious form to guess it. Even if I can make Jacob verify with his cookie, the csrfmiddlewaretoken won't bypass the check, and I can't successfully make the POST request. Pretty cool, eh? It's the little things that matter.


jacob posted 2 months ago


Yuh. Django will throw out a bunch of warnings if you don’t put that in there for each form. Django smaht