peppertech
peppertech

Reputation: 605

Trying to create a DOM based XSS example

I'm trying to learn more about XSS prevention and in doing so, wrote some really simple javascript that I thought would allow XSS

<label id="searchLbl" for="search">Search</label>
<input id="search" autocomplete="off"/>

<div id="results"></div>

<script>
   document.getElementById('search').addEventListener('keypress', function(e) {
   var code = e.keyCode || e.which;
       if (code === 13) { 
           document.getElementById('results').innerHTML = document.getElementById('search').value;
            }
        });
</script>

This code works fine for taking what I type into the input field and showing it in the results div. However, if I try typing in:

<script>alert("Failed");</script>

Both Chrome (v31) and Firefox(v25.0.1) refuse to set the div's innerHTML to the value. It appears that any string that has a < character in it, is truncated at the first instance of the character.

Using jQuery instead of JavaScript fails as I would expect.

$('#results').html($('#search').val());

What am I missing?

Upvotes: 0

Views: 2106

Answers (1)

AlliterativeAlice
AlliterativeAlice

Reputation: 12587

Injecting JavaScript code in a <script> tag into the DOM doesn't cause the code to be executed. Inline <script> tags are only executed when the page is loaded.

Nothing is being truncated at the < character. You can see that if you try to inject HTML such as <b>test</b>

If you want to perform XSS using <script> tags, you would have to do something like make a request to the page with the HTML in a query string parameter, and then echo it onto the page with a serverside language like PHP.

Upvotes: 1

Related Questions