Search code examples
javascriptjqueryxsshtml-sanitizing

option.text() is vulnerable to xss in my example fiddle


Why am I getting the alert box in

    $(function() {  
      $('#users').each(function() {  
        var select = $(this);  
        var option = select.children('option').first();  
        select.after(option.text());  
        select.hide();  
      });  
    });  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="users" name="users">  
    <option value="bad">&lt;script&gt;alert(&#x27;xss&#x27;);&lt;/script&gt;</option>  
</select>  

though I have the encoded version (&lt;script&gt;alert(&#x27;xss&#x27;);&lt;/script&gt;) in the option text ??

I am trying to prevent showing the alert because I have encoded html in the option text.Can someone tell me what am i missing?

https://jsfiddle.net/hf1fbhmg/


Solution

  • I have encoded html in the option text.

    That doesn't matter because you are getting a text representation of it (with text()). (Even if you were getting an HTML representation, the rules for how browsers convert the text in the DOM back to HTML might give you unexpected results anyway).

    You then use select.after(that_text);. If you pass a string that looks like HTML (which you are) to after then jQuery will treat it as HTML. You need to explicitly treat it as text.

    For example:

    select.after(
        jQuery("<span />").text(that_text)
    );