Home arrow JavaScript arrow JavaScript Security

JavaScript Security

JavaScript has a long and inglorious history of atrocious security holes. Its security problems are not limited to implementation errors. There are numerous ways in which scripts can affect the user’s execution environment without violating any security policies. This chapter examines the security policies browsers enforce on JavaScript embedded in Web pages. (From JavaScript: The Complete Reference, second edition, by Thomas Powell and Fritz Schneider McGraw-Hill/Osborne, ISBN: 0072253576.)

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 107
October 04, 2004
  1. · JavaScript Security
  2. · Exceptions to and Problems with Same-Origin Policy
  3. · Signed Scripts in Mozilla Browsers
  4. · Signed Script Practicalities
  5. · Security Zones in Internet Explorer
  6. · ActiveX Controls
  7. · Browser Security Problems with JavaScript
  8. · Cross-Site Scripting
  9. · Preventing Cross-Site Scripting

print this article

JavaScript Security
(Page 1 of 9 )

PowellDownloading and running programs written by unknown parties is a dangerous proposition. A program available on the Web could work as advertised, but then again it could also install spyware, a backdoor into your system, or a virus, or exhibit even worse behavior such as stealing or deleting your data. The decision to take the risk of running executable programs is typically explicit; you have to download the program and assert your desire to run it by confirming a dialog box or double-clicking the program’s icon. But most people don’t think about the fact that nearly every time they load a Web page, they’re doing something very similar: inviting code—in this case, JavaScript—written by an unknown party to execute on their computer. Since it would be phenomenally annoying to have to confirm your wish to run JavaScript each time you loaded a new Web page, the browser implements a security policy designed to reduce the risk such code poses to you.

A security policy is simply a set of rules governing what scripts can do, and under what circumstances. For example, it seems reasonable to expect browsers’ security policies to prohibit JavaScript included on Web pages downloaded from the Internet from having access to the files on your computer. If they didn’t, any Web page you visited could steal  or destroy all of your files!

In this chapter we examine the security policies browsers enforce on JavaScript embedded in Web pages. We’ll see that these policies restrict JavaScript to a fairly benign set of capabilities unless the author of the code is in some way “trusted,” though the definition of “trusted” can vary from browser to browser, and is in any case a somewhat suspect notion.

JavaScript Security Models

The modern JavaScript security model is based upon Java. In theory, downloaded scripts are run by default in a restricted “sandbox” environment that isolates them from the rest of the operating system. Scripts are permitted access only to data in the current document or closely related documents (generally those from the same site as the current document). No access is granted to the local file system, the memory space of other running programs, or the operating system’s networking layer. Containment of this kind is designed to prevent malfunctioning or malicious scripts from wreaking havoc in the user’s environment. The reality of the situation, however, is that often scripts are not contained as neatly as one would hope. There are numerous ways that a script can exercise power beyond what you might expect, both by design and by accident.

The fundamental premise of browsers’ security models is that there is no reason to trust randomly encountered code such as that found on Web pages, so JavaScript should be executed as if it were hostile. Exceptions are made for certain kinds of code, such as that which comes from a trusted source. Such code is allowed extended capabilities, sometimes with the consent of the user but often without requiring explicit consent. In addition, scripts can gain access to otherwise privileged information in other browser windows when the pages come from related domains.

The Same-Origin Policy

The primary JavaScript security policy is the same-origin policy. The same-origin policy prevents scripts loaded from one Web site from getting or setting properties of a document loaded from a different site. This policy prevents hostile code from one site from “taking over” or manipulating documents from another. Without it, JavaScript from a hostile site could do any number of undesirable things such as snoop keypresses while you’re logging in to a site in a different window, wait for you to go to your online banking site and insert spurious transactions, steal login cookies from other domains, and so on.

The Same-Origin Check

When a script attempts to access properties or methods in a different window—for example, using the handle returned by window.open()—the browser performs a same-origin check on the URLs of the documents in question. If the URLs of the documents pass this check, the property can be accessed. If they don’t, an error is thrown. The same-origin check consists of verifying that the URL of the document in the target window has the same “origin” as the document containing the calling script. Two documents have the same origin if they were loaded from the same server using the same protocol and port. For example, a script loaded from http://www.example.com/dir/page.html can gain access to any objects loaded from www.example.com using HTTP. Table 22-1 shows the result of attempting to access windows containing various URLs, assuming that the accessing script was loaded from http://www.example.com/dir/page.html.

URL of Target Window

Result of Same Origin Check with www.example.com Reason

http://www.example.com/ index.html


Same domain and protocol

http://www.example.com/ other1/other2/index.html


Same domain and protocol


Does not pass

Different port

http://www2.example.com/ dir/page.html

Does not pass

Different server


Does not pass

Different domain


Does not pass

Different protocol

TABLE 22-1 Listing of Same-Origin Check Results Assuming the Calling Script Is Found in the Document http://www.example.com/dir/page.html

Consider the following example:

var w = window.open(http://www.google.com);
// Now wait a while, hoping they'll start using the newly opened window.
// After 10 seconds, let's try to see what URL they're looking at!
var snoopedURL;
setTimeout("snoopedURL = w.location.href)", 10 * 1000);

Because of the same-origin policy, the only way this script will work is if it’s loaded from www.google.com. If you load it from your own server, the attempt to access the Location object will fail because your domain doesn’t match www.google.com (or whatever domain the user happens to be visiting). The attempt to access the Location object will similarly fail if you save the script to your local disk and open it from there, but this time because the protocol doesn’t match (file:// versus http://). Internet Explorer 6 silently fails for this example, but the output in the JavaScript Console for Mozilla-based browsers is

Sometimes browsers don’t fail at all but instead “pretend” the violating call worked, and return undefined if the violation was trying to get a value. The bottom line is that violations of the same-origin policy result in unpredictable behavior.

Embedded Documents

The same-origin check is performed when trying to access the properties or methods of another Window object. Since each frame in a framed page has its own Window object, the same-origin policy applies to scripts attempting to access the content of frames. If two frames haven’t been loaded from the same site using the same protocol, scripts cannot cross the framed boundary.

The policy additionally applies to <iframe>s, as well as <layer>s and <ilayer>s in Netscape 4, and documents included with the <object> tag.

External Scripts

Externally linked scripts are considered part of the page they are embedded in, and thus can be linked in from other domains. That is, the same-origin policy applies only when scripts attempt to cross a Window boundary; you can link a script into a page with confidence that it will work even if loaded from some other site. For example, the page at http://www.somesite.com/index.html could include the following script:

<script type="text/javascript" src="http://www.example.com/scripts/somescript.js"></script>

This script will load and work as expected.

Be careful, since linked scripts are considered part of the page they’re linked into, if JavaScript in the file http://www.example.com/scripts/somescript.js tries to access another window, it will be subject to a same-origin check for the document it is a part of. That is, it is considered to have come from http://www.somesite.com/index.html, even though the script itself resides elsewhere.

McGraw-Hill-OsborneThis chapter is from JavaScript: The Complete Reference, second edition, by Thomas Powell and Fritz Schneider, McGraw-Hill/Osborne, ISBN: 0072253576). Check it out at your favorite bookstore today.

Buy this book now.

blog comments powered by Disqus

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials