DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Cloud Security in Hybrid and Multi-Cloud
  • Penetration Testing: A Comprehensive Guide
  • How To Optimize the Performance and Security of Your Website Using Modern Tools and Techniques
  • Top 10 Secure Coding Practices Every Developer Should Know

Trending

  • Essential Complexity Is the Developer's Unique Selling Point
  • Auto-Scaling DynamoDB Streams Applications on Kubernetes
  • AI for Web Devs: Project Introduction and Setup
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Content Security Policy (CSP) Explained

Content Security Policy (CSP) Explained

We explore the concepts behind Content Security Policy, such as hashes and nonces, and how to implement CSP in your application or site.

Sven Morgenroth user avatar by
Sven Morgenroth
·
Feb. 26, 18 · Analysis
Like (4)
Save
Tweet
Share
24.55K Views

Join the DZone community and get the full member experience.

Join For Free

The Content Security Policy (CSP) standard is a way to selectively specify which content should be loaded in web applications. This can be done by whitelisting specific origins, using nonces or hashes.

How Does Content Security Policy Work?

As a developer, you can specify the Content Security Policy through an 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.

What Kinds of Web Application Vulnerabilities Can CSP Prevent?

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. Below are a few basic examples of the different methods you can use to implement Content Security Policy in your web applications:

Whitelisting of Domains

This is an example of a whitelist allowing inline scripts and all scripts loaded from https://www.netsparker.com:

Content-Security-Policy: script-src 'self' https://www.netsparker.com

Even though domain whitelisting sounds like a good idea be careful when using it because if attackers manage to gain unauthorized access to the web application's code they can include outdated libraries (e.g. on a trusted CDN), or abuse open redirects or a JSONP callback. This should only be done on trusted domains, preferably controlled by the site owner.

Using Nonces

A nonce (a number that is used only once) is similar to a 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=='

The nonce should be a random string, generated with a cryptographically secure function to make sure it is not predictable, as this would render it useless. The idea behind a nonce in Content Security Policy is that it is a value that is impossible for the attacker to know but is known and set by the developer. It has to be refreshed on every new page load. The developer has to add the nonce to the resource he wants to load. For example:

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

The reason behind adding the nonce to the script call is that with the above CSP setting all script blocks without a nonce are not executed. If an attacker manages to insert a script block into the page, he can't know the nonce, as it is randomly generated on every page call. Therefore, the injection will have no effect on the user.

Hashes

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 implements 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 the web server level. If the HTTP headers are different for every page or on every reload, such as when using nonce or hash, then they have to be generated at the 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 an HTML meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; child-src 'none'; object-src 'none'">

Example of a Content Security Policy (CSP) Rule

Below is an example of a Content Security Policy rule to only allow scripts that have the following nonce "bmV0c3BhcmtlciBydWxlcyA7KQ==":

Content-Security-Policy: script-src 'self' 'nonce-bmV0c3BhcmtlciBydWxlcyA7KQ=='

<script nonce=bmV0c3BhcmtlciBydWxlcyA7KQ==>
     console.log("code works")
</script>

The above rule is sent using an HTTP response header or a meta element. Of course, the nonce has to be random and must not be reused. As mentioned above, external scripts are only included if the nonce is present in the script tag they are called with. If it doesn't match or there is no nonce the script will not be loaded or executed.

Demo of Content Security Policy

Cryptographic Service Provider security Web application

Published at DZone with permission of Sven Morgenroth, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Cloud Security in Hybrid and Multi-Cloud
  • Penetration Testing: A Comprehensive Guide
  • How To Optimize the Performance and Security of Your Website Using Modern Tools and Techniques
  • Top 10 Secure Coding Practices Every Developer Should Know

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: