Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable cross-domain ajax request

Is there any way to disable cross-domain ajax request?

Lets say there are two domains: mywebsite.com and hackerswebsite.com. On the mywebsite.com there is a website which contains javascript with AJAX function which sends data to hackerswebsite.com. All I want is to prevent this and allow only sending AJAX request to mywebsite.com domain.

I know there is something like "Same origin policy" but what I understand it works on the second domain and can prevent connections from other domains.

To be more precise, lets say that I have a website where users can run their own javascript. If they can write their own scripts they can get any data from DOM document and send it asynchronously to their own server which will accept data from my domain. For example login name. Am i right?

Please correct me if I'm wrong. I'm just trying to understand this security policy thing.

like image 841
mkatanski Avatar asked Nov 18 '13 16:11

mkatanski


1 Answers

Sounds like you want a content security policy (CSP) to restrict what resources and Ajax destinations the page can and can't use.

The same-origin policy is designed to prevent websites from reading credentialed responses from a third party (e.g., I load evil.com, and that site instructs my browser to fetch my online bank statements, using my bank.com cookies). The SOP is not intended to prevent users or sites from sending data wherever they like.

The site's CSP is intended to whitelist access to resources, in the event that either:

  1. the site is compromised by an XSS attack and suddenly behaves in ways you didn't anticipate, or
  2. the site runs content supplied by user A on a browser owned by user B, and that content needs to be sandboxed.

To be clear, the danger in case #2 is not that a user can run his own JavaScript, but that a user might run some other user's script.

An example CSP might be:

Content-Security-Policy: default-src 'self'; frame-src 'none'; object-src 'none';

This will block any attempt to load iframes or plugins, and it restricts all other resource loads (including images, scripts, stylesheets, and Ajax requests) to the current origin. If you want to allow plugins or iframes, you can remove either or those directives and they will fall back to the default-src directive. You can use the connect-src directive to limit Ajax specifically.

Note also that if you lets users run arbitrary scripts, you will likely still have serious problems (e.g., rewriting the page with misleading content), even with a very restrictive CSP taking care of cross-origin network requests.

like image 90
apsillers Avatar answered Nov 05 '22 03:11

apsillers