Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I know about cookies domain and scope for security purposes?

Where can I learn (or what is) about a cookie's scope to avoid CSRF and XSS attacks for authenticated users?

For example, if I have a multi-tenant system where a single user can be access to one or more sites what is more secure:

  • company1.hoster.com
  • company2.hoster.com
  • company3.hoster.com

or

  • www.hoster.com/company1
  • www.hoster.com/company2
  • www.hoster.com/company3

What happens if I set a cookie at "hoster.com"?

like image 264
TLDR Avatar asked Apr 15 '11 13:04

TLDR


Video Answer


1 Answers

You can restrict the validity scope of cookie in the domain and the path separately. So you could set a cookie in both scenarios that is only valid for that specific domain/path combination:

  1. To set a cookie for //company1.example.com/ only:

     Set-Cookie: name=value; Path=/
    

    Omitting the Domain attribute makes the cookie only valid for the domain that it was set in. And with Path=/ the cookie is valid for any path that has the prefix /.

  2. To set a cookie for //example.com/company1/ only:

     Set-Cookie: name=value; Path=/company1/
    

    Same explanation as for the example above. The only restriction is that you need to use /company1/ instead of /company1 as Path=/company1 would be equivalent to Path=/ and thus would make the cookie also valid for /company2 and /company3.

And to avoid that the cookie can be read via JavaScript (reducing the assets accessible using XSS), set the HttpOnly attribute.

like image 77
Gumbo Avatar answered Sep 26 '22 16:09

Gumbo