How to fix CSP script-src-elem Error although it is being defined? - node.js

I have something like this in a meta tag in my pug. I have a ton 2 3 CDN in my File.
meta(http-equiv='Content-Security-Policy' content="default-src * 'unsafe-inline' 'unsafe-eval'; script-src-elem * 'unsafe-inline';" )
I get an error something like this although I have defined the script-src-elem.
Refused to load the script '<URL>' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
I would really appreciate your help. Thank you in Advance

Let me guess. You use PUG linked with Express. In the Express you use Helmet security middleware.
The point is that Helmet 4 publishes CSPs by default via an HTTP header, and
script-src 'self' is a fragment of this Helmet's default CSP.
Since you have one CSP published, you can't relax it using a meta tag. In case of 2 CSPS published all sources should pass unscratched through both CSPs. Therefore your script-src-elem * 'unsafe-inline' from meta tag does not trigger violation, but script src 'self' from the CSP HTTP header - does rise it.
You have to remove meta tag and configute Helmet via helmet.contentSecurityPolicy(options). Or disable CSP in Helmet and use a meta tag:
app.use(
helmet({
contentSecurityPolicy: false,
})
);

Seems like your browser does no support this directive.
The Message you get is explained on MDN script-src-elem
If script-src-elem is absent, User Agent falls back to the script-src
directive, and if that is absent as well, to default-src.
And by the way:
specifies valid sources for JavaScript elements, but not inline script event handlers like onclick

Related

How to change Content Security Policy by meta tag?

I build a MERN app in which I used Stripe for payments but when I upload it over heroku the following error comes:
I tried to set Content Security Policy meta tag in header of index.html as
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src *; img-src *; connect-src * ; style-src *; font-src * ">
Even then I got the same error while I set script-src to '*'.
I have also used helmet to set headers as:
app.use(
helmet()
);
Please just some ways to remove this error.
You can't relax a CSP by adding another one, by adding another one the result can only become stricter. You need to identify where and how the preexisting CSP is set and modify it to allow whatever you need to run.

antiClickJack snippet's style tag part being inline requires unsafe-inline. How can we avoid the use of unsafe-inline?

I am working on Drupal 9.3.8 site and using CSP module to setup the CSP header.
There are few core dependencies or contrib modules which require unsafe-inline in CSP header but scanner recommends not the have unsafe-inline, so looking for the fix to remove the use of unsafe-inline.
Dependencies that require unsafe-inline:
Drupal core ckeditor, modernizer and AJAX calls - which can be handled by CSP module used above which adds unsafe-inline only when ckeditor renders, but not when only modernizer is required.
Google Analytics module - which adds the script inline instead of putting it in a file and include it on each page. We have the patch compatible with D7 but not for D8/9.
AntiClickJack snippet which is as below:
<style id="antiClickjack">body{display: none !important;}</style>
Solutions:
Installed and setup CSP module as mentioned above to handle Drupal core libs/dependencies requirement.
To handle only rendering of modernizer.js and unsafe-inline, will need customization to the CSP module.
For antiClickJack and google analytics script and style tags, cannot add hash or nonce as unsafe-inline will be ignored which will break the handling of Drupal core requirements
CSP header that I have is as below:
Content-Security-Policy: default-src 'self'; connect-src 'self' www.google-analytics.com; frame-src 'none'; img-src 'self' data: https://www.google-analytics.com; object-src 'none'; script-src 'self' www.googletagmanager.com www.google-analytics.com ajax.googleapis.com 'unsafe-inline'; script-src-elem 'self' www.googletagmanager.com www.google-analytics.com ajax.googleapis.com; style-src 'self' 'unsafe-inline'; frame-ancestors 'none';
Questions:
How to handle antiClickJack snippet to avoid the use of unsafe-inline?
Do we have a customized approach to add the google analytics script to a file instead of adding it inline?
Add the following hash to your style-src: 'sha256-NHgJfLahpnqTyd+gTNfZfM2wjTUfB3Wk1CvqZfZpeHY=' Most browsers will suggest a hash for you, or you can use https://report-uri.com/home/hash. Note that the hash works as long as the content is unchanged, so only use it for static code.
Google Analytics and Google Tag Manager are not easy to implement without 'unsafe-inline'. You might be able to move to a file, but I don't know if that has an impact on the order of events. You will also need to look into CSP nonces for the code they insert. You will need to configure them to use your nonce and make sure that a new nonce is created for every page load. My experience is that setting a custom value for the nonce and change it for every page load is not trivial or possible within some frameworks, but worth giving a try.

CSP Image Base64 not loading with proper server configuration

Yes, another question about the CSP not loading a base64 image BUT I have researched a lot and can't find the solution. I have tried every configuration I've founded and still doesn't works.
So, what I'm trying is to load an Base64 image via Javascript.
var dataString = jQuery('#signature').jSignature('getData');
JQuery('#sig').append("<img class='imported' src='" + dataString + "'></img>");
As you can see it's not a big deal appending the base64 image (in localhost it works).
Then, searching about the CSP I found that the correct configuration to avoid the CSP with the Base64 Images is (and this is how I have the configuration):
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:; font-src 'self' data:";
I have no problem with the font base64 but with the images it always throws this error:
Refused to load the image 'data:image/png;base64,...' because it violates the following Content Security Policy directive: "default-src *". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
Any ideas will be really appreciated, I really have no idea what is happening.
Have you tried as #Phonolog said. I have tried creating a plugin to support image url in importData rather than data-url-formatted.
Please check this post and see if it helps.
Create a jSignature plugin which sets the img src to the signature url.
inject the plugin
on importData remember to pass the plugin identifier
This way you can remove the data: from the csp header and self should be enough (img-src 'self')

Content Security Policy ignored by Latest Chrome Update

My CSP policy is being ignored by the latest version of Chrome. I decided today to recreate the policy to try debug why, but as you can see from the error below, Chrome is advising me to add a hash that is already in the CSP (see sha256-idz8mDU5fJ8lJuEwY6hbkXVde/nqBBjQE/u5rxw1HUk=):
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://pro.fontawesome.com/ 'sha256-LpfmXS+4ZtL2uPRZgkoR29Ghbxcfime/CsD/4w5VujE=' 'sha256-F+21FF3QOEHS5CNuMQEs3Q+LB0uULZF9DODEYnH/mMQ=' 'sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=' 'sha256-nK6A3vwzvwoN92MnHZrWtylYkYmW1jCQgTqWKQJNBMI=' 'sha256-idz8mDU5fJ8lJuEwY6hbkXVde/nqBBjQE/u5rxw1HUk='". Either the 'unsafe-inline' keyword, a hash ('sha256-idz8mDU5fJ8lJuEwY6hbkXVde/nqBBjQE/u5rxw1HUk='), or a nonce ('nonce-...') is required to enable inline execution.
This is working correctly in Firefox and Safari, so I'm thinking that there is something in my policy that is causing Chrome to stop reading values?
The content of my .htaccess file is:
Header set Content-Security-Policy "default-src 'none'; connect-src 'self'; font-src 'self' https://pro.fontawesome.com/; frame-src 'self'; img-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' https://pro.fontawesome.com/ 'sha256-LpfmXS+4ZtL2uPRZgkoR29Ghbxcfime/CsD/4w5VujE=' 'sha256-F+21FF3QOEHS5CNuMQEs3Q+LB0uULZF9DODEYnH/mMQ=' 'sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=' 'sha256-nK6A3vwzvwoN92MnHZrWtylYkYmW1jCQgTqWKQJNBMI=' 'sha256-idz8mDU5fJ8lJuEwY6hbkXVde/nqBBjQE/u5rxw1HUk=';"
Any advise is greatly appreciated.
I think this resource answers your question:
https://bugs.chromium.org/p/chromium/issues/detail?id=546106
The styles being blocked in the examples are styles in a style
attribute, Chrome only applies styles in style attributes when
'unsafe-inline' is set in 'style-src'. Safari behaves similarly but
Firefox does apply the styles if they match a hash in 'style-src'.
The CSP specification defines the hash and nonce exceptions only for
the and elements, not for the style and script
attributes so Chrome's behaviour seems to follow the spec. But the
error message generated in the console is incorrect (and confusing).
By the looks of it Chrome is following the CSP specification. I was facing the same issue with inline styles and seeing the same response as you, matching sha256 hashes! My solution has been to remove my inline styles and add them into my CSS to avoid inline styles completely.
While the console logged:
Refused to apply inline style because it violates the following
Content Security Policy directive: "style-src 'self'
'sha256-tLBf5MoZ1LfLjLmXgREJmfznfoX6mUwoWQJnC30N6JI='. Either the
'unsafe-inline' keyword, a hash
('sha256-tLBf5MoZ1LfLjLmXgREJmfznfoX6mUwoWQJnC30N6JI='), or a nonce
('nonce-...') is required to enable inline execution.
The solution would be to add 'unsafe-hashes', like so: style-src 'self' 'unsafe-hashes' 'sha256-tLBf5MoZ1LfLjLmXgREJmfznfoX6mUwoWQJnC30N6JI='.
See the 'unsafe-hashes' directive: https://w3c.github.io/webappsec-csp/#unsafe-hashes-usage

Kendo widgets does not work when CSP is enabled

I have ASP.NET Core application and i am using Telerik's UI for ASP.NET Core framework for certain widgets like Date, DropDownList, Charts etc.
Application is loading all javascripts, images, css from its own server. So i have enabled CSP policy as below
script-src 'self' 'unsafe-eval';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
font-src 'self';
media-src 'none';
object-src 'none';
child-src https://xxxx.yyyy.com;
report-uri http://myapplication/csp/report;
However when the page load i see error in chrome's console
Refused to execute inline script because it violates the following
Content Security Policy directive: "script-src 'self' 'unsafe-eval'".
Either the 'unsafe-inline' keyword, a hash
('sha256-oii70XYoqukWS9204nbwatxgYOYcr06+rftc4egdfUk='), or a nonce
('nonce-...') is required to enable inline execution
this error is repeated for several Kendo widgets that i'm using on that page. For example date widget. In cshtml i have configured date as below
#(Html.Kendo().DatePicker()
.Name("sbDate")
.HtmlAttributes(new { #class = "mydate" }))
which gets render in html as
<input class="mydate" id="sbDate" name="sbDate" type="date" value="" /><script>jQuery(function(){jQuery("#sbDate").kendoDatePicker({"format":"M/d/yyyy","footer":false});});</script>
I have already gone through Telerik's suggestion here and here for CSP. And as per the suggestion i only i have to add unsafe-eval to get widgets working. However looks like that is not true. I also have to add unsafe-inline to get widgets working.
But the whole point of enabling CSP is to not allow inline scripts.
Questions
Is there any way to solve this issue?
Update 1
Widgets only works in IE 11 without adding unsafe-inline. In chrome and IE edge widget requires unsafe-inline to work.
The solution below might work (i have not tried yet)
1> Add Deferred method for each kendo widget. Like
#(Html.Kendo().DatePicker().Name("BeginDate").Deferred())
2> In each view that is using Kendo control, at the bottom add the script tag
<script asp-add-nonce="true">
#Html.Kendo().DeferredScripts(false)
</script>
Note that asp-add-nonce is not out of the box from asp.core. You have to install Joonasw.AspNetCore.SecurityHeaders nuget library. I found this article from the author that shows how to configure CSP for .net core application and also how to generate new nonce for each request.
3>Dont configure CSP policy in web.config because we need different nonce value for each request, instead configure the CSP policy using Joonasw.AspNetCore.SecurityHeaders middleware as mentioned in the article.
4>I thinks we don't need to add unsafe-inline if we use random nonce (unless you are targeting to older browsers)
I can't really tell if this would solve your issue, but in our Application, we are using the Deferring feature, but for other reasons. Our reason is that we load all scripts (esp. jquery.js) at the end of the page. But the side effect is that no jQuery script calls are rendered into the page anymore. You can control the place to generate all scripts by executing #Html.Kendo().DeferredScripts() (but you will find more help in the docs above). Anyway, probably in the context of CSP, even that <script> block at the very end of the page is still considered "inline". But give it a try.

Resources