Not able to apply css to the asp.net mvc login page where it says refuse to apply inline css, - asp.net

Not able to apply css to the asp.net mvc login page. chrome browser says
'Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-PyLHmjCk4/4GwQUxB5Nv2ZOIHPu1XXusXCu09QBy+nc='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.
enter image description here
Thanks in Advance.

It looks from the error message that you have an inline style, which CSP blocks. You can put that style in your CSS file instead.
You can also use style-src 'self' 'unsafe-inline'; in your content-security-policy declaration, but this is not recommended for security concern.
Check this OWASP explanation for more details.

Related

Why does Content-Security-Policy header calls "inline" scripts "unsafe"?

Had to set Content-Security-Policy header to...
default-src https: 'unsafe-inline';
object-src 'none'
... for a single html page with no dependencies (with inline scripts) to run the <script> tag.
Why is inline considered unsafe?
MDN says inline are excluded but it doesn't say why, same in reference.
CSP protects against XSS injections.
If a user is able to inject a <script> tag or onclick, because you forgot to escape user-input CSP will prevent that Javascript from running.
So for security purposes it can be good to just avoid any inline scripts altogether, so you can say: "Anything appearing in my HTML body is unintentional and should be blocked", and this is definitely a recommended practice.

Electron: Security concern regarding inline styles in an iframe

Question: I'm trying to load an external script (let's say from example.com) in the Electron app. The External script loads everything in an iframe and it's using inline styles, which renders the widget without any styles due to Electron CSP. I don't want to use unsafe-inline CSP on the whole application, I need it just on this iframe which comes from "example.com".
Error which I get: Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'"
For resolving this I am thinking to add this code block in my electron app -
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
if(details.url.includes("example.com") && details.url.includes(".html")) {
callback({
responseHeaders: Object.assign({
"Content-Security-Policy": [ "default-src 'self';style-src 'unsafe-inline' https://*.example.com https://example.com" ]
}, details.responseHeaders)});
}
This code block will ensure to have 'unsafe-inline' CSP only in the iframes of "abc.com". But, I want to check that can this code block still cause any kind of security threat to my app?
Does your iframe contain any user entered data? If not then this is fine. If it does then you will need to find another way to check they have not entered any inline styles

Getting "Refused to apply inline style because it violates the following Content Security Policy" error

I am getting the below error while running the application
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/ 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs='". Either the 'unsafe-inline' keyword, a hash ('sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ='), or a nonce ('nonce-...') is required to enable inline execution.
Below is the code currently I am using
const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
app.UseCsp(options => options
.DefaultSources(s => s.Self())
.ScriptSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/"))
.StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))
.FontSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/"))
.ImageSources(s => s.Self().CustomSources("data:"))
);
The hash 4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ= is for the CSS word-wrap: break-word; white-space: pre-wrap;, the inline style Chrome automatically applies when you are not serving a HTML document;
Example server response:
Content-Type: text/plain; charset=utf-8
Content-Length: 9
Content-Security-Policy: default-src 'self'
Date: Thu, 04 Nov 2021 11:33:49 GMT
some text
DOM in Chrome
<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">some text</pre></body></html>
Console error
Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'"
. Either the 'unsafe-inline' keyword, a hash ('sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ='), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.```
Adding the hash to default-src or style-src won't help because it is an "inline style" and "hashes do not apply to style attributes".
The best fix is to make sure you serve a proper HTML document with your CSP header, so browsers don't decorate it with their own styling.
You are getting this error because the inline styles (which can be hashed to sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=) aren't allowed, as per your Content Security Policy and the error that is returned.
I would recommend two possible steps, either:
Move away from inline styles (as they can be insecure) and will require you to change your CSP each time that the inline styles change.
Add the supplied SHA to the StyleSources for your CSP. But Be aware that this will have to be maintained and updated for each inline style added across all pages in your application.
UPDATE based on comments below answer
Note: There is no issue when i am running it in IE browser, only in the chrome and firefox i am getting the issue
Taking a look at Can I Use shows that IE has only partial support for Content Security Policy, which would explain why you aren't seeing this error in the console. i.e. Internet Explorer doesn't support CSP, so it isn't applying it.
I have fixed the issue by changing the hash keys shown in the browsers console error, I have replaced the console error hash key with my code hash key, but not sure whether this is the permanent solution or not
This is not really a permanent solution. If (and when) your inline styles change, you will have to change the hash in your CSP in order for the styles to be applied again.
Which leads me on to:
Could you please guide me how the hash keys are getting generated and how i can fix this permanently
Looking at the code in your original question:
const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
// other things
.StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))
You are telling the browser (via the Content Security Policy that you are generating) that it is only permitted to load styles from:
self (the origin domain of your site)
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/
and those which match the following hashes:
sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=
You mention that you've also included the hash:
sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=
When the browser starts to render the page, it will look at the resources that the page requires in order to render and will compare it to the list in the Content Security Policy. If a resource (inline styles and inline javascript are classed as a resource) is not in the list, then the browser will do a simple SHA-2 of the contents of the resource and compares it to any of the hashes listed in the CSP.
Note: the same thing can be achieved by the use of a nonce
If the resource isn't from an allowed source, or it's hash does not match those listed in the CSP, then the browser will actively refuse it.
Because the SHA-2 algorithm uses the content of the resource to generate the hash, when the contents of it changes the calculated value of the hash will be different.
For example, the inline style here:
<p style="color: red;">hello, world</p>
might hash to F1FF77E5DDBB1AF52EB51C98F725927143221549385937595112128987CF39E4 (which is the hash of "color:red")
whereas the following inline style:
<p style="color: green;">hello, world</p>
might has to 2F262B22412B633D12B27FA9F94A3B0495821CB8341CFF0A88C80E3FED5DC9E8 (which is the hash of "color:green")
As you can see, there is a massive difference in the hashed styles. This is by design (in the algorithm).
To stop alleviate this problem, I would swap the inline styles for a css file describing how the content of the page should be styled. As long as the css file is served from the same origin as your HTML, then the self rule will cover it.
CSP is a pretty complex topic to pick up (but easy to master, once you have learned the basics). I would recommend taking a look at the MDN page for Content Security Policy for more information on how it works and how you can use it to secure your web applications.

How to define a Content Security Policy (CSP) that utilizes 'strict-dynamic' but includes fallback to use 'unsafe-inline'?

I'm implementing the CSP header on a website that needs to dynamically load some scripts due to various reasons (mostly plugins).
This is easily achieved by defining script-src using 'strict-dynamic' along with a hash/nonce for the non-dynamic scripts.
The recommendations everywhere suggest also including some high level sources/schemes and 'unsafe-inline' as fallback, in case the browser doesn't support CSPv3 and thus, doesn't support 'strict-dynamic' and dynamic loading:
script-src: 'strict-dynamic' 'sha256-somesortofhash...' https: 'unsafe-inline';
This fallback method will work fine for browsers that only support CSPv1:
'strict-dynamic' is ignored (unrecognized).
hash value is ignored (unrecognized).
https: and 'unsafe-inline' are enforced.
But doesn't seem to work for CSPv2 browsers:
'strict-dynamic' is ignored (unrecognized).
hash value is enforced.
https: is enforced.
'unsafe-inline' is ignored (due to enforcement of hash).
How can I define a policy with proper fallback for CSPv2 browsers as well?
'strict-dynamic' was designed mostly to work in combination with nonces. You are right - there is no perfect CSPv2 fallback when used in combination with hashes.
The uncovered case is dynamically generated inline scripts - a rare pattern, in my experience:
var s = document.createElement('script');
s.innerText = 'alert(1)';
document.body.appendChild(s);
will not work in CSPv2-compatible browsers, and the best solution in that case is to do UA sniffing and not send a policy at all.
Sourced scripts will work just fine.
On the other hand, a nonce-based policy such as:
script-src 'nonce-r4nd0m' 'strict-dynamic' 'unsafe-inline' https:
will fall-back gracefully, because for the case above you can always set a nonce manually:
var s = document.createElement('script');
s.setAttribute('nonce', 'df7Af03DRTs66pP');
s.innerText = 'alert(1)';
document.body.appendChild(s);
More about backward compatibility and fallbacks in our presentations[1][2].
[1] https://speakerdeck.com/mikispag/content-security-policy-a-successful-mess-between-hardening-and-mitigation?slide=52
[2] https://speakerdeck.com/mikispag/so-we-broke-all-csps-dot-dot-dot-you-wont-guess-what-happened-next-michele-spagnuolo-and-lukas-weichselbaum?slide=15
Your policy:
script-src: 'strict-dynamic' 'sha256-somesortofhash...' https: 'unsafe-inline';
It utilizes hash and it is not well suited with strict-dynamic, I would suggest using nonce-{randomNumber} and it could solve your issues.
I would suggest checking your policy with https://csp-evaluator.withgoogle.com. It would help you with all the attributes as per the version whether they are supported with the corresponding CSP version.
And if you need more help around CSP3 you could look at this:
Firefox refuses to load any scripts with strict-dynamic set

Google maps API error "refused to load font"

I am using Google maps in my angular2/Ionic2 app and I get the following error:
js?libraries=geometry,drawing,places:79 Refused to load the font
'https://fonts.gstatic.com/s/roboto/v15/isZ-wbCXNKAbnjo6_TwHThJtnKITppOI_IvcXXDNrsc.woff2'
because it violates the following Content Security Policy directive:
"font-src 'self' data:".
What is this error, and how can I fix it?
My index.html has:
<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src * data:; default-src * 'unsafe-eval' 'unsafe-inline'">
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing,places"></script>
Removing the meta tag solves the problem, but I am not sure what it does and whether I should remove it.
This is not about inline javascript, but inline style tags. Either you have them (probably not), or you are using something (possibly a jquery plugin) that is adding them. Based from this blog, you ned to enable it by adding the configuration from https://github.com/rwjblue/ember-cli-content-security-policy#options into your config/environment.js.
The default contentSecurityPolicy value is:
contentSecurityPolicy: {
'default-src': ["'none'"],
'script-src': ["'self'"],
'font-src': ["'self'"],
'connect-src': ["'self'"],
'img-src': ["'self'"],
'style-src': ["'self'"],
'media-src': ["'self'"]
}
Check these related links: Violating Content Security Policy directive after ember-cli 0.0.47 upgrade and "[Report Only] Refused to load the font..." error message on console

Resources