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

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.

Related

Google Tag Manager - Any possible way of adding CSP nonce to Custom HTML snippets? Script attributes get stripped

I'm implementing CSP on an existing website and have been following along with this article on passing a CSP nonce to GTM and using it as a Custom Variable in GTM.
<script nonce="9CZ9vGge7C9At2iwrPtSNG7Ev10=" id="gtmScript">
<!-- Google Tag Manager -->
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');
n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MYID');
<!-- End Google Tag Manager -->
</script>
Variable gets added as a DOM Element Variable. Then I add the variable value to my custom script. Here is a demo script. It is the entirety of a Custom HTML tag in GTM.
<script nonce="{{nonce}}">
console.log("CSP-allowed script with nonce:", "{{nonce}}");
</script>
The issue is, CSP still blocks this. And it has nothing to do with the {{nonce}} variable - proven by changing CSP to 'unsafe-inline' and seeing the correct value output in console.
I have since been reading that GTM strips attributes out of the tags it injects inline. Which would be odd, as it would mean the linked article above actually never would have worked (it's only a 3 month old article). But does this mean that it's physically impossible to get scripts in Custom HTML GTM tags to function with CSP? The solution in the above link is impossible because the script will always be blocked by CSP.
UPDATE: Here is my CSP
<meta http-equiv="Content-Security-Policy" content="
default-src 'none' ;frame-src 'self';
script-src 'self' 'nonce-$CSPNonce' *.googletagmanager.com;
style-src 'self' 'nonce-$CSPNonce';
font-src 'self';
img-src 'self' 'nonce-$CSPNonce' data:;
connect-src 'self'">
And the console error
gtm.js?id=GTM-MYID:782 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-mQoPSCSszFQ8loJF5jii6quCHeY=' *.googletagmanager.com". Either the 'unsafe-inline' keyword, a hash ('sha256-3kt898DvY8z+SqQyfz8g06pUzzBokMjvzcQ5uN50wTs='), or a nonce ('nonce-...') is required to enable inline execution.
OK I found the cause here. I'm leaving the question up in case someone stumbles across this in future.
When you create a Custom HTML tag in GTM, under the code window is a tickbox called "Support document.write". The tooltip beside it doesn't mention much other than allowing you to use document.write() in your scripts via a "new rendering engine".
For whatever reason, if this is not ticked, the nonce attribute is stripped. With it ticked (using the new rendering method I guess), it is not stripped.
You must both turn on support for document.write AND use an additional alternate name for your nonce attribute. Between GTA and chrome your nonce value will be eaten for security reasons.
<script nonce="NONCEHERE" data-dsn="NONCEHERE" id="gtmScript">
<!-- Google Tag Manager -->
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;var
n=d.querySelector('[nonce]');n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MYID');
<!-- End Google Tag Manager -->
</script>
Then use the data-dsn attribute to pull it into GTM.

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

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.

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.

Content Security Policy and Google Analytics without unsafe-inline?

Currently, my CSP config in Apache looks like that:
Header set Content-Security-Policy "default-src 'self' 'unsafe-inline' https:"
I'd like to remove the unsafe-inline directive to improve my site's security, see Mozilla's Observatory.
Nevertheless, whenever I remove it, my browser's console shows an error indicating that the inline GA couldn't load…
Is there a workaround?
Sorry to Edit again. The proposed solution in
New Google Analytics code into external file
did not work for me. instead i got it to work like this:
i add a script tag to my page to load the analytics.js:
<script src="https://ssl.google-analytics.com/analytics.js" async id="ga"></script>
<script src="my_other.js" async></script>
and then in my_other.js file i do this:
window.addEventListener("load", function(){
ga('create', 'UA-********-1', 'auto');
ga('send', 'pageview');
})
then in your csp header you have to set some exeption to script-src and image-src. somthing along these lines:
img-src data: 'self' *.google-analytics.com *.g.doubleclick.net;
script-src 'self' *.google-analytics.com
As an alternative work-around, you can allow specific, static scripts by adding the script's hash to your content security policy. (A nonce works for dynamic scripts):
Hash your script (e.g., using sha256). Do include white space/capitalization. Don't include the script tags.
Add script-src 'sha256-[MYHASH]' to your content security policy.
See MDN for details. Not supported on IE11 .

Google Analytics and Content-Security-Policy header

The Content-Security-Policy HTTP header is meant to block inline script and resources from untrusted servers. However, the sample Google Analytics code snippet depends on both. What are the best practices in this area?
This is the Content-Security-Policy header that I'm currently using:
default-src 'self'; script-src 'self' https://ssl.google-analytics.com; img-src 'self' http://www.google-analytics.com/__utm.gif https://ssl.google-analytics.com/__utm.gif;
So far, I've done the following:
I added two script tags to my html:
<script src="/js/google-analytics.js"></script>
<script src="https://ssl.google-analytics.com/ga.js" async="true"></script>
google-analytics.js sets up the _gaq array with _setAccount and _trackPageview.
I added the domain for ga.js to the script-src.
I noticed that ga.js was loading two images, so I added them to img-src.
Is there anything I'm missing? Will Google change things on me and break all of this? Is there any official recommendation?
This is mostly right:
You don't need the path to the image, just the protocol + host + (implied) port
Firefox differs slightly in its CSP implementation. For older versions, replace default-src with allow. There was a cutoff where Firefox supported default-src as equal to allow but most still implement with allow until it fully supports the spec (no citation included).

Resources