Can XHR patching prevent XSS side-effects?

Are there any caveats to this approach? (security-wise)

Yeah, it's not very thorough, you can get a new instance of the constructor from a new window object instead:

XMLHttpRequest = null;

var iframe = document.createElement('iframe');
iframe.style.display = 'none'; // optional
document.body.appendChild(iframe);
var XHR = iframe.contentWindow.XMLHttpRequest;
console.log(new XHR());

You would have to overwrite a lot more things to ensure a XMLHttpRequest cannot be accessed, that's just 1 way to do this.

For XSS protection, just use a Content Security Policy and only use trusted libraries from trusted sources.


Even if this would work and you could block JavaScript from performing XMLHttpRequests - which as shown by @Alexander is not the case (ActiveXObject would be another alternative) - it doesn't really limit the dangers of XSS.

An attacker still has a number of possibilities:

  • Defacement
  • Phishing: For example, add a login form, which sends the entered data to an attacker controlled server
  • Extracting Data: While an attacker cannot send acquired data via XMLHttpRequest, they can force a redirect via meta tag refresh and send the data that way.
  • CSRF: The token can be acquired as described above, then a form can be created and submitted via JavaScript.
  • Network Requests: The form example from above is also how any network requests can be performed without using XMLHttpRequests.

There really is no good way to prevent all of these points (at the very least, you would need to prevent any changes to the DOM, which I don't think is possible).

You need to trust the third party JavaScript libraries that you use.

If you do not trust the vendor, you need to reproduce the functionality yourself.