wuxiekeji
wuxiekeji

Reputation: 1902

Is it okay to use eval() when your data source is secure?

A lot of people seem to freak out at the notion of using eval(). I completely understand the XSS attacks and security issues that come with this. However, is it bad to use eval() to parse a JSON document that is obtained from your own server over HTTPS, guaranteed valid by the server, and does not contain user-generated data?

Upvotes: 0

Views: 63

Answers (1)

Brad
Brad

Reputation: 163234

As others have said in the comments, use a JSON parser (such as JSON.parse(), built into most browsers) to parse JSON. While JSON is compatible with JavaScript, it isn't the same thing and serves a different purpose.

I wanted to respond to your question more generally, as this is a thought I see a lot of folks have as they are just getting started:

However, is it bad to use eval() [...] does not contain user-generated data?

If you are writing code that transfers data from one layer to another layer, or from one system to another, it is absolutely critical that this occurs with the proper encapsulation. Any time you find yourself mixing data with command, you should be especially careful to make the data escaped properly so that it is never ambiguous, and cannot confused for the command.

Security isn't the only issue when it comes to injection. The problem exists whether someone is trying to exploit it or not. You could very well have some data that has quotes in it, or values that you didn't expect. Your code should be as transparent as it is supposed to be when handling data. If you are writing an ORM, for example, that ORM shouldn't modify the data in any way. It should just make sure it ends up where it is supposed to, in one piece, reliably.

I see a lot of folks using data in URLs all the time. It's common for someone to concatenate a numeric ID number into a URL as-is without escaping. I ask them... are you sure that your ID will always be a number and may never contain a reserved character? What if someone wants to re-use your code some day in a different context?

Assumptions about how something should be used are often the source of bugs and security vulnerabilities, which are really one of the same.

Upvotes: 3

Related Questions