2017-07-30 67 views
1

我想知道下面的函數如何設置'this'元素並獲取數組單元格?請。JavaScript安全問題

//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)

+0

根據上下文,'this'關鍵字可能有不同的含義。您還沒有在任何地方聲明'result'變量,所以默認情況下它具有全局範圍,這就是爲什麼它可以在函數外部使用。你能否提供關於你的問題的更多細節 – CROSP

+0

@CROSP我有一些關鍵的內容,我想保證它們的安全。 我的一位朋友向我發送了這段代碼,我意識到他可以使用我的API對象訪問私有變量。 – easa

+0

@easa如果攻擊者可以在同一個環境中執行任意代碼,通常你已經丟失了。你究竟想要保護什麼? – Bergi

回答

4

什麼情況是,api.store('push',function(){result = this[0]});覆蓋priv陣列的push方法。這意味着在此行之後push不再是JavaScript本身提供的推送方法,而是攻擊者自定義函數,即function(){result = this[0]}。現在,當您撥打api.push()時,它會調用priv.push(x),這被覆蓋。由於在對象上調用push,所以this被綁定到該對象,即priv(更多關於該in the MDN article on this)。因此,result = this[0]等於result = priv[0],結果將包含第一個數組條目。

+0

我無法理解它是如何被覆蓋的?在哪一行?怎麼樣? – easa

+0

'api.store('push',function(){result = this [0]});'調用'api.store = function(i,x){priv [i] = x}'。在這裏,'i'是推送的,x是攻擊者通過的功能。這意味着您正在有效地執行'priv [「push」] = function(){result = this [0]}'這等於'priv.push = function(){result = this [0]}'覆蓋'push'方法)。 –

+0

謝謝Daniel :-) – easa