0

Mozilla says eval (T) is dangerous. how is x = new Function(T);x() less dangerous? I effectively used AJAX to pass some code for JAVASCRIPT to execute The eval (T) seemed not to work, so I switched code (actually bad code was passed)

Not relevant here but finally did alert('code='+T) to help find problem

However, if wanted to make a little safer, I suppose I could add:

  T_safer="try{"+T+"}catch (e){alert(e.message+\n code="+T+")}"
  eval (T_safer)  ..... or x =  new Function(T_safer);x()
Jacob Krall
  • 28,341
  • 6
  • 66
  • 76
  • 3
    Why do you think `x = new Function(T);x();` is less dangerous? "Calling the `Function` constructor directly can create functions dynamically, but **suffers from security** and similar (but far less significant) performance **issues to `eval`.**" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function – Jacob Krall Aug 11 '19 at 16:25
  • 2
    Your "safer" version adds no safety. – melpomene Aug 11 '19 at 16:31

1 Answers1

2

It's not.

eval and new Function are just about equally dangerous.

To understand the security flaw caused by eval and new Function, read Why is using the JavaScript eval function a bad idea?.

The basic issue is that, when evaluating a string provided by someone else, you can't trust that user to always act appropriately. This is called an injection attack. The attacker can trick your page into doing just about anything they want.

Even if you wrote the code to be executed, you still shouldn't use a String, either. In almost every case, you can use a function expression to pass a Function instead of a String. This is very likely to perform faster, as well as being more readable because it looks like code instead of a string. Compare the formatting on the following definitions:

T1 = new Function('a', 'b', 'alert("hi");return a + b');
T2 = function(a, b) { alert("hi");return a + b }

See how the second one has all of the tokens inside the function body highlighted correctly? That's a sign things are going well.


What are you trying to do?

I effectively used AJAX to pass some code for JAVASCRIPT to execute

There's a better way to get the browser to execute some trusted code from a server: a <script src=...> element. You can add these dynamically. Then you don't have to load a (potentially enormous) String payload and pass it through the eval pipeline, and your browser can start doing smart things code caching.


What's the nuance between eval and new Function?

In terms of security, eval and new Function have the same flaw. The only difference is that code in a new Function does not form a closure over your local scope, so there is a very puny increase in security by preventing the injected code from accessing your local variables. But that's really not worth much at all.

Jacob Krall
  • 28,341
  • 6
  • 66
  • 76