20080523

document.write()

These days I am working on Ajax, learning how to do simple HTTP request through Ajax.
Accidentally, I found an interesting property that js has: document.write(). Some of you may already know how to use it to do evil thing, but it is really new to me and I would like to share it with you.

document.write() is a function in js going to write data into the browsing page. The interesting point of this function is that it will overwrite the original HTML file. Let see an example using it with HTTP request.
Let say we have a evil.html containing a piece of code as follow.
<html>
<script type="text/javascript">
function fetch() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("You Win!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.write(xmlHttp.responseText);
document.close();
}
}
xmlHttp.open("GET", "index.html", true);
xmlHttp.send(null);
return true;
}
</script>
<body onload="javascript:fetch()">

</body>
</html>

The index.html file that evil.html want to get is a normal page. Once a user going to browse evil.html, the script will replace evil.html as index.html. The code above is no harm at all. It tried to request the index.html under the same directory. However, it can easily be used to do malicious thing. Consider we add some code before getting the index.html, eg.
userInfoRequest = new XMLHttpRequest();
userInfoRequest.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var content = userInfoRequest.responseText;
/* send the content to somewhere hacker want to store it */
}
}userInfoRequest.open("GET", "user_info.html", true);
userInfoRequest.send(null);
You can imagine what's going on with this piece of code. I am going to find a vulnerable site that allow me to demo this malicious code. I will back on this topic soon.

Should you have any comment or idea or whatever interesting stuff, please feel free to share with me.

No comments: