dB'
dB'

Reputation: 8330

Is it safe to run JSON.parse() on window.location.hash?

I'm looking for a way to store a few javascript variables in my URL's hash. My aim is to allow users to restore a particular state of a web application using a bookmark.

It occurred to me that one approach might use JSON serialization. I.e., I'd store my variables like this

var params = { var1: window.val1, var2: window.val2 }
window.location.hash = JSON.stringify(params)

and recover them like this

var paramStr = window.location.hash.substring(1) // substring removes the initial "#"
var params = JSON.parse(paramStr)
window.var1 = params.var1
window.var2 = params.var2

This seems like the simplest and most concise technique for doing what I want. It's easy for me to understand, and it uses fewer lines of code, than, for example, this popular SO suggestion. However, it also feels insecure. A malicious user would be able to write arbitrary code into the url, and my app would execute it. This seems dangerous, but I'm pretty new to web programming and so I don't know how big a deal this is.

Is the technique I've outlined above for storing variables in window.location.hash safe to use? If not, why not? What's the worst that could happen?

Upvotes: 2

Views: 1703

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340723

malicious user would be able to write arbitrary code into the url [...] Is the technique [...] safe to use?

It's safe. One of the advantages of JSON.parse() over old eval() approach is that it's safe and won't run arbitrary code.

A separate question is: is it a good idea to put JSON in hash? I would go for more concise representation.

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Lesson number one is that all user input should never be trusted.

Always validate everything. In the case of your app, if it is offline-only then it really doesn't matter what the malicious user types since it will only affect their own computer.

If it involves server-side activity, then you should check to make sure that the input you received makes sense. For instance, if the user is trying to access a saved file, does the user have permission to view it?

There is no security in obscurity, so JSON in the hash is just as secure as some complex encryption method.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

Yes, it is safe to parse arbitrary data. A JSON parser does not execute any code that does something different from defining an Object/Array/String/Number. Native ones don't even use eval at all (and non-native ones validate the JSON data before using eval).

It is also safe to assign it to predefined (global) variables assuming your code doesn't do "bad" stuff with those variables.

However, it's not necessarily safe to assign it to arbitrary global variables. While JSON can't contain functions you don't want anyone to be able to overwrite any globals.

Upvotes: 5

Related Questions