Security considerations using “new Function(…)” (during rendertime, expression coming from my Javascript sources)

后端 未结 4 1134
小蘑菇
小蘑菇 2021-01-13 02:09

I\'d like to use new Function(...) to generate a function from very reduced code. I\'l like to do this to

  • avoid parsing the expression on my own
4条回答
  •  耶瑟儿~
    2021-01-13 02:11

    Old thread with answers considered dangerous these days. new Function() still allows access to global variables. So an adversary, when given the chance to effect the function string - which is usually the very reason for considering new Function and hard to guarantee it can't be done maliciously -, can read and modify any global. Good luck from that point on :-)

    Which is why new Function falls under the same category as eval from the viewpoint of CSP (Content Security Policy) as mentioned here.

    Example:

    a = 10
    > 10
    
    b = new Function('a = 20; return 42')
    > function(...)
    
    a
    > 10
    
    b()
    > 42
    
    a
    > 20
    

提交回复
热议问题