JavaScript - Cookies Explained 
by The Sandman
19th March 1999 
here
 
Title
 
Understanding & Using Cookies
Written by The Sandman 
 
Rating
( X )Beginner   ( )Intermediate   ( )Advanced   ( )Expert 
 
Introduction
Greetings Crackers,  

The Cookie, which is a part of Netscape and Internet Explorer, is a packet of information that has been sent to you via your browser as you visit web servers and web pages. Some Cookies have a life span of just one session of you using your browser and others can persist for months.  Those Cookies that need to exist longer than one session will utilize a special file on your hard disk called cookies.txt. 

Contrary to what you may have heard about Cookies, they can be very useful in helping you to monitor for instance, visitors to your web pages and informing them of when your web page(s) have been updated since their last visit. Many of my web pages utilize Cookies to inform it's visitors when it has been updated and is fully automatic. The script takes care of when to display and not display the message "This page has been updated since your last visit!".  You will no doubt have seen web pages that can remember your name and tell you how many times you have visited that particular web page as you surf the Internet. It can all be done in JavaScript. 

For many people, the idea of working with Cookies sounds mysterious and daunting, where in reality it's actually very easy once you have grasped the general idea behind them..  
 

Tools
Required
    
1 Pen.    
1 sheet of A4 paper.    
An open mind.    
 
About this
tutorial
  
In this tutorial I will try and show you how you how we can use Cookies in our JavaScript and hopefully dispel any doubts you may have about using them in your own web pages.  For those of you looking for some unusual ideas you might want to try out in your next js-crackme, then this may be of interest to you..Read on.. 
 
T
H
E
 
E
S
S
A
Y
  
In order to use Cookies in JavaScript you need two functions to be able to Write to, Read from a Cookie. Deleting a cookie is handled automatically by the User's Browser so therefore we don't really need to be concerned about deleting our cookies. However, we can delete cookies if we wish and just as easily as creating them. More on this later.  

Before you can use a Cookie you need to create one, then, and only then can you read  the data you have saved to your Cookie.   
   
In order to create our cookie, we need three items of information, they being:- 

1. Name of our cookie. 
2. The Data we want to save to our cookie. 
3. Number of seconds our cookie will exist for. 

Huh?. Seconds!. Yep, keep reading on, all will be explained. 

Our first function therefore is to create our cookie, which we will call CreateCookie. 

  

 Create A Single Cookie Function
  
function CreateCookie (name, value, expires) {  
     if (!expires) expires = new Date();  
         document.cookie = name + "=" + escape (value) +     <-- save cookie value  
         "; expires=" + expires.toGMTString() +  "; path=/";         <-- set expiration date  
         }                                                                                              <-- and universal path  
 
  
Bet you didn't think this function would be so small!.  At this point don't worry about how it functions, the important thing for you right now is how we can use this function to save our information. 

Using the above function, here's how we can create a cookie called _sandman and save in this cookie the name the seeker and make our cookie last for 1 month before it is automatically deleted by the User's Browser. 

First, we need to create a variable that will hold today's date, this is important because we need to then add 1 month to this date in order to give our cookie 1 month of life from the date we set it. 

             var expiredate = new Date ();   <---Variable expiredate = Current date 

Next, we need to 'add' 1 month to this date, this you will remember will be the life span of our cookie. 

             expiredate.setTime (expiredate.getTime() + (1000 * 60 * 60 * 24 * 31));  

The formula for calculating the life span of our cookie is:- 

1,000 milliseconds X by 60 seconds     = 60,000 milliseconds per minute 
60,000 milliseconds X by 60 minutes    = 360,00000 milliseconds per hour 
360,00000 milliseconds X by 24 hours  = 864,00000 milliseconds per day 
864,00000 milliseconds X by 31 days   = 26784,00000 milliseconds for 31 days 

So our cookie will last 26784,00000 milliseconds starting from the time it was created. 

Once we have our expiredate variable correctly set, all we need to do is call our CreateCookie function with the information we have already decided on. 

             CreateCookie ("_Sandman", "the seeker", expiredate);  

That's it! Our cookie will be created as soon as this function is executed!. 

Now all we would need is a function that can read our cookies and retrieve the information contained within it.  We can do this quite easily using the following function:- 
 

 Read A Single Cookie Function
 function ReadCookie (name) {  
         var dcookie = document.cookie;   
         var cname = name + "=";  
         var clen = dcookie.length;  
         var cbegin = 0;  
             while (cbegin < clen) {  
             var vbegin = cbegin + cname.length;  
                 if (dcookie.substring(cbegin, vbegin) == cname) {   
                 var vend = dcookie.indexOf (";", vbegin);  
                     if (vend == -1) vend = clen;  
                 return unescape(dcookie.substring(vbegin, vend));  
                 }  
             cbegin = dcookie.indexOf(" ", cbegin) + 1;  
                 if (cbegin == 0) break;  
             }  
         return null;  
         }  
 
  
  
This function searches through the Cookie until it finds the Cookie name that you  
specify. Then it finds the value of the Cookie and returns it. To get the Cookie named "_sandman" that was saved with the value "the seeker", you would call this function like this:- 

         document.write(ReadCookie("_sandman"));  

This would print out the value of the "_sandman" cookie, which was created with the value "the seeker". If you had more than one cookie in use then simple call GetCookie with the name of the cookie you want to read from. 

Finally, if you ever need to delete your cookie then the following function will do just this:- 
 
 

 Delete A Single Cookie Function
  
function DeleteCookie (name) {  
         var expireNow = new Date();  
         document.cookie = name + "=" +  
         "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";  
         }  
 
  

Notice that we pass the name of our cookie and the function then sets our cookie expire date to Jan 01 00:00:01 which in effects means our cookie has now expired and should be deleted by the User's browser. 

One important item of information you need to be aware of.  As a security measure to prevent misuse of cookies, you cannot Read/Set or Delete anyone else's cookies other than those created in YOUR Domain. 

  
 While the above three routines do an excellent job of creating and storing information in cookies they are limited to handling one cookie at a time. Cookies are so useful that we may find ourselves using more than one cookie at a time, so how can we use multiple cookies at the same time?. 

Our old friend 'Arrays' has the answer.. While we can't create cookies containing arrays we can however simulate this quite easily and to all intentional purposes, this is just as good as the real thing.  The idea is that we create multiple cookies using a simple FOR loop and have our GetCookie function read all these cookies  into an Array, which we can then access just as though we were using an ordinary array itself.  

While this means our new, updated functions will be a more powerful and therefore more useful to us  than those shown above, they will never-the-less be just as easily to use.  If your still unsure how Array's operate, then I recommend that you read up on Arrays either from your JavaScript books or, you can read the Example 3 (Arrays)  I wrote that attempts to explain how Arrays work. 
 
 

  

 Create Multiple Cookies Function
  
function CreateCookieArray(name){  
         this.length = setCookieArray.arguments.length - 1;  
             for (var i = 0; i < this.length; i++) {  
             data = setCookieArray.arguments[i + 1]  
             setCookie (name + i, data, expiredate);  
             }   
         }  
 
  
If you compare this function against the create 'single' Cookie function then you'll quickly notice that this.length is used for extracting the number of data items we pass onto this function.  The value from this.length-1 is then used in a FOR loop to create a cookie for each of the data items we want to store. The cookie expire date is obtained by reading the last non-string value passed onto this function using: data = setCookieArray.arguments[i + 1] 
 

If this still doesn't make sense to you then perhaps this example might. 

Example:- 

Suppose we want to save the following information:- 

"Cookie1" 
"Cookie2" 
"Cookie3" 
"Cookie4" 
"Cookie5" 
"Cookie6" 
"Cookie7"  

And our cookies are to last 62 days (2 Months)  

Then we might use the  following lines of code to  call our new, more powerful CreateCookieArray function:-  

       var expdate = new Date();   
       expiredate.setTime (expdate.getTime() +  (24 * 60 * 60 * 1000 * 62));    

         var testArray = new setCookieArray(   
         "_sandman", <-- name of the Cookie array   
         "Cookie1",     <-- data for first element of our Cookie array   
         "Cookie2",     <-- data for second element of our Cookie array.   
         "Cookie3",     <-- data for third element of our Cookie array.   
         "Cookie4",     <-- data for fourth element of our Cookie array.   
         "Cookie5"      <-- data for fifth element of our Cookie array.   
         "Cookie6"     <-- data for sixth element of our Cookie array.   
         "Cookie7");   <-- data for seventh element of our Cookie array.   

variable expiredate is now a global variable, rather than one that is created inside our function, as was the case in the 'single' create cookie function..   

Can you see that inside our new CreateCookieArray(name) that it is able to create multiple cookies simple by adding a number, corresponding to the FOR loop at the end of our original Cookie name!.  Here's the line that performs this task:-  

                 setCookie (name + i, data, expiredate);   

Here's what our example of multiple cookies will look like:-  

           Cookie Name: _sandman0       = "Cookie1"  
           Cookie Name: _sandman1       = "Cookie2"  
           Cookie Name: _sandman2       = "Cookie3"  
           Cookie Name: _sandman3       = "Cookie4"  
           Cookie Name: _sandman4       = "Cookie5"  
           Cookie Name: _sandman5       = "Cookie6"  
           Cookie Name: _sandman6       = "Cookie7"  

Pretty impressive stuff!  Well, maybe not yet perhaps, but do read on, the possibilities of using cookies can be of great importance to reverser's who are looking for new ways to manage their data and privacy.  

To access the data that is stored in the "_sandman" Cookie array, we would need a modified the Read (single) Cookie function so that now handles multiple cookies and inserts them into arrays for us.  Like this one:-  
  
  

 Read Multiple Cookies Function
   
function ReadCookieArray(name){  
         var i = 0;  
             while (getCookie(name + i) != null) {  
             this[i + 1] = getCookie(name + i);  
             i++; this.length = i;   
             }  
         }  
 
   
        
To access the data that is stored in the "_sandman" Cookie array, simply make one call to ReadCookieArray() like this:  
   
  var CookieArray = new ReadCookieArray("_sandman"); 
  
After loading the "_sandman" Cookie array using ReadCookieArray(), treat the array like you would any other array (but starting at 1, not 0).  This is because array(0) contains the name of the array and not the first item of data.  

To display out the first element, or piece of data, in the array, use this:  
  
    document.write (CookieArray[1]);   

Which willl display "Cookie0" or document.write (CookieArray[5]); which will display "Cookie6".  
   
Now how might we use cookies in our JavaScript protected web pages..  Well, for starters you can record the number of failed attempts someone makes at accessing your protected web page and then create a cookie that then tell your web page to ignore any further attempts from that user for a set period of time.  If you have created a JS-Crackme then it's quite easy to store the User's name/handle and date and any other information you want storing in a cookie on the User's hard disk so that when they visit your 'Congratulation' page you can then read this information and display this information automatically without you having to keep updating this information yourself.  Can you imagin the look on their faces when they see their name/handle already written on the 'Congratulation' page when they bust your crackme!. 

Another use for Cookies might be to use a modified 'Devious Visitor Monitor that automatically emails you with all kinds of information, such as.  When and which of your web pages your visitor has visited, how many times they have visited these pages and with what browser. These are just a few examples you can use cookies to your advantage, there are many more just waiting for you to discover them..:)
 

Final Notes
Original format of this tut by (c) flipper (upg) 12/30/97 All rights reversed. 
way out
 
 

Page  by The Sandman  
Page Created: 6th March 1999