Let's consider the following scenario:
a user loads https://foo.com/index.html in one of the modern browsers which allow CORS.
index.html loads a javascript from https://bar.com/script.js via the script tag.
considering a hypothetical situation where this script.js is never cached and the content of script.js has changed.
script.js makes an XHR request to https://baz.com
https://baz.com has enabled Access-Control-Allow-Credentials: * thus this XHR made by script.js goes through.
important user information now can be passed to https://baz.com which is a security risk.
Prior to CORS, XHR calls were strictly followed same-origin policy and thus calls to https://baz.com from https://foo.com would not be permitted by the browsers.
I am wondering if there is a way for https://foo.com/index.html to specify a list of XHR permissible domain names so that the above scenario would not be possible.
Any pointer is highly appreciated.
[UPDATED]
I guess I have found the answer to my question.
Thank you for being considerate 🙏
Best!
I guess I found the answer to my question.
Using connect-src directive of the Content-Security-Policy Header https://foo.com/ can restrict the XHR, fetch calls along with WebSocket, EventSource, <a> ping to desired domains.
Content-Security-Policy: connect-src <source> <source>;
More information at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src
I once thought of deleting my question but someone else like me can be benefited.
CORS blocking is done on the server side, where the response headers are set to allow requests from certain origins or not.
If bar.com/script.js fetches data from baz.com, then baz.com should have the CORS restriction.
Related
Is there a way to globally catch mixed content errors?
To be clear: I don't want to allow the insecure content, all I want to do is handle the error gracefully.
Backstory: I'm integrating programmatic ads, that is i have to include some script tag, which returns some more JavaScript, which can load even more resources, etc...
It is impossible for me to control, what's coming to my website and sometimes those resources include http resources, which throw a mixed content error. I#m then left with an empty ads container, which looks kind of ugly. Also, I could try to resell this ad-space, since the first try failed.
I already tried window.onerror, but with no avail.
There is no way to catch mixed content warnings, as they have no relation to JavaScript and are handled by your browser instead.
What you can do instead is use Upgrade-Insecure-Requests header to prevent browser from loading unsafe content entirely. And, depending on your use case, you may use MutationObserver to react to changes in your HTML, or listen to Error Events on document.body during capture phase to react to errors:
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="upgrade-insecure-requests"
/>
</head>
<body>
<script>
const el = document.createElement("img");
el.src = "http://unsafeimg";
document.body.appendChild(el);
document.body.addEventListener(
"error",
(err) => {
console.log("Failed to load\n", err.target);
},
/* Notice the true value here. It is required because Error Events do not bubble */
true
);
</script>
</body>
</html>
Another option would be to set up a Service Worker to intercept and handle insecure requests. This is probably the best solution, as this gives you full overview of what data your website it trying to load.
Sounds like you are having an issue specifically revolving around fixing mixed content policies. There are many approaches to tackle and arrive at a solution.
My recommendation is to go off some documentation provided and referenced by Google: https://web.dev - Fixing Mixed Content.
Mixed content occurs when initial HTML is loaded over a secure HTTPS connection, but other resources (such as images, videos, stylesheets, scripts) are loaded over an insecure HTTP connection. This is called mixed content because both HTTP and HTTPS content are being loaded to display the same page, and the initial request was secure over HTTPS.
First off mixed content will occur when such initial-based HTML is transferred over the network through a secure HTTPS connection. Although, the problem arises when other resources as you stated such as:
Images
Videos
Stylesheets
Scripts
...are loaded over an insecure HTTP connection. This is the definition of a mixed content issue described. It is because of an issue pertaining to assets both HTTP and HTTPS content that is being requested and loaded to display on the website of the desired origin. And the main issue is the initial request was originally sent over secure over the HTTPS protocol.
Note: Before continuing, when requesting any of these subresources overusing the insecure HTTP transfer protocol, will open up vulnerabilities of the entire origin site. Such vulnerability attacks are named on-path attacks.
Depending on the browser your website user base is primarily targeting, there are fixes and preventions to take note of being rolled out by browsers such as Google Chrome. Which will upgrade passive mixed content where it is possible. Such a process will be deciding if the resource asset is available over HTTPS, but determine if it was created to be served over the HTTP protocol, the browser will load the HTTPS version instead. So in conclusion, it will disregard the HTTP resource.
Content Security Policy (CSP)
You need to reference the below section of https://web.dev - Fixing Mixed Content linked here. It will allow you to utilize a browser-based implementation that may be used to solve and manage mixed content issues. Which allows and opens up opportunities for different enforcement policies to be implemented.
To enable CSP, you have the opportunity to set up your site to return the Content-Security-Policy HTTP header. Which has replaced the X-Content-Security-Policy older policy.
My suggestion is to make use of the <meta> HTML element. This will allow you to customize which domains you trust in regards to CSP in general and implement different customizations using this element.
This is an example where you do wish to allow any resource content from a trusted domain, and you may use alternative formatting to allow sub-domains and other aspects to grant desired outcomes. Notice the formatting, following the subdomain setting.
Content-Security-Policy: default-src 'self' example_trusted.com *.example_trusted.com
So when utilizing this, you may take an approach for certain resources such as advertisements or images you decide to trust, but must be set up appropriately.
One vague example might be, without an asterick:
content="default-src 'self' https://example.com http://example.com:80/images/"
This concludes a result conclusive of:
https://example.com # Correct
http://example.com/images/ # (Missing) Incorrect Port
http://example.com:80/images/image.jpg - Correct Port
https://example.com:81 # (Missing) Incorrect Port
You may use approaches like these referenced here at Mozilla - Content-Security-Policy, which may help form a solution.
Or just go completely vulnerable.
content="default-src * 'unsafe-inline' 'unsafe-eval'"
Many references on StackOverflow such as How does Content Security Policy (CSP) work?, which was referenced in this post. Hope I was of some help.
Complete References List:
https://web.dev/fixing-mixed-content/
https://web.dev/fixing-mixed-content/#content-security-policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
How does Content Security Policy (CSP) work?
What I do whenever dealing with mixed content is updating the .htaccess file with the following:
Header always set Content-Security-Policy: upgrade-insecure-requests
That should by take care of the mixed content and make sure that you load everything trough HTTPS.
I need a script to deliver information to requesting-pages hosted on different domains, through XMLHttpRequest. There are many questions and answers on the subject, but none of the ones I found fully answered my questions.
Searching on the net brought me to find out that I must allow these domains through headers like
header("Access-Control-Allow-Origin: *"); or
header("Access-Control-Allow-Origin: http://example.com");
As I need more than one external domain, but still I find * much too open, further researches brought me on solutions relying on server-side comparison of $_SERVER['HTTP_ORIGIN'] with authorized values. (on StackOverflow: Access-Control-Allow-Origin Multiple Origin Domains? for instance)
BUT I found no mention of $_SERVER['HTTP_ORIGIN'] in php manuel (http://php.net/manual/fr/reserved.variables.server.php) and my tests revealed that this entry isn't always set.
So my questions are:
- when is the $_SERVER['HTTP_ORIGIN'] superglobal set?
- is it reliable globally?... or client browser dependant?
It seems (but just empirically, from my tests / Firefox 34.0.5 & ios Safari) that it is only set when 'needed', ie when request actually comes from another domain.
See short code extract hereunder to help understand the need
- no header sent if $_SERVER['HTTP_ORIGIN'] not defined
(assuming it's effectively not a cross domain call, there shouldn't be any problem),
- send "allow" header if defined and belonging to an array of accepted domains.
if(isset($_SERVER['HTTP_ORIGIN'])) {// in case of cross domain ajax call
$http_origin = $_SERVER['HTTP_ORIGIN'];
if(in_array($http_origin, $ajaxAllowedDomains))
{ header("Access-Control-Allow-Origin: $http_origin"); }
}
when is the $_SERVER['HTTP_ORIGIN'] superglobal set?
When the HTTP request includes an Origin header. Browsers will set one when making a cross-domain request with XMLHttpRequest.
is it reliable globally?
It is in situations where you might want to set CORS response headers.
I know if on my own webpage, if my user is on :
http://www.example.com/form.php
and I make an ajax request from that page to :
http://example.com/responder.php
It will fail because of the Same origin policy (subdomain is different).
What I am trying to understand is, how is it that AJAX requests can pull data from API's like flickr when the request and server are obviously different.
Edit :
eg: Why does this code work?
$.getJSON('http://api.flickr.com/services/rest/?&;method=flickr...'
(Referred this Community Wiki)
Is it using Cross Origin Resource Sharing?
Thanks!
There are few known methods to work around the Same Origin Policy. One popular technique is to use "Script Tag Injection" such as in JSONP. Since the <script> tag is not constrained by the Same Origin Policy, a script on a third-party domain can provide executable code that interacts with a provided callback function. You may want to check out the "Tips and Tricks" section in the following article for further reading on the topic:
Howto Dynamically Insert Javascript And CSS (hunlock.com)
You may also be interested in checking out the following Stack Overflow post for further reading on other techniques to work around the Same Origin Policy:
Ways to circumvent the same-origin policy
UPDATE: Further the updated question:
Quoting from the jQuery documentation on $.getJSON():
If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead.
I want to make an XMLHttpRequest to a secure uri (https://site.com/ajaxservice/) from javascript running inside a nonsecure page (http://site.com/page.htm). I've tried all kinds of nutty stuff like iframes and dynamic script elements, so far no go. I know I am violating 'same origin policy' but there must be some way to make this work.
I will take any kind of wacky solution short of having the SSL protocol written in javascript.
That won't work by default due to the same origin policy, as you mentioned. Modern browsers are implementing CORS (Cross-Origin Resource Sharing) which you could use to get around this problem. However this will only work in Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome, and requires some server-side work. You may want to check out the following article for further reading on this topic:
Cross-domain Ajax with Cross-Origin Resource Sharing by Nicholas C. Zakas
You can also use JSONP as Dan Beam suggested in another answer. It requires some extra JavaScript work, and you may need to "pad" your web service response, but it's another option which works in all current browsers.
You can't circumvent cross-domain origin with XHR (well, only in Firefox 3.5 with user's permission, not a good solution). Technically, moving from port 80 (http) to 443 (https) is breaking that policy (must be same domain and port). This is the example the specification itself sites here - http://www.w3.org/Security/wiki/Same_Origin_Policy#General_Principles.
Have you looked into JSONP (http://en.wikipedia.org/wiki/JSON#JSONP) or CSSHttpRequests (http://nb.io/hacks/csshttprequest)?
JSONP is a way to add a <script> tag to a page with a pre-defined global callback across domains (as you can put the <script>s src to anywhere on the web). Example:
<script>
function globalCallback (a) { /* do stuff with a */ }
And then you insert a <script> tag to your other domain, like so:
var jsonp = document.createElement('script');
json.setAttribute('src','http://path.to/my/script');
document.body.appendChild(jsonp);
</script>
And in the source of the external script, you must call the globalCallback function with the data you want to pass to it, like this:
globalCallback({"big":{"phat":"object"}});
And you'll get the data you want after that script executes!
CSSHttpRequests is a bit more of a hack, so I've never had the need to use it, though feel free to give it a try if you don't like JSONP, :).
You said you would take anything short of having the SSL protocol written in JavaScript... but I assume you meant if you had to write it yourself.
The opensource Forge project provides a JavaScript TLS implementation, along with some Flash to handle cross-domain requests:
http://github.com/digitalbazaar/forge/blob/master/README
Check out the blog posts at the end of the README to get a more in-depth explanation of how it works.
I need to make an AJAX request from a website to a REST web service hosted in another domain.
Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.
The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.
Here is the JavaScript code that makes the asynchronous call:
var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
How can I have this work in other browsers beside Internet Explorer?
maybe JSONP can help.
NB youll have to change your messages to use json instead of xml
Edit
Major sites such as flickr and twitter support jsonp with callbacks etc
The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways.
The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is to use JSONP. Any other solutions demand a serverside proxy located on your own domain, or a client side proxy located on the remote domain and som sort of cross-site communication (like easyXDM) to communicate between the documents.
The fact that this works in IE is a security issue with IE, not a feature.
Unfortunately cross-site scripting is prohibited, and the accepted work around is to proxy the requests through your own domain: do you really have no ability to add or modify server side code?
Furthermore, the secondary workaround - involving the aquisition of data through script tags - is only going to support GET requests, which you might be able to hack with a SOAP service, but not so much with the POST request to a RESTful service you describe.
I'm really not sure an AJAX solution exists, you might be back to a <form> solution.
The not very clear workaround (but works) is using iframe as container for requests to another sites. The problem is, the parent can not access iframe's content, can only navigate iframe's "src" attribut. But the iframe content can access parent's content.
So, if the iframe's content know, they can call some javascript content in parent page or directly access parent's DOM.
EDIT:
Sample:
function ajaxWorkaroung() {
var frm = gewtElementById("myIFrame")
frm.src = "http://some_other_domain"
}
function ajaxCallback(parameter){
// this function will be called from myIFrame's content
}
Make your service domain accept cross origin resource sharing (CORS).
Typical scenario: Most CORS compliant browsers will first send an OPTIONS header, to which, the server should return information about which headers are accepted. If the headers satisfy the service's requirements for the request provided (Allowed Methods being GET and POST, Allowed-Origin *, etc), the browser will then resend the request with the appropriate method (GET, POST, etc.).
Everything this point forward is the same as when you are using IE, or more simply, if you were posting to the same domain.
Caviots: Some service development SDK's (WCF in particular) will attempt to process the request, in which case you need to preprocess the OPTIONS Method to respond to the request and avoid the method being called twice on the server.
In short, the problem lies server-side.
Edit There is one issue with IE 9 and below with CORS, in that it is not fully implemented. Luckily, you can solve this problem by making your calls from server-side code to the service and have it come back through your server (e.g. mypage.aspx?service=blah&method=blahblah&p0=firstParam=something). From here, your server side code should implement a request/response stream model.
Just use a server side proxy on your origin domain. Here is an example: http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html
This can also be done using a webserver setup localy that calls curl with the correct arguments and returns the curl output.
app.rb
require 'sinatra'
require 'curb'
set :views,lambda {"views/"+self.name.to_s.downcase.sub("controller","")}
set :haml, :layout => :'../layout', :format => :html5, :escape_html=>true
disable :raise_errors
get '/data/:brand' do
data_link = "https://externalsite.com/#{params[:brand]}"
c = Curl::Easy.perform(data_link)
c.body_str
end
Sending an ajax request to localhost:4567/data/something will return the result from externalsite.com/something.
Another option would be to setup a CNAME record on your own domain to "Mask" the remote domain hostname.