Snippets Of Defense Pt.I
This article is the start of a series of posts about small and easy to understand code fragments you can use on your site for protection against certain kinds of attacks. Also this series is targeted to help you understand better what tricks are used by attackers to break your site and how to avert this. If you have a Snippet of defense yourself and want to share it feel free to contact us.
The first snippet - overwrite alert() wit a logger
The JavaScript method alert() is mostly used for debugging purposes and very rarely found in live applications. Attackers though very often use this method for initial probing for XSS vulnerabilities on websites and web applications. Most PoCs found in forums and newsgroups make use of this method and meanwhile you can even find tons of links including alert()-based PoCs via Google.
So combining those facts puts up the question why not overwrite the alert()
method with a method that logs the request - which probably was fired by an attacker. First, we know that the attacker managed to inject JavaScript on our page because the modified alert() method has been executed. And second you logger script will tell you all you need to know about the malicious request. So here we go - place this code in between script tags inside your application's header or add it inside your application's JavaScript files:
var old_alert = alert;
alert = function(a) {
var img = new Image();
img.src = 'http://the/uri/to/your/logger/file';
img.style.height = 0;
img.style.width = 0;
document.body.appendChild(img);
old_alert(a);
return false;
}
Till the next time.
Archived Comments
alert=old_alert;alert("test");
but i know you didn't intended this as a silver bullet, more like a kiddie protection. wisec has published some info on how to block the fetch/set of a cookie value for geko based browsers, it's more generic than trap alert()
http://www.wisec.it/sectou.php?id=44c7949f6de03
it can be bypassed too using frames and other techniques (eg: you can try everything but if it's hooked in js it can also be reverted to the original in js). anyway why not? it's cheap! i'm going to implement both on my sities
ps: pdp make this textbox larger please : )javascript:(function(){var i,x; for(i=0;x=document.getElementsByTagName(%22textarea%22)[i];++i) x.cols += 150; })()
alert = (function(){
var old_alert = alert;
return function(m){
// logging goes here
old_alert(m);
}
})();
then by-passing would be a little harder. This is creating private members thru closures.(new function () {
return function (self) {
// your code here
};
})(this);
This is almost like self executing, self destructive code. sweet!