Cross-Site Request Forgery (CSRF)
In a Cross-Site Request Forgery (CSRF) attack, the attacker tricks the victim into sending a request to the web application which the victim is authenticated to. In contrast to the other typical weaknesses, every web app is usually vulnerable to CSRF, as long as it uses cookies for authentication and does not use any explicit CSRF protection.
Exploit
GET-Request
- Prepare an HTML document containing an IMG-tag (with size 1x1) and specify the URL of the web app as the source of the image to match the attack URL.
- Trick user into loading the document
POST-Request
- Prepare an HTML document containing a FORM-tag and specify the URL of the web app as the action of the form and the parameters of the request as the fields of the form.
- Add JS code that automatically submits the form
- Trick user into loading the document
- When the form is submitted, it sends the desired POST request including the cookie
- Prepare another HTML document that embeds the first document in a a frame of size zero (so the user does not see the submitted request)
XMLHttpRequest (XHR) is also a way to send requests to the web app, but it is not supported by all browsers. Also, the request has to match exactly what you could also do with the normal form to not be blocked by the same-origin policy.
Countermeasures
- Create user-specific CSRF tokens and include them in every request
- should be random and long
- Set SameSite attribute to "Strict" or "Lax" for the cookie (in the Set-Cookie HTTP response header)
- "Strict": Cookie is only sent with same-site requests
- "Lax": Cookie is sent with same-site requests and GET requests from other sites
- (Use the HTTP header "Referer" to check if the request comes from the same site)