What HTTP source sends GM_xmlhttpRequest?

I want my REST API application to be available in different ways:

  • From the same domain (use regular AJAX request here)
  • From another domain through a script attached by the site owner (CORS)
  • From another domain via usercript (GM_xmlhttpRequest (?))

I want to limit the list of sites for my application from the white list.

I know how to do this with CORS, but I'm not sure if it works with GM_xmlhttpRequest in the same way, since GM_xmlhttpRequest does not require the Origin header to be sent from the server.

I do not need a client, but I still need to check the server from which site the request was sent, and respond with something like {response:"site not supported"} if it is not in the white list.

So, when I run usercript on some web page and create GM_xmlhttpRequest , can the server determine the source?

+4
source share
1 answer

You cannot use the Origin header to reliably restrict user API access to your APIs.

By default, GM_xmlhttpRequest() Doc does not send an Origin header at all. In addition, GM_xmlhttpRequest blocks cross-site requests; this is the main reason for the existence of GM_xmlhttpRequest .

Also, for Greasemonkey (Firefox) and Tampermonkey (Chrome) , GM_xmlhttpRequest does not send a default referer header.

However, both headers can be overridden for what the scriptwriter wants.

Here is a demo script that tricks both headers (use the packet sniffer to see for yourself):

 // ==UserScript== // @name _Test Fake Referrer // @include http://stackoverflow.com/questions/18178934/* // @grant GM_xmlhttpRequest // ==/UserScript== GM_xmlhttpRequest ( { method: "GET", url: "http://www.google.com", headers: { referer: "http://microsoft.com", origin: "http://microsoft.com" } } ); 



Chrome’s simple user protocol didn’t get to the script developer. Chrome’s custom user scripts never send the Origin header and always send the current page as a referer .

If you try to trick any of these headers, the console will show errors, for example:

Refused to set unsafe referer header
Failed to set unsafe header "origin"

This is another reason to use Tampermonkey for your custom Chrome scripts.

+3
source

Source: https://habr.com/ru/post/1496482/


All Articles