简体   繁体   中英

what are the issues javascript eval can pose

i tried googling but didnt get a very specific answer.. then again, i might be not using the right keywords.. can someone point out the "security" issues javascript eval can cause? with examples with be very nice. will also do if you can point to an existing web resource which does the same.

Edit : I only need the security implications for eval.

eval() may be a sign of poor design. For instance, sometimes people use it to access object properties because they don't know you can use the [] notation, ie, eval('obj.' + prop_name). It's also a source of XSS holes if you eval() user content, since it might be interpreted as JS. It also tends to be slower than the alternatives.

This would be the most basic example of XSS while using eval() to parse JSON:

eval({"a": "b", 'c': "d" + alert("xss") + ""})

To get a hole like this you would have to be lazy about building your JSON and not escape quotes, but there are more complex examples, and using a specialized library like Douglas Crockford's ( json.org ) one would avoid it.

In general, there is almost always an alternative method that will be:

  • Faster
  • Easier to read
  • Easier to debug if it goes wrong
  • Have a lower probability of breaking on unexpected user input

Performance

The eval function parses a string as code, which is quite a lot more work than for example accessing a property.

Consider the effect of eval('myForm.'+field+'.value') compared to myForm[field].value .

Structure

Almost always when the eval function is used, there is a more stuctured way to do it. Avoiding using the eval function causes you to come up with a better solution to the problem.

Consider the effect of using dynamic variables names like eval('myVars'+i) compared to using an array like myArray[i] .

The security implications are that if the parameters to eval() are fetched from some third party (User input, Web Service, etc), you may be running someone elses code which may do something you don't expect.

Why is this important? Imagine you are using some third party web service to enrich your user's experience, perhaps fetching information from facebook, and that web service gets hacked. Now the hacker can execute javascript code on your page, because you eval() some of the results from the web service, making the hacker able to inject anything in your DOM, infecting your users with trojans etc.

Now, if you hadn't used eval(), all that would have happened is that you'd have gotten bad data which you may have displayed or even, if you're a studious programmer, displayed an error message regarding the particular data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM