Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid prototype pollution in javascript?

In javascript, it's possible to "override" properties or methods of Object.prototype. For example:

Object.prototype.toString = function(){
  return "some string";
};

It can break an entire application if not used carefully. Are there any tools, techniques or approaches to avoid this (for example, some kind of 'strict mode' that doesn't allow the developer to override properties of Object)?

like image 901
Eduardo Melo Avatar asked Jul 22 '17 17:07

Eduardo Melo


People also ask

What is prototype pollution JavaScript?

Prototype Pollution is a vulnerability that allows attackers to exploit the rules of the JavaScript programming language, by injecting properties into existing JavaScript language construct prototypes, such as Objects to compromise applications in various ways. JavaScript allows all Object attributes to be altered.

What is one method for stopping exploitations of an object and preventing prototype pollution?

Freezing the prototype. Using Object. freeze will mitigate almost all the exploitable case.

What is prototype pollution in async?

1) Prototype pollution The vulnerability allows a remote attacker to escalate privileges within the application. The vulnerability exists due to improper input validation when handling data passed via the mapValues() method.

What is object prototype pollution?

Description. Prototype pollution is a vulnerability where an attacker is able to modify Object. prototype. Because nearly all objects in JavaScript are instances of Object, a typical object inherits properties (including methods) from Object.


1 Answers

Object.freeze(YourConstructor.prototype) can help protect your constructor's associated prototype object from being mucked with. From MDN:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed.

It works on the object itself, rather than making a copy that's frozen. It returns the same reference you pass it.

It's best to leave built-in prototypes alone, so using it on Object.prototype and such may not be a great idea. :-) Certainly you'd need to do a lot of testing if you did... See this thread on the es-discuss mailing list for relevant, useful info.

like image 122
T.J. Crowder Avatar answered Oct 08 '22 17:10

T.J. Crowder