Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an XSS attack possible when a script is displayed in an HTML textarea?

I have an HTML textarea in my UI (for a Java-based web app) where a user can enter any value. Once it is saved, it is displayed in the textarea (which is disabled) in the browser.

If a user enters any script as free text in the textarea, will it be executed as a script (even if the value is shown in the textarea, and not not as label/text)?

like image 949
emilly Avatar asked Oct 30 '13 05:10

emilly


1 Answers

That depends on how you set the value of the textarea. In the HTML code, the content of the textarea is the text inside the element.

I've created a JSFiddle to demonstrate various ways to change the content of a textarea

<div><textarea id="e1"></textarea></div>
<div><textarea id="e2"></textarea></div>
<div id="e3"/>

var dangerous = '<scri' + 'pt>alert("Danger!");</scri' + 'pt>';
document.getElementById('e1').value = dangerous;

document.getElementById('e2').innerHTML = dangerous;

dangerous = '</textarea>' + dangerous;
var content = '<textarea>' + dangerous + '</textarea>';
document.getElementById('e3').innerHTML = content;

console.log('Done.');

This creates two textarea elements with a script inside (save) and an empty one.

In the last test, I close the textarea in the input and then append the script. Interestingly enough, setting innerHTML is safe to use in this case: It doesn't execute scripts inserted in this way.

So as long as you do it in JavaScript, you're pretty safe. But usually, you render the DOM of the page on the server and then you must make sure you properly escape the content of the textarea because:

String unfilteredInput = "</textarea><script>alert(\"Danger!\");</script>";

out.write("<textarea>");
out.write(content);
out.write("</textarea>");

will execute the script.

Note: I also tried to demonstrate document.write() but that's not allowed in a JSFiddle. I'm pretty sure that document.write() is vulnerable to the same attack.

like image 86
Aaron Digulla Avatar answered Sep 17 '22 20:09

Aaron Digulla