2

I am trying to create a very simplistic XSS detection system for a system I am currently developing. The system as it stands, allows users to submit posts with javascript embedded within the message. Here is what I currently have:-

var checkFor = "<script>";
alert(checkFor.indexOf("<script>") !== -1);

This doesn't really work that well at all. I need to write code that incorporates an array which contains the terms I am searching for [e.g - "<script>","</script>","alert("]

Any suggestions as to how this could be achieved using JavaScript/jQuery.

Thanks for checking this out. Many thanks :)

4

3 回答 3

2

Replacing characters is a very fragile way to avoid XSS. (There are dozens of ways to get < in without typing the character -- like &#60; Instead, HTML-encode your data. I use these functions:

var encode = function (data) {
    var result = data;
    if (data) {
        result = $("<div />").html(data).text();
    }
};
var decode = function (data) {
    var result = data;
    if (data) {
        result = $("<div />").text(data).html();
    }
};
于 2013-03-29T21:33:03.733 回答
0

As Explosion Pills said, if you're looking for cross–site exploits, you're probably best to either find one that's already been written or someone who can write one for you.

Anyway, to answer the question, regular expressions are not appropriate for parsing markup. If you have an HTML parser (client side is easy, server a little more difficult) you could insert the text as the innerHTML of an new element, then see if there are any child elements:

function mightBeMarkup(s) {
  var d = document.createElement('div');
  d.innerHTML = s;
  return !!(d.getElementsByTagName('*').length);
}

Of course there still might be markup in the text, just that it's invalid so doesn't create elements. But combined with some other text, it might be valid markup.

于 2013-03-29T21:29:10.463 回答
-1

The most effective way to prevent xss attacks is by replacing all <, > and & characters with &lt;, &gt;, and &amp;.

There is a javascript library from OWASP. I haven't worked with it yet so can't tell you anything about the quality. Here is the link: https://www.owasp.org/index.php/ESAPI_JavaScript_Readme

于 2013-03-29T21:28:07.533 回答