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 c
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
.
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.
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, i.e., 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: