0% found this document useful (0 votes)
78 views11 pages

Content Security Policy Cheatsheet

Content Security Policy Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
78 views11 pages

Content Security Policy Cheatsheet

Content Security Policy Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series Content Security Policy Cheat Sheet Introduction This article brings forth a way to integrate the defense in depth concept to the client-side of web applications. By injecting the Content-Security-Policy (CSP) headers from the server, the browser is aware and capable of protecting the user from dynamic calls that will load content into the page currently being visited. Context The increase in XSS (Cross-Site Scripting), clickjacking, and cross-site leak vulnerabilities demands a more defense in depth security approach Defense against XSS CSP defends against XSS attacks in the following ways: 1. Restricting Inline Scripts By preventing the page from executing inline scripts, attacks like injecting - will not work: 2. Restricting Remote Scripts By preventing the page from loading scripts from arbitrary servers, attacks like injecting will not work, By preventing the page from executing text-to JavaScript functions like evel , the Website will be safe from vulnerabilities like the this: -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml at rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series /1 & Simple Calculator var op! = getUriParaneter("op1") ; var op2 = getUrParaneter("op2") var sum = eval(*${opt) + ${0p2}" console.log( "The sum is: ${sun} 4. Restricting Form submissions By restricting where HTML forms on your website can submit their data, injecting phishing forms wort work either.

Session expired! Please login again.

5. Restricting Objects And by restricting the HTML object tag it also won't be possible for an attacker to inject malicious flash/Java/cther legacy executables on the page. Defense against framing attacks ‘Attacks lke clickjacking and some variants of browser side-channel attacks (xs-leaks) require a malicious website to load the target website in a frame. Historically the x-Frane-options header has been used for this, but it has been obsoleted by the frome-encestors CSP directive. Defense in Depth A strong CSP provides an effective second layer of protection against various types of vulnerabilities, especially XSS. Although CSP doesrit prevent web applications from containing vulnerabilities, it can make those vulnerabilities significantly more difficult for an attacker to exploit. Even on a fully static website, which does net aocept any user input, a CSP can be used to enforce the use of Subresource Integrity (SRI). This can help prevent malicious code from being Icaded on. -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml am rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series the website if one of the third-party sites hosting JavaScript files (such as analytics scripts) is compromised. CSP is not a substitute for secure development CSP should not be relied upon as the only defensive mechanism against XSS. Yournust still follaw ‘good development practices such as the ones described in Cross-Site Scripting Prevention Cheat ‘Sheet, and then deploy CSP on top of that as @ bonus security layer. Policy Delivery ‘You can deliver @ Content Security Policy to your website in three ways. 1. Content-Security-Policy Header Send a Content-Security-Policy HTTP response header from your web server. Content-Security-Policy Using a header is the preferted way and supports the full CSP feature set. Sendit in all HTTP responses, nct just the index page. 2. Content-Security-Policy-Report-Only Header Using the Content-Securiity-Pol icy-Report-Only ,youcan deliver a CSP that doesrit get enforced. Content -Security-Policy-Report-Only Siill, violation reports ate printed to the console and defvered to aviolation endpoint ifthe resort- to and report-uri directives are used. Browsers fUly support the ability ofa site to use both content-Security-Policy and content= Security-Policy-Report-Only together, without any issues. This pattem can be used for exemple tonna strict Report-only policy (toget many violation reports), while having a looser enforced policy (to avoid breaking legitimate site functionality). 3, Content-SecurityPolicy Meta Tag -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml sit rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series ‘Sometimes you cannot use the Content Seaurity-Policy header if youare, e.4., Depleying your HTML files in 2 CDN where the headers are out of your control. Inthis case, you can still use CSP by specifying http-equiv metatagin the HTML markup, ike so: Almost everything is still supported. including full XSS defenses. However, you will nct be able 10 Use framing protections, sandboxing, of a CSP violation logging endpoint. HTTP Headers The following are headers for CSP. * Content-Security-Policy : W3C Spec standard header. Supported by Firefox 23+, Chrome 25+ and Opera 19+ “WSC Spec standard header. Supported by Firefox 23+, Chrome25+ and Opera 19+, whereby the policy is non-blocking (‘fail oper) and a report is ssentto the URL designated by the report-uri (ornewer -eport-to) directive. This is often Used as a precursor to utilizing CSP in blocking mode (‘fail closed’) ‘00 NOT use X-Content Security Policy or X WebKit-CSP. Their implementations are obsolete (Since Firefox 23, Chrome 25), limited, inconsistent, andincredbly bugcy. © Content-Security-Policy-Report~ CSP Directives Multiple types of directives exist that allow the developer to control the flow of the policies granularly. Fetch Directives Fetch directives tell the browser the locations to trust and load resources from. Most fetch directives have a certain fallback list specified in w3. This list allows for granular contral of the source of scripts, images, files, etc. ‘+ chilé-sre allows the developer to control nested browsing contexts and worker execution contexts. -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml an rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series * connect-sre provides control over fetch requests, XHR, eventsource, beacon and websockets connections. ‘specifies which URLs to load fonts from. ‘+ img-sre specifies the URLs that images can be loaded from. ‘* manifest-sre specifies the URLs that application manifests mzy be loaded from, © font ‘* medie-sre specifies the URLs ftom which video, audio and text track resources can be loaded from. * prefeteh-sre specifies the URLs from which resources can be prefetched from * object-sre specifies the URLs from which plugins can be loaded from. ‘* seript-sre specifies the locations from which a script can be executed from. It isa fallback directive for other script-like directives. ‘¢ script-sro-elem Conttols the location from which execution of script requests and blocks can occur, * script-sre-attr conttols the execution of event handlers. + style-sre controls from where styles get applied 10 a document. This inchides elements, einport rues, and requests originating froma Link HTTP response header fel + style-sre-elen controls styles except for iniine attributes. « style-sre-attr controls styles attributes. ‘+ default-sre is a fallback directive for the cther fetch directives. Directives that are specified have no inheritance, yet directives that are nct specified wil fall back to the value of defauit- Document Directives Document directives instruct the browser about the properties of the document to which the Policies will apply to. ‘+ base-uri specifies the possible URLs thet the element can use. ‘+ plugin-types limts the types of resources that can be loaded into the document (¢.g. application/pdf). Srules apply to the affected elements, and : + The ekmentneedsto explicitly dectare its type. + The element’stype needs to match the declared type + The element's resource need to match the declared type. ‘+ sandbox restricts a page's actions such as submitting forms. -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml sm rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series ‘+ Only applies when used with the request header Content-Security-Policy. ‘+ Not specifying a value for the directive activates all of the sandbox restrictions. content- Security-Policy: sandbox; Sandbox syntax Navigation Directives Navigation directives instruct the browser about the locations that the document can navigate to. ‘* navigate-to restricts the URLs which a document can navigateto by any mean (not yet supported by modem browsers in Jan 2021). form-action restricts the URLs wrich the forms can submt to. frame-ancestors restricts the URLs that can embed the requested resource inside of , , , , OF elements. ‘= If this ditectiveis specified ina tag, the directive is ignored. ‘* Thisdirective doesnt fallback to default-sre ditective. ‘+ X-Frame-Options is rendered otsolete by this directive and is ignored by the user agents. Reporting Directives Reporting directives deliver violations cf prevented behaviors to specified locations. These directives serve no purpose on their own and are dependent on other directives. ‘* report-to which is a groupname defined in the header in a json formatted header value. ‘¢ MDN report-to documentation + report-ura directiveis deprecatedby report-to, which is a URI that the reports are sentto. Goes by the format of: Content-Seourity-Policy: report-uri nttps://exanple. con/esp-reports In ofderto ensure backward compatibility, use the 2 directives in conjunction, Whenever a browser supports repors-to, itwill iqiore report-uri.. Otherwise, report-uri will be used ‘Special Directive Sources Value Description -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml amt rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series Value Description ‘none’ NoURLs match. ‘self Refers to the origin site with the same scheme and port number. ‘unsafe-inline’ Allows the usage of inline scripts or styles. ‘unsafe-eva’ Allows the usage of eval in scripts. ‘strict dynamic’ _ Informs the browser to trust scripts originating from a root trusted sctipt. Note: strict-dynamic is ncta standdone directive and should be used in combination with other directive values, such as nonce, hashes, etc. To better understand hew the directive sources work, check out the source lists from w3c. Hashes When inline scripts are required, the seript-sre ‘hash.aigo-hash’ is one option for allowing only specific scripts to execute. Content-Security-Policy: seript-sre ‘sha256- \2kaaafInTjnBRQTWZnFAI f6FOQ70sqsw9GHaF jzFNP Toget the hash, look at Google Chrome developer tools for vilations ke this: Refused to execute inline script because it violates the following Content Security Policy directive:"..” Either the Uunsafe-inine’ keyword, ahash (sha256- \V2kaaafim TinBROTWZmF4fGIQ7 Qsqsw9GWaFjZFNPG=), oF a nonce... You can also use this hash generator. Thisis a great example of using hashes. Note Using hashes is generally nct 2 very good approach. If you change anything inside the script tag (evenwihitespace) by,e.<., formatting your code, the hash willbe different, and the script wor't render. Nonces -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml mt rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series Nonces are unique one-time-use random values that you generate for each HTTP response, and addto the Content Security Folicy header, lke so: const nonce = wuid.va(); scriptsre ‘nonce-S{nonce}'*; ‘You would then pass this nonce to your view (using nonces requires anan-static HTML) and render script tags that look something lke this: Warming Dontt create a middleware that replaces all script tags with "soript nonce=.." because attacker- injected scripts will then get the nonces as well. You need an actual HTML templating engine to usenonces. strictdynamic ‘The strict-dynanic directive can beused in combination with either, hashes or nonces. If the script blockis creating additional DOM elements and executing JS inside of them, strict- dynanie tells the browser to trust those elements. Note that strict-dynanie is a CSP level’ feature and net very widely supported yet. For more details, check out strict-dynamic usage, CSP Sample Policies Basic CSP Policy This policy prevents cross-site framing and cross-site form-submissions. It will only allow resources from the originating domain forall the default evel directives and will nct allow inline scripts/styles to execute. If your application functions with these restrictions, it drastically reduces your attack surface and ‘works with most madem browsers. ‘The most basic policy assumes: -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml amt rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series All resources are hosted by the same domain of the document, There are no inlines of evals for scripts and style resources. ‘There is no need for other websites to frame the website, There are no form-submissions to external websites. Content-Security-Policy: defau: "self"; ‘sre ‘self’; frane-ancestors ‘self"; form-action To tighten further, one can apply the following} Content-Security-Policy: default-sre ‘none’ sre ‘self'; img-sre ‘self’; style-sre ‘self self! ; script-sre ‘self'; connect- frame-ancestors ‘self’; forn-action This policy allows images, scripts, AJAX, and CSS from the same origin and does not allow any other resources to load (e.g., object, frame, media, ete.) Upgrading insecure requests If the developer is migrating from HTTP to HTTPS, the following directive will ensure that all requests will be sent over HTTPS with no fallback to HTTP: Content-Security-Policy: upgrade-insecure-requests; Preventing framing attacks (clickjacking, cross-site leaks) ‘+ To prevent all framing of your content use: + Content-Security-Poliey: frame-ancestors ‘none’ + Toallew for the site itself, use: © Content-Security-Policy: frame-ancestors ‘self’; ‘* Toallew for trusted domain, do the following: + Content-Security-Policy: freme-ancestors trusted.con; Strict Policy A strict policy's role is to pretect against classical stored, reflected, and some of the DOM XSS attacks and should be the optimal goal of any team trying to implement CSP. -ntps:ifcheatshectseries.owasp.orgicheatsheets!Content_Securty_Polcy_Cheat_Sheetniml amt rasa, 2105 AM Content Securty Poy - OWASP Cheat Sheet Series Google went ahead and set Up a guide to adopt a strict CSP based onnonces. Based on a presentation at LocaMocoSec, the following two policies can be used to apply a strict policy: ‘+ Moderate Strict Folicy: script-sre ‘nonce-rénd@m’ 'strict-dynamic’ ; object-sre ‘none’; bese-uri ‘none’ + Locked dewn Strict Policy: script-sre “nonce-réndom’ ; object-sre ‘none’; base-uri ‘none’ ; Refactoring inline code When default-sre or script-sre* directives are active, CSP by default disables any JavaScript codeplacedininein the HTML source, such as this: spp. js"> With app.js containing the var foo = "314" code. The inline code restriction also applies to inline event handlers, so that the follawing construct will be blocked under CSP:
Language: