Telerik blogs

Content Security Policy (CSP) is a security standard that helps deter cybersecurity attacks. Why should web developers care? Learn more in this post.

For 19 years now, October has been known as Cybersecurity Awareness Month, a dedicated month for the public and private sectors to collectively emphasize the importance of cybersecurity. This reminds me that in the dawn of its 20th year, Cybersecurity and Infrastructure Security Agency (CISA) announced a new enduring cybersecurity awareness program, Secure Our World.

October 2023 is long gone, however, and I’d rather every month be considered a cybersecurity awareness month. Not only am I talking about being extra cautious when receiving an unexpected email with a call to action or referring to the major social networks’ security breaches, but Hey it’s cybersecurity—just make it a habit. Period.

First things first, though: Let’s get to some basics on the topic of this blog post. In the world of cyberspace, where information flows ceaselessly, hardening the security of your digital environment is crucial. Among the myriad tools used to fortify the defenses of websites and apps, Content Security Policy (CSP) stands out as a sole guardian, working behind the curtains to help shield against an array of multiple threats.

CSP has been around since 2004 (when it was known as Content Restrictions) and currently has an active working draft of Level 3. Long story short, CSP is a security standard that helps thwart malicious activities such as cross-site scripting (XSS), clickjacking and data injection attacks. But why should we, as devs on the web, pay heed to this seemingly technical aspect of web security?

Defending Against Injection Attacks

XSS attacks succeed if a web app lacks sufficient validation or encoding. The browser cannot detect if the malicious script is untrustworthy and grants it access to any cookies, session tokens or so on. Additionally, the malicious script may manipulate and rewrite the HTML content without detection.

At its core, CSP is a browser security standard that helps combat such injection attacks. While XSS attacks compromise user data and undermine the integrity of the application, CSP acts as a gatekeeper, dictating which sources of scripts and content are deemed trustworthy and should be executed. This allows only authorized scripts to run. As an ultimate level of protection, sites that aim to never allow scripts can globally disallow script execution.

Restricting Resource Loading

A key strength of CSP is its ability to control and restrict the loading of external resources, helping to mitigate risks associated with data injection and unauthorized content delivery. The HTTP Content-Security-Policy response header allows website admins to control resources the user agent is allowed to load on a page.

With a few exceptions, policies mostly involve specifying server origins and script endpoints. Think of a page that uploads and displays images—it could allow images from anywhere but restrict a form action to a specific endpoint. By defining and enforcing policies on the types of resources a webpage can load, CSP reduces the attack surface, making it harder for malicious actors to exploit vulnerabilities related to resource loading.

CSP operates through a set of directives, each serving a specific purpose in shaping the security posture of a web application. From script-src to style-src, these directives allow developers to finely tune the origins from which various types of content can be safely loaded.

Crafting a well-defined CSP policy involves a meticulous balance, enabling the necessary functionality while prohibiting potential security risks. A robust policy should encompass either a default-src or script-src directive to counteract the execution of inline scripts and prevent the use of eval().

Similarly, incorporating a default-src or style-src directive is crucial to confine the application of inline styles, whether they originate from a <style> element or a style attribute. To read further, check this full list of policy directives.

Mitigating Data Breach Risks

One of CSP’s primary roles is to act as a guardian against data exfiltration attempts. By helping to prevent the execution of unauthorized scripts and controlling resource loading, CSP forms a barrier against attempts to siphon sensitive information. This includes support with safeguarding user credentials, personal data, financial activities and other critical information that, if compromised, could lead to severe data breaches sending shockwaves across industries.

CSP’s style-src directive extends its protective reach by restricting the application of inline styles from style attributes. This helps prevent attackers from manipulating the visual presentation of content to conceal or modify data. By controlling how styles are applied, CSP contributes to the overall integrity of the webpage, helping to minimize the risk of data tampering.

Embracing the Evolution of Security

In the ever-evolving landscape of cybersecurity, where new threats surface with relentless creativity, CSP stands out as an adaptive defense mechanism. Its evolutionary nature keeps it at the forefront of safeguarding web applications against emerging threats.

CSP is designed to accommodate dynamic updates to its policies. This flexibility allows web developers and security professionals to adapt swiftly to evolving threat landscapes by incorporating real-time threat intelligence and adjusting policy directives accordingly. CSP integrates the latest security standards and best practices, helping to address novel threats as they emerge.

The protective measures enforced by CSP are synced with the latest browser security capabilities, creating an improved defense ecosystem, yet CSP’s biggest positive aspect is rooted in the collaborative efforts of the Web Security Community.

Web developers, while recognizing the security benefits of CSP, will probably face several challenges (as it happens in real programming life) when implementing and working with it.

Balance: Crafting a CSP policy that has the right balance between security and functionality can be tricky. Overly restrictive policies may hinder the execution of legitimate scripts, impacting the functionality of the web app. It is imperative to carefully analyze and understand the app requirements to create policies that allow essential scripts while keeping the security posture.

Refactoring: Lots of existing web applications heavily rely on inline scripting and styling—hence the necessity to refactor code. Allowing all inline scripts is considered a security risk, so it’s recommended to use a nonce-source or a hash-source instead. Still, use nonce only for cases where there is no other way of using unsafe inline script or style contents.

Browser Compatibility: Browser support for CSP may vary, resulting in inconsistencies in the way policies are enforced. It is more than recommended to test that CSP policies are compatible with major browsers and have a fallback mechanism for browsers with limited CSP support.

Third-Party Dependencies: Integrating third-party libraries or dependencies is always challenging, especially if they use inline scripts or violate the defined CSP policy. Vet them for CSP compatibility and/or look for alternatives with modifications per case. Using nonces or hashes can also help manage these dependencies.

Debugging: More of a best practice than a challenge, use browser console messages and security headers to debug CSP violations.

Education: Enabling the entire development team to understand the importance of CSP and follow best practices can be a hurdle, along with adapting CSP policies to the evolving security threats. Providing comprehensive trainings, doing code reviews, integrating CSP practices into the development workflow and regularly reviewing and updating CSP policies can foster a safety-first-aware culture.

Progress Prioritizes Content Security Policy

Quoting Progress Chief Information Security Officer Richard Barretto:

Progress places the highest importance on the security of our products in order to better protect our customers and their systems; and you can learn more about our vulnerability remediation and customer notification process [here]. We employ a variety of procedures and tools to quickly identify vulnerabilities, remediate them as soon as possible and communicate the urgency for customers to apply software upgrades.

Progress Telerik and Kendo UI libraries help developers build more secure user experiences, targeted for organizations that need to follow strict security standards. Be it for the .NET or JavaScript development realm, the respective UI component libraries conform to CSP, providing regular updates and configuration support.

Telerik UI for Blazor

These CSP policy directives allow the Telerik UI for Blazor components to look and work as expected. You can remove the Telerik domain or font-src if you don’t use our CDN or font icons:

<meta http-equiv="Content-Security-Policy" content="
  script-src 'self' https://blazor.cdn.telerik.com;
  style-src 'self' 'unsafe-inline' https://blazor.cdn.telerik.com;
  img-src 'self' data:;
  font-src 'self' data:;
" />

In the most recent enhancement, the font icon styles and the custom font WebComponentsIcons are moved to two additional separate files. This will avoid the need to set font-src data: even when using font icons. Learn more about CSP in Blazor here.

Kendo UI for jQuery

With strict CSP mode on in Kendo UI for jQuery, these browser features are disabled by default:

  • Inline JavaScript, such as <script></script>, or DOM event attributes, such as onclick, are blocked. All script code must live in separate files that are served from a safe-listed domain.
  • Dynamic code evaluation through eval() and string arguments for both setTimeout and setInterval are blocked.

Since the beginning of 2023, Kendo UI for jQuery components have addressed (rewritten to discard the usage of the eval() and new Function() calls) the unsafe-eval directive. With the sole exception of the Spreadsheet.

Find more on the CSP in Kendo UI for jQuery here. And the Getting Started guide demonstrates how to define single-line functional CSP templates, also specify CSP templates with simple operations and complex logic, as well as convert existing templates into CSP-compatible ones.

Telerik UI for ASP.NET Core and ASP.NET MVC

The following code shows how to turn on the strict CSP mode for Telerik UI for ASP.NET Core and UI for ASP.NET MVC:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self'; script-src 'self' https://kendo.cdn.telerik.com https://code.jquery.com/; style-src 'self' https://kendo.cdn.telerik.com;" />

In the most recent enhancement, the unsafe-inline keyword is no longer required in the style-src directive except for in the Editor, ReponsivePanel, GridLayout and StackLayout components. The rendering of these components will be improved to help achieve compatibility with strict Content Security Policy. Read more about CSP for Telerik UI for ASP.NET Core and on CSP for Telerik UI for ASP.NET (Telerik UI for ASP.NET MVC) respectively..

KendoReact, Kendo UI for Vue and Kendo UI for Angular

These CSP policy directives allow the KendoReact and Kendo UI for Vue components to look and work as expected. More on the topic can be found here for KendoReact and here for Kendo UI for Vue.

Kendo UI for Angular offers a sample application on the public GitHub repo:

<meta http-equiv="Content-Security-Policy" content="
  style-src 'self' 'unsafe-inline' https://kendo.cdn.telerik.com;
  style-src-elem 'self' 'unsafe-inline' https://kendo.cdn.telerik.com;
  img-src 'self' data:">

Most recently as an enhancement, the font icons that were previously available out of the box are now accessible through the CDN link. With this, all icons used in the components are SVG ones. If a version update is not possible and you are using font icons, you need to add the following CSP configuration:

font-src 'self' data:;

Telerik UI for ASP.NET AJAX

For Telerik UI for ASP.NET AJAX, I suggest going over our extensive documentation on the topic here.

Conclusion

That’s it. Remember—elevate your cybersecurity one click at a time! Happy coding!


This post was prepared by Petar Grigorov in their personal capacity. The opinions or representations expressed herein are the author’s own and do not necessarily reflect the views of Progress Software Corporation, or any of its affiliates or subsidiaries. All liability with respect to actions taken or not taken based on the contents of this post are hereby expressly disclaimed. The content on this posting is provided “as is” with no representations made that the content is error-free.


About the Author

Petar Grigorov

Petar is a Principal Sales Engineer at Progress with equal sympathy in coding and automation testing. In his spare time he turns into a DIY guy who can successfully setup and use anything from IoT gadgets to paintbrushes and a trowel. When not dreaming of piloting the Millennium Falcon, he is a fan of any engine that is close enough and runs on two or four wheels.

Comments

Comments are disabled in preview mode.