Why is it bad pratice calling an array index with a variable?

后端 未结 3 1825
灰色年华
灰色年华 2020-12-11 03:17

I\'m currently developing a little game in Javascript and I\'m using Codacy to review my code and help me cleaning it.

One of the most seen error is Generic O

3条回答
  •  星月不相逢
    2020-12-11 03:30

    The security issue present here is that the stringified value of value may be accessing a property that is inherited from the Object's __proto__ hierarchical prototype, and not an actual property of the object itself.

    For example, consider the scenario when value is a string literal of "constructor".

    const property = "constructor";
    const object = [];
    const value = object[property];
    

    The result of value in this context will resolve to the Array() function - which is inherited as part of the Object's prototype, not an actual property of the object variable. Furthermore, the object being accessed may have overridden any of the default inherited Object.prototype properties, potentially for malicious purposes.


    This behavior can be partially prevented by doing a object.hasOwnProperty(property) conditional check to ensure the object actually has this property. For example:

    const property = "constructor";
    const object = [];
    if (object.hasOwnProperty(property)) {
        const value = object[property];
    }
    

    Note that if we suspect the object being accessed might be malicious or overridden the hasOwnProperty method, it may be necessary to use the Object hasOwnProperty inherited from the prototype directly: Object.prototype.hasOwnProperty.call(object, property)
    Of course, this assumes that our Object.prototype has not already been tampered with.

    This is not necessarily the full picture, but it does demonstrate a point.


    Check out the following resources which elaborates in more detail why this is an issue and some alternative solutions:

    • https://github.com/nodesecurity/eslint-plugin-security/blob/master/docs/the-dangers-of-square-bracket-notation.md
    • Securely set unknown property (mitigate square bracket object injection attacks) utility function

提交回复
热议问题