Question

I am considering the following architecture. A client connected to a server via websockets send a JSON package to the server. Inside of the JSON besides other data there is "action":"somefunction();". The server will then parse the JSON and if the action is not empty then it will eval and thus run that command.

The alternative to this would be to simply put a string "somefunction" in the action attribute and have a switch statement on the server to run the appropriate code.

Thoughts or other possibilities?

Was it helpful?

Solution

What you describe does not prevent a hostile client from sending arbitrary code to be executed. It is a security hole.

If you want to have client code trigger some functions on the server, then pass some data that your server will parse and check to make sure that only the appropriate code is executed. It could be a JSON structure like this that the client sends:

{
    "name": "foo",
    "arguments": ["a", "b", "c"]
}

When the server receives it and parses it with JSON.parse, it verifies that name is a valid value and invokes the corresponding function. The functions could be in a structure like this

var dispatch = {
    foo: function (a, b, c) { },
    bar: function (a) { }
    // etc...
}

And once the JSON data is parsed and stored into a variable named data (for instance), the invocation could be:

dispatch[data.name].apply(undefined, data.arguments)

If needed return data could also be returned to the client as a JSON structure.

OTHER TIPS

I tend to use window["function_name_as_string"](param1,param2); if I am calling a function by name with dynamic data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top