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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How to Secure Your Angular Apps: End-to-End Encryption of API Calls
  • Flask Web Application for Smart Honeypot Deployment Using Reinforcement Learning
  • Design Principles-Building a Secure Cloud Architecture

Trending

  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • How to Practice TDD With Kotlin
  • Emerging Data Architectures: The Future of Data Management
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  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.

By 
Sven Morgenroth user avatar
Sven Morgenroth
·
Feb. 26, 18 · Analysis
Likes (4)
Comment
Save
Tweet
Share
25.3K 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

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How to Secure Your Angular Apps: End-to-End Encryption of API Calls
  • Flask Web Application for Smart Honeypot Deployment Using Reinforcement Learning
  • Design Principles-Building a Secure Cloud Architecture

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!