Вы находитесь на странице: 1из 52

8Lesson 8:

JavaScript Security
Objectives
By the end of this lesson, you will be able to:

3.3.1: Distinguish between the browser and the operating system in relation to the
elements responsible for security.

3.3.2: Discuss browser security issues relevant to JavaScript, including script


blocking, frame-to-frame URL changing, and document.write behavior differences
among browsers.

3.3.3: Define signed scripts.

3.3.4: Perform client-side browser detection and determine browser compatibility.

3.3.5: Identify common issues and procedures for creating secure JavaScript code.

3.3.6: Define cross-site scripting and the associated security risks.

3.3.7: Define the functions of cookies and manipulate them effectively, including
testing for presence of cookies, clearing cookies, enabling/disabling cookies in the
browser, and deleting cookies from your hard drive.

3.3.8: Assign a cookie using JavaScript.

3.3.9: Use cookies and passwords to restrict entry to a page.

Authorized to be used in American Public University System.


To report abuse, go to www.CIWcertified.com/abuse.

8-2

JavaScript Specialist

Pre-Assessment Questions
1.

Which JavaScript method is used for client-side browser detection?


a.
b.
c.
d.

2.

In one JavaScript-related security vulnerability, an attacker embeds malicious


script into a link that appears to be from a trusted site. Upon clicking the link,
the embedded script is submitted in the client's HTTP request and can execute
on the user's computer, enabling the attacker to steal information. What is the
term for this security issue?
a.
b.
c.
d.

3.

navigator
AppName
BrowserType
UserAgent

Signed script
Cross-site scripting
Client-side browser detection
Frame-to-frame URL changing

What is a cookie?

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-3

Introduction to JavaScript Security Issues


JavaScript is a fairly secure language, although you need to consider the security
problems it may cause. JavaScript is an open scripting language. It is not meant to
replace proper security measures, such as encryption.
JavaScript has some security features, but these are only intended to protect users from
malicious Web sites by enforcing strict limits on the page authors. JavaScript does not
protect data passed between browser and server, nor does it protect the Web site owner,
who can only control his own page in the browser. When used as a client-side language,
JavaScript can be viewed as easily as X/HTML in the browser. Therefore, you should
never use it for collecting or validating user names or passwords.
For true security, you must ensure that your Web pages use SSL/TLS (HTTPS) and that
your server has all the checks in place. You can also implement security lockouts for
brute-force attacks. JavaScript cannot replace these security devices. However, a
JavaScript developer can implement scripting practices that create secure JavaScript
code and reduce the threat of their pages being exploited. JavaScript developers should
also be aware of scripting practices that pose threats to users, so they can avoid using
problematic or malicious script on their sites, and recognize (and avoid) sites that do use
them.
Some misunderstandings about JavaScript's powers result in perceived threats. It is
important to understand what JavaScript cannot do before learning about how you can
use it:

JavaScript cannot open windows that the user is unable to see (based on window
location or size), and it can only close a window that it opened (in most browsers).

JavaScript cannot determine which Web pages a user has open or has visited (unless
the user accepts a signed script that explicitly allows this).

JavaScript cannot set the value attribute of a file input (unless the user accepts a
signed script that explicitly allows this), or upload files without permission.

However, there are several ways in which a determined hacker can manipulate
JavaScript's inherent qualities to generate undesirable results. In relation to security,
JavaScript brings the following issues:

JavaScript is interpreted differently by different browsers and browser versions,


which can cause developers to use deprecated code or workarounds that aid
compatibility but open the code to vulnerabilities.

JavaScript opens users to security risks as well as some widely annoying


functionality, and therefore it is commonly blocked by users.

JavaScript is implemented differently in various browsers, with particular differences


in document.write behavior.

JavaScript programs can include code that causes the browser to malfunction or
lock.

JavaScript can be used in frame-to-frame URL changing, which can open security
risks.

JavaScript can bypass certain security features and take privileges with the user's
browser by using signed scripts.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-4

JavaScript Specialist

JavaScript can be used for cross-site scripting, which is typically malicious.

JavaScript can read and write files on a user's disk drive, particularly in the form of
cookies.

This lesson will discuss these issues, teach you to recognize and avoid unsecure and
unethical scripting practices, explore ways to use cookies safely, and review coding
practices for creating secure scripts.

Browser vs. Operating System


OBJECTIVE
3.3.1: Browser vs.
operating system in
security

It is important to be able to distinguish between the browser and the operating system in
relation to the elements responsible for security. By understanding the roles of the
browser and the operating system, you can better protect your computer from malicious
software.
The operating system allows the computer to interface directly with users. Typical
operating systems include Windows (e.g., XP, 7, Vista, ME), Mac and Linux/UNIX. It
provides an environment for a variety of practical applications such as word
processors, calculators, spreadsheet programs and X/HTML interpreters to run on the
computer.
A Web browser is one of many applications that runs on the operating system. It is an
X/HTML interpreter that enables the user to access and view documents posted on the
World Wide Web. You have used several major browser types in this course, such as
Firefox, Internet Explorer, Google Chrome and Safari.
The browser is one of a few applications that connect your operating system to the
unprotected network that is the Internet. As such, the browser can be considered a
doorway for security problems that can affect your operating system.

Securing operating systems and browsers


The operating system is typically secured using anti-virus software (such as Norton,
McAfee and AVG), which also protects the applications and data on the system. A
browser can be further secured from malware (malicious software) and pop-ups using upto-date versions of the software, as well as pop-up blockers. Many programs, such as
StopZilla and Ad-Aware, specialize in malware detection and pop-up blocking.
Most software vendors also offer updates, fixes and patches that you can download from
their Web sites. Always make sure that you have the latest stable version of the software
and the latest updates to best protect your operating system, browser and other
applications.
Although vendors and developers make many attempts to verify and secure JavaScript, it
is wise for developers to accept the fact that JavaScript is not secure. It can be read, and
a determined and experienced hacker can have JavaScript source code within minutes.
You should keep this in mind as you develop pages for the Web. Always develop code with
usability and functionality in mind, but do your best to protect your users as well.

Browser-Specific Security Issues


Most versions of most browsers have some security holes. As they are discovered, the
vendors release patches and correct the problems in subsequent browser versions.
However, subsequent versions often have new security holes. For every tool, there is some
malicious person out there looking for ways to use it for malicious purposes.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-5

Example issues with older browsers


For example, Netscape Navigator 3.0 allowed savvy developers to create forms that could
capture and use a client's e-mail address. Users would usually have the option to be
warned before this occurs. However, if this warning option was deactivated, JavaScript
could be coded to send a message without a user's knowledge.
Note that although JavaScript helped mask the form and its purpose, mailing the
contents of a form to yourself did not require JavaScript. It did, however, require the use
of the Netscape 3.0-era browser. At the time, the only way to capture and send form data
via e-mail using the Internet Explorer browser was to create a VBScript procedure. No
single solution for mailing form information worked on all browsers.
Another example of malicious use of JavaScript in older browsers related to the Close
button (the "X" at top-right) on a window. The user would see a pop-up alert and be
requested to close it. But when the user clicked the closing X button, the JavaScript
would fire its malicious code. JavaScript can control the X in browser windows, which
pop-ups also include. Through manipulation of the script that created the button and the
alert, the browser thought it had permission to fire the code.

Example issues with recent browsers


Another common example began with older browsers, but variations of it still exist today.
The users sees a pop-up claiming, "Your browser is infected, Click here to repair it," or
some similar message. In truth, the computer is not infected at least not until the user
clicks the link, which launches a virus. These types of viruses can often be triggered by
any keyboard action (such as CTRL+ALT+DELETE), making them very dangerous. You
should use care to simply close and delete the e-mail immediately.
Consider also an example discussed in an earlier lesson. The JavaScript status property
can be used to display a specified string in the status bar at the bottom of the browser
window. The status bar normally displays the URL target when you hover over a link. So
the status property could be used to mask the URL of a malicious site. Some browsers
(such as Internet Explorer) still allow the status property, but others (such as Firefox)
have stopped supporting it because of the security risk. This makes the status property
a prime candidate for deprecation.

Helper application problems


OBJECTIVE
3.3.2: JavaScript
and browser
security issues

If the user has defined helper applications for certain MIME types (which provide file
name extensions to help encode and decode data for e-mail transmission), then a hacker
can use JavaScript to launch the applications. This method is rather crude because it
will also generate an "out of memory" error, which will alert an aware user that something
is wrong. In addition, although the application will be launched, the launching itself is
unlikely to cause damage without help from the user because the anti-virus program will
detect any malicious code.
However, you should understand that determined hackers will use any means at their
disposal. If they can open one of your programs (especially in the background), then they
can manipulate its contents.

helper application
An application
launched
separately from the
browser that helps
the browser render
certain file types,
such as .pdf, .mpeg
and .doc.

Plug-ins (programs that run within the browser, such as the Flash Player) and helper
applications (applications launched separately from the browser, such as Acrobat for
reading PDFs) rely on specified MIME information to define the file formats and
extensions required by various plug-ins or helper applications. MIME types are defined by
two pieces of information: the content type and the subtype. For example, a sound file

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-6

JavaScript Specialist

might have a MIME type of audio/x-wav, wherein "audio" identifies the category or
content type (a sound file) and "x-wav" indicates the subtype (WAV files). The "x" indicates
that this file type is not a MIME standard type. Another MIME type might be
application/msword, which would indicate a Microsoft Word file with a .doc extension.

What users and developers can do


Because all browsers older and newer versions have some security problems, all end
users should be diligent about staying abreast of news from the vendors. If a security
problem is announced, update your software with the patch or the recommended version.
Remember that a more recent browser version will not necessarily be more secure. You
should keep your browser updated to the latest stable version. Also remember to use the
browser's pop-up blocking settings wisely, and always keep your anti-virus software up to
date.
As a developer, you can take the further step of keeping security problems in mind when
you are coding your pages:

Avoid practices known to pose risks to users.

Explain functionality on your site if you think it may concern your users.

Use standards-based code as much as possible; minimize browser-specific code.

Avoid using deprecated code.

Browser Compatibility and Client-Side Detection


OBJECTIVE
3.3.4: Client-side
browser detection

In this course, you have already learned that you can use the JavaScript navigator
object to detect the browser type and version being used to view a Web page. This process
of client-side detection allows you to tailor your Web pages for optimum viewing in
particular browsers, and then serve those tailored pages to the browsers for which they
are meant.
Of course the reason for this necessity is that browsers vary in the way that they
render JavaScript code and even X/HTML. Because the browsers vary, it is
difficult and for some functionality, impossible to create truly cross-browser
compatible Web pages. This course has stressed the fact that every browser
implements JavaScript differently. Internet Explorer implements the JScript flavor,
whereas Mozilla browsers implement true JavaScript. Also, each browser
interprets the flavor standards differently as well. This is the main reason you
should always test your Web pages in as many browsers as possible.

Standards-based browsers
Internet Explorer 6 is perhaps the perfect example of a browser that caused problems for
designers and developers everywhere due to its quirky implementation of standards.
Later versions of this browser are striving to correct this.
Firefox, Mozilla and Netscape browsers (among others) are members of a family of user
agents based on the Gecko layout engine, which was designed to comply with the W3C
standards for HTML, CSS, XML and DOM, plus the ECMA JavaScript standards. It also
includes compatibility features for handling content developed for legacy generations of
browsers. Unlike other browsers, Gecko is truly cross-platform and provides consistent
behavior across the operating systems that support it.
Therefore, to support Gecko browsers, you should create content that follows the Web
standards. Unfortunately, because other browsers do not support the standards as
completely as Gecko, developers must continue to support multiple browsers. Currently,

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-7

however, other browsers are evolving toward better support for standards. There may
even come a day when Web developers can cease browser detection.
In the meantime, you must balance standards-based content with support for various
modern browsers while also providing some measure of support for older browsers.
Browser detection is still essential for this purpose.

Problems with browser detection


However, the practice of browser detection comes with some problems. As you know, the
JavaScript navigator object enables client-side scripts to detect the vendor and version
of browsers. Using the user agent string for detection is actually a server-side practice
that was borrowed by client-side developers. The classic example of this vendor/version
client-side detection strategy can be found in the Ultimate Browser Sniffer script, which
is found on many Web sites and is a common source of detection problems.
Consider that performing all the detection in an example such as the Ultimate Browser
Sniffer requires the use of code forks for many browsers and versions. Attempting to
perform browser detection to this level of detail is impossible to maintain, and developers
are advised against it.
You can explore several classic browser sniffers at Internet.com's WebReference
Browser Sniffer Links page at www.webreference.com/tools/browser/links.html.

Although using browser detection may seem to solve the browser-compatibility problems
of your Web pages, it has some disadvantages, such as:

Misidentifying browsers.

Excluding some browsers.

Excluding unknown or future browsers.

Excluding mobile devices.

But what alternative is there to browser detection for compatibility?

Alternative coding for browser compatibility


There are several approaches you can take to develop your Web pages for browser
compatibility:

Target the standards instead of particular browsers Earlier browsers supported


a technique called DOCTYPE switching, in which you could switch the browser from
"Quirks" mode (buggy implementations from earlier browsers) to Standards mode
(more strict adherence to the standards). You can use a DOCTYPE to invoke
Standards mode in Gecko and Internet Explorer 6. Internet Explorer 8 has a
Compatibility setting (under Tools) that allows older (IE7) programs to run on it. This
strategy gives your pages cross-browser compatibility in browsers that support the
standards, which also provides support for unknown and future browsers.

Develop pages that avoid using vendor- or version-specific features, unless


required Creating standards-compliant pages helps you support the widest
possible range of browsers, as well as decrease your work and maintenance. In
addition, you can provide simpler pages with simpler code and fewer features to
accommodate older browsers.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-8

JavaScript Specialist

Limit the use of detection based on the user agent string Remember that this
type of detection is actually a server-side practice that was borrowed by client-side
developers. Although there are times that you need your pages to cater to specific
browsers (for example, on the intranet for a company that uses a standardized
browser), you can often leave detection on the server side.

Use non-script detection methods whenever possible Also use the <noscript>
tag to provide alternative versions of your pages to users with older browsers,
alternative browsers (such as mobile devices or accessible speech browsers for those
with vision disabilities), or browsers whose users have turned off script rendering.

Provide only code that supports standards-based browsers This gives users a
compelling reason to choose only these browsers. As a Web developer, if you continue
you provide workarounds for non-compliant browsers, users can continue to use
them. But many vendors now make it a point to comply with standards and become
compatible with other browsers. You can make a choice to stand firm in supporting
these standards-based browsers. If all developers did this, their content could be
more dynamic, and their development and maintenance costs could be lower.

Browser detection and security


While developing pages based purely on standards is ideal, in the real world you must
still accommodate a variety of browser types and versions, because it is difficult to
provide every service and function on a modern Web site without scripting. You can
provide simpler versions of pages that are still usable without script, but completely
omitting scripted features deprives your audience of the rich and interactive experience
that they have come to expect from the Web. You need to keep your customers coming
back.
So some level of browser detection continues to be a necessity for Web pages. You can
detect a wide variety of browser information using JavaScript, from a simple browser
name to the specific version, and even the plug-ins installed and the MIME types they
use.
From a security point of view, a detection script can reveal a significant portion of your
browser information. Although this may be useful for determining browser compatibility,
it could also provide a hacker with enough information about your system to stage an
attack. Hackers preparing exploits typically use very sophisticated scripts to find out
about a user's operating system, patch level and anti-virus software (these are called
environmental variables). This information can help hackers find a good match for their
malicious code, increasing their chances for the success of their planned security breach.
In the following lab, you will perform client-side browser detection to check for the
browser's compatibility with your page. Suppose you want to tailor some of your Web site
pages to individual browsers so you can optimize your users' viewing experience. You can
use JavaScript to check for browser compatibility, then direct each user to the
appropriate customized page. But how much information do you need to detect for this
purpose?

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-9

Lab 8-1: Performing client-side browser detection


OBJECTIVE
3.3.4: Client-side
browser detection

In this lab, you will write a script that performs both basic and advanced browser
detection. Most sites in the present time will check the type of browser the client is using
first, and then redirect the user to the pages that have been optimized for the browser.
Unfortunately, malicious scripters will specifically look for an exploitable browser (this is
called zero-day vulnerability) and take advantage of it before the virus protection or
browser vendor has a chance to create and distribute a patch.
1.

Editor: Open the file lab8-1.htm. This file provides the shell of a page you will
further develop.

2.

Editor: Find the comments the direct you where to place the JavaScript code. In that
location, enter the following code (provided in the file lab8-1code.htm):
<script type="text/javascript">
mactest=(navigator.userAgent.indexOf("Mac")!=-1) //My browser sniffers
is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1
Netscape=(navigator.appName.indexOf("Netscape") != -1)
msafari=(navigator.userAgent.indexOf("Safari")!= -1)
wsafari=0; if(!mactest&&msafari){wsafari=1;msafari=0}
is_opera = 0; if(window.opera){is_opera=1}
is_ie_mac = 0; is_ie=0;if(document.all){is_ie=1}
if(is_ie&&mactest){is_ie_mac=1}
alert("mactest:"+mactest+", Netscape:"+Netscape+", wsafari:"+wsafari+",
msafari:"+msafari+", is_ie:"+is_ie+", is_ie_mac:"+is_ie_mac+",
is_opera:"+is_opera+", is_chrome:"+is_chrome)
</script>

3.

Editor: Save the file lab8-1.htm.

4.

Browser: Open the file lab8-1.htm. You will see a pop-up window similar to the one
shown in Figure 8-1.

Figure 8-1: Pop-up describing browser type detected

5.

Browser: Notice that this pop-up lists several browser types, and gives a value after
each type. The browser type you are using will be specified by a value of true (or a
Boolean value of 1); all the browser types that were not detected will show values of
false (or Boolean 0). This alert does not provide user-friendly readability, but rather a
raw data string that would be used further in a program. This script identifies the
type of browser you are using, but it does nothing further with this information.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-10

JavaScript Specialist

Many Web sites use the detection information to legitimately enhance your
experience by automatically directing you to pages that are optimized for your
browser.
6.

Editor: Open lab8-1a.htm. Find the comments that direct you where to place the
JavaScript code. In that location, enter the following code (provided in the file lab81a_code.htm) as shown in bold, then save the file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 8-1a</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!-// write out some introductory blurb and begin the table.
document.writeln('<h3>CIW JavaScript Specialist</h3><hr />');
document.writeln('<table width=470 align=center><tr><td><p
class="narrow">' +
'The table below shows the principal properties of your '
+
'browser, the name by which it identifies itself, and ' +
'the plug-ins supported. The final part of the table ' +
'lists all the document types for which a plug-in has ' +
'been defined, together with the name of the plug-in ' +
'that handles each type. Types for which no plug-in is '
+
'available are not shown.<' + '/p><hr /><' +
'/td><' + '/tr><' + '/table>');
document.writeln('<table cellpadding=2 cellspacing=1 border=0 ' +
'width=470 align=center><tr>');
document.writeln('<th width=100 align=left class="small"' +
'bgcolor="#666699">Property<' + '/th>');
document.writeln('<th width=100 align=left class="small"' +
'bgcolor="#666699">Variable<' + '/th>');
document.writeln('<th width=100 align=left class="small"' +
'bgcolor="#666699">Value<' + '/th><' + '/tr>');
// set up the variables we need to test the first few properties
var number_of_values_to_test = 4;
var name_array = new Array(number_of_values_to_test);
var properties = new Array(number_of_values_to_test);
name_array[0] = "Application Name";
properties[0] = "appName";
name_array[1] = "Code Name";
properties[1] = "appCodeName";
name_array[2] = "Version";
properties[2] = "appVersion";
name_array[3] = "User Agent";
properties[3] = "userAgent";
// Loop through the properties, outputting one table row for each one.
for (var index=0;index < number_of_values_to_test;index++) {
document.write('<tr><td bgcolor="#9999cc" align=left class="small">' +
name_array[index] + '<' + '/td>');
document.write('<td bgcolor="#ccccff" class="small">' +
properties[index] +
'<' + '/td>');
document.write('<td bgcolor="#ccccff" class="small">' +

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-11

navigator[properties[index]] + '<' + '/td>');


document.writeln('<' + '/tr>');
}
// Write out details about the user's installed plug-ins
document.write('<tr><td bgcolor="#9999cc" align=left class="small">PlugIns<' +
'/td>');
document.write('<td bgcolor="#ccccff" class="small">plugins<' + '/td>');
document.writeln('<td bgcolor="#ccccff" class="small">');
if (navigator.plugins != null) {
for (var index=0;index < navigator.plugins.length; index++) {
document.writeln(navigator.plugins[index].name + '<br />');
}
}
else {
document.writeln("Browser doesn't recognize " +
"'navigator.plugins' property.");
}
document.writeln('<' + '/td><' + '/tr>');
// Do the same for the MIME types. This is more complex because we need to
// build a subtable within our main table, showing the types, their names
// and extensions, and the plug-in assigned to them.
document.write('<tr><td bgcolor="#9999cc" align=left class="small">' +
'MIME Types<' + '/td>');
document.write('<td bgcolor="#ccccff" class="small">mimeTypes<' + '/td>');
document.writeln('<td bgcolor="#ccccff" class="small">');
if (navigator.mimeTypes != null) {
document.writeln('<table>');
document.writeln('<tr bgcolor="#9999cc">' +
'<th class="small" align=left bgcolor="#9999cc">'
'mime type<' + '/th>' +
'<th class="small" align=left bgcolor="#9999cc">'
'identifier<' + '/th>' +
'<th class="small" align=left bgcolor="#9999cc">'
'extn.<' + '/th>' +
'<th class="small" align=left bgcolor="#9999cc">'
'plug-in<' + '/th><' + '/tr>');

+
+
+
+

for (var index=0;index < navigator.mimetypes.length; index++) {


if (navigator.mimetypes[index].enabledplugin != null) {
document.write('<tr><td class="small" valign=top>' +
navigator.mimetypes[index].type +
'<' + '/td><td class="small" valign=top>' +
navigator.mimetypes[index].description +
'<' + '/td><td class="small" valign=top>' +
navigator.mimetypes[index].suffixes +
'<' + '/td><td class="small" valign=top>' +
navigator.mimetypes[index].enabledplugin.name +
'<' + '/td><' + '/tr>');
}
}
document.writeln('<' + '/table>');
}
else {
document.writeln("Browser doesn't recognize " +
"'navigator.mimeTypes' property.");
}
document.writeln('<' + '/td><' + '/tr>');
// finish up the table.
document.writeln('<' + '/table>');
// -->
</script>

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-12

JavaScript Specialist

</body>
</html>

7.

Editor: Save the file lab8-1a.htm.

8.

Browser: Open the file lab8-1a.htm to run the script. You should see the page
shown in Figure 8-2 with information about your browser. Notice that this script is
using standard JavaScript to identify a host of information about your browser.
Tech Note: Be sure to view this file in multiple browsers. You will see plug-in
information in Firefox.

Figure 8-2: Table detailing your browser properties

From a security point of view, consider that this script reveals a significant portion of
your browser information. Although this may be useful for determining browser
compatibility, it could also provide a hacker with enough information about your system
to stage an attack.
This demonstration is a reminder that no computer or server is 100-percent safe.
However, by keeping your browser, operating system and anti-virus software current, you
can dramatically decrease the chances that your system or server will be compromised.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-13

Script Blocking
OBJECTIVE
3.3.2: JavaScript
and browser
security issues

JavaScript can add a large variety of functionality, interactivity and dazzling effects to
your Web pages. However, it does pose some common problems as well. Some scripts are
malicious and can cause damage to the user's computer. Others are simply annoying. For
example, pop-up windows can be useful for certain tasks but are overused for purposes
that tend to irritate users, such as advertising.
For this reason, many third-party tools are available to enable users to block JavaScript
code and other executable content. Most browsers offer this capability built-in, and in
many cases, they block scripts by default unless you change the settings. You can also
obtain script-blocking add-ons and plug-ins designed for specific browsers.

IE7Pro add-on This free tool extends the latest version of Internet Explorer with a
great many features, including an ad blocker that blocks all forms of advertising,
including fly-ins, slide-ins, pop-ups, pop-unders, spyware and adware ads, Flash
ads, rich media, and messenger ads.

The NoScript add-on This free, open-source script blocker for Mozilla-based
browsers (e.g., Firefox, SeaMonkey) allows JavaScript, Java, Flash and other
executable content to execute only if you accept the source as a trusted Web site.

Dev channel of Chrome on Windows The latest Dev channel v5.0.317.0 for
Windows offers an option to control JavaScript, plug-ins, cookies and images
selectively on the Google Chrome browser. Users can block this content, or choose to
allow only trusted sources they specify.

Anti-virus protection applications Most anti-virus software now offers pop-up


blocking, malware protection, and warnings for unsecure pages. Many brands are
available, such as Norton and AVG.

Tools such as these are meant to prevent scripts from exploiting known (and not yet
known) security vulnerabilities, but without losing functionality by disallowing all
executable content.

How script blocking affects developers


Script blocking is a wise precaution for browser users, but how does it affect JavaScript
developers?
You should be aware that the scripts you develop and incorporate in your Web pages may
be used and enjoyed by your site visitors, or they may be blocked. For this reason, it is
wise to consider carefully the functionality on your site that is dependent on scripts.
If a script is needed for users to complete important activities, then you should advise
users about the script so they can choose to allow it or to accept your site as a trusted
source. You can also provide alternative ways of delivering scripted functionality so that
users who block your scripts can still use your site.

Blocking JavaScript from your browser


There may be times when, as a developer, you need to disable JavaScript completely from
your own browser. A typical example is when you are asked to examine a page you are
unfamiliar with, possibly because of a security problem. The most convenient solution is
to turn off JavaScript, examine and run the source code, perform your tasks, then reenable JavaScript when you have deemed the site to be safe. Typically you would do this

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-14

JavaScript Specialist

a single browser so you do not have to reset all your browsers. Following are the steps for
disabling JavaScript in Internet Explorer 8.x.
1.

Internet Explorer: In the main browser menu, click Tools and select Internet Options.

2.

Click the Security tab. This tab allows you to select a variety of security settings,
including whether to allow, disallow or prompt for scripts and cookies. You can
choose an automatic setting level with the slider, or you can customize your settings.

3.

Click the Custom Level button. Scroll down the settings to Scripting, and click the
Disable option, as shown in Figure 8-3.

Figure 8-3: Blocking JavaScript in Internet Explorer 8.x

4.

Restart your browser. JavaScript is now disabled. Try opening one of the lab files for
this course and see what happens. You can disable JavaScript by following similar
steps in other browsers.

Differences in document.write Among Browsers


OBJECTIVE
3.3.2: JavaScript
and browser
security issues

The document.write method provides the simplest way to use JavaScript to write text
onto a Web page. For this reason, many novice developers rely on it for much of their
scripted functionality.
However, it is not necessarily the best way. For example, a document.write statement
must be run before a page finishes loading (i.e., in the page body or its functions),
otherwise it will create a new page and overwrite your existing page content. More
experienced developers learn that document.write is actually quite limiting.
When it comes to performance in the browser, the document.write method only works
properly in pages that the browser processes as HTML not XHTML, but HTML. The
reason for this is that pages defined as XHTML in the <!DOCTYPE> tag are generally
processed by the browser as XML, rather than HTML. Some browsers, such as Internet
Explorer (prior to v7.x), have problems displaying XML pages and thus cannot process
document.write properly.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-15

For example, when you create code in a simple text editor such as Notepad, you may add
extra spaces and breaks to indent lines and make the code easier to read. When
processing XML, many browsers treat line breaks (new line) and spaces (white space) as
text nodes. Internet Explorer does not do this. Therefore, Internet Explorer will read the
same document as having fewer text nodes than another browser would, if processing as
XML. This may affect how the page is rendered, as well as the accuracy of the code if the
code relies on counting nodes or reporting data.
At the time of this writing, some authorities say that document.write should not
render in Internet Explorer. In fact it does render, but the page does not validate
as XHTML. It is likely that because document.write is so widely used, browser
vendors continue to include legacy compliance for it. However, document.write
can pose security risks (e.g., it can be used to redirect to another [possibly
malicious] site against the user's and developer's will). In speculation, this
method may be under scrutiny for eventual deprecation, which might explain
the insistence that it does not work in some browsers.

What JavaScript developers can do


Because of the problems processing document.write with XHTML, you should declare
your pages as HTML 4 Transitional in the <!DOCTYPE> tag if you want to use
document.write with Internet Explorer. While this may not be a problem (as long as you
are not required to validate your code to XHTML), it may require you to code your pages
to be handled differently, and thus your pages may render as expected in Internet
Explorer but not in other browsers.
One solution is to create multiple versions of the page, writing each to conform to the
appropriate HTML or XHTML standards. You can use the JavaScript navigator object to
detect the user's browser type, then serve the most appropriate page on a user-by-user basis.
Browsers are constantly updating and beginning to conform more closely to standards.
This conformance serves to decrease the differences in document.write among the
browsers with every new version. With the eventual adoption of HTML5, the differences
among browsers when processing document.write should be few or none at all.
In the meantime, you can develop different versions of your pages, as discussed, or use
alternatives to document.write where possible. For example, innerHTML is more difficult to
write, but it works well with XHTML. You will use the innerHTML property in a later lesson.

Malicious and Accidental Coding


OBJECTIVE
3.3.2: JavaScript
and browser
security issues
3.3.5: Secure
JavaScript code
infinite loop
A JavaScript
statement that has
no attainable
conditions for
ending, and thus
requires the user to
close the browser in
order to end the
script.

Every developer makes some mistakes while coding. However, ill-advised or malicious
users sometimes upload such a script to the Web deliberately. Other coding errors could
cause similar problems. The goal of this section is to teach you to prevent not cause
such errors.
Accidental or malicious coding can generate infinite sequences that may cause the
browser to malfunction or lock. If this happens, the user must force the browser to quit
with CTRL+ALT+DELETE. For example, a do...while statement or a for statement can
create an infinite loop that has no conditions for ending and will lock the browser, thus
requiring the user to shut it down in order to stop the script. The following lab
demonstrates this point to teach you how to avoid coding infinite (or "broken") loops.
Many broken loops do include conditions or expressions to end, but they can never be
reached. For example:
do while (i=1; i < 5; i--)

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-16

JavaScript Specialist

In this statement, i will start at 1. It will decrement (-1) each time through the loop, and it
will not stop until it reaches 5, which it can never do. Developers do not usually forget to
end a statement, but rather they misuse (or fail to use) the parameter (such as increment
or decrement) that will cause the condition to be met. This parameter can also be called
the update expression (i.e., the expression that updates the variable which will cause the
loop to exit), which in this example is i--.
In the following lab, you will see how JavaScript can be used to lock a user's browser.
Suppose you are attempting to write a script for your Web page. Because you are short
on time, you borrow some code from a library without researching it quite as closely as
you know you should. When you test the code in your browser, you find that it locks your
browser with an alert until you close the browser. You do not know if the library provided
this bad code by accident or intentionally, but you do know that this type of script is
unethical, as well as annoying for your users. So you review the script carefully and look
up the parts you do not understand, trying to figure out what caused the locking. You
find the culprit: an infinite loop in a for statement. You remove this loop from your code.
Then you visit a more reputable code library and search for a new script to do what you
need. This time, you take the time to research the code more closely before implementing
it in your page.

Lab 8-2: Locking the browser with malicious code


OBJECTIVE
3.3.2: JavaScript
and browser
security issues
3.3.5: Secure
JavaScript code

In this lab, you will observe JavaScript used to lock a user's browser.
1.

Editor: Open the file lab8-2.htm from the Lesson_8 folder of the Student_Files
directory.

2.

Editor: Examine the following source code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/><title>Lab 8-2</title>
<script language="JavaScript" type="text/javascript">
<!-for (i=0; i >= 0; i++) {
alert("Stop me if you can!");
}
//-->
</script>
</head>
<body>
This page demonstrates poorly written or malicious JavaScript code that locks
the browser.
</body>
</html>

3.

Editor: Close lab8-2.htm.

4.

System: Close any open programs.

5.

Browser: Open lab8-2.htm. You will see an alert dialog box as shown in Figure 8-4.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-17

Figure 8-4: Alert dialog box

6.

Browser: You can click the OK button repeatedly, but the message will return.

7.

System: To stop execution of this script, you must close the browser. To do this, hold
down the CTRL + ALT keys and press the DELETE key on your keyboard. This action will
open a dialog box similar to Figure 8-5.

Figure 8-5: Close Program menu

8.

System: Verify that the Internet Explorer task (or whichever browser you are using)
is selected. Click the End Task button to close the browser. You will see the message
shown in Figure 8-6.

Figure 8-6: End Task message

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-18

JavaScript Specialist

9.

System: Click End Now to complete the operation. You have now closed your
browser with no damage done.

10. Editor: The browser lock is caused by an infinite loop in the for statement. This sort
of loop is typical when a developer is first learning to script loops, but it is rarely
found in production, because it is simple to stop and easy to fix. An infinite loop has
no conditions for ending. You can correct it by creating a condition that will cause
the program to finish the loop. Open the file lab8-2.htm. In the script section, change
the code as shown in bold, then save the file:
<script language="JavaScript" type="text/javascript">
<!-var i=0;
for (i=0;i<=5;i++)
{
alert("The number is " + i);
}
//-->
</script><body>
<h3>CIW JavaScript Specialist</h3>
<hr />
This page demonstrates repaired JavaScript code that will no longer loop
infinitely.
</body>

11. Browser: Open the file lab8-2.htm. You should see that the alert box counts up and
then stops as expected at the number 5. You have now performed your diligent
troubleshooting and corrected the code to remove the infinite loop.
OBJECTIVE
3.3.2: JavaScript
and browser
security issues
frame-to-frame URL
change
A technique in
which one frame in
a frameset can
direct the URL in
another frame to
display a different
page. This ability
introduces security
concerns.

Frame-to-Frame URL Changing


On modern Web sites, frames are not commonly used. They have been widely replaced by
newer technologies such as AJAX and Java, which can both change pages on the fly or at
the click of a button. Therefore, frame-to-frame URL changing is not the problem it once
was. However, it does still occur, and inline frames (iframes), which are more common,
are a particular target. Therefore, you should be aware of the security issues involved if
you are going to work with JavaScript.

How frames work


Frames are a Web site technique in which the browser window is divided into two or more
adjacent window panes that can display different content. Frames allow one part of the
page to remain static while another can change dynamically. For example, you can create
a frameset page with links in one window that, when clicked, will open new pages in the
adjacent window pane(s).
Frame content usually comes from within the Web site, but can also come from another
site. The ability to share content from other sources makes frames vulnerable, thus the
site developer must carefully control the content. Using content from another Web site
without permission is a copyright violation. Also, frames within your own site can be
hijacked by malicious code and used to infect browser software.

Cloaking
When one frame in a frameset redirects a URL, the browser still displays the URL of the
frameset document rather than the URL of the target page in the address bar. This

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-19

technique is sometimes called cloaking, and can be used for legitimate purposes (such as
displaying a more memorable URL to users). It can also be used maliciously (such as
concealing a "phishing" site as part of a Web site spoofing scam).

Inline frames
A frames page can also contain an inline frame (iframe), which displays a separate file
floating within the page. These frames appear to be part of the parent page, and generally
offer no security indicator or address bar of their own. Thus users (and browsers) trust
them implicitly. This security issue becomes more urgent because iframes are sometimes
used for password entry on sites (see Figure 8-7), where protecting the integrity of
information is essential. If your site earns a reputation for security problems with user's
information, you will have far fewer visitors.

Figure 8-7: Inline frame used for password entry

Browser restrictions
Historically, any window could change the location of any other window. But this became
a problem because it meant that using a frame or iframe window for a login, for example,
was unsafe (a malicious site could replace your login page with a spoofed version). It also
allowed hackers to hijack your frames page by redirecting a link to display unwanted
content in a frame.
Because of these problems, restrictions have been applied over time that attempt to limit
location changes in browser windows, particularly when using any type of frames. And as
you know, you can use JavaScript to redirect URLs with the location object.
There are now rules that limit the types of pages you can redirect to in a frame or iframe.
In a frameset page, if you try to improperly change one frame's URL from another frame
using JavaScript, many modern browsers will return an error that says, "Unsafe
JavaScript attempt to access frame with URL." And the URL will not change. There are
ways to get around this, but such procedures are not considered best practice and the
code is quite complex.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-20

same origin
A policy that defines
the relationships
among various
pages within a
single Web site. It
requires that pages
be "ancestors" (e.g.,
parents, siblings,
children) in order to
be allowed to
navigate each
other.

JavaScript Specialist

Same origin policy


Among the major browsers, the restriction policies have varied and become stricter over
the years. With the current development of HTML5, most browser vendors have reached
agreement on a "same origin" policy that allows a frame to navigate another frame only
to "ancestor" pages, which include parent, sibling and child pages, but not pages from
other sites. The rules for the concept of same origin are complicated, but in general, Page
X can change the location of Page Y in a frame only if:

The locations of X and Y have the same origin (i.e., the same protocol/port and host)
and share a parent or grandparent window at some level.

Y is a top-level window, and X is frame nested within Y (direct child, grandchild, etc.).

Y is a window opened using window.open, and X can change the location of the
window that opened Y (i.e., Y is a pop-up opened by X, or Y was opened by a pop-up
opened by X).

Figure 8-8 illustrates some examples of these relationships.

Figure 8-8: Examples of same-origin relationships

In general, qualifying ancestor pages must use the same protocol/port and host. So using
the example from the preceding figure, the following pages would not be allowed to
change the location of Page Y.htm in http://www.CIW.com:

https://www.CIW.com/secure_X.htm (different protocol/port)

http://intranet.CIW.com/X.htm (different host)

http://CIW.com/X.htm (different host)

ftp://CIW.com/X.htm (different protocol/port)

This browser security model was evolved more than it was designed, and inconsistencies
still exist across browsers. However, you will notice that JavaScript does factor into the

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-21

policy in that scripted relationships (such as pop-ups) can affect the ability for a page to
navigate a frame.
Frames are no longer commonly used on the Web, and therefore this course
does not discuss them in further detail. However, the course does offer a related
appendix with legacy information about frames and JavaScript. See the
appendix if you are interested in knowing more about creating frames.

What JavaScript developers can do


Knowing that users can easily view and tamper with JavaScript code, you can see how
JavaScript is part of both the problem and the solution.
Although you may never work with frames sites, it is wise for you to be familiar with
these policies and understand their purpose, so you can consider them when scripting
any pages, particularly those that will ask users to enter sensitive information, such as
user names and passwords.
Furthermore, all developers and end users should be encouraged to take these specific
steps:

Update your browser software often to the latest stable version It is important
not to be complacent about such security issues. Do not think that a more recent
browser version will always solve your problems. Web browser vendors often
unintentionally reintroduce old problems back into their code.

Use the browser's pop-up blocking settings wisely Most browsers have native
pop-up blocking functionality. All you need to do is change the browser preferences
to a suitable setting. Generally, blocking all pop-up windows is the preferred default
setting. You can always allow exceptions to this general policy.

Keep your anti-virus software up to date This step is tangential, but related. If
you do become a victim of some malicious URL changing on the Web, you can still
protect your system from running any malware that a detour site might attempt to
download.
Keeping your browser software updated and using pop-up blocker settings are
the primary means to keep your system secure in regards to frame-based
attacks.

OBJECTIVE
3.3.3: Signed scripts

Signed Scripts

signed script
A script validated
by a certificate
authority that can
request extended
privileges and
abilities in the
browser.

Since JavaScript 1.2, developers can create electronically signed scripts and Java
applets. A signed script is validated by a certificate to prove the identity of the author and
integrity of the script. Because it carries this validation, the script is allowed to request
expanded privileges and abilities, which may override the usual security. This allows the
page developer to exercise more control over activities than is usually allowed to
JavaScript.
Signed scripts were Netscape's implementation of configurable security for JavaScript.
However, other browsers such as Microsoft did not support the technology, so signed
scripts never caught on widely.
Microsoft Internet Explorer still does not support signed scripts. Rather, it allows the
user to define security zones of trusted sites, then specify security settings for the entire
zone. But it does not allow the option to disable the same-origin policy for a trusted site,
for example, or to allow scripts from trusted sites to send e-mail messages without a user
confirmation.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-22

JavaScript Specialist

How signed scripts work


A signed script will activate a dialog box that advises the user about the script, and asks
if the user chooses to trust the source of the script and run it. The user must agree
before the script can launch. Examples of such privileged activities include:

Reading settings on your computer, such as your browser preferences.

Changing browser preferences, such as your home page or favorites.

Installing other scripts and running files, such as unwelcome Web pages.

Signed scripts provide a mechanism by which programs can perform operations that were
considered security risks in previous versions of JavaScript. An example of this type of
operation is reading a user's preference settings in the Mozilla Firefox browser. Prior to
the operation being executed, the signed script asks the user whether the operation
should be allowed. The type of operation is clearly explained to the user, with access
limited to specific areas of the client machine. Figure 8-9 shows an example of this type
of security warning and request.

Figure 8-9: Example of security request for signed script

Creating a signed script


digital certificate
An electronic
mechanism used to
establish the identity
of an individual or
an organization.

The script-signing process involves the use of digital certificates. A digital certificate is
an electronic mechanism that establishes your identity and is issued by a certificate
authority. The digital certificate is packaged in a Java Archive file (JAR file) and attached
to the script using the archive attribute of the <script> tag.
However, more recent browser versions, such as Firefox, do not require the archive
attribute for this purpose, and no longer recognize it. Mozilla browsers use the <script>
tags src attribute to reference the signed script. The entire X/HTML page and its scripts
are signed and placed in a JAR file with the signature. The signature is automatically
associated with the script and verified as the page loads when you refer to the X/HTML
page using the following syntax:
jar:http://www.mysite.com/myjar.jar!/signed.html

Further discussion about the creation and use of signed scripts is beyond the scope of
this course. You can investigate the following URL for more information about signed
scripts:
www.mozilla.org/projects/security/components/signed-scripts.html

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-23

Cross-Site Scripting (XSS)


OBJECTIVE
3.3.6: Cross-site
scripting
cross-site scripting
(XSS)
A security
vulnerability in
which an attacker
embeds malicious
script into a link that
appears to be from
a trusted site. Upon
clicking the link, the
embedded script is
submitted in the
clients HTTP request
and can execute
on the users
computer, enabling
the attacker to steal
information.

One of the most popular sources of hacking is a practice called cross-site scripting
(XSS). XSS typically uses JavaScript code to enable an attacker to steal sensitive
information from a user without the users knowledge. XSS can be damaging and costly
to your business, because problems with user information make customers question your
sites security and privacy.
XSS is a type of code-injection attack. It occurs when an attacker takes advantage of
holes, or vulnerabilities, in your Web application, which enables him to bypass the
security normally imposed by browsers. The attacker injects malicious client-side script
into your Web page to gain access to sensitive page content, session cookies or other user
information stored by the site. XSS can also be used to bypass access controls such as
the same-origin policy (which was discussed earlier in this lesson).
Thus, the attacker can use script to load his malicious application from an unrelated,
vulnerable site, which is trusted by the user hence the term cross-site scripting.
Depending on the sensitivity of data that users enter, cross-site scripting attacks can
range from a minor nuisance to a significant security risk. They are popular among
hackers, comprising a majority of reported security vulnerabilities.

How XSS works


An XSS application collects data from the user, usually through a hyperlink that the user
is enticed to click, which carries the malicious content within it. Attackers generally mask
the malicious portion of the link using hexadecimal or other encoding so the link looks
less suspicious.
After the XSS application collects the user data, it generates an output page to the user
that contains the data originally sent to it, but in a way that makes it appear to be valid
content from the site. Because many guest book and forum programs allow users to
submit posts with X/HTML and JavaScript coding embedded in them, these are popular
targets for XSS.
The users input is manipulated and reflected back, which may not seem like much of a
problem. However, if an attacker places deceptive links or hidden frames on unrelated
sites, this can cause the users browser to point to URLs on the vulnerable site often
unnoticed which allows the attacker to violate the users security context.
In essence, if the attacker can get a user to click a link on the trusted (but vulnerable)
site or in a spoofed e-mail pointing to the trusted site then the malicious script in the
link URL will execute in the users browser, looking like expected content from the
trusted site. This malicious script can send a session cookie from the user to the
attacker, without the users knowledge. Depending on the nature of the trusted site, the
cookie can contain sensitive data from the user, such as a password or billing
information. A cookie can also be used to hijack a users session on a forum site, allowing
the attacker to impersonate the user on that site. You will learn more about cookies later
in this lesson.

Types of XSS
There are three general types of XSS, which are described in Table 8-1.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-24

JavaScript Specialist

Table 8-1: Types of cross-site scripting (XSS)

XSS Type

Description

Example

Reflected
(NonPersistent)

The most common type.

A user performs a site search


for a string that includes
X/HTML special characters,
and the search string is
redisplayed on the result page.
If the search terms are not
encoded as X/HTML entities,
an XSS hole will result.

Persistent

Enables the most powerful attacks.

These holes occur when data provided by a


browser is used immediately by server-side
scripts to generate a page of results for that
user. If unvalidated user-supplied data is
included in the resulting page without
X/HTML escaping (entities for special
characters), then the client-side code can be
injected into the dynamic page.
When a user enters data in the browser, it is
first stored persistently on the server (in a
database or file system, for example), then
later displayed to other users in a Web page
without proper XHTML escaping.

Some online message boards


allow users to post X/HTMLformatted messages for other
users to read. An attacker can
obtain a session cookie and
impersonate the user in the
forum.

Table 8-1: Types of cross-site scripting (XSS) (contd)

XSS Type

Description

Example

DOM-Based

This problem exists in a page's client-side


script itself.

An attacker hosts a malicious


site with a link to a vulnerable
page on a client's local system.
The hacker could inject a
script that would run on the
user's system with the
privileges of the browser. This
bypasses the entire client-side
sandbox, not just the crossdomain restrictions that are
normally bypassed with XSS
exploits.

A JavaScript program accesses a URL


request parameter and uses it to write some
X/HTML to its own page. If this information
is not encoded using X/HTML entities
(escaping), it can create an XSS hole because
the written info will be re-interpreted by
browsers as X/HTML, which might include
additional client-side script.
With Internet Explorer, which runs clientside script in objects located in the local zone
(e.g., the client's local hard drive), an XSS
hole of this type in a local page can result in
remote execution vulnerabilities.

Code and servers in XSS


XSS is essentially a code-injection attack. The attacker's code sends malicious user input
from the server to the victim's browser, all within the HTTP response that the browser is
waiting to render onscreen for the user. The browser cannot distinguish between the real
site content and user input that might be malicious, so the browser renders the
malicious code as X/HTML or a scripting command, instead of the plain text string that it
should have been. The result is a hole, or vulnerability, in the site.
Servers typically have policies that prevent scripts or database information from one site
being run on another site. But XSS bypasses this restriction, allowing a hacker to hack
many sites from one site.
XSS also can appear in your e-mail. A user may receive mail from what appears to be a
trusted Web site. Upon clicking a link in the e-mail message, the user may indeed be
accessing the trusted site (such as a bank), but malicious code has been embedded
within the URL, allowing the hacker to steal any passwords or banking information that
the user sends during that session.
Never click a link in an e-mail message, even when you explicitly trust the Web
site. Always go to the site manually to log in. This simple precaution will help

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-25

prevent you from becoming a victim of XSS and other exploits, such as "phishing."

What JavaScript developers can do


In general, you should not trust user input, and you should always encode output to
filter metacharacters. This will help prevent most XSS attacks.

X/HTML entities
Symbol characters
(such as < or &) that
can be represented
as themselves or, in
X/HTML, as an
alphanumeric code
for purposes of
programming or
security. Also known
as X/HTML escape
characters.

Output encoding
Output encoding is the best defense mechanism for XSS. This means that certain special
characters need to be properly encoded as entities. Output encoding can ensure that
information returning from the server is re-mapped so that when the browser receives the
info, it knows to display it onscreen rather than execute it.
For example, the following X/HTML special characters used in URLs or for displaying
Web page content can be properly encoded as entities, as follows:

Ampersand ( & ) encode as &amp; or &#38;

Opening angle bracket or "less than" symbol ( < ) encode as &lt; or &#60;

Closing angle bracket or "greater than" symbol ( > ) encode as &gt; or &#62;

Apostrophe or single quotation mark ( ' ) encode as &#39;

Double quotation mark ( " ) encode as &quot; or &#34;

These are only some of the characters to encode. You can set the page encoding with the
<meta> tag. The actual encoding is specific to context and must be tailored to the correct
part of the X/HTML file. This technique must be done correctly and consistently to be
useful.

Input validation
Ouput encoding alone is not enough because may applications accept user input in
X/HTML format to render the input in the browser. Input validation can help. However,
validating untrusted X/HTML input is a complex task that requires an HTML policy
engine that can check for XSS. Tools from trusted security organiztions such as OWASP
are available for this purpose.
Input validation cannot filter out all XSS, however. One reason is that the variety of
applications on the Web today make validation difficult. For example, the mashup model
means that you sometimes do not know the source of an application or whether it uses
validation, fully or at all. Another reason is that zero-day exploits can take advantage of a
situation instantly, often before the system's anti-virus software is able to respond and
provide a patch for the virus.

Cookies and XSS


Because session cookies are often the target of XSS attacks, you can try to secure cookies
by tying session cookies to the IP address of the user who originally logged in, then
permit only that IP address to use that related cookie. This practice can be helpful when
the cookie is the target, although an experienced hacker can also spoof the IP address.

Script blocking and XSS


Probably the most effective way for users to avoid being attacked by a script is to deny
any scripts from running in their browsers. However, blocking all scripts means less
functionality and responsiveness, and a substantial degradation in the Web browsing

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-26

JavaScript Specialist

experience. Like anything else, there is a price to pay for all that you get from the Web,
and that price is the risk of vulnerability.

OWASP and XSS


The Open Web Application Security Project (OWASP) is dedicated to helping developers
secure their sites. For more information about preventing XSS, you can visit its XSS
Prevention Cheat Sheet at the following page:
www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

Cookies and Security in JavaScript


OBJECTIVE
3.3.7: Manipulating
cookies

One of the reasons that JavaScript is so popular is its ability to assign cookies. In this
section, you will learn about cookies, how to control their use on your computer, and how
to assign them. More importantly, you will learn the reasons that cookies are used so
often, and you will consider some of the security issues involved with cookies.

What are cookies?


cookie
Small pieces of
information
collected by a Web
browser to help
maintain state and
track user activities.
Cookies can reside
in memory or be
placed on a hard
drive in the form of
a text file.

Cookies are small pieces of information sent to a client computer via the browser and
stored in memory. Cookies are often sent by a server from a site the user has visited, but
can also be set on the client side using JavaScript. Once a cookie is placed on a
computer, the cookie can be used to keep track of the visitor on subsequent visits to the
site that placed it. The user can delete these cookies at any time.
A cookie is originally stored in the memory of the client computer, but the cookie can be
scripted to store its information permanently on the hard drive, which has become
prevalent. Almost every commercial Web site uses cookies; one site can deposit several of
these files on your hard drive upon just one visit. Cookies are often referred to as
"persistent cookies" and even "persistent HTML." In fact, Netscape created the cookie
specification, which refers to cookies as "persistent client-state HTTP cookies."
The term "cookie" was chosen at random and has no special meaning. One possible
explanation is that it is a slang term for a small token used to denote a transaction. For
example, when you go to a movie and pay for admission, the ticket you receive is a type of
"cookie" that you can use to prove you have permission to enter. Another explanation
could be that UNIX programs contain operators, or keywords, called "magic cookies."
These cookies help to track a user's operation of a specific program (such as storing and
retrieving the data a user generated with the program, and so forth).

Cookie crumbs
"Cookie crumbs" are cookies that leave a trail following the user's progress. If a site
employs cookie crumbs, then a user can leave the site, and when he returns at a later
time, he can resume where he left off, instead of having to re-navigate. Cookies crumbs
can be useful for gaming sites on which a user might want to save his progress and
resume where he left off when he returns. Some shopping sites also use cookies crumbs
so that if a user places items in the shopping cart then exits the site before completing
the transaction, she can return at a later time or day to find the items waiting for her in
the cart (provided they are still available), ready to be purchased.
Whether stored in memory or in small text files on your hard drive, cookies have a variety of
uses. They can help maintain state, aid authentication, remove redundant steps, and track
user behavior. You will learn more about each of these uses shortly. The most common

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-27

usage of cookies is when a Web site asks if you want to stay logged in. When you select
"Yes," a cookie is placed on your computer that will bypass the login sequence.

How are cookies sent?


Cookies are sent from a Web page or server to the client system's browser in the HTTP
response header. The browser accepts the response from the page assigning the cookie,
and then accepts (or gives the user the chance to accept or reject) the cookie. After the
cookie has been accepted, the browser program stores the cookie information in system
memory or, if the cookie is scripted to do so, in files. Most browsers now are typically set
to accept cookies, unless the user changes the cookie settings. In Mozilla Firefox, you can
set the cookies setting to delete cookies upon exiting Firefox.
When a user generates an HTTP request, one of two actions can occur:

Any cookies already on the client's system that match the server's domain can be
passed along in the request header.

A server can send a cookie back in the HTTP response header.

In subsequent exchanges between the client and the server, the server can then test and
evaluate the contents of any cookies that may be present.

Cookie header syntax


A cookie header appears to your browser as follows:
Set-Cookie: name=value; expires=date; path=path; domain=domain; secure

Each cookie header contains a set of parameters. Not all of these parameters must be
assigned to use cookies. The cookie header parameters include the following:

name=value
The name of the cookie and its value are set by this expression. The name=value pair is
the only information required to generate a cookie. All other parameters are optional.

expires=date
The expires=date pair determines when the cookie will expire. The date is formatted
as follows:
weekday, DD-Mon-YY HH:MM:SS GMT

GMT stands for Greenwich Mean Time. The time expiration scheme is specified in
RFCs 822, 850, 1036 and 1123.
If the expires attribute is not used, the cookie will expire at the end of the user's
session with the Web application.

path=path
The path=path pair contains path information for the URL that issued the cookie. This
attribute defines subsets of the URL for which the cookie is valid. The most commonly
used path is / (forward slash), used to denote the root directory of the server.
If the path attribute is not used, the URL path of the document setting the cookie is used.

domain=domain
The domain=domain pair contains the domain name of the URL that issued the
cookie. When an HTTP request header is formed, the path and domain name pairs
are checked; if they match the page being requested, any cookies pertaining to that

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-28

JavaScript Specialist

domain are passed back to the server for evaluation. A cookie in a client's request
header appears to the server as follows:
Cookie: name=value; name2=value2; etc.

The server does not see any information other than the name=value pairs. Only
URLs matching the path and domain values in the cookie file can be read again and
evaluated by the server.
If the domain attribute is used, the server setting the cookie must be part of the
domain being set in the cookie. Thus, a server named www.ThisServer.com cannot
set a cookie for the domain www.ThatServer.com.
If the domain attribute is not used, the domain of the document setting the cookie is used.

secure
If the secure parameter is present, the cookie will only be sent using a secure
protocol, assuming one is available. If the secure attribute is not used, the cookie is
deemed safe to be sent over unprotected channels.

Who can send cookies?


Traditionally, the general guideline for cookies was that a server can set, or deposit, a
cookie only if a user visits that particular site. In other words, one domain cannot deposit
a cookie for another, and (in theory) cross-domain posting is not possible. Additionally, a
server can retrieve only those cookies it has deposited; one server cannot retrieve a cookie
set by another. However, in recent years, various technologies that bend this rule have
come into play. Cookies from another site can be deposited on your computer if there is a
pop-up or ActiveX control present. This is one of the reasons that pop-up blockers were
created and are popular today.

Shared cookies
A more recent technique for using cookies includes several domains uniting and creating
a large network, thereby setting cookies on the hard drives of users who have never
visited a particular site. By simply visiting one site, a user can become enrolled in a larger
network through the setting of one cookie. This practice is called sharing cookies.
For example, Facebook has joined with several different Web sites, such as Zynga and
various advertising sites. When you log into Facebook, you can access these other sites to
perform various actions based on the single cookie deposited with Facebook. This allows
users to, for example, play games on Facebook seamlessly while the game content is
hosted on another Web site. The gaming applet can deposit its own cookie when the
Facebook site loads the game into the browser. Therefore, even though a user has visited
only Facebook, the cookie can be set from another site (Zynga.com).
Another example is Yahoo, which has news subsidiaries that you are allowed to view with
the same cookie created when you logged in to Yahoo, even though the content is from
several different locations.
These practices are increasingly common, and they seemingly bypass the rule about
cross-domain posting. But note that the initial jump must be from the trusted site, and
frequently there are enormous security measures in place.

Why use cookies?


Cookies can be used for many reasons. You can use cookies on your Web site to:

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

Provide authentication.

Store user information.

Maintain user state.

8-29

Authentication
You can deploy cookies to aid user authentication. For example, if a user visits your Web
site and properly authenticates, you can deposit a cookie on that user's hard drive. Then,
when the user returns, he or she will no longer have to enter a password because that
information is stored in a cookie on his or her hard drive.
Although this practice can provide a level of convenience, it can also present a hazard.
Because the cookie is stored on that user's hard drive, any other user could sit down at
that computer and instantly log on to the password-protected site and impersonate the
authenticated user.

Storing user information


Using cookies, a Web site can gain the following information about a client:

Operating system and browser type

Service provider

IP address

A history of sites visited

State maintenance with cookies


One of the most common uses of cookies is to store information about a user to maintain
state. HTTP primarily uses TCP, which is a stateful (i.e., connection-oriented) protocol.
However, most Web servers terminate these connections in a short time. It is also natural
for a user to end a connection quickly.
To compromise for brief connections on either side of the Web browser, cookies allow
your system to remember connections over time. For example, suppose a user is playing
an adventure game on your Web site and decides to leave it. You could create a cookie
that tells your site where that user left the game. When the user returns, he or she can
resume at that point. In another example, a user could choose a color scheme for touring
your site. You could script pages to respond to cookie information so the user's color
preferences follow his or her path.
As a part of state maintenance, you can create cookies that eliminate certain steps. For
example, during the registration process, Amazon.com deposits a cookie that saves the
user's billing and shipping information. On subsequent visits to the site, the user can
purchase products with only one click. The user does not have to re-enter credit card or
any other information.
In general, cookies have no right or wrong uses. You can use them for any purpose you
want, but be prepared for the possibility that the user might reject or delete the cookie.

Storing cookies
Cookies store in name=value pairs as text strings, and the maximum size of a cookie is
4096 KB. Depending on the browser, it can store from 30 to 50 cookies per domain, and
a system can store unlimited cookies on its hard drive. When the maximum for cookies is
reached, the oldest cookie is deleted to make room for the newest cookie. Session cookies

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-30

JavaScript Specialist

are stored only for as long as the user remains on the site (this period is called a session),
and they are deleted when the user leaves the site. By contrast, persistent cookies have
time and date expiration, and can remain on a computer for many years, or until deleted
by the user).

Cookies and specific browsers


Many different browsers exist, and each stores cookies differently. Additionally, different
versions of the same program can store cookies in different directories. For the purposes
of clarity, this lesson will discuss major browsers such as Mozilla Firefox, Microsoft
Internet Explorer and Google Chrome.

Mozilla Firefox
Firefox always store cookies in a single text file named cookies.txt. Firefox versions 3.x
and later store the file in the \documents and settings\username\application
data\Mozilla\Firefox\Profiles\profilename\cookies.txt

Microsoft Internet Explorer


Internet Explorer versions 7 and later store cookie files in the C:\Documents and
Settings\UserName\Local Settings\Temporary Internet Files directory. Internet Explorer
sets cookies two ways by user and location. It also uses two types of files when setting
cookies.

A cookie text file (for example, jdoe@ciwcertified.txt) The name of each file is
similar to an e-mail address in that it lists the user name of the browser, then the
name of the domain that set the cookie. The first part of the name is taken from the
user name registered by Internet Explorer. The second part of the name (after the @
sign) denotes the origin of the cookie file.

A DAT file (for example, mm2048.dat or mm256.dat) The DAT file is technically
not a cookie; it is used by the browser to enable caching. However, Internet Explorer
uses both the text and DAT files in tandem when working with cookies.

Google Chrome
Google Chrome's scheme for distributing cookies is very similar to Internet Explorer's.
Chrome recognizes there are two types of cookies:

First-party cookies, which come from the sites browsed.

Third-party cookies, which come from other domain sources and contain objects,
such as images or icons.

Chrome sets cookies as individual text files. Chrome allows you to set preferences for
which cookies to accept and reject on a specific basis. The directory location where
cookies are stored varies by operating system. For example:

Windows XP %USERPROFILE%\Local Settings\Application Data\Google\Chrome\

Windows Vista, Windows 7 %USERPROFILE%\AppData\Local\Google\Chrome\

Mac You can view cookies in the Safari browser at Preferences | Security tab |
Show Cookies.

Linux/UNIX Many different versions of UNIX and Linux exist, and each stores
cookies in a different place.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-31

Mobile browsers
Although the browsers used on mobile devices are more limited than their full-featured
counterparts for computers, they still use cookies. Mobile browsers generally use the
rendering engines found in Firefox, Chrome and Safari. Therefore, they set and store
cookies in a similar manner. However, each mobile browser can have its own way of
setting and reading cookies. You can consult the specific mobile device's user manual to
learn exactly where cookies are stored on it.

Users deleting or disabling cookie files


Any knowledgeable user can delete or disable cookie files. A user can also write-protect
cookie files and folders, as well as use a statement in the computer's autoexec.bat file
that automatically deletes cookie files every time the machine boots. For this reason, you
should thoroughly test any application that depends upon cookies for its functionality.
You would need to include code that tests for the presence of cookies, and possibly
provide alternative code for situations in which cookies cannot be used.

Assigning a cookie with JavaScript


OBJECTIVE
3.3.8: Assigning
cookies

The document object contains the cookie property to work with cookies in JavaScript.
Assigning a cookie is quite simple. The syntax is as follows:
document.cookie = "name = value";

Alternatively, you can use the following syntax:


document.cookie = "name = value;expires = date";

For example, to create a cookie named userName, the following code could be used:
document.cookie = "userName = Raul";

The only parameter pair required is the name=value pair. If no expiration date is
assigned, the cookie will be deleted when the browser is closed. If an expiration date is
present, the cookie will expire on that date.
If you want to ensure that your cookie is sent over a secure connection (assuming one is
available), you can add the secure parameter at the end, after another semicolon. For
example:
document.cookie="name=value;expires=date;secure";

In addition, if you want to specify a particular domain and path name, you can add these
parameters as well. However, be aware that when you want to evaluate the contents of a
cookie, you will only be able to access cookies with a domain and path name that
matches that of the server's response header.

Testing for cookie presence


You can easily test for the presence of any cookie by using the document.cookie
statement in your script. For example:
<script type="text/javascript"><!-alert(document.cookie);
//-->
</script>

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-32

JavaScript Specialist

Each time a user accesses this page, he or she will see a quick listing of all cookies
associated with that particular browser session in the following format:
name1=value1,name2=value2, etc.

If no cookies are present, the user will see an empty alert.


Generally, you should test for a specific cookie by name or by value to see whether it
exists. Then you can extract the relevant information from the cookie.

Clearing a cookie
As a developer, you sometimes need to clear a cookie that you have set. To do this, simply
reassign it, adding an expiration date that has already passed. If a cookie is assigned to
an existing cookie name, the new cookie will replace the old one. By setting the date in
the past, the cookie will expire and be deleted from the user's computer.

Users controlling cookies in the browser


Any user can choose which cookies to accept by adjusting the settings in the browser.
Following are procedures for controlling cookies in various browsers.

Cookies in Microsoft Internet Explorer


Follow these steps to enable or disable cookies in Microsoft Internet Explorer 7.x. (The
steps are similar in Internet Explorer 8.x.)
1.

From the browser's main menu, click Tools, then select Internet Options. You will see
the Internet Options dialog box.

2.

Click the Privacy tab. You can move the Settings slider up and down to read the
choices for automatic cookie handling. The most permissive setting is Accept All
Cookies, the most strict is Block All Cookies. Between these two are Low, Medium
and High security settings.

3.

Click the Advanced button to see the Advanced Privacy Settings dialog, which allows
you to override the automatic cookie handling settings and customize the types of
cookies that your browser will accept, block or prompt. Figure 8-10 shows both the
Privacy tab and the Advanced Privacy Settings dialog.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-33

Figure 8-10: Enabling and disabling cookies in Internet Explorer 7.x

Cookies in Mozilla Firefox


Follow these steps to view, delete, enable and disable cookies in Mozilla Firefox 3.x:
1.

From the browser's main menu, click Tools, then select Options. Click the Privacy
tab. You should see the Options dialog box, as shown in Figure 8-11.

Figure 8-11: Options dialog in Mozilla Firefox 3.x

2.

Click the Show Cookies button to display the Cookies dialog, shown in Figure 8-12.
You can view and delete cookies one at a time or all at once. The individual cookies
are stored and displayed by site, so you can delete all the cookies from a selected site
if you like.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-34

JavaScript Specialist

Figure 8-12: Deleting cookies in Mozilla Firefox 3.x

3.

You can access settings for enabling and disabling cookies in the Privacy tab of the
Options dialog (shown previously in Figure 8-11). If you choose the Accept Cookies
From Sites setting, you can specify how long to store cookies and whether or not to
accept shared (third-party) cookies. You can also click the Exceptions button to set
specific exceptions for the cookies you will allow, shown in Figure 8-13.

Figure 8-13: Accessing cookie settings in Mozilla Firefox 3.x

Cookies in Google Chrome


Google Chrome's process for controlling cookies is similar to Firefox's. Follow these steps
to enable, disable, view and delete cookies in Google Chrome 9.x:
1.

On the top-right, click the wrench (Tools), select Options, then select the Under The
Hood tab.

2.

Under Privacy, click the Content Settings button, which will open the Content
Settings dialog box. In the Features box, select Cookies, as shown in Figure 8-14.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-35

You can allow, disallow and view cookies from this dialog. You can also set specific
exceptions for the cookies you will allow.

Figure 8-14: Accessing cookie settings in Google Chrome 9.x

3.

To view and delete cookies, click the Show Cookies And Other Site Data button. You
can select a single or several cookies, or an entire domain of cookies, then delete
them by clicking the Remove button. Or you can delete all cookies at once by clicking
the Remove All button, as shown in Figure 8-15.

Figure 8-15: Deleting cookies in Google Chrome

In the following lab, you will create, view and delete a cookie. Suppose your supervisor
says that she wants to add a new function to the Web site. For added interactivity, she
wants to store each user's first name in a cookie. When users who frequent the site visit,
they can be greeted with an alert that welcomes them by name. You realize that although
some users will enjoy this, others would rather that the browser did not store their name
or other information about them. So you add the cookie functionality to the site, but you

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-36

JavaScript Specialist

also add a confirm dialog box that advises users about the cookie and offers them the
option to keep it or delete it.

Lab 8-3: Setting, viewing and clearing a cookie with JavaScript


OBJECTIVE
3.3.7: Manipulating
cookies

In this lab, you will set a cookie, delete a cookie and retrieve cookie values, which you can
apply to an X/HTML document.

3.3.8: Assigning
cookies

1.

Editor: Open the file lab8-3.htm from the Lesson_8 folder of the Student_Files
directory. Study the <script> portion of the code in the <head> section of the file,
which appears as follows. This is where the cookie is created:
<script language="JavaScript" type="text/javascript">
<!-var myColor = prompt("Please enter a hexadecimal color code (must be 6
characters, including 0 thru 9 and A thru F):","FFFFFF");
var myName = prompt("Please enter your name:","Cookie Monster");
if ((myColor == null) || (myColor == "") || (myColor.length < 6 ||
myColor.length > 6)) myColor = "#ffffff";
var keepCookie = (confirm("A cookie will be set. Delete cookie?")) ?
"delete" : "keep";
if (keepCookie == "delete") {
document.cookie="testCookie=" +"YColor=" + myColor + " " + "name=" +
myName + ";expires=20-May-2010";
message= "Here is the cookie that was deleted: ";
message += document.cookie;
alert(message);
}
else {
document.cookie="testCookie=" +"YColor=" + myColor + " " + "name="
+ myName + ";expires=20-May-2015";
message= "Here is the cookie that was set on your system: ";
message += document.cookie;
alert(message);
}
var start = document.cookie.indexOf("YColor=");
start=start + 7;
var pos = "#" + document.cookie.substr(start,6);
alert("Your background color will be: " + pos);
var nameLengthS = document.cookie.indexOf("name=");
nameLengthS=nameLengthS + 5;
var PersonName = document.cookie.substr(nameLengthS,25);
alert("Your name is: " + PersonName);
//-->
</script>
</head>

2.

Editor: Now examine the following code after the <body> tag in the file, which will
display the cookie contents:
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<script language="JavaScript" type="text/javascript">
<!-if ((pos == null) || (pos == "")) pos = "#ffffff";
document.bgColor = pos;
document.write("Your background color is: " + document.bgColor +
"<br />");
document.write("Your name is: " + window.PersonName + "<br />");
document.write("Cookie contents: " + document.cookie);

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-37

document.write();
//-->
</script>
</body>
</html>

3.

Editor: Save lab8-3.htm.

4.

Internet Explorer Browser: Open lab8-3.htm in Internet Explorer.

5.

Internet Explorer Browser: You should first see a prompt dialog box asking for a
color. You need to supply the color in hexadecimal code, as described in the prompt.
The default is #FFFFFF, which is white. (Some example colors are #FF0000 for red,
#00FF00 for green, and #0000FF for blue.)

6.

Internet Explorer Browser: The next dialog will ask you to enter your name. After
you enter a name and click OK, you will see a dialog advising you that a cookie will
be set when you proceed, and asking if you would rather delete it, as shown in Figure
8-16.

Figure 8-16: Dialog asking whether to delete cookie

7.

Internet Explorer Browser: For this step, click Cancel to allow the cookie to be set.
The next message, as shown in Figure 8-17, will specify the cookie you just accepted
based on your answers to the questions.

Figure 8-17: Cookie accepted

8.

Internet Explorer Browser: Click OK to continue. You will see two more dialogs
specifying the name and color you entered, then you will see a landing page that
resembles Fig 8-18 and uses the background color you entered.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-38

JavaScript Specialist

Figure 8-18: Landing page for lab8-3.htm

9.

Internet Explorer Browser: Reload the file. Repeat Steps 5 and 6 by entering the
same information, but this time, when asked if you want to delete the cookie, click
OK to delete it. You will see the dialog shown in Figure 8-19.

Figure 8-19: Cookie deleted

10. Internet Explorer Browser: Click OK or Yes. This sets the expired cookie, which
replaces (deletes) the existing cookie with the same name. Because this new cookie
has an expired date, it is automatically deleted from your system when you restart
Internet Explorer.
11. Internet Explorer Browser: Click OK to continue. The cookie is gone. You will see
the same dialogs recapping your entries, then the same landing page that specifies
your information.
12. Firefox Browser: Open lab8-3.htm in Firefox, and perform the same steps to accept
the cookie. It should perform as it did in Internet Explorer. However, when you click
OK to delete the cookie, notice that no cookie information appears in the prompts or
the final page. The reason for this is that Firefox disposes of the cookie immediately;
it will not run the expired cookie at all. By contrast, Internet Explorer will retain the
expired cookie for the session, displaying its information now, then delete it when you
close the browser.
In this lab, you learned how to set a cookie. You also learned that an easy method for
deleting a cookie is to replace it with an expired one.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-39

Examining Lab 8-3


This lab demonstrated setting and retrieving cookie values. You learned how to set a
cookie, delete a cookie, and apply the value from a cookie to the X/HTML document.
Following is an examination of the first three lines of code from the this lab:
var myColor = prompt("Please enter a hexadecimal color code (must be 6
characters, including 0 thru 9 and A thru F):","FFFFFF");
var myName = prompt("Please enter your name:","Cookie Monster");
if ((myColor == null) || (myColor == "") || (myColor.length < 6 ||
myColor.length > 6)) myColor = "#ffffff";

The first two lines declare the variables myColor and myName, and assigns them the
values of the user's input captured by the prompt dialog boxes. The third line checks the
variable myColor for various conditions, and assigns it a default value in case any of
those conditions are true. The next line of code creates and assigns a value to a cookie:
var keepCookie = (confirm("A cookie will be set. Delete cookie?")) ?
"delete" : "keep";

The variable keepCookie is declared and assigned the result of a confirm() method. The
value delete is assigned if the user chooses to delete the cookie (by clicking the OK
button), or the value keep is assigned if the user chooses to keep the cookie (by clicking
the Cancel button). Next, the code contains an if...else statement, as follows:
if (keepCookie == "delete") {
document.cookie="testCookie=" +"YColor=" + myColor + " " + "name=" +
myName + ";expires=20-May-2010";
message= "Here is the cookie that was deleted: ";
message += document.cookie;
alert(message);
}

If the variable keepCookie equals delete, the cookie named testCookie is assigned a
backdated expiration date. The non-existent cookie is then displayed to the user. If the
variable keepCookie equals keep, the cookie is again displayed to the user. Next are the
following lines of code:
var start = document.cookie.indexOf("YColor=");
start=start + 7;
var pos = document.cookie.substr(start,6);
alert("Your background color will be: " + pos);

These lines of code extract the value portion of the cookie and assign that value to the
variable color. The indexof() method searches for the first instance of a string. In the
case of the color, the code designates YColor= to ensure it is unique, and that more than
one variable may be stored in the cookie. Then the number of characters of YColor
(which is six) is added to the variable start to ensure that when the variable is placed, it
will begin in the correct position. The following line of code pulls the hexadecimal value
(color) from the cookie:
"var pos = document.cookie.substr(start,6);"

This program could have simply used the variable myColor as a value for the color
variable. However, learning another method of extracting a value from a cookie
name=value pair is beneficial because you sometimes do not have access to the cookie's
value, as you did in this program.
Be cautious when using the substr and substring methods. They do two similar but
different things. The substring(start-index,stop-index) method uses the starting
point and the ending point to determine substring. By contrast, the substr(startindex,length) method uses the starting point and the length to determine the

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-40

JavaScript Specialist

substring. Thus these similar methods can lead to two drastically different results.
Be sure that you are using the correct method in your code.

The following line of code is located in the body of the document:


if ((myColor == null) || (myColor == "") || (myColor.length < 6 ||
myColor.length > 6)) myColor = "#ffffff";

This line assigns a value to the color variable in case the user has deleted the cookie.
The remaining lines in the program assign the color variable as the value for
document.bgColor and output the appropriate values to the screen.

Cookies and passwords


OBJECTIVE
3.3.9: Cookies for
password protection

Cookies provide a way to create simple password protection on a Web page or series of
pages. You can even set the cookie to remember the password access so the user does
not need to log in again when he or she returns to the page(s). However, remember that
this type of return access can defeat the purpose of protection if an unauthorized user
sits at the computer and uses the previously granted access. This type of password
protection offers a small measure of security, but is not appropriate for mission-critical
data or any other information that is important to keep private.
In the following lab, you will store a password in a cookie. Note that the functionality
demonstrated by this lab should only be used for sites or pages that do not require strict
security. Suppose you are part of the festivity committee at your office. Your group plans
parties and celebrations for everyone in the office, during the holidays and on people's
birthdays. Because you work for the company's Web development team, the committee
members ask you to post a simple Web page on the company intranet for the festivity
committee's use. The page will include details about parties that the committee is planning,
committee member assignments, and lists of holidays and employee birthdates. This
information is not top secret, but the committee does try to keep plans quiet so that festivities
can be a surprise for the employees. So you incorporate some JavaScript into the page that
requires the user to enter a password to access the page. Only festivity committee members
are given the password, and they are asked not to share it. Now you can keep party plans a
surprise, but there will not be any serious trouble if an unauthorized user cracks the page.

Lab 8-4: Setting passwords with cookies


OBJECTIVE
3.3.9: Cookies for
password protection

In this lab, you will use a cookie that allows access to a second XHTML page. If the cookie
is present in the password-protected page and the user enters the correct password
value, then the user will be allowed to view the page. If the password is incorrect, the
user will be returned to the previous page.
1.

Editor: Open the lab8-4.htm file from the Lesson_8 folder of the Student_Files
directory.

2.

Editor: Scroll down in the source code and examine the following code:
<form name="myForm" id="myForm">
<input type="text" name="pWord" />
<p>
<input type="button" value="Submit" onclick="storePass(this.form);" />
<input type="Reset" />
</p>
</form>

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

3.

8-41

Editor: Locate the existing <script> tags in the <head> section of the document.
Locate the comment that reads as follows:
// Create cookie here

Create a cookie named password and assign as its value the user's entry in the
pWord text box.
4.

Editor: The following code shows the storePass() function before your changes:
<script language="JavaScript">
<!-function storePass(form) {
// Create cookie here
alert(document.cookie);
location.href = "lab8-4a.htm";
}
//-->
</script>

5.

Editor: Save lab8-4.htm.

6.

Editor: Open lab8-4a.htm from the Lesson_8 folder of the Student_Files directory.
Examine the following code in the <head> section of the file:
<script language="JavaScript">
<!-all = document.cookie;
if (all.indexOf("password=hello") != -1){
alert("You entered the correct password. Proceed.");
} else {
alert("Incorrect password. Return and re-enter.");
location.href = "lab8-4.htm";
}
//-->
</script>

7.

Editor: Close lab8-4a.htm.

8.

Browser: Open lab8-4.htm. Your screen should resemble Figure 8-20.

Figure 8-20: Page for lab8-4.htm

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-42

JavaScript Specialist

9.

Browser: Enter the password hello and click the Submit button. This calls the
storePass() function that stores your password into a cookie. Accept the cookie (if
you are warned). You should then see the alert dialog box shown in Figure 8-21.

Figure 8-21: Alert dialog box

10. Browser: The alert shows the password name=value pair that you entered in the
page. (It may also show information from a previous cookie used in another lab; that
information will disappear after the associated cookie is cleared from memory.) Click
OK to continue. You should see another alert with the cookie's name=value pair, and
then the alert dialog box shown in Figure 8-22.

Figure 8-22: Alert dialog box

11. Browser: Click OK to continue. You will see the password-protected page, as shown
in Figure 8-23.

Figure 8-23: Password-protected page (lab8-4a.htm)

12. Browser: To ensure that your script works for both correct and incorrect passwords,
click the Return link to return to the previous page.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-43

13. Browser: Enter an incorrect password and click the Submit button. After the alert
displaying the cookie's name=value pair, you should see the message shown in
Figure 8-24.

Figure 8-24: Alert dialog box

14. Browser: Click OK to continue. Rather than seeing the password-protected page (file
lab8-4a.htm), you should be returned to the page where you entered your password
(file lab8-4.htm).
Tech Note: This lab is for demonstration purposes only. Any sensitive content in a Web
application should not be protected with the mechanism shown in this lab.

Examining Lab 8-4


The preceding lab demonstrated another use of cookies. After you created the cookie
named password, an alert displayed the cookie value to the user, and a location.href
statement sent the user to the password-protected page. Following is the code from the
file lab8-4a.htm:
all = document.cookie;
if (all.indexOf("password=hello") != -1){
alert("You entered the correct password. Proceed.");
} else {
alert("Incorrect password. Return and re-enter.");
location.href = "lab8-4.htm";
}

An alert displays the cookie's contents to the user. Next, a variable named all is
assigned the value held in the cookie. An if...else statement then checks the string
held in the variable all and sends the user back to lab8-4.htm if an incorrect password
was entered. The most important line of code from this operation is the following:
if (all.indexOf("password=hello") != -1){

The indexOf() method is used to search the variable all for the string password=hello.
The indexOf() method returns the integer -1 if it does not find the specified string
("password=hello"). So if the integer returned by indexOf()is not equal to -1, then the
cookie string must contain the string password=hello, meaning the user entered the
correct password.
The preceding lab was presented for demonstration purposes only. Any sensitive
content in a Web application should not be protected with the mechanism shown in
this lab. It is much safer to store user names and passwords in a database. Server-side
scripting in conjunction with the operating system's security features would then be
used to authenticate and authorize users.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-44

JavaScript Specialist

Creating Secure JavaScript Code


OBJECTIVE
3.3.5: Secure
JavaScript code

JavaScript is an interpreted language. It sends and receives its instructions in cleartext,


and can therefore be read by looking at source code or downloading the .js files.
JavaScript security for the end-user is rather straightforward: You can deny it, or you
can allow it and accept the risks. For the developer, there is more to consider.
JavaScript code can be used maliciously, accidentally or irresponsibly to produce
undesirable results. However, there are also practices you can follow to ensure that the
code you create and use in your Web pages is secure for your users. As you develop your
Web pages, keep the following tips in mind to make your JavaScript as safe as possible:

Test, test, test your scripts. Test them yourself, in several browsers. Ensure that
each script runs as expected you should see nothing unexpected happening.

Keep current in your knowledge about JavaScript and its security. Use the
resources out there, do your reading and stay informed. For example, the Slashdot
site (www.slashdot.com) typically posts any zero-day exploits, giving you the chance
to repair them before your site(s) are compromised.

Do not use deprecated code. The W3C deprecates certain HTML tags when it
updates the standards, often due to security issues. Many developers continue to use
deprecated tags as workarounds for older browsers, but this practice hinders
forward-compatibility and can leave your pages vulnerable to exploits. If you are
responsible for a Web site, you should update the pages to compliant XHTML (or at
least consistently code to HTML 4 Transitional). Cleanly written, current code is by
far your best defense. And when your X/HTML is up-to-date, your JavaScript
performs better.

Use proper encoding and validation practices. As you learned with cross-site
scripting, creating code that follows rigorous syntax standards and checking
practices can protect your site and your users from certain types of attacks. Use
the tools provided by reputable organizations to help with these tasks.

Know the code you are using before putting it on a Web site. Do not simply copy
and paste code that promises to do what you need carefully examine it first. You
can find very useful code on the Internet, but you must understand how it works
prior to using it.

Write your code consistently, so the next developer who works with it can
understand your code and why you wrote it in the way you did.

Comment your code liberally. Comments that explain where or how things are
coded help the next developer who works with your code. Also, if a security issue
occurs, you can find it easier and faster in well-written, well-documented code.

Keep security patches up-to-date. This goes not only for browsers and operating
systems, but databases as well. If you are maintaining a database, update its
security patches. Many database hacks (called SQL injection) begin with a security
hole in your page code either X/HTML or JavaScript. Hackers can place malicious
code right into the database. This makes the attack much more difficult to discover
and clean, because your source code still looks perfect.

Keep your operating system up-to-date as well. Many computers are now sold preloaded with a specific version of the operating system, and the buyer must purchase
any OS upgrades. Bear this in mind when purchasing a computer the best time to
buy might be right after a new OS becomes available.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

8-45

Version 1.01

8-46

JavaScript Specialist

Case Study

Does Insecure Code Have Low Self-Esteem?


Phil is one of the most careful Web developers, programmers and teachers you would ever
meet. Before he even thinks of releasing JavaScript code, he tests it in UNIX and Mac,
and with several browsers in Windows. He is an open-source advocate, so when he finds
JavaScript code that does not work with freeware, he makes sure to tell everyone far and
wide. When other developers work around Phil, they are very cautious before they show
him any code because if the code has any issues, Phil is sure to find them.
Phil's particular pet peeve is Microsoft Internet Explorer. In his opinion, Internet Explorer
has never worked properly and makes a developer's job harder because it uses the
JScript flavor instead of standard JavaScript. So whenever he tests JavaScript code, the
first thing he does is check it on Internet Explorer because this browser is most likely to
show any issues.
As he tests the code in IE, he looks for security problems that he can exploit, and he
resolves the issues in the code. When the script runs clean and he cannot find any
security issues, it has passed his IE test, and he will then check the code in several other
browsers and platforms, looking for errors. Only after it has passed his testing in all
these browsers will he deem the code acceptable. In private, he will then check the code
in Netscape Navigator 4, which he believes was the best browser ever built.
One day, another developer named Dave brought Phil a snippet of code that included
cookies and used the document.write method for URL redirects. It ran fine in all browsers
except Internet Explorer. Although it appeared to be ok, the code had vulnerabilities.
As Phil wrote his deficiency report, he noted that Dave is a strong Microsoft advocate, and
that Dave's code had shown glaring security deficiencies and was easily exploitable.
Phil then sent Dave an anonymous e-mail message reminding him to research his script
for holes, test his code in multiple browsers, and check for zero-day exploits. And Phil
used Dave's code snippet to include an enticing link in the e-mail with an XSS exploit,
just to show how unsecure the script was. He wanted to remind Dave how careful you
need to be with JavaScript, since users can see your code.
*

Consider this scenario and answer the following questions.

What type of code or functionality did Dave's script include, and how was Phil able to
exploit it? (Hint: Cookies store information from the user, which can persist a long
time. Cross-site scripting [XSS] can place a user's input on a Web page.)

When Dave tested his code in IE, why didn't he find the problem that Phil found?

What steps should Dave have taken to avoid this issue?

What are some reasons to use JavaScript cookies? What are some reasons not to use
them? Note that you can create more secure cookies with another language, Dynamic
HTML (DHTML).

Name the three main browsers and the two platforms that you should always test
your code on, and why.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-47

Lesson Summary
Application project
This project will challenge you to use some of what you have learned in this lesson.
Create an XHTML page with a form. The form will contain a text box for the user's name
and a Submit button. Create a function in the <head> section of the document that will
set a cookie to the user's name submitted via the text box.
Add JavaScript code to the <form> tag. Use the onsubmit event handler to call the
function that creates the cookie. Create code that informs the user if the name field is left
blank. If the name field has a value, pass the user's name in the function call. In both the
if clause and the else clause, use a return false statement to negate the submission
of the form. The setting of the cookie is all that should occur for the submit event.
Add another button to the XHTML form. Use an onclick event handler with this
scriptable button to open a new window. Write code that will display the user's name
(extracted from the cookie) in a welcome message in the document of the new window.

Skills review
In this lesson, you learned that determined hackers can manipulate JavaScript's inherent
qualities to generate undesirable results. Therefore, many users choose to block scripts
from their browsers. JavaScript is implemented differently in various browsers, resulting
in incompatible code, workarounds, and differing implementations, such as
document.write behavior. Malicious and accidental coding can cause problems such as
locking the browser or launching helper applications. JavaScript can be used for frameto-frame URL changing, which poses security concerns. Signed scripts provide a
mechanism whereby programs can perform operations that were considered security
risks in previous versions of JavaScript. JavaScript can also be used for cross-site
scripting. Cookies are small pieces of information sent to a client computer in the HTTP
response header and stored in the browser. Subsequent requests from the client can
include the cookie information in the HTTP request header. Servers can then use that
information for a variety of purposes, including storage of user preferences, user
validation or maintenance of user state. Users can choose which cookies to accept or to
reject them all by adjusting the settings in the browser. Finally, you reviewed many
techniques and practices for developing secure JavaScript code.
Now that you have completed this lesson, you should be able to:

3.3.1: Distinguish between the browser and the operating system in relation to the
elements responsible for security.

3.3.2: Discuss browser security issues relevant to JavaScript, including script


blocking, frame-to-frame URL changing, and document.write behavior differences
among browsers.

3.3.3: Define signed scripts.

3.3.4: Perform client-side browser detection and determine browser compatibility.

3.3.5: Identify common issues and procedures for creating secure JavaScript code.

3.3.6: Define cross-site scripting and the associated security risks.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-48

JavaScript Specialist

3.3.7: Define the functions of cookies and manipulate them effectively, including
testing for presence of cookies, clearing cookies, enabling/disabling cookies in the
browser, and deleting cookies from your hard drive.

3.3.8: Assign a cookie using JavaScript.

3.3.9: Use cookies and passwords to restrict entry to a page.

Lesson 8 Review
1.

How does the browser differ from the operating system in relation to the elements
responsible for security in a computer system?

2.

Name two ways that JavaScript can be used maliciously (or accidentally) on the Web.

3.

What is a signed script?

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-49

4.

What is cross-site scripting? Name at least one associated security risk.

5.

What is a cookie?

6.

What abilities does JavaScript offer the developer in relation to cookies?

7.

How are cookies sent? What two actions concerning cookies can occur when a user
generates an HTTP request?

8.

How can cookies aid user authentication?

9.

What types of information about a client can a cookie obtain?

10. How can cookies aid state maintenance?

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-50

JavaScript Specialist

11. How can you test for the presence of a cookie? What information is returned when
you do this?

12. How does a cookie appear in an HTTP response header?

13. How would two cookies appear in a client's HTTP request header?

14. Describe the best mechanism for deleting a JavaScript cookie.

15. Write JavaScript code to create a function that sets a cookie named user that uses
the user's input from the following form field as its value:
<form name="myForm">

Enter Name:

Set an expiration date of Saturday, December 31, 2011 at one second before
midnight. Also, set the path to root (/) and indicate that a secure protocol should be
used for the cookie.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

Lesson 8: JavaScript Security

8-51

16. Consider the following malicious JavaScript code:


var myColors = new Array;
myColors[0] = "#FF0000";
myColors[1] = "#00FF00";
myColors[2] = "#0000FF";
for(var i = 0; i < myColors.length; i++){
document.bgColor = myColors[i];
if(i == 2){
i = 0;
}
}
Describe this malicious JavaScript code.

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

Version 1.01

8-52

2011 Certification Partners, LLC. All Rights Reserved.


Authorized to be used in American Public University System.
To report abuse, go to www.CIWcertified.com/abuse.

JavaScript Specialist

Version 1.01

Вам также может понравиться