I am attempting to use the new Content Security Policy (CSP) HTTP headers on a test site. When I use CSP in conjunction with Modernizr I get CSP violation errors. This is the CSP policy I am using:
Content-Security-Policy: default-src 'self'; script-src 'self' ajax.googleapis.com ajax.aspnetcdn.com; style-src 'self'; img-src 'self'; font-src 'self'; report-uri /WebResource.axd?cspReport=true
These are the errors from the Chrome browser console:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. window.Modernizr.injectElementWithStyles - modernizr-2.7.2.js:134 window.Modernizr.tests.touch - modernizr-2.7.2.js:457(anonymous function) modernizr-2.7.2.js:949(anonymous function) - modernizr-2.7.2.js:1406
I discovered the following workaround on the Github Modernizr site. However, the workaround was first put forward in March and doing a little Google-Fu I can find no fixes or workarounds to this issue.
I know that I can include the unsafe-inline directive which can get around this error but this also enables unsafe code to run and negates the use of CSP in the first place. Does anyone have any solutions?
Update - What is CSP
CSP is a HTTP header supported by all major browsers (Including Edge). Essentially its a white list of content the browser is allowed to use to render the page. Find out more here or read Mozilla's documentation for CSP here and here.
Update - Help Highlight CSP
CSP is now available on all browsers (Edge added support, yay!) and its a gigantic leap forward in web security. For those interested in getting more third party support for CSP, see these:
When you see any of the following messages logged in the browser devtools console, it indicates that a problem related to CSP has occurred. The page's settings blocked the loading of a resource at %2$S ("%1$S").
Turn off the CSP for your entire browser in Firefox by disabling security. csp. enable in the about:config menu. Note: You must log in to the ELM instance in the new tab of the same browser before you access the resource or configuration picker through Publishing Document Builder.
If the application is using angular JS and scripts are loaded from a whitelisted domain. It is possible to bypass this CSP policy by calling callback functions and vulnerable class.
Content Security Policy blocks all resources that don't match it's policy. To view the policy for a specific website use the CSP Evaluator.
I suspect there's no other solution than to rewrite the parts of Modernizr that use inline code or dynamically evaluated code (which applies to both JS and CSS). The experiences of AngularJS ngCsp might be useful here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With