How does Content Security Policy (CSP) work?

后端 未结 2 2074
鱼传尺愫
鱼传尺愫 2020-11-22 15:33

I\'m getting a bunch of errors in the developer console:

Refused to evaluate a string

Refused to execute inline script because it violates the fol

2条回答
  •  天命终不由人
    2020-11-22 16:16

    Apache 2 mod_headers

    You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

    # First enable headers module for Apache 2,
    # and then restart the Apache2 service
    a2enmod headers
    apache2 -k graceful
    

    On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

    #
    # Setting this header will prevent MSIE from interpreting files as something
    # else than declared by the content type in the HTTP headers.
    # Requires mod_headers to be enabled.
    #
    #Header set X-Content-Type-Options: "nosniff"
    
    #
    # Setting this header will prevent other sites from embedding pages from this
    # site as frames. This defends against clickjacking attacks.
    # Requires mod_headers to be enabled.
    #
    Header always set X-Frame-Options: "sameorigin"
    Header always set X-Content-Type-Options nosniff
    Header always set X-XSS-Protection "1; mode=block"
    Header always set X-Permitted-Cross-Domain-Policies "master-only"
    Header always set Cache-Control "no-cache, no-store, must-revalidate"
    Header always set Pragma "no-cache"
    Header always set Expires "-1"
    Header always set Content-Security-Policy: "default-src 'none';"
    Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
    Header always set Content-Security-Policy: "style-src 'self' www.example.com;"
    

    Note: This is the bottom part of the file. Only the last three entries are CSP settings.

    The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

    Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

    While you're at it you could take a look at the other header settings and install mod_security

    Further reading:

    https://developers.google.com/web/fundamentals/security/csp/

    https://www.w3.org/TR/CSP/

提交回复
热议问题