Академический Документы
Профессиональный Документы
Культура Документы
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.5: Identify common issues and procedures for creating secure JavaScript code.
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.
8-2
JavaScript Specialist
Pre-Assessment Questions
1.
2.
3.
navigator
AppName
BrowserType
UserAgent
Signed script
Cross-site scripting
Client-side browser detection
Frame-to-frame URL changing
What is a cookie?
Version 1.01
8-3
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 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.
Version 1.01
8-4
JavaScript Specialist
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.
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.
Version 1.01
8-5
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
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.
Explain functionality on your site if you think it may concern your users.
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,
Version 1.01
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.
Although using browser detection may seem to solve the browser-compatibility problems
of your Web pages, it has some disadvantages, such as:
Misidentifying browsers.
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.
Version 1.01
8-9
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.
4.
Browser: Open the file lab8-1.htm. You will see a pop-up window similar to the one
shown in Figure 8-1.
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.
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">' +
Version 1.01
8-11
+
+
+
+
Version 1.01
8-12
JavaScript Specialist
</body>
</html>
7.
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.
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.
Version 1.01
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.
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.
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.
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.
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.
Version 1.01
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.
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--)
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.
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.
3.
4.
5.
Browser: Open lab8-2.htm. You will see an alert dialog box as shown in Figure 8-4.
Version 1.01
8-17
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.
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.
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.
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
Version 1.01
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.
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.
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
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).
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:
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
Version 1.01
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.
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.
Version 1.01
8-22
JavaScript Specialist
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.
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
Version 1.01
8-23
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.
Types of XSS
There are three general types of XSS, which are described in Table 8-1.
Version 1.01
8-24
JavaScript Specialist
XSS Type
Description
Example
Reflected
(NonPersistent)
Persistent
XSS Type
Description
Example
DOM-Based
Version 1.01
8-25
prevent you from becoming a victim of XSS and other exploits, such as "phishing."
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:
Opening angle bracket or "less than" symbol ( < ) encode as < or <
Closing angle bracket or "greater than" symbol ( > ) encode as > or >
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.
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.
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.
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
Version 1.01
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.
Any cookies already on the client's system that match the server's domain can be
passed along in the request 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.
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
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.
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.
Version 1.01
Provide authentication.
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.
Service provider
IP address
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
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).
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
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:
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:
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.
Version 1.01
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.
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";
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.
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.
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.
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.
Version 1.01
8-33
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.
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.
Version 1.01
8-34
JavaScript Specialist
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.
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.
Version 1.01
8-35
You can allow, disallow and view cookies from this dialog. You can also set specific
exceptions for the cookies you will allow.
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.
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
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.
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);
Version 1.01
8-37
document.write();
//-->
</script>
</body>
</html>
3.
4.
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.
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.
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.
Version 1.01
8-38
JavaScript Specialist
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.
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.
Version 1.01
8-39
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
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.
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 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.
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>
Version 1.01
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.
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.
8.
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.
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.
11. Browser: Click OK to continue. You will see the password-protected page, as shown
in Figure 8-23.
12. Browser: To ensure that your script works for both correct and incorrect passwords,
click the Return link to return to the previous page.
Version 1.01
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.
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.
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.
Version 1.01
8-44
JavaScript Specialist
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.
Version 1.01
8-45
Version 1.01
8-46
JavaScript Specialist
Case Study
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 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.
Version 1.01
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.5: Identify common issues and procedures for creating secure JavaScript code.
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.
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.
Version 1.01
8-49
4.
5.
What is a cookie?
6.
7.
How are cookies sent? What two actions concerning cookies can occur when a user
generates an HTTP request?
8.
9.
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?
13. How would two cookies appear in a client's HTTP request header?
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.
Version 1.01
8-51
Version 1.01
8-52
JavaScript Specialist
Version 1.01