JavaScript安全问题

eas*_*asa 1 javascript security this

我想知道以下函数如何设置'this'元素并获取数组单元格?请.

//my secure code
var priv = ['item-0','item-1'];
var api = {push: function(x){priv.push(x)}}

api.store = function(i,x){priv[i] = x}

//the attaker script
var result;
api.store('push',function(){result = this[0]});
api.push();

//the result is cell 0 of private array
//how?
//if i change the 'push' parameter then the result is empty!
document.write(result)
Run Code Online (Sandbox Code Playgroud)

Dan*_*ies 5

会发生什么是api.store('push',function(){result = this[0]});覆盖数组的push方法priv.这意味着在此行之后push不再是javascript原生提供的推送方法,而是攻击者自定义功能,即function(){result = this[0]}.现在,当你调用api.push()它时priv.push(x)被覆盖的调用.因为push在一个对象上调用,this所以绑定到该对象priv(更多关于此的MDN文章).因此,result = this[0]等于result = priv[0]并且结果将包含第一个数组条目.