Content-Security-Policy
=======================

La cabecera HTTP **`Content-Security-Policy`** en la respuesta permite a los administradores de un sitio web controlar los recursos que el User-Agent puede cargar a una pagina. Con algunas (Poquísimas) excepciones, las políticas implican principalmente especificar el servidor de origen la protección de puntos finales del script. Esto ayuda a protegerse contra ataques Cross-site scripting (XSS (en-US)).

Para mas información, ve también este articulo en Content Security Policy (CSP).

|  |  |
| --- | --- |
| Tipo de cabecera | Response header |
| Forbidden header name | no |

Sintaxis
--------
```

Content-Security-Policy: <policy-directive>; <policy-directive>
```

Directivas
----------

### Fetch directives (en-US)

"Fetch directives" controla la ubicación o ubicaciones desde la cual se pueden cargar ciertos tipos de recursos

#### Lista de Content Security Policy Fetch directives

`child-src` (en-US)

Define los origenes válidos para web workers y contextos de navegación anidados cargados usando elementos como `<frame>` and `<iframe>`.

**Advertencia:** En lugar de **`child-src`**, los autores quienes deseen regular los contextos de navegación anidados y "workers" deberían usar las directivas `frame-src` (en-US) y `worker-src` (en-US), respectivamente.

`connect-src` (en-US)

Restringe las URLs que pueden ser cargados usando scripts.

`default-src` (en-US)

Serves as a fallback for the other fetch directives (en-US).

`font-src` (en-US)

Especifica origenes válidos para las fuentes cargadas usando `@font-face`.

`frame-src` (en-US)

Especifica origenes válidos para contextos de navageción anidada cargados usando elementos como `<frame>` y `<iframe>`.

`img-src` (en-US)

Especifica origenes válidos de imágenes y favicons.

`manifest-src` (en-US)

Especifica origenes válidos de archivos de manifiesto de una aplicación.

`media-src` (en-US)

Especifica origenes válidos para carga de archivos usando elementos como `<audio>` , `<video>` y `<track>`.

`object-src` (en-US)

Specifies valid sources for the `<object>` and `<embed>` elements.

Elements controlled by `object-src` are perhaps coincidentally considered legacy HTML elements and aren't recieving new standardized features (such as the security attributes `sandbox` or `allow` for `<iframe>`). Therefore it is **recommended** to restrict this fetch-directive (e.g. explicitly set `object-src 'none'` if possible).

`prefetch-src` (en-US)

Specifies valid sources to be prefetched or prerendered.

`script-src` (en-US)

Specifies valid sources for JavaScript.

`style-src` (en-US)

Specifies valid sources for stylesheets.

`webrtc-src` 
Experimental

Specifies valid sources for WebRTC connections.

`worker-src` (en-US)

Specifies valid sources for `Worker`, `SharedWorker` (en-US), or `ServiceWorker` (en-US) scripts.

### Document directives (en-US)

Document directives govern the properties of a document or worker environment to which a policy applies.

`base-uri` (en-US)

Restricts the URLs which can be used in a document's `<base>` element.

`plugin-types` (en-US)

Restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded.

`sandbox` (en-US)

Enables a sandbox for the requested resource similar to the `<iframe>` `sandbox` attribute.

`disown-opener` 
Obsoleto

Ensures a resource will disown its opener when navigated to.

### Navigation directives (en-US)

Navigation directives govern to which location a user can navigate to or submit a form to, for example.

`form-action` (en-US)

Restricts the URLs which can be used as the target of a form submissions from a given context.

`frame-ancestors` (en-US)

Specifies valid parents that may embed a page using `<frame>`, `<iframe>`, `<object>`, or `<embed>`.

`navigate-to` (en-US) 
Experimental

Restricts the URLs to which a document can navigate by any means (a, form, window.location, window.open, etc.)

### Reporting directives (en-US)

Reporting directives control the reporting process of CSP violations. See also the `Content-Security-Policy-Report-Only` (en-US) header.

`report-uri` (en-US) 
Obsoleto

Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP `POST` request to the specified URI.

**Advertencia:** Though the `report-to` (en-US) directive is intended to replace the deprecated **`report-uri`** directive, `report-to` (en-US) isn't supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get `report-to` (en-US) support, you can specify both **`report-uri`** and `report-to` (en-US):
```

Content-Security-Policy: ...; report-uri https://endpoint.example.com; report-to groupname
```


In browsers that support `report-to` (en-US), the **`report-uri`** directive will be ignored.

`report-to` (en-US) 
Experimental

Fires a `SecurityPolicyViolationEvent`.

### Other directives

`block-all-mixed-content` (en-US)

Prevents loading any assets using HTTP when the page is loaded using HTTPS.

`referrer` (en-US) 
Obsoleto

Used to specify information in the referer (sic) header for links away from a page. Use the `Referrer-Policy` header instead.

`require-sri-for` (en-US)

Requires the use of SRI (en-US) for scripts or styles on the page.


`trusted-types` (en-US) 
Experimental

Used to specify a whitelist of Trusted Types policies (Trusted Types allows applications to lock down DOM XSS injection sinks to only accept non-spoofable, typed values in place of strings).


`upgrade-insecure-requests` (en-US)

Instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

CSP in workers
--------------

Workers en general no se rigen por las politicas de seguridad de contenido de el documento (o padre del worker) que los creó. To specify a content security policy for the worker, set a `Content-Security-Policy` response header for the request which requested the worker script itself.

The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the content security policy of the document or worker that created it.

Multiple content security policies
----------------------------------

CSP allows multiple policies being specified for a resource, including via the `Content-Security-Policy` header, the `Content-Security-Policy-Report-Only` (en-US) header and a `<meta>` element.

You can use the `Content-Security-Policy` header more than once like in the example below. Pay special attention to the `connect-src` (en-US) directive here. Even though the second policy would allow the connection, the first policy contains `connect-src 'none'`. Adding additional policies *can only further restrict* the capabilities of the protected resource, which means that there will be no connection allowed and, as the strictest policy, `connect-src 'none'` is enforced.
```

Content-Security-Policy: default-src 'self' http://example.com;
                         connect-src 'none';
Content-Security-Policy: connect-src http://example.com/;
                         script-src http://example.com/
```

Ejemplos
--------

Example: Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https:
```

// header
Content-Security-Policy: default-src https:

// meta tag
<meta http-equiv="Content-Security-Policy" content="default-src https:">
```


Example: Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
```

Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
```


Example: Don't implement the above policy yet; instead just report violations that would have occurred:
```

Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/
```


See Mozilla Web Security Guidelines for more examples.

Especificaciones
----------------

| Specification |
| --- |
| Content Security Policy Level 3 # csp-header |

Compatibilidad con navegadores
------------------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Mirar tambien
-------------

* `Content-Security-Policy-Report-Only` (en-US)
* Learn about: Content Security Policy
* Content Security in WebExtensions (en-US)
* Display security and privacy policies In Firefox Developer Tools
* Adopting a strict policy