views:

40

answers:

2

is the following safe?

index.html

    <div id="loader">loading...</div>
    <div onclick="foo()">click me</div>
    <div id="change"></div>
     <script>
        function foo(){
           jQuery.ajax({
              url: 'get.html',
              success: function(txt){
                  var x = $('#loader').html(txt)
              x=$('loader').find('script').html()
              eval(x)
          }
       })
    }
    </script>

get.html

<div>Header</div>
<script>
   function newfoo(){
        $('#change').html('hello world')
   }
</script>

in theory this should work....

note: above may not work it's a demonstration only...

my question is: as the newFoo() will not be run by itself when the get.html is loaded due to some security reasons... would the above alternative pose any security threat?

+2  A: 

Assuming you can always trust the source (in your case get.html) it's going to be secure, but personally I always avoid eval if I can. It does open you up to injection attacks if someone manages to pass in bad data.

Also see : a good SO question about eval

Parrots
+2  A: 

The code, just like that, is not secure because it can be easily used from any server by setting the target of a <script> to it's url. Thus, anyone who's interested could call this script from any server. Not very secure.

There are some work arounds though. The gmail way is to append while(1) to the beginning of the function that's being returned and then removing it on the client before executing the code. Because a <script> will automatically execute the code, no one other than scripts running locally would be able to use this code.

Ariel