1

Possible Duplicate:
How to run user-submitted scripts securely in a node.js sandbox?

I want that my user can create their own format function that work with a particular object. I find two ways of doing it but I don't know if that functions can be hacked. It is run inside nodeJS.

//First way with eval (evil ?)
function convertObj(formula) {
   return function (obj) {
        return eval(formula);
    };
}

// Second way with function (same as eval ?)
function convertObj2(formula) {
  return new Function("obj", "return " + formula);
}

var inst = {
      "name": "BOB",
      "age": "30"    
    };

var formula = "obj.name.toLowerCase() + ' is ' + obj.age + ' years old'";

var next = convertObj(formula);
var next2 = convertObj2(formula);

document.write('<p>' + next(inst) + '</p>');
document.write('<p>' + next2(inst) + '</p>');​

Print

bob is 30 years old
bob is 30 years old

The example is also available at http://jsfiddle.net/DeWYy/2/

Community
  • 1
  • 1
Farandole
  • 539
  • 2
  • 8
  • 23
  • [Both are bad](http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx), but hey depending on what you're actually trying to do there might not be any other way! – Jamiec Oct 05 '12 at 14:40
  • both versions are `eval`ed, there is no difference. And yes, they can be abused. – Christoph Oct 05 '12 at 15:24

1 Answers1

1

Both are vulnerable, because you are literally leaving anyone run anything without any control.

What you probably want to do is run the code inside a sandbox. There are library that will help you with that (a quick Google search comes up with Sandbox). Do note that even if you run user-submitted code in a sandbox there will always be risk, but they are mostly mitigated. So unless you run a critical service, it can be consider secure.

I also recommend you to take a look at this question about running user-submitted code securely.

Community
  • 1
  • 1
HoLyVieR
  • 10,985
  • 5
  • 42
  • 67