How can I secure my website from injections (Cookie editing) - javascript

I'm using cookies in my Java EE application (jQuery on the client) and while taking security as a key point, I came to know that one can read the cookies and edit them by reading article's. I'm really want to make application out of these attacks.
I read How to prevent Javascript injection attacks within user-generated HTML on SO and didn't find a solution to make my cookies secure.

There are several flags you can set for cookie to mitigate the security risk.
The secure flag. It mandates that cookie should only be sent through https. This is important, even when your site is using https. Why? Let's say a bank site forces end user to use https. The user connects to the bank site through https, login successfully. The bank site sends the cookie back to the user browser through https. Assuming a hacker can sniff the network and see all the cleartext communcation between the end user and the bank site. Obviously for now, the hacker cannot see anything, as the cookie is transmitted through secure channel. Here is what the hacker can do if the HttpOnly flag is not set
a) The hacker creates a site www.maliciouscode.com.
b) He sends an email to the end user with the link, luring the end user to the site.
c) The user takes the bait, connecting to http://www.maliciouscode.com site through another browser tab.
d) The malicious site redirects the user browser to the bank site through http.
e) The user browser sends the cookie through HTTP to the bank site.
f) The hacker intercepts the cookie since it is sent as cleartext, places it in his own browser and login as the user
The HttpOnly flag. The name is misleading. It is not the opposite of the secure flag. It means the cookie should only be used by browser through http (and https) protocol only, but not used by other means such as JavaScript. If a browser that supports HttpOnly detects a cookie containing the HttpOnly flag, and client side script code attempts to read the cookie, the browser returns an empty string as the result. This is to prevent the XSS attack.

Unless there is some other vulnerability in your site (or the user's system), there is no way for a third party to modify cookies.
Therefore you can treat them exactly the same as you would any other data that comes from the client (except that you don't need to worry about cookie data being faked with a CSRF attack). That is to say: Trust the cookie as much as you trust the user.

Cookies are not secure. Forget protecting them.
You should protect your server by having all communication on HTTPS. HTTPS protects your cookies more than anything else (it cannot protect against Session Hijacking though).
Do not store any sensitive information in the cookie other than the session id.
Make sure your cookies are configured as HTTP ONLY. If not, the session id will be sent as a part of the query string and can be intercepted (and cached) by any one.
Regenerate your session id on major events like user login, password change, etc.

Related

How does httpOnly prevent from malicious package to steal the content in it?

If for example, an installed third party package issues an HTTP request to their servers, and by default, any HTTP request leaves with the cookies content in the request headers, doesn't it make the content to be exposed to the server who receives the request? I don't get how httpOnly prevents from the access token to be revealed...
HTTP requests carry with it only cookies that are applicable to the domain being requested, not all of the browser's cookies. If you have a browser with cookies for bank.com, shop.com, and evil-site.com, a request to evil-site.com would only send evil-site.com cookies with the request. Not so useful.
Now say a malicious script has infected bank.com and has placed itself on a page in that domain. Now that script is running in the context of bank.com and the currently viewing user. It can now read bank.com's non-HttpOnly cookies using document.cookie and send them to evil-site.com with a simple script. This means that if you logged in to bank.com and viewed that infected page, your login cookies can now be stolen.
Marking a cookie as HttpOnly tells the browser not to expose the cookie to JavaScript, i.e. any script, legit or not, cannot read the cookie's value from document.cookie. So if bank.com made their login cookie HttpOnly, this cookie would not be readable by any script on the page. However, the cookie is still passed back and forth between browser and bank.com in requests and responses while the cookies are present and valid.
HttpOnly is just one of the many measures to prevent cookie theft and should be complemented by other security features. Secure makes sure the cookie is only ever sent through HTTPS connections. SameSite defines when the cookie is allowed to cross sites. HTTPS connections prevent reading the request over the network.
The httpOnly attribute purpose is to hide the cookie from the JavaScript context.
To observe it, you can type document.cookie in the console of any web page, and you'll notice that the result contains all of the cookies that are not httpOnly and from the current domain. You can verify it with the Application tab of the DevTools.
That means if an attacker somehow manages to execute malicious code on a user's web page (e.g. by exploiting a script injection vulnerability), he may be able to send requests on behalf of that user but he should not be able to retrieve the cookie's value.

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.

Risk of using a persitent XSRF-TOKEN cookie in Angular

This is related to this question CSRF Protection for Refresh Token Cookie in SPA
I want to use the recommended XSRF-TOKEN cookie mechanism to protect another HttpOnly cookie. For this scenario I need to make the XSRF-TOKEN cookie persitent, because it has to be available at app start up after a reload. The default implementation in Angular $http looks up in session cookies only.
What are risks if I make the cookie persitent and manually set the X-XSRF-TOKEN HTTP header?
What are risks if I make the cookie persistent and manually set the
X-XSRF-TOKEN HTTP header?
The risk is that an attacker could eventually brute force the token value.
The recommendation is to have a new CSRF token per session. If you make this persistent then a malicious site could keep trying to submit a cross site request including a different token value each time. Eventually it will try every combination of token character and succeed in making the request.
Practically however, the user would have to visit the malicious website at the same time and every time. This can happen with browsers that remember the user's open tabs and automatically load each time.
You could also build in some brute force protection. For example, after 10 requests made with an invalid CSRF token you could abort the session and then inform the user that they have been logged out. This will mitigate the brute force attack, however this converts the attack into a Denial of Service attack as the malicious website will be successful at logging out the user. Therefore you should follow this up by contacting the user and informing them that a site that they are visiting is attempting to compromise them (you can check your server logs to determine the referer and origin headers).
If you choose to use Persistent cookies, you will be still vulnerable for CSRF attacks since the browser will send these cookies with the requests
For angularjs, the following is what i'm using in my SPA app; a CSRF token is generated by the backend server and passed as a header only in the request for the index.html file. from that point angular is configured to add the token in the header + in a session cookie - for each internal $http.post/delete/put/... requests
app.config(['$httpProvider', function ($httpProvider)
{
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
Test it
use this small snippet to manually test your api:
<!DOCTYPE html>
<html>
<head>
<script>
function csrf(id)
{
document.getElementById("csrf-form-" + id).submit();
}
</script>
</head>
<body>
<form method="POST" action="http://127.0.0.1:8080/api/test" enctype="text/plain" target="_blank" id="csrf-form-1">
<input name='{"protected":false, "ignore_me":"' value='test"}'type='hidden'>
</form>
<button onclick="csrf(1)"}>CSRF!</button>
</body>
</html>
A CSRF attack works on an unprotected site to which the user is logged in. Consider site S that uses session cookie C (and nothing else) to identify a user's session. This means that the browser will send C on every request to S. As the presence of the session cookie is all that's required to confirm a session, the user will be logged in when they access S. This is great. Exactly what we want.
Except...
Let's assume that S can is a website that can email cash via an URL such as https://S/email-cash?email=recipient#examplecom. An evil website E can have embed the link https://S/email-cash?email=ATTACKER#examplecom in one of its pages. Now, when the user is browsing site E while logged into site S and they click on this link, they'll end up emailing the attacker money. Even worse, this link can be executed in JavaScript behind the scenes so the user only needs to visit site E. Very bad.
The problem happens because every request accompanied by a valid session ID cookie C is treated as a valid request. The solution is to require the browser to send some piece of ID that it could only have gotten very recently from site S. This is the CSRF token. There's no way for the browser to get it unless it is given it by S and S will only give it when it's serving a page, not for a cross-site attack.
Now if you start storing the CSRF token as a persistent cookie, it defeats the entire purpose because it becomes something that the browser can send on a cross-site attack.

Secure way to communicate OAuth token to javascript client

I am designing a multi-platform application at the moment (clients would include internally developed mobile apps, and an AJAX heavy javascript client initially) centred around a REST API. Since in the future the API may be open to third parties, I am looking at using OAuth 2.0 for authentication and authorization with the API.
I am trying to get my head around some of the security issues with this arrangement, particularly with regard to the javascript client. I don't want this client to behave like a third party client might, with a whole bunch of redirects and popups and stuff, which is what most OAuth documentation seems to focus on. Since it will be delivered from my own domain, I am thinking that the server side of the webapp can be the actual client, and store the client secrets and refresh tokens, while the javascript retrieves new auth tokens from the server as it needs them.
To put it in step by step form:
The user logs in using non-ajax html form, generating auth and refresh tokens which are stored server side. This sets a HTTP-only login session cookie.
The javascript client code is sent to the user's browser after login.
The javascript client makes a request to a resource that is part of its own application (not part of REST api) to retrieve the token. The session cookie ensures that the client is genuine, and the referer will also be checked. Auth token is returned.
The javascript client validates the token with the REST API.
The client can now use the token to make requests against the REST API until it expires.
If the auth token expires or the page is closed and re-opened, the javascript client can request a new token. The server side of the webapp takes care of refreshing the token and sends the new token, as long as the login session cookie is still valid.
Does this make sense, or would it leave massive holes in the system? In particular, is it insane to have a resource on the web that hands out authentication tokens based on a cookie being set?
Just make sure that any communication to browser is HTTPS, so that no one in the middle can steal your tokens. And set the "secure" flag on your auth cookies.
Most browser authorization schemes nowadays boil down to a session token that's passed in a cookie. The OAuth 2 scheme is a couple steps ahead because a) the tokens (can be) dumb tokens with no dangerous user info inside, and b) they expire.
(Just to put that comment in context: one time I popped open a session token from a site and discovered my home address and phone number was in there. Ack!)
I've seen code that does HMAC signing of requests inside the brower javascript, but it came with a huge disclaimer: don't use this in production. A signing scheme requires the client (javascript) to know a "secret" string, but the browser/javascript is so insecure that it amounts to handing your secret strings to the world.
But if you keep all your commuinication over HTTPS, then you're really just putting an OAuth twist on the familiar scheme of passing session tokens as cookies.

Categories