All Articles

HTTP Request Interceptor in JavaScript

This proof of concepts demonstrate how it’s possible via JavaScript to interecept all the HTTP requests performed and inject a custom payload.

// Intercept all the HTTP requests and inject a tracker if the payload is JSON
!function() {
XMLHttpRequest.prototype._original_send = XMLHttpRequest.prototype.send;
let interceptor_send = function(data) {
try {
obj = JSON.parse(data);
obj._tracker = 'tracker_id';
let new_data = JSON.stringify(obj);
this._original_send(new_data);
}
catch(err) {
this._original_send(data);
}
};
XMLHttpRequest.prototype.send = interceptor_send;
}();

  1. The requests get captured thanks to the overwrite of XMLHttpRequest.prototype.send default method that is called whenever a HTTP request is fired by the page / app.
  2. The payload is parsed as JSON;

    • If no exception is thrown, the injection is performed adding a new attribute _tracker with the value tracker_id.
    • Otherwise the HTTP request gets forwarded without changes.

This technique can be used to track the user behaviour across websites or pages (e.g. Google Analytics).

A possible mitigation to this kind of tampering could be the encryption and addition of checksum to the payload sent via HTTP request.