I have a question regarding a potential security issue/limitation regarding JavaScript hosted on a domain (ex: domain of a CDN, say example.com), but loaded from a website under
Isn't this a possible security issue?
Yes, this is called Cross-Site-Scripting (XSS).
It is most definitely a security issue.
Bottom line, never include code, from any domain, that you don't trust. End of story.
If an attacker can get code running on your domain, it's game-over.
Shouldn't this trigger the same-origin-policy protection?
No.
The same-origin-policy basically means that the script can only ever view/modify the DOM of the domain to which it was loaded. So you can't create an iframe to an arbitrary site and read that DOM from the parent unless CORS is on, or your script is running there too.
Perhaps, are there user agents that prevents a Javascript, hosted on a different domain, to access elements in the page that executes the script?
The only way to do this, is to sandbox that javascript inside of an iframe which is on a different domain.
So you could create a sandbox.example.com
domain, which generates a wrapper page which includes the javascript.
Then, instead of linking to the JS directly, create an iframe to the sandbox domain. The JS will have access to that domain, and everything in that DOM, but nothing outside of the iframe.
You still have to be careful to set cookies properly (don't do wildcard domains, etc). But it can help.
All URL based security restrictions in client side JavaScript are based on the URL of the webpage containing the <script>
element which loads the JS.
The URL the JS itself is hosted at is irrelevant.
Now, I know that I can't access Cookies under mysite.com from the JS.
The script is loaded into example.net
and hosted on example.com
. It can read cookies from example.net
. It cannot read cookies from example.com
. (Server side code on example.com
could dynamically generate the JavaScript and embed data taken out of cookies though).
But, I can access all the DOM on the page, and, in case, modify it.
Yes
Isn't this a possible security issue? Shouldn't this trigger the same-origin-policy protection?
It is a potential security issue, but it should not trigger the Same Origin Policy.
By loading the script, the author of the page is trusting the site hosting the script.
Do not embed JS from sites you do not trust.
And, moreover, will the example above work also on HTTPS pages? (ex:
https://example.net/index.html
loads the script fromhttps://example.com/myscript.js
)
URLs with different schemes have different origins, just as URLs with different hostnames. The Same Origin Policy rules are the same as they are based on origin not particular features of origins.
Sometimes you will get additional restrictions where a page loaded over HTTPS will be forbidden from accessing content loaded over HTTP since that breaks the SSL security. This is a different security restriction that is unrelated to the Same Origin Policy.