WP What is Content Security Policy (CSP) | Header Examples | Imperva

Content Security Policy (CSP)

88.9k views
Web and Application Security

What is Content Security Policy?

A Content Security Policy (CSP) is a security standard designed to add an additional layer of security for web applications. They allow developers to restrict which resources (such as JavaScript, CSS, Images, and others) can be loaded. This helps reduce the risk of cross-site scripting (XSS), clickjacking, online skimming attacks such as Magecart and other code injection attacks. It is a defensive measure against any attacks that rely on executing malicious scripts and content from alternate domains in a trusted web context, or other attempts to circumvent the same-origin policy.

With CSP, you can limit which data sources are allowed by a web application, by defining the appropriate CSP directive in the HTTP response header.

Content Security Policy evaluates and blocks requests for assets

Content Security Policy evaluates and blocks requests for assets

Why is a Content Security Policy Important?

Mitigating Cross-Site Scripting

The main purpose of CSP is to mitigate and detect XSS attacks. XSS attacks exploit the browser’s trust in the content received from the server. The victim’s browser is exposed to execution of malicious scripts, because the browser trusts the source of the content.

CSP allows server administrators to reduce or eliminate the ability of an attacker to trigger XSS, by specifying which Internet domains browsers should consider as legitimate sources of executable scripts. CSP-compliant browsers only run scripts contained source files that are retrieved from whitelisted domains, and ignore all other scripts (including inline script and HTML event handling attributes).

Mitigating Packet Sniffing and Enforcing HTTPS

In addition to whitelisting domains from which a browser may load content, servers can also specify the allowed protocols. For example, the server can specify that browsers must load content via HTTPS.

A comprehensive data transfer protection policy involves not only implementing HTTPS in data transfer, but also marking all cookies with the secure attribute, and automatically redirecting HTTP pages to HTTPS. Additionally, sites may use HTTP Strict-Transport-Security headers to ensure that browsers only connect to the site via encrypted channels.

CSP Header Examples

The web server can add an HTTP header called Content-Security-Policy to each response. You can set the following properties in the CSP header:

  • default-src—an optional method if no other attributes are defined. In most cases, the value of this property self—meaning the browser can only upload resources from the current website.
  • script-src—locations from which external scripts can be loaded. If your website or application does not use client-side scripting, set the value to none.
  • img-src—locations from which images can be retrieved.
  • media-src—locations from which rich media like video can be retrieved.
  • object-src—locations from which plugins can be retrieved.
  • manifest-src—locations from which application manifests can be retrieved.
  • frame-ancestors—locations from which another web page can be loaded using a frame, iframe, object, embed, or applet element.
  • form-action—URLs that can be used as part of an action in a <form> tag, meaning the browser restricts where form results can be sent. The form action does not revert to default-src, so this is a mandatory property if you are using form elements on your site.
  • plugin-types—the set of plugins that can be invoked via objects, embeds, or applets, defined using MIME types.
  • base-uri—allows URLs in the src attribute of any tag.

Refer to the complete and up-to-date list of properties from Mozilla.

Which Vulnerabilities Can CSP Prevent?

One main challenge CSP can prevent is that attackers may attempt to access your resources over an unsecure protocol.

You can use CSP to enforce the HTTPS protocol to any value defined in *-src attributes, by adding the https:// prefix to any URL in your whitelist. This way resources will never load over an unencrypted HTTP connection. You can achieve the same effect by adding the block-all-mixed-content property.

In addition, CSP can prevent the following common vulnerabilities:

  • Unsigned inline CSS statements in <style> tags
  • Unsigned inline Javascript in <script> tags
  • Dynamic CSS using CSSStyleSheet.insertRule()
  • Dynamic Javascript code using eval()

It is best to keep the script and CSS in separate files that are referenced by the HTML page. If your site needs to allow this, you can enable it using the keywords unsafe-eval and unsafe-inline.

When to Use CSP

In general, complex web applications are more sensitive to XSS, making CSP important to use.

Use CSP for any application that manages sensitive data, such as administrative user interfaces, device management consoles, or any products hosting files, documents or messages created by users. In modern frameworks, adding CSP is easy and can provide high return of investment in terms of added security.

When Not to Use CSP

CSP may not be the best choice in these cases:

  • Static applications hosted on their own domains or subdomains without login or cookies.
  • Applications that have experienced XSS in the past, or have known vulnerabilities in templates or frameworks they are using. In this case the best approach is to invest in patching or fixing vulnerable code, because CSP on its own will not provide sufficient protection. CSP should be added on top of a secure application with no known vulnerabilities.

Implementing Content Security Policy

The best way to add CSP retroactively to an entire website is to define a completely empty whitelist, essentially blocking everything. Initially, run CSP in report-only mode, which means the browser evaluates rules but does not block the content yet.

You can then review errors and see which of them should be added to the list (allowed) or not (disallowed).

The difficult part is deciding how much to block. For example, if you are using a script hosted through a CDN and you allow the addresses, you accept all traffic coming from those CDNs, which could include malicious traffic.

Running CSP in report mode for a few weeks, or at the most a few months, should give you all the possible cases of errors. When you feel your set of rules captures all relevant use cases, disable report-only and start blocking resources that are not on the whitelist.

What Are the Limitations of a Content Security Policy?

While CSP headers are a powerful security tool, they are not without their limitations:

  1. Creating CSPs can be a challenging task. Before establishing a Content-Security-Policy (CSP), you must identify which domains and subdomains can access your website and what resources they may load, such as JavaScript, CSS, or PHP. This data can be laborious to gather and inventory without dedicated tools, taking expensive time and effort that can be better spent on other tasks. Once you have this information, you can begin crafting your CSP, which may span several days or weeks. Assuming that you have compiled a comprehensive list of the scripts, resources, and integrations running on the client-side, the task of understanding the functionality of each presents another unique challenge. Additionally, there is always the risk of misconfiguration. If not correctly set, CSP headers can inadvertently block legitimate content or allow the execution of malicious scripts.
  2. Managing CSPs is a demanding undertaking. After constructing and implementing your CSP, someone must continuously update it with each website release. Additionally, they must monitor the browser console log for any reported CSP violations. This maintenance process is labor-intensive and necessitates a monitoring solution capable of notifying you when the CSP blocks content. Furthermore, CSP alone does not provide meaningful and actionable insights crucial for your security posture. For example, what if a resource or script that has been previously reviewed and approved is now compromised and exfiltrating data to a malicious actor?
  3. CSPs are notably intricate. Most CSPs have numerous configuration lines, and the documentation can appear overwhelming, even for those with technical expertise. Specifying the resource types authorized for loading by various domains and subdomains is a complex task that offers no room for error.

Creating and managing a Content Security Policy is time-consuming and complex. However, inventorying, aggregating, and understanding what each resource is doing after it has been discovered complicates things even further. CSP headers alone do not offer inventorying and aggregating capabilities nor provide the meaningful and actionable insights crucial for your security posture. While it remains a powerful tool to defend against XSS and client-side script injections, it is not sufficient to stop client-side attacks on its own.

Securing the Client-Side with Imperva

Imperva Client-Side Protection prevents attacks that result from malicious code injection by making Content-Security-Policy headers a viable part of your client-side security strategy. It prevents data theft from client-side attacks like formjacking, Magecart, and other online skimming techniques that often exploit vulnerabilities in the website supply chain.

Instead of manually implementing and maintaining CSP headers, which can be laborious and risky, Imperva takes care of that for you with a safe, one-click deployment. Client-Side Protection effectively leverages CSP headers, automating the labor-intensive, time-consuming inventory management and aggregation processes, freeing your valuable time and resources.

In addition to managing CSP headers, Imperva Client-Side Protection offers further capabilities to ensure client-side safety and compliance with the latest PCI DSS 4.0 regulations, including requirements 6.4.3 and 11.6.1.

In addition to XSS protection, Imperva provides multi-layered protection to make sure websites and applications are available, easily accessible and safe. The Imperva application security solution includes:

  • Web Application Firewall (WAF) – Prevent attacks with world-class analysis of web traffic to your applications.
  • DDoS Protection—maintain uptime in all situations. Prevent any type of DDoS attack, of any size, from preventing access to your website and network infrastructure.
  • CDN—enhance website performance and reduce bandwidth costs with a CDN designed for developers. Cache static resources at the edge while accelerating APIs and dynamic websites.
  • Bot management—analyzes your bot traffic to pinpoint anomalies, identifies bad bot behavior and validates it via challenge mechanisms that do not impact user traffic.
  • API security—protects APIs by ensuring only desired traffic can access your API endpoint, as well as detecting and blocking exploits of vulnerabilities.
  • Account takeover protection—uses an intent-based detection process to identify and defends against attempts to take over users’ accounts for malicious purposes.
  • RASP—keep your applications safe from within against known and zero‑day attacks. Fast and accurate protection with no signature or learning mode.
  • Attack analytics—mitigate and respond to real security threats efficiently and accurately with actionable intelligence across all your layers of defense.