Search code examples
javascriptgoogle-caja

A JavaScript vulnerability - "this"-stealing:


I'm learning about Caja, and I am confused about the concept of "this"-stealing:

Another security vulnerability that Caja addresses is called “this” stealing – if an object’s clients can add methods to the object’s state which alias its “this” then the aforementioned protected “this” rule does not apply.

Then they show the following constructor:

function Cell(value) {
  this.x_ =  "secret";
  this.value = value;
}

There's a hidden leak involving "x_" :

The following code can make the expression reveal that secret value:

(new Cell(
  function (){
    return this.x_;
  })).value()

How does this work? Why is it such a problem? I appreciate any tips or advice.


Solution

  • Simplify it:

    (new Cell( )).value()
    

    We're creating a new object from the Cell constructor, and immediately calling its value method. Of course the value method doesn't do anything yet, which is where our next portion comes in:

    function (){ 
      return this.x_; 
    }
    

    This is what we're passing into the constructor as the value parameter. This function is assigned to this.value within the Cell constructor.

    So the Cell constructor effectively looks like this now:

    function Cell(value) {
      this.x_ =  "secret";
      this.value = function (){ 
        return this.x_; 
      };
    }
    

    So what happens when you create a new object from Cell, and call its value member? A function from within returns the Cell object's x_ value, thus revealing the secret text.