Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to prevent override/overwrite of functions/variables in singleton instance?

Consider this pseudo code:

(function(window){
   var options = { /*where everything goes */ };

   var instance = (function(options){
       for (var i in options){
       if (options.hasOwnProperty(i)){
         this[i] = options[i];
       }
     }
   })(options);

   instance.callbacks = function(cb){
     //...
   }

   instance.is_allowed = function()
    //... checks, return boolean
   }

   window.instance = instance;
})(this);

If anyone ever wanted to manipulate this code (a malicious user for example), he would rewrite the is_allowed function with his own, for example, using the address bar (he doesn't have firebug, who knows).

javascript:(function(){ window.instance.is_allowed = function(){ return true; } })();

This is a naive example, but that's the point, anything in Javascript can be overwritten.

I know in es5 we have the Object.defineProperty so you can set:

// being explicit
Object.defineProperty(instance, "is_allowed", {
  enumerable: false,
  configurable: false,
  writable: false,
  value: function(){
    // do checks
  }    
});

Actually, what is BEST in this sense is to use Object.freeze(instance) or Object.seal(instance) instead of Object.defineProperty, since the later can be called again with writable: false (silly huh?)

Is there ANY way that it work in old browsers (namely IE6-8) without too much hassle? If it's impossible, then I'll just shrug and move on.

like image 224
pocesar Avatar asked Feb 03 '13 10:02

pocesar


1 Answers

If anyone ever wanted to manipulate this code (a malicious user for example), he would rewrite the is_allowed function with his own

He could rewrite your whole javascript code or not even use a browser but simulate a "browser-less" request to your server.

Is there ANY way that it work in old browsers (namely IE6-8) without too much hassle?

No. Anything you globally expose can be altered by the user, it is up to the browsers restrict the javascript: behavior to avoid users from being fooled to access pre-crafted links. Firefox recently have made some kind of change to the javascript URL protocol.

As said on this article: http://survey-remover.com/blog/javascript-protocol-dangers/

As of Chrome v13, Firefox v6 and IE 9, the browser developers have taken notice to the dangers of the "javascript:" protocol and have subsequently disallowed code ... In the case of Chrome and IE, the "javascript:" substring is stripped when the code is pasted, whereas Firefox no longer executes the script within the scope of the active page.

So...

If it's impossible, then I'll just shrug and move on.

You should.

like image 52
Fagner Brack Avatar answered Oct 21 '22 22:10

Fagner Brack