> For the complete documentation index, see [llms.txt](https://0xkourama.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xkourama.gitbook.io/blog/vulnerabilities-and-techniques/web-vulnerabilities/xss-prevention-or-csp.md).

# XSS prevention | CSP

<figure><img src="https://3344169606-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjoHbOFRbwrmbD6PvIUkf%2Fuploads%2FlmBZQv7PX0iZUmQ2naHi%2Fimage.png?alt=media&amp;token=6e05e869-656a-4281-bad6-dc486b6c8219" alt=""><figcaption></figcaption></figure>

| Content                                        |
| ---------------------------------------------- |
| ▶◀ Inputs & Outputs                            |
| ⚪⚫ Whitelisting vs blacklisting                |
| 🛡 X-XSS-Protection                            |
| ⚔ Content Security Policy (CSP) Respose Header |
| 📕 Referance                                   |

### ▶◀ Inputs & Outputs <a href="#inputs-outputs" id="inputs-outputs"></a>

In general Cross-site scripting prevention can generally be achieved via **two layers of defense** for parameters:

**1. Encode data on output**&#x20;

**2. Validate input on arrival**

In an **HTML** context, you should convert non-whitelisted values into HTML entities:

```
< converts to: &lt;
> converts to: &gt;
```

In a **JavaScript** string context, non-alphanumeric values should be Unicode-escaped:

```RUBY
< converts to: \u003c
> converts to: \u003e
```

### ⚪⚫ Whitelisting vs blacklisting <a href="#whitelisting-vs-blacklisting" id="whitelisting-vs-blacklisting"></a>

Input validation should generally employ whitelists rather than blacklists. For example, instead of trying to make a list of all harmful protocols (javascript, data, etc.), simply make a list of safe protocols (HTTP, HTTPS) and disallow anything not on the list.

***

### 🛡 X-XSS-Protection <a href="#x-xss-protection" id="x-xss-protection"></a>

The HTTP **X-XSS-Protection** **response** **Header** is a feature of **Internet Explorer**, **Chrome,** and **Safari** that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. These protections are largely **unnecessary in modern browsers** when sites implement a strong **Content-Security-Policy** that **disables** the use of **inline JavaScript** ('**unsafe-inline'**).

Syntax:

```http
X-XSS-Protection: 0
X-XSS-Protection: 1
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=<reporting-uri>
```

<mark style="color:red;">**0 Disables XSS filtering.**</mark>

<mark style="color:red;">**1 Enables XSS filtering:**</mark>

(usually, default in browsers). If a cross-site scripting attack is detected, the browser will sanitize the page (remove the unsafe parts).

<mark style="color:red;">**1; mode=block**</mark> \
\
Enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

<mark style="color:red;">**1; report=**</mark>\
\
(Chromium only) Enables XSS filtering. If a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. This uses the functionality of the CSP report-uri directive to send a report.

***

### ⚔ Content Security Policy (CSP) Response Header <a href="#content-security-policy-csp-respose-header" id="content-security-policy-csp-respose-header"></a>

Content security policy (**CSP**) is the last line of defense against cross-site scripting.

If your XSS prevention fails, you can use CSP to mitigate XSS by restricting what an attacker can do.

The **HTTP Content-Security-Policy response header** allows website administrators to control the resources the user agent is allowed to load for a given page.

With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (Cross-site\_scripting).

![](https://i.imgur.com/JPjzh1q.jpg)

Implemented via response header:

Implemented via a meta tag:

Defining resources CSP works by restricting the origins that active and passive content can be loaded from. It can additionally restrict certain aspects of active content such as the execution of inline javascript, and the use of eval()

#### Directives: <a href="#directives" id="directives"></a>

<mark style="color:red;">**script-src:**</mark> This directive specifies allowed sources for JavaScript. This includes not only URLs loaded directly into elements but also things like inline script event handlers (on click) and XSLT stylesheets which can trigger script execution.

<mark style="color:red;">**default-src:**</mark> This directive defines the policy for fetching resources by default. When fetch directives are absent in CSP header the browser follows this directive by default.

<mark style="color:red;">**Child-src**</mark>**:** This directive defines allowed resources for web workers and embedded frame contents.

<mark style="color:red;">**connect-src:**</mark> This directive restricts URLs to load using interfaces like fetch, Websocket, and XMLHttpRequest

<mark style="color:red;">**frame-src:**</mark> This directive restricts URLs to which frames can be called out.

<mark style="color:red;">**frame-ancestors:**</mark> This directive specifies the sources that can embed the current page. This directive applies to, and tags. This directive can’t be used in tags and applies only to non-HTML resources.

<mark style="color:red;">**img-src:**</mark> It defines allowed sources to load images on the web page.

<mark style="color:red;">**font-src:**</mark> directive specifies valid sources for fonts loaded using @font-face.

<mark style="color:red;">**manifest-src:**</mark> This directive defines allowed sources of application manifest files.

<mark style="color:red;">**media-src:**</mark> It defines allowed sources from where media objects like, and can be loaded.

<mark style="color:red;">**object-src:**</mark> It defines allowed sources for the and \<applet> elements.

<mark style="color:red;">**base-uri:**</mark> It defines allowed URLs that can be loaded using an element.

<mark style="color:red;">**form-action:**</mark> This directive lists valid endpoints for submission from tags.

<mark style="color:red;">**plugin-types:**</mark> It defines limits the kinds of mime types a page may invoke.

<mark style="color:red;">**upgrade-insecure-requests:**</mark> This directive instructs browsers to rewrite URL schemes, changing HTTP to HTTPS. This directive can be useful for websites with large numbers of old URLs that need to be rewritten.

<mark style="color:red;">**sandbox:**</mark> sandbox directive enables a sandbox for the requested resource similar to the sandbox attribute. It applies restrictions to a page’s actions including preventing popups, preventing the execution of plugins and scripts, and enforcing a same-origin policy.

***

#### Sources: <a href="#sources" id="sources"></a>

<mark style="color:red;">\*:</mark> This allows any URL except data: blob: filesystem: schemes

<mark style="color:red;">**self:**</mark> This source defines that loading of resources on the page is allowed from the same domain.

<mark style="color:red;">**data:**</mark> This source allows loading resources via the data scheme (eg Base64 encoded images)

<mark style="color:red;">**none:**</mark> This directive allows nothing to be loaded from any source.

<mark style="color:red;">**unsafe-eval:**</mark> This allows the use of eval() and similar methods for creating code from strings. This is not a safe practice to include this source in any directive. For the same reason, it is named as unsafe.

<mark style="color:red;">**unsafe-hashes:**</mark> This allows to enable specific inline event handlers.

<mark style="color:red;">**unsafe-inline:**</mark> This allows the use of inline resources, such as inline elements, javascript: URLs, inline event handlers, and inline elements. Again this is not recommended for security reasons.

<mark style="color:red;">**nonce:**</mark> A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. sha256-: Whitelist scripts with a specific sha256 hash

### Unsafe Scenarios <a href="#unsafe-scenarios" id="unsafe-scenarios"></a>

<mark style="color:red;">**unsafe-inline**</mark>

**Working payload:**

\
`"/><script>alert(1);</script>`

<mark style="color:red;">**unsafe-eval**</mark>

**Working payload:** \
\
`<script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>`

***

### 📕 Reference <a href="#referance" id="referance"></a>

1. [**hacktricks**](https://book.hacktricks.xyz/pentesting-web/content-security-policy-csp-bypass)
2. [**csp-evaluator**](https://csp-evaluator.withgoogle.com/)
3. [**cspvalidator**](https://cspvalidator.org/#url=https://cspvalidator.org/)
4. [**Ebrahem Hegazy**](https://www.youtube.com/watch?v=OcrmPMSjdSw\&t=761s)
5. [**mozilla CSP**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
6. [**mozilla X-XSS-Protection**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection)
7. [**portswigger**](https://portswigger.net/web-security/cross-site-scripting/preventing)

<br>
