All you need to know about CSP[Content Security Policy]
Tags: programming, api, html, frontend
Published: 2024-01-08 10:46:23

### Introduction

"While this sounds like some police and enforcement agency theories, I still want to know what or how this is of concern to me as a developer [especially a FE bettle]". 
Relax okay, in this article I'll expose you to what CSP is, a couple of its advantages, and how to implement it in your next project.

### What Is CSP

**CSP**? a short for Content Security Policy according to the [Mozilla developer network](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP#using_csp) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting and data injection attacks. 

All these have to do with your site being exposed to vandalization, malware distribution, data leakage, and theft among others.


This is in most cases a line or two header directives that script your entire document as shown below. [_don't worry there's not much code in this one_]

```html
<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; img-src https://*; child-src 'none';" />
```

Also, compatibility could be a thing of concern on the CPS version 2 for some [reasons](https://www.w3.org/TR/CSP2/), however, the V1 enables backward compatibility which means if it isn't compatible with your browser it falls back to a default same-origin policy [SOP _if you like_] and ignore anything to do with CPS, which is not so much of a good idea as it might allow hackers to subvert your systems.

### What Examples of Threats Does CPS Address?

1. **Alleviation of Cross-Site Scripting (XSS) Attacks**: 
XSS attacks have everything to do with malicious script injection into your web pages and hence the execution of the unwanted scripts in your[the user] browser. Examples of such attacks are spamming, phishing, or DDoS. CSP allows you[the owner] to decide your policy that specifies sources that are allowed to load scripts to your site.

2. **Data theft prevention**: 
When CSP prevents the execution of unauthorized scripts, it also means that data theft is protected against or cut out entirely. Malicious scripts attempting to steal sensitive user data, such as login credentials or personal information, are restricted by the owner-defined CSP policy.

3. **Alleviation of clickjacking**:
Clickjacking happens when you click on something on a website then it performs something else or takes you to another place different from what you intended the click for. CSP headers can help prevent clickjacking by restricting which domains can embed your content in iframes.

4. **Reduces the Impact of Cross-Site Request Forgery (CSRF) Attacks**:
Even though CSP primarily focuses on alleviating XSS attacks, it can also help reduce the impact of CSRF attacks by preventing the execution of unauthorized scripts that might attempt to perform actions on behalf of an authenticated user.

5. **Compliance with Security Standards**:
When Content Security Policy guidelines are followed duly, it exposes a requirement for compliance with certain security standards and regulations, hence enhancing the overall security posture of the site or application.

### Importance of CSP To A Developer

1. **Implementation of Strict Policies**:
Developers can specify strict CSP policies that limit the sources from which scripts, styles, and other resources can be loaded. This encourages a more secure coding practice by only allowing resources from trusted origins including owners.

2. **External Dependencies Management**:
Many web applications use third-party libraries and dependencies. Developers especially on the frontend need to consider the impact of CSP on the inclusion of external scripts and ensure that these dependencies comply with the defined security policies.

3. **Setting CSP Headers**:
Devs especially on the backend are responsible for configuring HTTP headers, including the Content-Security-Policy header, which defines the CSP policy for the web application. They need to understand the security requirements of the application and set up the appropriate CSP directives to mitigate potential security risks.

4. **Safe Management of User Input**:
User inputs are mostly handled by backend developers, and they need to ensure that data received from users is properly validated, sanitized, and encoded to prevent threats like injection attacks. A correct management[handling] of user input contributes to preventing security vulnerabilities that could be exploited via CSP.

5. **Testing and Debugging**:
Testing and debugging are important aspects of app or site creation and developers should test and debug their applications in environments with CSP enabled. This includes but is not limited to checking the browser console for CSP-related errors and ensuring that the application behaves as expected under the defined security policies.

### Usecases/Implemmention of CSP

Most times and even all time XSS attacks leading to resource exploitation are caused as the result of the browser's inability to differentiate between trusted and malicious sources to download its resources.

For example, you're filling out and expected to submit a form that gets your image from `https://icloudimageservices.com/images/my-photos` which means that the URL is trusted and enabled to make supplies to the site, but the browser does not know if `https://wickedboysassociation.killsite` is the trusted one or the malicious source.

And your browser [_cause using free WiFi or any enabling data transfer source_] goes ahead and downloads everything from all these sources not minding if trusted or not, now posing a potential harm aforementioned.
To not allow this to happen the `Content-Security-Policy` is the main HTTP header to specify the precise and allowed sources to make content supplies to the site by giving the browser the rendering or execution permission.

### Use case 1: Allowing self/other sites for scripting

One thing to note is, that the fact that you are the writer of the policy intuitively means that you are the owner of the site and hence a need to allow your content on the allowed list, and this is how you set yourself in. [ _Remember_ `https://wickedboysassociation.killsite` & `https://icloudimageservices.com/images/my-photos` ]

```yaml
Content-Security-Policy: script-src 'self' https://icloudimageservices.com/images/my-photos

```

The above shows us how we can set the allowed site to supply us with anything that relates to (Java)script execution on the site with the keyword `script-src` enabling `https://icloudimageservices.com/images/my-photos` to make script actions and the `'self'` means you allow yourself to be a script supplier too.

There are up to four types of source directive keywords and they include.

- `'none'`, which matches to nothing.

- `'self'` as explained, it sets the origin to the current one [excluding the subdomian].

- `'unsafe-inline'` permits scripts from JavaScript and styles from CSS in an inline code.

- `'unsafe-eval'` text-to-JavaScript tools like `eval()` , are permitted 

### Use case 2: Allowing all Sources

You[_an admin_] want to set a site and all its subdomains as the primary origin to supply contents to the site, remember this doesn't bond to what is set on the CSP, [`https://icloudimageservices.com/images/my-photos`] in our case.

```yaml
Content-Security-Policy: default-src 'self' alldomainsite.com *.alldomainsite.com

```

Hence `default-src` allows all contents from your `site` and `alldomainsite.com`, and all its subdomains as the default.

### Use case 3: Allowing only Secured Sources

You want to make sure that all contents and resources are downloaded from trusted and only secure channels and not having to go through long third-party hard-to-understand code implementations.

```yaml
Content-Security-Policy: default-src 'self' https://alldomainsite.com; 
script-src https: 'unsafe-inline'; 
style-src https: 'unsafe-inline'

```
Even though the `default-src` is set as `https://alldomainsite.com`, it does not have any supply obligation to the site that will supply the script and the styles, they all would mind their specifications based on set directives.

### Reporting

We can generally say that CSP is a big savior to threats we might experience from untrusted client-site, however it is of great importance and needs to monitor and get a response sent back showing all the possible causes[bugs] that led to the malicious injection in the first place and hence destroying it.

Hence you can make a POST request that will send back a report to the specified `report-uri` in your directives.

```yaml
Content-Security-Policy: default-src 'self'; report-uri /asap_csp_report_parser; 
```

And the following report response is expected.

```json
{
    "csp-report": {
    "document-uri": "http://wickedboysassociation.org/page.html",
    "referrer": "http://wickedboysassociation.killsite.org/",
    "blocked-uri": "http://wickedboysassociation.killsite/evil.js",
    "violated-directive": "script-src 'self' https://myallowedsiteonly.com",
    "original-policy": "script-src 'self' https://apis.myallowedsiteonly.com; report-uri http://reports.org/asap_csp_report_parser"
    }
}
```

### NOTE: 

It is advisable that the CSP directives are set in your HTTP header, nonetheless, you can still set the page policy directly in your project with the `<meta>` tag and the `http-equiv` attribute.

```html
<meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'">
```

### Conclusion

In this article we have learned what CSP is, and how it is beneficial to developers' projects and users' data, we have learned major ways to implement it in our next project and we can now feel like heroes to threats like XSS (Cross Site Scripting) attacks, clickjacking, Cross-Site Request Forgery (CSRF) among others.

Please share If you find this helpful thanks!