Content Security Policy

I got distracted looking at some issue or another, and came across: securityheaders.com
Where, exactly, on the scale of "completeness" this site falls, I'm not sure, but I do know that a grade of F is unacceptable.
Looking at the results I realize I've completely left out the <customHeaders> section in web.config.
Fixes can be done in IIS or web.config. In my instance I chose web.config, for awhile. I'm not going into any details here, but locking down inline JavaScript and CSS is a pain, and I use it extensively in my Admin pages, so the web.config route was abandoned in favor of creating a 2nd master page for the admin area with more relaxed rules.

The Master Page Code - (public pages)

The following code is inside Page_Init() in the master page. I'm just covering the Content-Security-Policy header here, add more to the collection item if necessary.

// !!! need to trim \r, \n, \t from the following lines, the CSP "value" won't be valid for the browser otherwise.
string csp_val = @"
	default-src 'self' cdnjs.cloudflare.com;
	script-src 'self' https: 'unsafe-inline' 'unsafe-eval' unpkg.com;
	style-src 'self' cdnjs.cloudflare.com cdn.jsdelivr.net unpkg.com;
	img-src 'self' data: w3.org/svg/2000;
	font-src 'self' cdn.jsdelivr.net;
	worker-src 'self' blob:;";

NameValueCollection collection = new NameValueCollection
{
	{ "Content-Security-Policy", Util.TrimWhiteSpaceSpecials(csp_val) }			
};

Response.Headers.Add(collection);

Note the comment - without trimming out \r and \n, (and \t for good measure), the error will be obvious in the Console of the Dev Tools, (a.k.a. F12), section of the browser.
Here's the header value - note the %0d%0a blocks:
Here's the console error:
The function TrimWhiteSpaceSpecials() inside Util.cs is quick and dirty:

public static string TrimWhiteSpaceSpecials(string s)
{
	return s.Replace("\r", "").Replace("\n", "").Replace("\t", "");
}

And that's it. Adjust the header and add more if needed, just remember to somehow trim the \r, \n and \t chars out of the string before .Add()'ing them to the header.

Remedy for Inline CSS

Here's a quick example of what needs to be done for some common (for me) CSS, which simply shows/hides a div element.

The commented section uses CSS, while the un-commented section uses classes.


function fnToggleDiv(idDiv) {

	var fldDiv = document.getElementById(idDiv);

	// applies classes
	if (fldDiv.classList.contains('d-none')) {
		fldDiv.classList.remove('d-none');
		fldDiv.classList.add('d-block');
	}
	else {
		fldDiv.classList.remove('d-block');
		fldDiv.classList.add('d-none');
	}

	// uses inline CSS
//	if (fldDiv.style.display == 'none') {
//		fldDiv.style.display = 'block';
//	}
//	else {
//		fldDiv.style.display = 'none';
//	}

	return false;
}

Not too bad, but this can be a bit time consuming, which is why I use a separate CSP header for Admin pages.