javascriptsecurityfirefox-addongecko

How to convert anything to a String safely in JavaScript


If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.


Solution

  • JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype itself, meaning any object is vulnerable to "evil code" in the manner that you explained.

    Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:

    function safeToString(x) {
      switch (typeof x) {
        case 'object':
          return 'object';
        case 'function':
          return 'function';
        default:
          return x + '';
      }
    }