How to CSP restrict to file:/// urls in chrome? - google-chrome

I have an iframe in a webview which loads a script from the android app's asset using the following :-
<script src='file:///android_asset/trusted-iframe-script.js'></script>
Now I want to have a content security policy on the iframe such that no other script can be loaded.
For this I added the following to the iframe CSP
script-src: 'file:///android_asset/trusted-iframe-script.js';
This doesn't work since the file uri is ignored by chrome.
The source list for Content Security Policy directive 'script-src' contains an invalid source: 'file:///android_asset/trusted-iframe-script.js'. It will be ignored.
Refused to load the script 'file:///android_asset/trusted-iframe-script.js' because it violates the following Content Security Policy directive: "script-src file:///android_asset/trusted-iframe-script.js".
I read about filesystem uri, but that requires requesting access to the user but I actually only need access to my own assets and not filesystem in general. I also read about blob: urls but that feels akin to inlining the whole script
What is the right way to csp restrict to only file urls ?

CSP URI's don't have quote marks - so try script-src: file:///android_asset/trusted-iframe-script.js;
If that doesn't work most Android browsers now support CSP2, which lets you specify a hash for a supported script.

If the CSP is set on the "page" which contains the iframe you should use
the ​child-src: directive instead of script-src: (Source)
Then, i am not use how to include an assert file and you could try with:
​child-src: file:///android_asset/trusted-iframe-script.js
// i cannot test it
​child-src: filesystem:///android_asset/trusted-iframe-script.js
// source and check if still requires requesting access to the user
child-src: https://your.trusted.website.com/trusted-iframe-script.js
// this should work but it requires to have a trusted server and the app must connect to the web (no obvious condition)

In short, this cannot be done for a sandboxed iframe.
Chrome CSP doesn't allow file urls to be whitelisted as a script src. You could use the directive file: (without any url) and that would work if the iframe wasn't sandboxed. But this is a bad idea, since
A. my iframe is sandboxed, and
B. this is an undocumented keyword which may stop working at anytime.
I also tried creating a blob url for the content and instead passing that to the iframe but that too doesn't work unless you set allow-same-origin on the iframe sandbox attribute.

Related

Why are two files in the same folder treated as cross-resource?

I've added an iframe to an Rmarkdown document. The iframe is an HTML file that is stored in the same folder as my .Rmd file and the HTML file it generates. I would like to determine the appropriate height/width to display the iframe based on the HTML file dimensions. I should be able to use iframe.contentWindow.document.body.scrollWidth/iframe.contentWindow.document.body.scrollHeight to do this.
Here is an example of what I tried in my Rmd file:
<iframe src="./test_file.html" style="display:block; border:none;
width:100%;" id="test"></iframe>
```{js}
var iframe = document.getElementById('test');
iframe.addEventListener('load', function(event) {
iframe.height = iframe.contentWindow.document.body.scrollHeight;
iframe.width = iframe.contentWindow.document.body.scrollWidth; });
```
However the contentWindow value is null for the iframe. When I look at the HTML page generated by Rmarkdown with Developer Tools, I see the error:
Uncaught DOMException: Blocked a frame with origin
"https://website.host.name" from accessing a cross-origin frame.
at HTMLIFrameElement. (https://website.host.name/R/Rmd_test/generate_preview.html:1636:42)
So it seems that the files are being treated as cross-origin resources rather than coming from the same-origin. I'm not sure why that is since they are both located in the same folder and their location.protocol, location.host, & location.port values are the same (port is null for both, which from my reading should be fine).
I did find a workaround to get the height/width using postMessages to have the pages communicate, but I'd like to figure out how to have the iframe content recognized as same-resource. Any ideas what I'm doing wrong/missing?
I don't think this is a duplicate of SecurityError: Blocked a frame with origin from accessing a cross-origin frame. I used that post to figure out my workaround to get the height/width. The accepted answer notes that the origin is considered to be different if the protocol, hostname, or port differs between the two resources. In my case, when I open each HTML file, that information is the same. Why are they being treated as cross resource?

Bypass blocking of subresource requests whose URLs contain embedded credentials

I have been automatically authenticating users visiting our internal wiki via a link with a token in the URL like this:
href="https://user:pass#host/"
In Chrome 59, this is being prevented.
[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass#host/) are blocked.
I read and I bypassed it in an ajax request like this:
how to replace embedded credentials in subresource requests
========================================================================
My Question is:
Does anyone know how to do it directly in the link, or can you provide some kind of workaround? Is this even possible?
Passing the command line option '--disable-blink-features=BlockCredentialedSubresources' restores the expected behavior. If you're using Selneium, you can pass it as an args option in the Browser Capabilities to restore the expected behavior.
PHP:
'chromeOptions' => array('args' => ['--disable-blink-features=BlockCredentialedSubresources']);
Python:
capabilities['chromeOptions'] = {'args': ['--headless']}
According to the Chromium ticket (https://bugs.chromium.org/p/chromium/issues/detail?id=731618) this behavior may not be restored in future versions despite it being in 'Deprecation'. In this case, it might be best to look at ssh conduits for testing or whitelist the IP if possible to prevent the HTTP Auth interaction.
Anthony
If your page includes css, javascript or other stuff with relative ("folder/file") or base-relative ("/folder/file") locations, then the problem is that these included files would be fetched from a URL relative to the base URL of the page, which includes a user:pass component.
It is that user:pass componenent (which you possibly never meant to imply anyway...) which makes the URL of the subresources illegal, following this change to Chrome.
If that is your problem, you can fix it by adding a <base href="https://host/"> tag to your page (i.e. the same base address, but without the user:pass component). (If your page is in a subdirectory, you need to include the subdirectory in the base href as well, for fully relative URLs to work.)
To be clear, links like Link still work (as long as the user:pass URL is in a link which opens in a new page, and is not a URL for an iframe, say - that is now banned). But even when the link works, the problem I've described above applies to elements included with relative paths in the newly opened page.
UPDATE:
This has been accepted as a bug in Chrome, directly related to the new changes banning user:pass in subresource URLs. Unfortunately, following through the links in that discussion, it seems that one proposed and quite likely solution is to remove support for user:pass URLs entirely. Any informed comments added to that discussion and arguing in favour of keeping this feature would presumably help.
To handle this, we have to pass chrome options : "--disable-blink-features=BlockCredentialedSubresources");
Complete code is mentioned below :
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--disable-blink-features=BlockCredentialedSubresources");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);

Iframe in Chrome error: Failed to read 'localStorage' from 'Window': Access denied for this document

I have a web app which uses localStorage. Now we want to embed this web app on other (third-party) sites via iframe. We want to provide an iframe embed similar to youtube so that other websites can embed our web app in an iframe. Functionally it is the same as if it wouldn't be embedded. But it does not work. Chrome prints the error message:
Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
I just do the following check (in the iframe):
if (typeof window.localStorage !== 'undefined') {
// SETUP SESSION, AUHT, LOCALE, SETTINGS ETC
} else {
// PROVIDE FEEDBACK TO THE USER
}
I checked my security settings in Chrome like described in another Stackoverflow Thread but it doesn't work. Is there any change to make embedding possible without the need of adjusting (default) security settings of most modern browsers?
To give more information, we use Ember-CLI for our web app and turned on CSP (more info about the Ember-CLI CSP). Could CSP cause our web app to throw security errors?
Under Chrome's Settings > Privacy > Content Settings, you have the cookie setting set to "Block sites from setting any data".
This checkbox is what is causing the exception.
According to this
This exception is thrown when the "Block third-party cookies and site data" checkbox is set in Content Settings.
To find the setting, open Chrome settings, type "third" in the search box, click the Content Settings button, and view the fourth item under Cookies.
On the following URL: chrome://settings/content/cookies uncheck "Block third-party cookies".
If you're using incognito mode, make sure you turn off "Block third-party cookies".
Open a new tab in any incognito window, and turn off the option:
localStorage is per domain, per protocol. If you are trying to access localStorage from a standalone file, i.e. with file:/// protocol, there is no domain per se. Hence browsers currently would complain that your document does not have access to localStorage. If you put your file in a web server (e.g. deploy in Tomcat) and access it from localhost, you will be able to access localStorage.
I ran into this problem in my phone, I couldn't open a certain site with chrome.
It took me some time to find the cookies on my phone, when I found it, I saw that my cookies was blocked.
go to your Settings --> Site settings --> Cookies
and allow the site to save and read cookie data, make sure that you don't block third-party cookies!
I hope this helps you.
I checked all the answers but ended up not finding anything. Then I realized what browser I'm using. If you're using Brave (Chromium Based), you will get this error if your shield is up. Try lowering your shield.
A more secure way of doing this in Chrome would be to allow only the site(s) that you trust:
Chrome
-> "Settings"
-> "Show advanced settings..."
-> "Privacy"
-> "Content settings..."
-> "Manage exceptions..."
-> (add a pattern such as [*.]microsoft.com)
-> be sure to hit enter
-> "Done"
-> "Done"
If disable block third-party cookies is not an option, you can use try...catch:
try {
// SETUP SESSION, AUHT, LOCALE, SETTINGS ETC
} catch(err) {
// PROVIDE FEEDBACK TO THE USER
}
As has been pointed out in the comments, localstorage is single origin only -- the origin of the page. Attempting to access the page's localstorage from an iframe loaded from a different origin will result in an error.
The best you can do is hack it with XDM via the postMessage API. This library purports to do the heavy lifting for you, but I haven't tried it. However, I would make sure you're aware of IE's terrible support for XDM before going down this route.
imho it has nothing to do with CSP settings on your ember cli app but to do with browser settings.
Some browsers (Chrome) block localStorage content loaded into an iframe.
We too are facing a similar situation for our Ember App,were we have an ember app and a plugin which loads on 3rd party websites, the user token loaded into the iframe gets blocked in Chrom,we are experimenting with some solutions, will keep this thread posted as to how it goes.
To get rid of this warning - under Chrome's Settings -> Privacy -> Content settings, you have to clear the "Block third-party cookies and site data" option
Secure way of doing this in Chrome top right, click on eye logo and allow the site you are on to use third-party cookies:
Check this image if you can't find the eye logo
Clear Cookie
Chrome->setting->privacy and Policy->Sites that can never use cookies In turnremove cookie for local storage.
For all others like me who search for a Javascript solution/fix:
var storageSupported = false;
try
{
storageSupported = (window.localStorage && true);
}
catch (e) {}
if (storageSupported)
{
// your code
}
Credits: https://github.com/zoomsphere/ngx-store/issues/91

Viewing IFRAME independent of whether using HTTP or HTTPS

Let's say I have the following IFRAME. It works fine as long as the browser is viewing the page using HTTP, however, if the browser is viewing the page using HTTPS, it will result in errors, and the IFRAME must be changed to also use HTTPS.
<iframe id="sitePreview" name="sitePreview" src="http://preview.administrator.test6.example.com/index.php?cid=17&preview=1330668404"></iframe>
Without using server script to customize the protocol of the HTML based on the protocol being used to view the page, is it possible to create the URI so that they will work with both HTTP and HTTPS?
Also, please comment if this applies to other links such as:
<img alt="Map" src="http://maps.google.com/maps/api/staticmap?markers=color:blue|31 Milk St Boston MA&zoom=14&size=400x400&sensor=false" class="map">
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places" type="text/javascript"></script>
Keep in mind cross site iframe calls can be tricky, read this article:
http://blog.cakemail.com/the-iframe-cross-domain-policy-problem/, however, since it does load, I'm assuming you are including an iframe from the same domain.
To answer your question, simply drop the protocol off the src, you would reference it as:
<iframe id="sitePreview" name="sitePreview" src="//preview.administrator.test6.example.com/index.php?cid=17&preview=1330668404"></iframe>
This will make sure that it will use whatever protocol the parent is using...
You could also hardcode it to https, but that would mean that every request will serve a secure image which creates unnecessary overhead...
I think this would work:
If(location == "https://whatever.com")
{
//this is https
}
Else
{
//it's http
}
Let me know if I didn't get it right and I will recode it.

accessing https iframe element on chrome-extension

I added an iframe and jquery to my popup.html.
<iframe id="xyz" border="0" src="https://xyz.com/test"></iframe>
and trying to reach an element of this iframe with this command via console :
$("#xyz").contents().find("body").fadeIn();
but it giving this error :
Unsafe JavaScript attempt to access frame with URL https://xyz.com/test from frame with URL chrome-extension://my-extension-id/popup.html. The frame requesting access has a protocol of 'chrome-extension', **the frame being accessed has a protocol of 'https'. Protocols must match**
I searched google for this error but there is no error like this. All of them saying domain must match etc. But this one saying only protocols must match. How can I solve this protocols problem?
And I have this line on my manifest file.
"permissions": [
"*://xyz.com/*"
]
Seems like an issue with same origin policy.
Try following the solution mentioned in this discussion. Also, try doing it through native Javascript first before trying to do it using jQuery.