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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…