3

Suppose I have a server-side variable containing JSON (named strJSON) that my own code created. In JavaScript I can consume it like this:

var data = <%= strJSON %>;

or use a JSON parsing library:

var data = JSON.parse('<%= HttpUtility.JavaScriptStringEncode(strJSON) %>');

I prefer the 2nd, for safety. Is what I'm doing unnecessary?

10

Suppose I have a server-side variable containing JSON, called strJSON that my own code created.

Was it created entirely by your code? Are you certain that at no point does it add in a piece of user input? Are you also certain that at no point in the future will it ever be modified to add in data that comes from user input? If you can be 100% sure of this, then you're probably safe. But since that's hard to be certain of, it's probably best to just use the built-in JSON parsing functions.

3

If the JSON string is encoded entirely under your control, it is exploitable to the extent that your encoding method is broken. That said, you should be safe if you're performing a straightforward serialization using a trusted serializer, like so:

var js = new JavaScriptSerializer();
var thingy123 = ThingyRepo.Get(123);
var json = js.Serialize(thingy123);

Response.Write(json); // or whatever

You should be safe, even if thingy123 contains user-submitted data. A well-established JSON serializer will safely encapsulate everything in a "non-executable" JSON format.

But, if you're rolling your own serialization, you'll want to be more rigorous in your validation.

1

No, there is nothing wrong with evaluating your own code, if you know for certain it's safe. Too many get caught up in blindly following rules. Evaluation of code in a string seems to really bring out strong opinions for some reason.

Evaluation of code in a string is a tool. Learn what it does, how it works, and why it can be unsafe. When you really understand why you generally shouldn't use evaluation, you then become free to use it when it's the right tool for the job.

If you think it's probably safe, don't do it. When you know it's safe, there's no reason not to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.