[英]How to access array outside of a function in javascript
I'm just wondering how to figure this strange security/scope question out:我只是想知道如何解决这个奇怪的安全/范围问题:
function vector() {
var array = [];
return {
append: function append(v) {
array.push(v);
},
get: function get(i) {
return array[i];
},
store: function store(i,v) {
array[i] = v;
}
};
}
This is the question asked:这是被问到的问题:
Can you spot any security concerns with this approach?
你能发现这种方法的任何安全问题吗? Mainly, can we get access to the
array
outside ofvector
?主要是,我们可以访问
vector
之外的array
吗? Note*: the issue has nothing to do with prototypes and we can assume that global prototypes cannot be altered.注意*:该问题与原型无关,我们可以假设全局原型无法更改。 Hint*: Think about using
this
in a method invocation.提示*:考虑在方法调用中使用
this
。 Can we override a method of vector?我们可以覆盖向量的方法吗?
var v = vector();
v.append(1);
v.append(2);
var internalData = exploitVector(v); // [1, 2]
Pretty sure I'm supposed to use the this
keyword somehow as the hint says.正如提示所说,我很确定我应该以某种方式使用
this
关键字。 I'm a beginner at javascript so I don't fully understand the context
that well.我是 javascript 的初学者,所以我不太了解
context
。 This code is written in a file with other functions on the text editor Atom, not a browser.此代码是在文本编辑器 Atom 上编写的具有其他功能的文件,而不是浏览器。
function exploitVector(v) {
v.get = function() {
return this.array;
};
console.log(v.get());
return v.get();
}
Also, this is just a fun exercise I saw on a github repo.此外,这只是我在 github 存储库中看到的一个有趣的练习。
Vector.store()
can be abused to modify the array methods (eg array.push
), followed by a v.append()
to trigger the modified array.push
method.可以滥用
Vector.store()
来修改数组方法(例如array.push
),然后使用v.append()
来触发修改后的array.push
方法。 The modified push method can for example either do something like window.visiblearray=this
after which, visiblearray can be accessed globally.例如,修改后的 push 方法可以执行
window.visiblearray=this
之类的操作,之后,可以全局访问 visiblearray。
Or as in the example below, store this
(Array instance) to visiblearray of local scope, and then return it.或者如下例所示,
this
(数组实例)存储到本地 scope 的 visiblearray 中,然后返回。
function vector() { var array = []; return { append: function append(v) { array.push(v); }, get: function get(i) { return array[i]; }, store: function store(i,v) { array[i] = v; } }; } var v = vector(); v.append(1); v.append(2); var internalData = exploitVector(v); // [1, 2] function exploitVector(v) { var visible_array; v.store('push', function(x){visible_array=this}) // modify array push v.append(12) // trigger the modified array push console.log(visible_array); return visible_array }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.