TransWikia.com

How to access array outside of a function in javascript

Stack Overflow Asked by Hamza Sayyid on February 8, 2021

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 of vector? 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. Can we override a method of vector?

Example

var v = vector();
v.append(1);
v.append(2);
var internalData = exploitVector(v); // [1, 2]

My attempts + thoughts

Pretty sure I’m supposed to use the this keyword somehow as the hint says.
I’m a beginner at javascript so I don’t fully understand the context that well. This code is written in a file with other functions on the text editor Atom, not a browser.

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.

One Answer

Vector.store() can be abused to modify the array methods (e.g. array.push), followed by a v.append() to trigger the modified array.push method. The modified push method can for example either do something like window.visiblearray=this after which, visiblearray can be accessed globally.

Or as in the example below, store this (Array instance) to visiblearray of local scope, and then return it.

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
}

Answered by visibleman on February 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP