Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a native Javascript function was monkey patched?

Tags:

javascript

For example I loaded a script on some website, and I would like to know if JSON.parse/stringify wasn't monkey patched.

I noticed that if I use toString on the function in Chrome/FF, JSON.stringify.toString, then I get back:

function stringify() {
    [native code]
}

My question is do you think this is a good way to verify if a function was monkey patched? Also would love to hear of any other approaches to this problem.

like image 956
itayad Avatar asked Jul 25 '16 08:07

itayad


People also ask

What is monkey patching in JavaScript?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What does monkey Patch_all () do?

A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.

What is a native function JavaScript?

The native prototype is a JavaScript property that all built-in constructor functions in JavaScript use to inherit methods and properties from one another.


1 Answers

One could easily fake JSON.stringify.toString

JSON.stringify = function() {}
JSON.stringify.toString = function() {return 'ha-ha'}

console.log(JSON.stringify); //ha-ha

A little more robust way would be to use Function.prototype.toString

Function.prototype.toString.call(JSON.stringify)

But really bad monkeypatcher could patch Function.prototype.toString as well :)

like image 146
Yury Tarabanko Avatar answered Oct 30 '22 01:10

Yury Tarabanko