Home > database >  Is CSRF middleware needed if HTTPOnly cookie is used? And should it be session-based?
Is CSRF middleware needed if HTTPOnly cookie is used? And should it be session-based?

Time:11-24

Now authorization sheme looks like this: If the user input the correct data, the server generates a unique sessionKey, inserts it into the session table with FK for this user. In response to a JSON request, I send this sessionKey. The web client sets this key it in a cookie.

But the problem is that if the web client stores this cookie, JS will have access to them, and it is not safe. The alternative is to set the HTTP-Only cookie. But it is not clear whether it is necessary to use CSRF middleware in this case. Does the HTTPOnly attribute solve the problem of XSS / CSRF attacks? If it does not decide and you need a CSRF middleware, then the csrf cookie must be a session cookie.

The problem is that all the csrf middlewares for my framework do not allow to use of the session csrf cookie. Alternatively, write my own middleware. Do I understand correctly that the csrf middleware stores the token that I gave to the client in RAM and verifies on every request? But then what's the point of this token if it can be intercepted in the same way as an authorization cookie?

CodePudding user response:

Let's start with stating that Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) are two different animals.

  • XSS is about embedding malicious code into a site to have it executed on the client machine. No HTTPOnly flag can mitigate this.
  • CSRF is about embedding malicious code on some third party site and sending you the link to the third party site. The malicious code can try to fire GET/POST request (which can bypass browsers Same Origin Policy) and execute some unwanted actions on the site the user is logged to. It's easier to understand this with an example:
    1. You are logged into your site on https://example.com. You are authenticated with a cookie.
    2. Someone sends you a link to https://malicious.net. You open the link in a separate browser tab.
    3. Malicious code is being executed and fires a request to https://example.com/deleteAccount=1. Cookie will be attached, request will be authenticated and executed.

The answer is no - the HTTPOnly flag will not mitigate any of this. But let us concentrate on solving CSRF issue. What options do you have?

In fact you have many: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

IMO the easiest could be passing the sessionKey not over a cookie, but over an Authorization header. This can not be done automatically by the browser so you would be safe from CSRF attacks.

  • Related