Thursday, July 18, 2019

Content Security Policy



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

https://www.netsparker.com/blog/web-security/content-security-policy/
As a developer you can specify the Content Security Policy through a HTTP response header called Content-Security-Policy. Then a web browser that supports CSP, such as Chrome or Firefox, parses the header information and determines which sources are trusted or not based on the instruction sent in the header. This is basically a whitelist approach which may consist of instructions like self (allowing inline scripts), specific domains, nonces or hashes that have to be present and valid in order for the content to be loaded.
CSP can prevent cross-site scripting vulnerabilities, clickjacking, mixed content security issues, protocol downgrading and any other kind of code injection which is the result of the injection of untrusted content into a trusted resource

Content-Security-Policy: script-src 'self' https://www.netsparker.com
A nonce (a number that is used only once) is similar to CSRF token but for specific resources. It is activated by using nonce-$random_value in the HTTP response header such as in the example below:
Content-Security-Policy: script-src 'self' 'nonce-bmV0c3BhcmtlciBydWxlcyA7KQ=='

<script nonce="bmV0c3BhcmtlciBydWxlcyA7KQ==">
     var a = 'b';
</script>

Content Security Policy can also be configured to only load resources if they match defined hashes. That way it's not possible to execute resources that have been tampered with. To set such a hash the following CSP header can be used:
Content-Security-Policy: script-src 'self' 'sha256-78iKLlw3hSqddlf6qm/PGs1MvBzpvIEWioaoNxXIZwk='
This contains the hash of the following script block
<script>alert("allowed");</script>
The developer creates the hash and implement the CSP rule with the following PHP code:
header("Content-Security-Policy: script-src 'self' 'sha256-".base64_encode(hash('sha256', 'alert("allowed");', true))."'");
The advantage of such a hash is that it only has to be generated once to offer good protection. It also offers protection against tampering with the script while a simple domain whitelist can't guarantee that.

How to activate Content Security Policy

As explained earlier, Content Security Policy can be activated by using HTTP response headers or html meta elements, which then the visitor's browser parses to enforce the rules the developer has set. If the HTTP headers are the same for every page, then you can configure them at web server level. If the HTTP headers are different for every page or on every reload, such as when using nonce or hask then they have to be generated at web application level.
The HTTP header format is simple. The header itself is called Content-Security-Policy and in it you specify the instructions for the browser as per the example below:
Content-Security-Policy: script-src 'self'
Below is an example of how to enable Content Security Policy via a HTML meta tag:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; child-src 'none'; object-src 'none'">
Add a nonce attribute to all <script> elements

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
One or more sources can be allowed for the script-src policy:
Content-Security-Policy: script-src <source>;
Content-Security-Policy: script-src <source> <source>;

'unsafe-inline'
Allows the use of inline resources, such as inline <script> elements, javascript:URLs, inline event handlers, and inline <style> elements. You must include the single quotes.
'unsafe-eval'
Allows the use of eval() and similar methods for creating code from strings. 
'none'
Refers to the empty set; that is, no URLs match. 
'nonce-<base64-value>'
A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource’s policy is otherwise trivial. See unsafe inline script for an example

https://stackoverflow.com/questions/42922784/what-s-the-purpose-of-the-html-nonce-attribute-for-script-and-style-elements
The nonce attribute enables you to “whitelist” certain inline script and style elements, while avoiding use of the CSP unsafe-inline directive (which would allow all inline script/style), so that you still retain the key CSP feature of disallowing inline script/style in general.
So the nonce attribute is way of telling browsers that the inline contents of a particular script or style element were not injected into the document by some (malicious) third party, but were instead put into the document intentionally by whoever controls the server the document is served from.
https://developers.google.com/web/fundamentals/security/csp/#if_you_absolutely_must_use_itgives a good example of how to use the nonce attribute, which comes down to the following steps:
  1. For every request your Web server receives for a particular document, have your backend generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator; e.g., EDNnf03nceIOfn39fn3e9h3sdfa. That’s your nonce.
  2. Take the nonce generated in step 1, and for any inline script/style you want to “whitelist”, make your backend code insert a nonce attribute into the document before it’s sent over the wire, with that nonce as the value:
    <script nonce="EDNnf03nceIOfn39fn3e9h3sdfa"></script>
  3. Take the nonce generated in step 1, prepend nonce- to it, and make your backend generate a CSP header with that among the values of the source list for script-src or style-src:
    Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
So the mechanism of using a nonce is an alternative to instead having your backend generate a hash of the contents of the inline script or style you want to allow, and then specifying that hash in the appropriate source list in your CSP header.
Note that because browsers don’t (can’t) check that the nonce value sent changes between page requests, it’s possible—though totally inadvisable—to skip 1 above and not have your backend do anything dynamically for the nonce, in which case you could just put a nonce attribute with a static value into the HTML source of your doc, and send a static CSP header with that same nonce value.
But the reason you’d not want to use a static nonce in that way is, it’d pretty much defeat the entire purpose of using the nonce at all to begin with—because, if you were to use a static nonce like that, at that point you might as well just be using unsafe-inline

It’s not for verifying the user—it’s for verifying that the inline contents of a particular script or style element were not injected into the document my some (malicious) third party, but were instead put into the document intentionally by whoever controls the server the document is served from.


Refactor any markup with inline event handlers (for example, onclick) and javascript: URIs 

https://stackoverflow.com/questions/11737873/why-are-inline-event-handler-attributes-a-bad-idea-in-modern-semantic-html

  • you can bind only one event of each kind with DOM-zero events (which is what the inline ones are), so you can't have two click event handlers
  • if an event is specified inline, the JS is specified as a string (attribute values are always strings) and evaluated when the event fires. Evaluation is evil.
  • Aside from semantics and other opinions expressed in the accepted answer, all inline scripts are considered a vulnerability and high security risk. Any website expecting to run on modern browsers are expected to set the 'Content-Security-Policy' (CSP) property, either via meta attribute or headers.
Doing so is incompatible with all inline script and styles unless explicitly allowing these as an exclusion. While CSP goals are mainly about preventing persistent cross-site script (xss) threats, for which inline scripts and styles are a vector of xss, it is not default behaviour currently in browsers but may change in future.

https://www.perspectiverisk.com/xss-post-2-event-handlers-breaking-out/
https://blogs.dropbox.com/tech/2015/09/unsafe-inline-and-nonce-deployment/
document.addEventListener('DOMContentLoaded', function () {
    var metaTag = document.createElement('meta');
    metaTag.setAttribute('http-equiv', 'Content-Security-Policy');
    metaTag.setAttribute('content', "script-src https: 'unsafe-eval';");
    document.head.appendChild(metaTag);
});
Just to recap: the DOMContentLoaded event is fired after the browser executes all the HTML and synchronous scripts (including inline scripts). After that, any other JavaScript tasks, events queued up, or other onload handlers fire. Following performance best practices, we already do not execute remote scripts synchronously, so the vast majority of our JavaScript code executes after DOMContentLoaded.
Don't use  *.innerHTML or document.write to output text


Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts