Cookie Security Considerations for CSRF attacks
CSRF attacks, by definition, usually involve abusing the fact that the user is already logged in on a site: i.e that a malicious form can submit some request to your website, using the user's existing session.
The first line of defence against them is utilising security regarding the cookies that have the user session ID stored, by preventing forms that exist on another website outside your website's domain from using said cookie.
Cookie SameSite Directive
In your webserver configuration, you can set the SameSite setting for user cookies, that determines when the cookie is sent in POST and GET forms:
- None: any third-party site can use your website's cookies to send GET or POST requests
- Lax: any third-party site can use your website's cookies to send GET requests, but not POST requests
- Strict: Only your website can use your website's cookies. This is usually not preferable, as it causes many legitimate requests to fail (for example, "subdomain-1.yourwebsite.com" and "subdomain-2.yourwebsite.com" count as cross-domain for the purposes of this: user cookies won't be sent from one to the other in a Strict scenario).
Modern browsers hold to the standard that if no directive is set, they default to Lax, which is generally the best option for most sites. Strict can interfere with a lot of functionality, and is not normally needed in most cases outside of security-critical applications.
As such, you should make sure you set Cookie SameSite to Lax, unless you have some special need for the Strict directive.
The SameSite Directive is just that: a directive
Other Cookie attributes
Cookie HTTPOnly
The HTTPOnly attribute makes the cookie only accessible via HTTP and not JavaScript, i.e. the user's browser will not have access to its contents. This should be enabled.