JavaScript Cookies
JavaScript Cookies
1
Overview
Cookies
What, why
In JavaScript
2
Typical Web Application
Design
Runs on a Web server or application server
Takes input from Web users (via Web server)
Interacts with back-end databases and third
parties
Prepares and outputs results for users (via
Web server)
Dynamically generated HTML pages
Contain content from many different sources,
often including regular users Blogs, social
networks, photo-sharing websites…
3
HTTP and Cookies
HTTP (Hypertext Transfer Protocol) is a stateless request/response
protocol. Each request is independent of previous requests
Advantage being stateless: servers do not need to retain
information about users between requests.
Web applications are often stateful. So the Client has to
remember things that the Server needs to know.
Cookie is a common way for maintaining states.
A cookie is a piece of information that contains the state (or
session ID) of
a client. A cookie consists of one or more name-value pairs.
Server: uses Set-Cookie parameters to ask client’s browser to
store a cookie.
Client: stores the cookie and sends the unchanged cookie in
EVERY request to the same server.
4
Cookies
5
Web Cookies (or HTTP
Cookies)
Browsers allow the storage of
limited data on the client machine
Can be created by the server
Or by a client-side scripts
Sent back to the server that left it
Or ready by a client-side script
6
What’s the Need Behind
Cookies?
HTTP is a stateless protocol
Client requests a page, and server sends it
Client later requests a 2nd page; it is sent
But HTTP doesn’t give a way for the
server to know it’s from the same user
Being stateless is simpler for HTTP
But limiting to applications
7
Cookies in Action
The scenario is:
Browser about to send a request for a URL
But it first looks for cookies linked to that
URL that are stored on client machine
If found, the cookie is sent to the server with
the HTTP request for the URL
Server uses cookie data
E.g. associate this current visit with a previous visit
Server may then set updated cookie on
client machine
E.g. to be sent back with the next request
8
Purposes of Cookies
Authentication
User-id, password stored on client
Sent on next visit. No login required!
Personalization
Remember user preference for fonts, colors,
skin, site-options, etc.
Shopping carts
Tracking
How is our site used?
Multi-site tracking by companies looking for
usage profiles etc.
9
Cookie FAQs and Myths
They don’t transmit viruses.
Can’t erase data on client machine.
Can’t read personal info on client
machine.
Not used for spamming, pop-ups.
10
What’s in a Cookie?
It’s just text data as follows:
NAME=VALUE
Name value pairs
expires=<date> (optional)
Without a date, deleted when browser
closed
path=<path> (optional)
domain=<domain> (optional)
secure (optional)
11
Create a Cookie with
JavaScript
document.cookie = "username=J
ohn Doe";
document.cookie = "username=J
ohn Doe; expires=Thu, 18 Dec
2013 12:00:00 UTC";
12
Read a Cookie with
JavaScript
let x = document.cookie;
document.cookie will return all
cookies in one string much like:
cookie1=value; cookie2=value;
cookie3=value;
13
Delete a Cookie with
JavaScript
Deleting a cookie is very simple.
You don't have to specify a cookie
value when you delete a cookie.
Just set the expires parameter to a
past date:
document.cookie = "username=;
expires=Thu, 01 Jan 1970
00:00:00 UTC; path=/;";
14
A Function to Set a Cookie
function setCookie(cname, cvalue, exdays)
{
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
15
A Function to Get a Cookie
function getCookie(cname) {
let name = cname + "=";
let decodedCookie
=decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
16
A Function to Check a
Cookie
17
Browser Control of Cookies
At least 20 cookies per domain
Newer browsers store more
But most sites use just one, and have
an ID value to reference info stored
on server
Total size limit on all cookies (e.g.
4K for IE)
18
Browser Control of Cookies
(2)
User can control how they’re handled:
Don’t let server write them to client PC
Asks permission (perhaps with a white-list)
Always accept them
Perhaps except for those on a black-list
User can view and manage cookies
E.g. Firefox’s Preferences->Privacy->Show
Cookies
19
Try This at Home!
In your browser’s address field, type:
javascript:alert("Cookies:
"+document.cookie)
21
JavaScript on the Client-
Side
Can just do this (on one line):
document.cookie=“user=tom;domain=
cs.uva.edu;path=/cs453; secure;”
we have three functions for your .js
library
SetCookie(…), GetCookie(name),
DeleteCookie(…)
22
More Reading
Wikipedia has a nice article
Note issues on laws governing
cookies!
Why? The White House, the NSA and
the have used cookies to track users
Various websites
Check your browser for what it
does and what it can tell you
23
Cookie Example
The domain and path tell the browser
that the cookie has to be sent back to
the server when requesting URLs of a
given domain and path.
Cookies are identified by the
combination of their name, domain,
and path, as opposed to only their
name.
Cookie values are changed only if a
new value is given for the same name,
domain, and path
24
Cookie Uses: Session
Management
Session Management: stores user related data across multiple accesses.
Originally, web developers put shopping cart content directly in a cookie.
This may make the cookie too big: cookies are intended to be used only for
infrequent storage of a small amount of data on the user’s machine.
25
Cookie Uses:
Authentication and
Personalization
Authentication: enable users to log in once but request multiple pages
─ Allowing users to log in to a website is a frequent use of cookies. Typically the web
server will first send a cookie containing a unique session identifier. Users then submit
their credentials and the web application authenticates the session and allows the user
access to services.
Personalization: Cookies may be used to remember the information about the user who
has visited a website in order to show relevant content in the future. Many websites use
cookies for personalization based on users' preferences. Users select their preferences
by entering them in a web form and submitting the form to the server. The server
encodes the preferences in a cookie and sends the cookie back to the browser. This
way, every time the user accesses a page, the browser sends to the server the cookie
where the preferences are stored, and then the server personalizes the page according
to the user preferences.
─ For example, the Wikipedia website allows authenticated users to choose the webpage
skin
they like best; the Google search engine allows users (even non-registered ones) to decide
how many search results per page they want to see.
26
Cookie Uses: Tracking
within One Site
1. If the user requests a page of the site, but the request contains no
cookie, the server presumes that this is the first page visited by the user;
the server creates a cookie back to the browser together with the
requested page.
2. From this point on, the cookie will be automatically sent by the browser
to the server every time a new page from the site is requested; the server
sends the page as usual, but also stores the URL of the requested page,
the date/time of the request, and the cookie in a log file.
3. By looking at the log file, it is then possible to find out which pages the
user has visited and in what sequence.
For example, if the log contains some requests done using the cookie
id=abc, it can be determined that these requests all come from the same
user. The URL and date/time stored with the cookie allows for finding out
which pages the user has visited, and at what time
27
Cookie Uses: Tracking
across Multiple Sites
A web page often contains objects from other sites.
When browser retrieves these objects from these sites that users do not know, these sites
may set cookies. These cookies are called third-party cookies. The cookies set by the
site in user’s browser address bar is called first-party cookies.
Modern browsers, such as Mozilla Firefox, Internet Explorer and Opera, by default, allow third-
party cookies, although users can change the settings to block them.
There is no inherent security risk of third-party cookies (they do not harm the user's
computer) and they make lots of functionality of the web possible, however some internet
users disable them because they can be used to track a user browsing from one website to
another. This tracking is most often done by on-line advertising companies to assist in
targeting advertisements.
For example: Suppose a user visits www.domain1.com and an advertiser sets a cookie in the
user's browser, and then the user later visits www.domain2.com. If the same company
advertises on both sites, the advertiser knows that this particular user who is now viewing
www.domain2.com also viewed www.domain1.com in the past and may avoid repeating
advertisements.
28
Cookie Privacy Concerns
and Misconceptions
Jupiter Research published the results of a survey, according to which some
people believed some of the following false claims:
─ Cookies are like viruses in that they can infect the user's hard disks
─ Cookies generate pop-ups
─ Cookies are used for spamming
─ Cookies are used only for advertising
The possibility of building a profile of users is considered by some a potential
privacy threat, especially when tracking is done across multiple domains using
third-party cookies. For this reason, some countries have legislation about
cookies.
Third-party cookies can be blocked by most browsers to increase
privacy and reduce tracking by advertising and tracking companies without
negatively affecting the user's Web experience.
29
Secure Cookie Scheme -
Requirements
1.Authentication
─ Login phase
2.Confidentiality
─ Need to toggle the “secure” flag. Then this cookie is only sent
over SSL.
3.Integrity
─ Need to detect whether a cookie is compromised.
4.Anti-replay
─ Detect replay of stolen cookies.
30
Insecure Cookies Schemes
Example of a silly mistake:
31
Cross Site Scripting -
Overview
Attacker causes a legitimate web server to send user
executable content (Javascript, Flash ActiveScript) of
attacker’s choosing.
Same- Origin Policy ─ Browser only allows Javascript from site
X to access cookies and other data from site X.
─ Key idea of XSS: Attacker needs to make attack come from
site X. Victim’s browser loads code from site X and runs it.
Vulnerable Server Program ─ Any program that returns user
input without filtering out dangerous code.
XSS used to obtain cookies used as authenticators for ─ Bank
site (transfer money to attacker) ─ Shopping site (buy goods
for attacker) ─ E-mail
32
Cross Site Scripting –
Sequence Diagram
33
Reflected XSS – Detailed
Flow
Reflected XSS ─ Injected script returned by
one-time message. ─ Requires tricking user to
click on link. ─ Non-persistent. Only works
when user clicks.
34
Stored XSS
Stored XSS ─ Injected script stored in comment, message,
blog, etc. ─ When visitor loads the page, web server
displays the content and visitor’s browser executes the
malicious script.
Many sites try to filter out scripts from user content, but
this is difficult. ─ Requires ability to insert malicious code
into web documents (comments, reviews, etc.) ─
Persistent until message deleted.
Example: auction site that allows buyers to post
questions and sellers to post responses. ─ If an attacker
can post a question containing a script, the attacker could
get a user to bid without intending to or get the seller to
close the auction and accept the attacker’s low bid.
35
XSS Conquences
An attacker can run a script in the wrong security
context
─ Cookies can be read/written
─ Attackers can hijack user accounts. Attacker can do
anything a user can do.
─ Plug-ins and native code can be launched or scripted
with untrusted data
─ User input can be intercepted
─ Complete credential exposure if the site is Passport
enabled
Only one vulnerable page on one Web server in a
domain is required to compromise the entire domain.
36
Why Users Click Malicious
Links?
Phishing email in webmail client
(e.g., Gmail).
Link in DoubleClick banner ad.
Many ways to fool user into
clicking.
37
Email Snare
Example: From: “Example Customer Services”
To: “J Q Customer”
Dear Valued Customer, You have been selected to participate
in our customer survey. Please complete our easy 5 question
survey, and return we will credit $5 to your account.
To access the survey, please log in to your account using your
usual bookmark, and then click on the following
link: https://example.com/%65%72%72...?message%3d...att
%61%63%6b.com...docum%65..%63ookie...
The link contains the correct domain name (unlike phishing).
The URL has been obfuscated. Below is another example: ─
ASCII Usage: http://host/a.php?variable=>
38
Past XSS Attacks
MySpace worm (October 2005) ─ When someone
viewed Samy’s profile:
Set him as friend of viewer.
Incorporated code in viewer’s profile.
Paypal (2006) ─ XSS redirect used to steal money from
Paypal users in a phishing scam.
BBC, CBS (2006) ─ By following XSS link from
securitylab.ru, you could read an apparently valid story
on the BBC or CBS site claiming that Bush appointed a
9-year old as head of the Information Security
department
39
XSS Countermeasures
Validate all input ─ Lack of proper input validation is the single
biggest cause of Web-App compromise
─ Dos
● Do Validate for Length, Range, Format and Type
● Do Validate from all sources: QueryStrings, Cookies, HTML
Controls
─ Don’ts
● Do not rely on Client-side Validation
● Do not rely on ASP.net Request Validation
● Do not use user-supplied file name and path input
● Do not directly echo Web-based user input
Filter output ─ Replace HTML special characters in output
Tagged cookies: Include IP address in cookie and only allow access
to original IP address that cookie was created for.
40
41
42
43
44
45
46
47
48
49
50
51
Style Sheets
Recall: design goal to separate
structure of documents from display
But display matters a lot
CSS: Cascading Style Sheets
For us, with HTML
Brief details here
Web resources: many, including:
http://www.w3schools.com/css/
default.asp
52
Ways to Specify Style
Multiple ways
Put STYLE= attribute on elements
<P STYLE=“font-size: 20pt; color:
#0000ff”> blah blah </P>
Use a STYLE element in your HTML
file
Use an external style-sheet
53
STYLE element in HTML
Think of this as an in-line style-sheet
Assigns style-rules for element types
Defines new style-classes
Groups a set of styles and gives them a name.
They can be applied to HTML elements.
Put in the <HEAD>
<STYLE TYPE=“text/css”>
<!-- style rules and class in here -->
</STYLE>
54
Example
<style type="text/css">
<!--
body { margin-left: 0px; margin-top: 0px;
background: blue; color: white; }
h1 { font-family: Arial, sans-serif;
color: yellow; }
h1:hover { color: red; }
.strong { font-weight: bold; color: red; }
-->
</style>
55
Example
<HTML><HEAD>
<TITLE>CSS Demo 1</TITLE>
<style type="text/css">
<!-- CSS on previous slide goes here -->
</style>
</HEAD>
<BODY>
<H1>A Header</H1>
<P>First paragraph</P>
<P CLASS="strong">Second Paragraph with
<SPAN STYLE="color: white">something that overrides</SPAN>
a style.</P>
</BODY></HTML>
56
Output
57
External Style Sheets
Want a common look and feel?
Write once!
Put CSS statements in a .css file
In your HTML file:
<HEAD>
<TITLE>CSS Demo 2</TITLE>
<LINK REL="stylesheet" TYPE="text/css"
HREF="demo1.css">
</HEAD>
REL means relationship between two files
58
Another Example
The CSS
A { text-decoration: none }
A:hover { text-decoration: underline; color: red;
background-color: #CCFFCC; }
LI EM { color: red; font-weight: bold; }
UL { margin-left: 1cm; }
UL UL { text-decoration: underline; margin-left:
3cm; }
59
HTML for previous CSS
<BODY><H1>Demo 3: More CSS</H1>
Here's <A HREF="http://www.sun.com">a link</A>
to <EM>Sun's site.</EM>
<UL>
<LI> Item one. <EM>Of course!</EM>
<UL>
<LI> SubItem one.
<LI> SubItem two.
</UL>
<LI> Item two.
</UL>
</BODY>
60
Output
61
More, Advanced CSS
Positioning options not normally
possible in HTML
Background images
Element dimensions
Text flow
User style sheets can override
page author’s
Compatibility issues
62
References
W3C
Documentation on various levels of
CSS
And Wikipedia
And many many books
See UVa’s Safari on-line collection
63
Concluding Remarks
the components of DHTML
HTML
JavaScript
CSS
the idea of Cookies
something more about client/server
relationships and web pages
64