01642 06 11 11 Arrange Call

Content Security Policy (CSP)

Picture This: you’re browsing a trusted website, and you find out your session is hijacked or sensitive data has been leaked through a rouge script. But you don’t know this because these processes happen in the background, and you probably won’t even realise they are running.

We are in an era where cyber threats lurk behind most corners of the digital landscape, well designed websites can inadvertently expose users and organisations to security risks. Content Security Policy (CSP) is a powerful shield in the in the arsenal of web security. Understanding and implementing them is a critical line of defence for reducing the potential attacks of web applications.

CSP acts as a layer of security that helps detect and mitigate certain types of attack, such as Cross-Site Scripting (XSS) and data injection attacks. This can lead to compromised data, unauthorised access, or even website takeovers. But what is CSP really? Let’s dive deeper to find out how it works.

Breaking Down CSP

 

What Exactly is Content Security Policy?

This is a security measure designed to control which content sources are allowed to load on a web page. It acts like a whitelist, blocking unauthorised scripts, images, or stylesheets that could compromise security by instructing the browser on what is safe to load. CSP significantly reduce the risk of malicious code uploaded by attackers.


Key Directives in CSP


  • default-src
    This directive serves as the baseline policy for content loading on a page. For example, if the CSP specifies default-src ‘self’;, it means that all resources must be loaded from the same origin as the page itself. No third-party scripts, images, or iframes are permitted unless explicitly allowed.

  • script-src
    JavaScript is a common vector for cyber attacks. The script-src directive controls which scripts can be executed, reducing the risk of XSS attacks. An example, script-src ‘self’ ‘https://trustedscripts.example.com’; this will allow scripts from its own website and allow the trusted scripts source but block everything else. This is very useful for preventing the execution of injected scripts.

  • img-src
    This directive controls what image sources are allowed. By using img-src ‘self’ data:; , a web app can restrict image loading  to the domain and base64-encoded data, reducing the risk of malicious image injections.

  • style-src
    For CSS security, style-src defines allowed stylesheets. Inline styles and their-party CSS libraries can pose a security risk, careful whitelisting through CSP can prevent attackers from manipulating page styles maliciously.

  • frame-ancestors
    Using frame-ancestors directive controls which sources are permitted to embed your web page in a <frame> or <iframe>. By default, if not explicitly restricted, any external website could attempt to load your content into an iframe, potentially compromising your users. Setting<frame-ancestors ‘none’> disallows all framing attempts, ensuring that the site cannot be embedded, even by trusted sources.

How Does Unsafe-inline Work?

By default, a CSP blocks the execution of inline scripts and styles because they are a common attack vector for Cross-Site Scripting (XSS) attacks. When the unsafe-inline keyword is included with the CSP, it explicitly permits script-src ‘self’ ‘unsafe-inline’; to execute within the page.

This policy tells the browser to allow:

  • Inline JavaScript inside <script> tags
  • Event handler attributes like oneclick or onload in HTML elements.
  • Inline styles defined using the styles attribute

 

Secure Alternatives

To avoid the risk associated with unsafe-inline, modern CSP implementations offer safer mechanisms.

  • Nonces

    A nonce (number used once) is a unique token generated for each page load. inline script with matching nonces are executed, while others are blocked.

    Example:

    <script nonce="random123" console.log('This script is allowed to be executed.') </script>

    CSP header:

    content-security policy: script 'self' 'nonce-random123';

  • Hashes

    A hash represents a cryptographic summary of inline script. Only scripts that match the hash in the CSP are allowed to execute.

    Example:

    <script>
    console.log('This script is allowed to run.');
    </script>

    CSP header with SHA-256 hash:

    content-security-policy: script-src 'self 'sha256-abc123...';

  • External Scripts
    When possible, externalise scripts into separate files and load them from trusted sources. This approach improves security and also enhances maintainability.

 

Implementing an effective CSP


Report-Only Mode
Before enforcing a CSP policy, use the Content-Security-Policy-Report-Only header. this allows a test to see how the policy works without blacking any content. Using this method will generate reports on potential issues and help fine-tune the policy accordingly.

Be Selective
Creating a restrictive CSP policy that blacks to much content can break functionality on the site. Start with broad restrictions and gradually tighten them while observing which resources are blocked.

Use Nonces and Hashes
CSP offers mechanisms like nonces (randomised tokens) and hashes to allow trusted inline scripts or styles without opening vulnerabilities. This method is more secure to whitelisting entire domains.

Implementation – Practical Tips and Impact

The implementation of CSP can typically use the Content-Security-Policy HTTP header to define which content sources the browser should accept.

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce' https://apis.example.com; img-src 'self'; frame-ancestors 'none'

This policy allows scripts to load from the same origin and from https://apis.example.com while blocking other external scripts. The images are limited to the site itself.

Considerations

CSP is a highly effective security mechanism, it is not however a single solution. It should complement other measures, such as input validation, secure coding practices, and regular vulnerability assessments.

Content Security Policy is a vital step towards creating secure web applications. Their ability to restrict content execution reduces the risk of common vulnerabilities, ensuring that web applications remain resilient against evolving threats. Implementing this to be effective requires a balance between security and functionality.

As cyber threats grow more sophisticated, adopting CSP is no longer optional – it is an essential element of a robust cyber security strategy. Take your time to understand, implement, and refine your polices to safeguard your applications and user data.