I have the Content Security Policy:
default-src 'none';
style-src 'self';
script-src 'self' https://www.google-analytics.com;
img-src 'self' https://www.google-analytics.com;
connect-src 'self';
On my page I have put the inline GA code into an async script:
<script src="/javascript/ga.js" async></script>
This causes a CSP error:
Refused to load the script 'data:application/javascript;base64,KGZ1bmN0aW9uKCkgewoJLy8gaHR0cHM6Ly9kZXZl…07Cgl9OwoJZ2EucmVtb3ZlID0gbm9vcGZuOwoJd2luZG93W2dhTmFtZV0gPSBnYTsKfSkoKTs=' because it violates the following Content Security Policy directive: "script-src 'self' https://www.google-analytics.com".
Is there any way to serve this script from a JS file, and if not how would I need to change the CSP?
Google Analytics is CSP-compatible. The base64-encoded data: blob OP is seeing is being injected by the uBlock Origin extension. To verify, disable it/try incognito. IIRC, this is due to an "experimental/unbreak" setting in the extension.
Please resist the temptation to whitelist data: in script-src. That would make the policy completely useless for XSS mitigation, since an attacker could just inject <script src="data:text/javascript,alert(1)"></script> to execute Javascript.
Please see Michele Spagnuolo's answer and upvote.
This is caused by uBlock Origin and it is because data URLs are not whitelisted:
script-src data:;
There is no point in doing this as this could leave your application vulnerable should untrusted data be used as URLs anywhere within your application, or if the attacker can inject tags that use such URLs. This of course depends on the injection point and which characters are allowed.
Of course you should be whitelisting any user entered URLs (e.g. make sure they start with http:// or https://), however as CSP is defence-in-depth measure you probably don't want to weaken it too much.
The upshot is that you're weakening your CSP by doing this in order to prevent a CSP report or error from being triggered.
Related
I want to access a website using javascript. but I am getting the following error in the console.
Refused to connect to 'https://example.com' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
I have added the following meta tag in the index.html,
meta http-equiv="Content-Security-Policy" content="connect-src 'self' http://example.com;" />
Isn't this the right way to add CSP? please help.
You already have one CSP published with the default-src 'self' policy. Quite possible it was done via HTTP header.
Check the Helmet middleware settings in case of NodeJS server, or Header set in the .htaccess file in case on Apache server. In case of Nginx it can be add_header in the config.
By adding <meta> tag you just publish a second CSP, which does not overrides the first one. 2 CSPs works subsequently - all sources should pass both CSP.
Figure out where CSP is publushed and add connect-src 'self' http://example.com; there.
I've just updated the Content-Security-Policy settings in the Web.Config file and added the Application Insights JavaScript snippet in my _Layout.cshtml.
Here is what the Content-Security-Policy in the Web.config looks like.
script-src-elem
'self'
'unsafe-inline'
'unsafe-eval'
https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js
*.mymapjs.com
script-src
'self'
'unsafe-inline'
'unsafe-eval'
https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js
*.mymapjs.com
mymapjs.com is not longer working properly, my maps aren't showing up, and my browser is upset with me yelling at me in red letters with the error:
Access to XMLHttpRequest at 'mymapjs.com' from origin 'mywebsite.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
When I remove the https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js url from the Web.config Content-Security-Policy I get the warning:
Refused to load the script 'https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js' because it violates the following Content Security Policy directive: "script-src-elem 'self' 'unsafe-inline' 'unsafe-eval' https://*.mymapjs.com use.other.net use.other.net/ https://myfont.net/it.js
It turns out I enabled the enableCorsCorrelation = true in the Application Insights configuration.
So then I tried updating the correlationHeaderExcludedDomains values with a wild card value for the mymapjs.com.
correlationHeaderExcludedDomains:
[
'myapp.azurewebsites.net',
'*.queue.core.windows.net',
'*.mymapjs.com'
]
The wild card alone didn't work. I had to strictly type the JS libraries urls AND have the wildcard for it to work properly. It wants the scripts that are directly being requested from the _Layout.cshtml as well as the ones generated from the JS libraries.
correlationHeaderExcludedDomains:
[
'myapp.azurewebsites.net',
'*.queue.core.windows.net',
'*.mymapjs.com'
'https://mymapjs.com-core-events.js'
'https://mymapjs.com-services.js'
'https://mymapjs.com-ui-services.js'
]
If anyone else gets caught up figuring this out, I hope this helps.
Can I inject custom JS in Microsoft Teams? When I tried injecting it says
Refused to load the script 'xxxxxxxxxx.js' because it violates the following Content Security Policy directive: "script-src *.protection.outlook.com 'nonce-yaXPKdhE1aa/JhA/PFsoyw==' 'report-sample' 'self' 'unsafe-eval' 'unsafe-inline' blob: *.office.net *.office365.us *.cms.rt.microsoft.com *.delve.office.com *.teams.microsoft.com *.onenote.com *.presence.skype.com *.streaming.mediaservices.windows.net *.trouter.io ajax.aspnetcdn.com amp.azure.net.
Of course, It's a genuine error. My question is that is there any ethical, legal way to inject even if it requires permission from the admin. In short, Is there any right way to do it?
I am creating a web app using the mean stack in angular 6 but I am getting below error message on the browser console.
"Refused to load the font '<URL>' because it violates the following
Content Security Policy directive: "default-src 'self'". Note that
'font-src' was not explicitly set, so 'default-src' is used as a
fallback."
Code:
getUsers() {
return this._http.get("/api/users")
.pipe(map(result => this.result = result.json().data));
}
Content security policy is a way for modern browsers, to define a set of restrictions when loading remote resources.
Response headers from the HTTP protocol can set those policies:
Content-Security-Policy header (official), X-Content-Security-Policy (supported by Mozilla Firefox and IE10) and X-WebKit-CSP (supported by Google Chrome and Safari) HTTP response headers with the list of Content Security Policy directives. (from seckit drupal module)
You can set different policies to different types of elements in the DOM (e.g <img>, <script>, <object>, <embed>, <iframe> and so on...), to restrict requests that originates from that element.
So you need to change 'self' to one of the following:
'none' - block content from any source
'self' - allow content only from your domain
'unsafe-inline' - allow specific inline content (note, that it is supported by a subset of directives)
'unsafe-eval' - allow a set of string-to-code API which is restricted by default (supported by script-src directive)
Wildcards (*) are allowed:
* - load content from any source
*.example.com - load content from example.com and all its subdomains
example.com:* - load content from example.com via any port. -
Otherwise, it will use your website default port
Adding 'self' and data: to the font-src works for me.
Content-Security-Policy: font-src 'self' data:;
font-src reference doc from MDN
The Content-Security-Policy header is set by your api. Check your api response for its value.
As per the error, I think your fonts are loaded from a different domain than your application domain. Unless your api whitelists that domain, your browser will not load the font.
Example:
Content-Security-Policy: font-src https://example.com/
just close all browser, clear cache and restart VSC or your code editor. Ir worked fro me.
I'm trying to use MathJax as part of our web application which uses pretty strict Content Security Policy (CSP). The problem is that MathJax is coded to use eval() [to be exact, in form of Function()] which is not considered safe by default by CSP.
I'm using following CSP header currently:
X-Content-Security-Policy: allow 'self'; img-src *; media-src *; frame-src *; font-src *; frame-ancestors 'none'; style-src *; report-uri '/:save-csp-violation';
Which causes MathJax 2.0 code to fail because it uses Function(). I tried to allow unsafe-eval (i.e. Function()) only for MathJax located within the same origin below path /:static/math/. To do that, I tried to add
unsafe-eval '/:static/math/*'
to make the full header look like
X-Content-Security-Policy: allow 'self'; img-src *; media-src *; frame-src *; font-src *; frame-ancestors 'none'; style-src *; report-uri '/:save-csp-violation'; unsafe-eval '/:static/math/*'
but I still cannot Firefox 13.0 to run the code. I'm getting an error message to Firefox Web Console (located in Tools - Web Developer):
[10:09:59.072] call to Function() blocked by CSP # http://localhost:8080/:static/math/2.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML:29
However, I'm not getting a CSP report to the 'report-uri'. (As you see, I'm currently running the test through custom localhost port without SSL, in case that makes a difference. The colon before static is not a typo, I'm reserving all path parts starting with a colon for internal use of the application, all user content may freely define other URLs.)
Is my use of unsafe-eval attribute incorrect or is it impossible to allow unsafe-eval only for subset of 'self'? The intent is to allow unsafe-eval only for same origin path prefix /:static/math, strict CSP JS code execution for 'self' and no JS code for any other method.
There're multiple issues:
The Content-Security-Policy (CSP) header does not work this way. CSP only has granularity of a single host+port combination (origin). If you cannot allow all scripts to have unsafe-eval, no script can have it. The only possible workaround is to not use a script that requires unsafe-eval (fortunately, MathJax no longer requires unsafe-eval since MathJax bug 256 was fixed).
The allow syntax is an old Mozilla variant and should not be used. The current syntax is to say default-src followed by scheme or host names or origins that are allowed as source of everything and then override the default value for each sub type (e.g. script-src) as needed. Some sources may support additional source keywords in addition to self. For example, the script-src supports unsafe-eval which means that any script that is otherwise allowed to execute is allowed to run eval() or Function(), and unsafe-inline meaning that any piece of markup that can support some kind of inline script is allowed to execute. Allowing unsafe-eval may be acceptable but unsafe-inline is pretty much no-go with script-src (otherwise, you should not bother with the CSP at all).
The correct syntax for script-src as follows:
script-src 'self' cdnjs.cloudflare.com
combined with loading MathJax from https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js
MathJax also uses inline style attributes so following is needed (unless already allowed) or MathJax will raise Exception while trying to render the math:
style-src 'self' 'unsafe-inline'
It is not possible to use CSP to allow JS to insert style attributes and not have style attributes already inserted in the HTML source to have an effect.
It seems that Firefox 13.0 (at least) does not immediately "call home" in case of CSP violation. Most of the violation reports do get submitted some time after the event. Chrome seems to be much more aggressive with the report submission which will make it a bit easier to test. From my experience, Firefox does not always send CSP report at all - it may be using some kind of heuristic to not send repeated messages.
In the end, to make MathJax work with Content-Security-Protection, you need following headers (assuming you're using MathJax via CDNJS):
Content-Security-Policy: default-src 'self'; script-src 'self' cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline';
Older browsers (e.g. Firefox 13) used to require extra parameters such as options or required using non-standard headere name such as X-Content-Security-Policy or X-WebKit-CSP. These hacks are no longer required because user agents support standard header nowadays. (With the exception of MSIE in contrary to MS Edge.)
Year 2021 Update:
CSP version 2 allows specifying paths in origins, too. However, be warned that using paths is a breaking change where backwards compatibility is a bit unknown. The problematic part is that server needs to emit CSP header before it knows if user agent supports CSP1 or CSP2.