Violates the Content Security Policy

This Date script won’t run when the page loads because it violates the CSP at top (it worked before adding the CSP). Yet it surely isn’t inline JS, is it? Why would it not run? (This page is “company1.”)

<meta http-equiv="Content-Security-Policy" content="default-src www.company1.com https://www.company2.com https://company3.com; script-src 'self' www.company1.com; child-src 'none'; object-src 'none'; font-src 'none'; plugin-types 'none'; frame-src 'none'; media-src 'none'; form-action www.company1.com;">

    <div class="rowgr pad2">
        <div class="rowflleft cen">
            <p><span id="copyright">&copy;2012-<span id="year"></span> company name, Inc.</span></p>
        </div>
    </div>
<script>
    var d = new Date();
    document.getElementById("year").innerHTML = d.getFullYear();
</script>

I think this needs to be moved to the JavaScript department.

Moved, as requested.

How do I make the following images not be rejected by the CSP for “company1”? After all, I added img-src… to it as an exception:

<meta http-equiv="Content-Security-Policy" content="default-src www.company1.com https://www.company2.com https://company3.com; img-src www.company1.com https://www.company2.com https://company3.com; script-src 'self' www.company1.com; child-src 'none'; object-src 'none'; font-src 'none'; frame-src 'none'; media-src 'none'; form-action www.company1.com;">

It needs to apply here:
<link rel="icon" type="image/png" sizes="48x48" href="http://www.companyname.com/ae/icon_48.png">

Moved back to general web dev since you’re no longer asking about JS files :wink:

1 Like

:roll_eyes: Got it! I deleted the earlier messages to cut down on scrolling.

You seem to have an incomplete or incorrect idea about what CSP is. I think it might help to read up some more on what CSP actually is and what it’s for.

Yes, it is.

If you want to allow this bit of JS you can do three things

  1. Put it in a separate .js file and include it using <script src="some-file.js" />
  2. Add nonce="{{ some random value }}" to the <script> tag (e.g. <script nonce="jhdgsd8asA">) and then add that same nonce to the CSP: script-src nonce-jhdgsd8asA
  3. Add unsafe-inline to the script-src part of CSP (NOT recommended, defeats the purpose of CSP)

The point of the CSP is that you explicitly state which domains your site is allowed to download stuff from. So if you want to show an image that is hosted on www.companyname.com then you need to have www.companyname.com in the img-src of your CSP.

PS. Don’t choose 3, it’s a bad option. Did I mention it’s not recommended?

3 Likes

I spent half a day yesterday reading all about SCP. However, I failed to follow through on the nonce aspect to grasp it’s implications. I followed #1 for some scripts. Yes, #3 is BAD.

Thanks for getting me out of this hole!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.