Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code example copied into a pre-tag gets executed

I'm trying to add a piece of javascript code to a certain <div>. I enclosed the code in pre and code tags, but when I actually run this the code gets executed. Obviously, that's not what I want at all.

    var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
    code = code + '<script type="text/javascript">\n';
    code = code + '\tadimp.id = ' + 1 + ';\n';
    code = code + '\tadimp.type = ' + 1 + ';\n';
    code = code + '\tadimp.generate();\n';
    code = code + '<\/script></code></pre>';

    $("#code").html(code);
like image 321
skerit Avatar asked Jan 19 '23 02:01

skerit


2 Answers

You should use &lt; and &gt; for < and > in this case. Try this

var code = '<pre><code>&lt;script type="text/javascript" src="http://source.com/test.js"&gt;&lt;\/script&gt;\n';
    code = code + '&lt;script type="text/javascript"&gt;\n';
    code = code + '\tadimp.id = ' + 1 + ';\n';
    code = code + '\tadimp.type = ' + 1 + ';\n';
    code = code + '\tadimp.generate();\n';
    code = code + '&lt;\/script&gt;</code></pre>';

 $("#code").html(code);
like image 150
ShankarSangoli Avatar answered Feb 23 '23 04:02

ShankarSangoli


Surprise! You just manufactured your own XSS vulnerability. Always HTML-encode any data you put into HTML. ("data" is anything you want to appear on screen.)

In the HTML DOM this is thankfully completely automatic. Just use the text property, not the HTML property.

var code = [
        '<script type="text/javascript" src="http://source.com/test.js"><\/script>',
        '<script type="text/javascript">',
        '\tadimp.id = ' + 1 + ';',
        '\tadimp.type = ' + 1 + ';',
        '\tadimp.generate();',
        '<\/script>'
    ].join('\n');

$('#code').text(code);
// --------^^^^

Live demo: http://jsfiddle.net/6qdBD/3/

like image 41
Tomalak Avatar answered Feb 23 '23 04:02

Tomalak