Access cookie information in Javascript - javascript

Is there anyway to access the data associated with a cookie such as path, flags, and expiration date from javascript? All I've been able to find for cookie access is document.cookie, which only provides a list of name value pairs. Why is the interface for cookie access so limited?

No, there is none, in terms of safe, cross-browser support.
Reasoning comes down to security.
The goal of cookies was to allow for communication back and forth from the browser to the server.
If you could allow any front-end script to manually edit the domain / path / expiration of a cookie, just for knowing its name, it would lead to a lot of potential security-holes, if not for spoofing access, then at least for invisibly tracking people.
That's not to say that cookies are inherently safe, or even particularly safe at all.
I mean to say that by allowing any and all JS to edit any and all cookie data sent to the server (moreso than just CRUD), any pretence of security would disappear in a heartbeat.

Related

Where and how save token JWT ? (Best Practice)

I've read that save token JWT in localStorage is a bad practice.
https://dev.to/rdegges/please-stop-using-local-storage-1i04
I'm working with ReactJs, and to other side have a API Rest with NodeJs.
Where and how I should save token JWT ?, in a Cookie?
Gretting from Chile,
If the choice is between cookie and localStorage, both have their pros and cons when it comes to security. With all security attributes set correctly (HttpOnly, secure, SameSite=strict) it is true that a cookies could be more protected against certain attacks.
However, SameSite attributes may not work for everyone, and may not protect all functions against CSRF (Cross Site Request Forgery) attacks.
HttpOnly will protect the value from being accessed from JavaScript which is good if the application suffers (XSS) Cross Site Scripting vulnerabilities. However, any moderately qualified attacker could easily achieve what they wanted without accessing the actual value of the token anyway.
The thing to remember when storing tokens in localStorage is that it is not cleared when the browser is closed, meaning that a user will not become logged out by closing the browser - which many have come to expect. If that is a problem, you may want to consider storing the JWT in the sessionStorage instead.
localStorage seems fine because many people are using localStorage.
If you want extra security feature
You can make your token lifespan short eg {30 min, 60 min}
Also You can check your user active state whether or not
The user will Logout automatically

JWT stateless sign-on with secure cookie storage : how to implement log out?

I am starting to implement a JWT based Single Sign On system (for several single page apps under the same domain, so something like app1.mydomain.com, app2.mydomain.com, auth.mydomain.com) using the mechanisms described in this article from Stormpath.
In order to protect my signed JWT token from XSS attacks, I want to store the token in a secure (HTTPS only) and HTTP-only cookie. The SPA itself will get the user info from the response body.
My main question is how can we implement a "log out" feature in JavaScript, since the cookie is, by design, not accessible from the JS code?
I am guessing that I will have to make a server call that will expire the cookie. Is there a pure-client-side way to do it though?
The best way would be to do the cleanup server-side as user JEY already suggested.
Additionally, I wanted to extend the bit on the possibilities so this did not fit a comment.
When dealing with browser-based applications selecting the token storage is almost a pick your poison game. If you go with a secure HTTP-only cookie you don't have to worry about XSS vulnerabilities leading to token disclosure. However, you'll still have to ensure you're not vulnerable to XSS by an whole set of another reasons.
This means you don't save any actual work, you just get that fuzzy feeling that if you do get compromised by XSS at least the token is safe.
On the other hand, by going with a cookie, CSRF is now something that needs to be on your radar and here is where things may get funny, some trivial methods of preventing CSRF like double-submit cookies can be implemented in such ways that they are virtually useless in the presence of exploitable XSS vulnerabilities in child domains for example.
I'm not saying that storing tokens in cookies is plain wrong, it isn't, likewise storing them in Web storage is also acceptable. In both cases you need to understand the consequences of your choice and the possibilities each one brings.
In this case, Web storage would simplify your logout scenario from a client-side perspective so you need to ask yourself which set of pros and cons are better suited for your scenario.
Given you mentioned multiple applications in child domains one thing to be aware of is the following:
With token-based auth, you are given the choice of where to store the JWT. Commonly, the JWT is placed in the browsers local storage and this works well for most use cases. There are some issues with storing JWTs in local storage to be aware of. Unlike cookies, local storage is sandboxed to a specific domain and its data cannot be accessed by any other domain including sub-domains.
(emphasis is mine, source: Where to Store Tokens? section of Cookies vs Tokens: The Definitive Guide)
(Disclosure: I'm an Auth0 engineer.)

Is letting users access cookies through javascript a security issue

I was wondering if allowing the user of a site to access and modify cookies with javascript from the console is a security issue? What harm can be done by allowing users to have this? Is it only considered a security issue in some situations but not others? Also does using HttpOnly cookies prevent the user from modifying cookies?
You are talking about two different scenarios:
Allowing JavaScript to read/modify cookies
Can a user modify cookies if they are flagged as HttpOnly
1) Allowing JavaScript to read/modify cookies.
The reason you normally do not want JavaScript being able to access cookies (reading or writing) is that most site use cookies to handle site authentication. It is common for attackers to create an exploit of Cross-Site Scripting (XSS) on a web site, and use that to read the values of the authentication cookie and send them to a server the attacker controls.
When the attacker has the session cookies, there is a chance (depending on the security of the site) that the attacker can insert the victims authentication cookie's values into the attackers session. Then when they go to the target site, they are treated as the victim and can do anything the victim can do.
Stealing cookies is not the only thing that can be done through XSS, to read more, look at OWASPS - A3 Cross-Site Scripting write-up.
2) Can a user modify cookies if they are flagged as HttpOnly
Yes. The user can modify the cookies, html, css, JavaScript, anything that is on their machine. That is why secrets should never be stored on the client's computer, and ANY values coming from the client/user's computer needs to be considered untrusted until proven to be valid.

Is http-only cookie safe?

I am setting http-only cookie from the server for storing some user info so that i can validate user on backend. Say some hacker steals this cookie from someone's browser and go to my webpage and add the same cookie using document.cookie = "cookie_name = cookie_value" if cookie is not there. If cookie is there then he can delete the existing http-only cookie using chrome developer tool and later add it using document.cookie = "cookie_name = cookie_value" on his browser.
Now when server gets a call from hacker browser, it gets a cookie set by hacker and would validate it. How can i stop this?
Cookies leave you vulnerable to Cross-Site Request Forgeries and their kin. Not just hackers stealing cookies, but hackers borrowing a user's browser which already has the cookies. This is part of why tokens are more common today.
If you have to use cookies, there are various things you can do to make them slightly less insecure--updating the cookie on each request, verifying request IP against sending IP, configuring your web pages not to allow the loading off offsite content, forcing re-login for any major actions, and other user verification means. None of them is perfect.
Simple: You cannot. http-only serves a different purpose than validation. Your assumption that a hacker will use a browser is the first problem you have. I would never use a browser for something like that since a browser would restrict me. I would forge a HTTP request with my own tools and send a header with http-only and secure and whatever you want me to to your server.
If you want to validate your cookies, you will need to implement your own solution instead of relying on browser mechanisms. You could for example bind the cookie to a certain IP range and add some kind of token to the end of the cookie-key or cookie-value.
In general, do what #bryanx says. DO NOT USE COOKIES TO STORE DATA. They are fine for session tokens and the like.
Don't use cookies.
Cookies are necessary for preserving information between sessions, but any time you leave information on the client, you open yourself up to potential issues like you described. If you only need the information maintained during the user's session, you may want to consider using a $_SESSION instead of a cookie.
If you must use cookies, you may want to consider building out logic that if the cookie doesn't match a previously authenticated device, that you challenge the user again for their credentials. There are many ways to solve for this, just get creative.

Cookie without httpOnly, how insecure it is?

Im developing a web application which requires cookie to be set httpOnly = false.
Since, I find no other way to pass authentication cookies(for checking whether user has logged in successfully) from server side to be accessible via Javascript in my front end. This cookie is then used to send an AJAX request to my server side(added to the header). (Please do correct me if Im wrong and suggest me any other way)
My question:
How insecure is httpOnly = false? Is it safe enough with just forcing it to use cookieSecureOption = true so that it will always be send via HTTPS.
How can I protect it from XSS attack?
A "non-HttpOnly cookie" isn't a vulnerability in itself.
An "HttpOnly cookie" mitigates the risk of an XSS attack. That is, any attacker injected scripts into your website will not be able to grab the value of this cookie, thus protecting the session.
If your application requires the use of the cookie value to add as a header, then you cannot mark this cookie as "HttpOnly". You can change the request handler to look for the value in the cookie rather than in the header (so you can set the flag), however this may put your site at risk of CSRF. The most secure approach is for your handler to check authorisation via a "HttpOnly" cookie, and to use another token value in a header ("non-HttpOnly") to check for CSRF. If these values are different, e.g. in the encrypted token pattern or the synchronizer token pattern, then there isn't much value in attacker in only retrieving the one value via XSS because they can't use it to authorise requests. Note that any XSS vulnerability is usually a bigger problem than a CSRF vulnerability, because the attacker could always use their XSS attack in order to submit requests directly from your site, however it is a much harder attack to accomplish. At least with "HttpOnly" they cannot grab the auth cookies from your site in order to remotely login.
The other cookie flag you mentioned is the secure flag. This will limit the cookie scope to https connections only, and is recommended if you are using https (which is also recommended). This does not affect whether JavaScript can access the value though.
If you do use a "non-HttpOnly cookie" then you can still mitigate the threat of XSS as follows.
Move all script code into external js files and set a Content Security Policy to prevent any inline scripts from executing.
Make sure you are correctly encoding all user input when output (e.g. < becomes < in HTML) and run a web security scanner against your application.
If you do not have HTTPOnly flagged, your users are still more vulnerable to XSS than they otherwise would be, as the cookie can still be accessed from JavaScript. From your description, you should not need access to the variable from JavaScript, simply access the cookie from the server side (which is still possible with HTTPOnly flagged, cookies are sent with every request including AJAX calls) to retrieve authentication information. The Secure flag and HTTPOnly flag defend against completely different attacks.
There is a hybrid way of doing this. I say hybrid because it involves half of what your doing and a mix of what bksi mentioned in a comment.
Since I do not know your full scenario this answer assumes you are just looking for a way to authenticate the user before allowing them to make changes or start a process server side; login, viewing an account page, and so on. You should never rely solely on httpOnly = false I would recommend using it with what is below.
A Solid Solution
Set a normal cookie when a user logs in successfully, this does not need to be sent over HTTPS although it would be nice. This cookie should be a randomly generated token for their session. I usually hash (md5 encrypt in PHP) their user id (assuming you use a database) and a time stamp of when they logged in. This insures the token is unique.
Now that you have a token saved on their local machine as a cookie also make sure to save this token in a PHP session which is server side. Now any time they visit a page or an AJAX request is sent you can compare the local cookie to the PHP session value server side. This is the fastest way you can authenticate a user interacting with your server. If the values match they are legitimate.
Now this is not entirely secure. The local cookie can always be edited which is something we usually don't care to much about because this will only harm the user by invalidating their session. On the flip side a crafty hacker could alter the PHP sessions and that could invalidate other users because their session was erased or hijacked. A hacker would have to get a legitimate session token and make a cookie to match.
The Better Solution(s)
1) On the server side you could use a database instead of PHP sessions. The process remains the same but now you need to do a bit more work of keeping the sessions table in your database up to date. Usually this is done by saving the token with a time stamp and updating this time stamp every time the token is checked. If the token is checked and the last time stamp is really old (you decide how long that is) you can un-authenticate the user by destroying their local cookie and having them sign in again. This is more resource intensive though and can slow down sites with large traffic loads.
2) Use a form of double authentication. This would be using PHP session 90% of the time for simple things but when an extremely important process comes up, say updating personal information or providing credit card information, check with the database as well. This would require two different cookies to be saved on the users machine. One if for checking PHP session for authentication and the second is for checking the database. This scenario would be really hard for a hacker to break through to the more important things because they would need to figure out both tokens and the database one is not easy to steal.
Final Thoughts
This is a fairly secure answer but you should still implement extra security precautions. It seems you are misunderstanding how cookies work in general; your recent comment sounds like your using cookies and ajax backwards but maybe I'm misunderstanding. Here is how I do it:
[User]-> Tries logging in to website with a login form
[Server]-> Checks this information against the database Pass, log 'em in.
[Server]-> Generate and set a random token as a cookie
I use PHP here and usually store this cookie with a name like sessionToken. This cookie immediately exists now on the users computer and we, the server, always have access to it server side; we can call it up any time. This is not really secure though because people could copy the cookie without the person knowing/ steal it as we send it to them. I'll deal with that in a minute.
[Server]-> Create a PHP session (session id: abc123) server side that has this same token.
This is step one in security. PHP sessions are not as easy to steal or hack. So even if someone steals our users token cookie when they try to use it on their computer it will fail. Here is a vaild user:
[User]-> (PHP session id: abc123) Tries to access secured page or content. PHP session is called up and is checked against the cookie token. If they equal each other this attempt passes.
Here the user has a session on the server they don't know about that recognizes who they are and can be accessed only by the server; usually. It is here where your AJAX request come into play. Every time the user tries to do something that you want to see if they are even allowed to do, send a request via AJAX to a PHP script that authenticates the user. All it does is send back PASS or FAIL. Then you can use AJAX or Javascript to do whatever you need. Here is a hacker exmaple:
[Hacker]-> Steals a cookie from a user over a cafe's wifi.
[Hacker]-> Tries to access the website you are on with it.
[Server]-> (PHP session id: ???) Doesn't have one, destroy the cookie and ask this user (the hacker) to login again.
This is as much information and help I can give. Your latest comments are starting to sound like new questions you should post on Stackoverflow.

Categories