RGS
RGS

Reputation: 4253

do I need to escape before append data

I have some simple jquery for a future chat system and I was wondering is it vulnerable to a XSS attack? Before appending what the user types, do I need to escape something in this example?

$("#textareadiv").on('keypress', function(e) {
var keyCode = (window.event) ? e.which : e.keyCode;

if(e.keyCode==13){
    e.preventDefault();

    var text2 = $("#textareadiv");
    var s = '<span class=right>'+text2+'</span>'; // can I just append this?

    $('#rightchat').append(s); // can I just append this?


}
});

Upvotes: 1

Views: 199

Answers (1)

Kaspar Lee
Kaspar Lee

Reputation: 5596

I put your code in a JSFiddle

Look at the Code Snippet below:

$('#textareadiv').val('<p>I am a "p" element </p>')

$("#textareadiv").on('keypress', function(e) {
    var keyCode = (window.event) ? e.which : e.keyCode;

    if (e.keyCode == 13) {
        e.preventDefault();

        var text2 = $("#textareadiv").val();
        var s = '<span class=right>' + text2 + '</span>'; // can I just append this?

        $('#rightchat').append(s); // can I just append this?


    }
});
#rightchat {
	float: right;
}

span {
    border: 2px solid #000;
	padding: 10px;
	display: block;
}

p {
    border: 1px dashed #FF0000;
	padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textareadiv"></textarea>

<div id="rightchat"></div>

The <span> elements ahve a block border, while the <p> elements have a dashed red border.

If you press enter with the default text added to the textbox, you will see that a <p> element has been added to the page. This means that if you do not escape what the user types, they could insert <script>s and you will be vulnerable to XSS attacks.


Here is an example on how to escape the string, using the code (removed from the functions) from this answer:

var escape = document.createElement('textarea');
escape.textContent = text2;
text2 = escape.innerHTML;

The new code:

$('#textareadiv').val('<p>I am a "p" element </p>')

$("#textareadiv").on('keypress', function(e) {
    var keyCode = (window.event) ? e.which : e.keyCode;

    if (e.keyCode == 13) {
        e.preventDefault();
        var text2 = $("#textareadiv").val()
        
        // Code to escape HTML code
        var escape = document.createElement('textarea');
        escape.textContent = text2;
        text2 = escape.innerHTML;
      
        var s = '<span class=right>' + text2 + '</span>'; // can I just append this?

        $('#rightchat').append(s); // can I just append this?


    }
});
#rightchat {
	float: right;
}

span {
    border: 2px solid #000;
	padding: 10px;
	display: block;
}

p {
    border: 1px dashed #FF0000;
	padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textareadiv"></textarea>

<div id="rightchat"></div>

Upvotes: 1

Related Questions