Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

Content Security Policy (CSP) es una capa de seguridad adicional que ayuda a prevenir y mitigar algunos tipos de ataque, incluyendo Cross Site Scripting (XSS) y ataques de inyección de datos. Estos ataques son usados con diversos propósitos, desde robar información hasta desfiguración de sitios o distribución de malware .

CSP está diseñado para ser completamente retrocompatible (excepto la versión 2 de CSP, donde hay algunas menciones explícitas de inconsistencia en la retrocompatibilidad; más detalles aquí sección 1.1).  Los navegadores que no lo soportan siguen funcionando con los servidores que lo implementan y viceversa: los navegadores que no soportan CSP simplemente lo ignoran, funcionando como siempre y delegando a la política mismo-origen para contenido web. Si el sitio web no ofrece la cabecera CSP, los navegadores igualmente usan la política estándar mismo-origen.

Para habilitar CSP, necesitas configurar tu servidor web para que devuelve la cabecera HTTP Content-Security-Policy (en ocasiones verás menciones de la cabecera X-Content-Security-Policy, pero se trata de una versión antigua y no necesitas especificarla más).

Alternativamente, el elemento <meta> puede ser usado para configurar una política, por ejemplo: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

Threats

Mitigating cross site scripting

A primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser's trust of the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from.

CSP makes it possible for server administrators to reduce or eliminate the vectors by which XSS can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those whitelisted domains, ignoring all other script (including inline scripts and event-handling HTML attributes).

As an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution.

Mitigating packet sniffing attacks

In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using HTTPS. A complete data transmission security strategy includes not only enforcing HTTPS for data transfer, but also marking all cookies with the secure flag and providing automatic redirects from HTTP pages to their HTTPS counterparts. Sites may also use the Strict-Transport-Security HTTP header to ensure that browsers connect to them only over an encrypted channel.

Using CSP

Configuring Content Security Policy involves adding the Content-Security-Policy HTTP header to a web page and giving it values to control resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack. This article explains how to construct such headers properly, and provides examples.

Specifying your policy

You can use the Content-Security-Policy HTTP header to specify your policy, like this:

Content-Security-Policy: policy

The policy is a string containing the policy directives describing your Content Security Policy.

Writing a policy

A policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a default-src policy directive, which is a fallback for other resource types when they don't have policies of their own (for a complete list, see the description of the default-src directive). A policy needs to include a default-src or script-src directive to prevent inline scripts from running, as well as blocking the use of eval(). A policy needs to include a default-src or style-src directive to restrict inline styles from being applied from a <style> element or a style attribute.

Examples: Common use cases

This section provides examples of some common security policy scenarios.

Example 1

A web site administrator wants all content to come from the site's own origin (this excludes subdomains.)

Content-Security-Policy: default-src 'self'

Example 2

A web site administrator wants to allow content from a trusted domain and all its subdomains (it doesn't have to be the same domain that the CSP is set on.)

Content-Security-Policy: default-src 'self' *.trusted.com

Example 3

A web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code.

Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com

Here, by default, content is only permitted from the document's origin, with the following exceptions:

  • Images may loaded from anywhere (note the "*" wildcard).
  • Media is only allowed from media1.com and media2.com (and not from subdomains of those sites).
  • Executable script is only allowed from userscripts.example.com.

Example 4

A web site administrator for an online banking site wants to ensure that all its content is loaded using SSL, in order to prevent attackers from eavesdropping on requests.

Content-Security-Policy: default-src https://onlinebanking.jumbobank.com

The server only permits access to documents being loaded specifically over HTTPS through the single origin onlinebanking.jumbobank.com.

Example 5

A web site administrator of a web mail site wants to allow HTML in email, as well as images loaded from anywhere, but not JavaScript or other potentially dangerous content.

Content-Security-Policy: default-src 'self' *.mailsite.com; img-src *

Note that this example doesn't specify a script-src; with the example CSP, this site uses the setting specified by the default-src directive, which means that scripts can be loaded only from the originating server.

Testing your policy

To ease deployment, CSP can be deployed in report-only mode. The policy is not enforced, but any violations are reported to a provided URI. Additionally, a report-only header can be used to test a future revision to a policy without actually deploying it.

You can use the Content-Security-Policy-Report-Only HTTP header to specify your policy, like this:

Content-Security-Policy-Report-Only: policy 

If both a Content-Security-Policy-Report-Only header and a Content-Security-Policy header are present in the same response, both policies are honored. The policy specified in Content-Security-Policy headers is enforced while the Content-Security-Policy-Report-Only policy generates reports but is not enforced.

Enabling reporting

By default, violation reports aren't sent. To enable violation reporting, you need to specify the report-uri policy directive, providing at least one URI to which to deliver the reports:

Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi

Then you need to set up your server to receive the reports; it can store or process them in whatever manner you feel is appropriate.

Violation report syntax

The report JSON object contains the following data:

blocked-uri
The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port.
disposition
Either "enforce" or "reporting" depending on whether the Content-Security-Policy-Report-Only header or the Content-Security-Policy header is used.
document-uri
The URI of the document in which the violation occurred.
effective-directive
The directive whose inforcement caused the violation.
original-policy
The original policy as specified by the Content-Security-Policy HTTP header.
referrer
The referrer of the document in which the violation occurred.
script-sample
The first 40 characters of the inline script, event handler, or style that caused the violation.
status-code
The HTTP status code of the resource on which the global object was instantiated.
violated-directive
The name of the policy section that was violated.

Sample violation report

Let's consider a page located at http://example.com/signup.html. It uses the following policy, disallowing everything but stylesheets from cdn.example.com.
Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports
The HTML of signup.html looks like this:
<!DOCTYPE html>
<html>
  <head>
    <title>Sign Up</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    ... Content ...
  </body>
</html>
Can you spot the mistake? Stylesheets are only allowed to be loaded from cdn.example.com, yet the website tries to load one from its own origin (http://example.com). A browser capable of enforcing CSP will send the following violation report as a POST request to http://example.com/_/csp-reports, when the document is visited:
{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
  }
}

As you can see, the report includes the full path to the violating resource in blocked-uri. This is not always the case. For example, when the signup.html would attempt to load CSS from http://anothercdn.example.com/stylesheet.css, the browser would not include the full path but only the origin (http://anothercdn.example.com). The CSP specification gives an explanation of this odd behaviour. In summary, this is done to prevent leaking sensitive information about cross-origin resources.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Content-Security-PolicyChrome Soporte completo 25
Notas
Soporte completo 25
Notas
Notas Implemented as X-Webkit-CSP header in Chrome 14.
Edge Soporte completo 14Firefox Soporte completo 23
Notas
Soporte completo 23
Notas
Notas Implemented as X-Content-Security-Policy header in Firefox 4.
IE Soporte completo 10
Notas
Soporte completo 10
Notas
Notas Implemented as X-Content-Security-Policy header, only supporting 'sandbox' directive.
Opera Soporte completo 15Safari Soporte completo 7
Notas
Soporte completo 7
Notas
Notas Implemented as X-Webkit-CSP header in Safari 6.
WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Soporte completo SiFirefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1
Notas
Soporte completo 7.1
Notas
Notas Implemented as X-Webkit-CSP header in iOS 5.1.
Samsung Internet Android Soporte completo Si
base-uriChrome Soporte completo 40Edge Sin soporte NoFirefox Soporte completo 35IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 10WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Soporte completo 35Opera Android ? Safari iOS Soporte completo 9.3Samsung Internet Android Soporte completo Si
block-all-mixed-contentChrome Soporte completo SiEdge ? Firefox Soporte completo 48IE Sin soporte NoOpera Soporte completo SiSafari ? WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 48Opera Android ? Safari iOS ? Samsung Internet Android Soporte completo Si
child-src
Deprecated
Chrome Soporte completo 40Edge Soporte completo 15Firefox Soporte completo 45IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 10WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Soporte completo 45Opera Android ? Safari iOS Soporte completo 9.3Samsung Internet Android Soporte completo Si
connect-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23
Notas
Soporte completo 23
Notas
Notas Prior to Firefox 50, ping attributes of <a> elements weren't covered by connect-src.
IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
default-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
disown-opener
Experimental
Chrome Sin soporte NoEdge Sin soporte NoFirefox Sin soporte NoIE Sin soporte NoOpera Sin soporte NoSafari Sin soporte NoWebView Android Sin soporte NoChrome Android Sin soporte NoEdge Mobile Sin soporte NoFirefox Android Sin soporte NoOpera Android Sin soporte NoSafari iOS Sin soporte NoSamsung Internet Android Sin soporte No
font-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
form-actionChrome Soporte completo 40Edge Soporte completo 15Firefox Soporte completo 36IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 10WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Soporte completo 36Opera Android ? Safari iOS Soporte completo 9.3Samsung Internet Android Soporte completo Si
frame-ancestorsChrome Soporte completo 40Edge Soporte completo 15Firefox Soporte completo 33
Notas
Soporte completo 33
Notas
Notas Before Firefox 58, frame-ancestors is ignored in Content-Security-Policy-Report-Only.
IE Sin soporte NoOpera Soporte completo 26Safari Soporte completo 10WebView Android ? Chrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Soporte completo 33
Notas
Soporte completo 33
Notas
Notas Before Firefox for Android 58, frame-ancestors is ignored in Content-Security-Policy-Report-Only.
Opera Android ? Safari iOS Soporte completo 9.3Samsung Internet Android Soporte completo Si
frame-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
img-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
manifest-srcChrome Soporte completo SiEdge Sin soporte NoFirefox Soporte completo 41IE Sin soporte NoOpera Soporte completo SiSafari Sin soporte NoWebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Soporte completo 41Opera Android ? Safari iOS Sin soporte NoSamsung Internet Android Soporte completo Si
media-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
navigate-to
Experimental
Chrome Sin soporte NoEdge Sin soporte NoFirefox Sin soporte NoIE Sin soporte NoOpera Sin soporte NoSafari Sin soporte NoWebView Android Sin soporte NoChrome Android Sin soporte NoEdge Mobile Sin soporte NoFirefox Android Sin soporte NoOpera Android Sin soporte NoSafari iOS Sin soporte NoSamsung Internet Android Sin soporte No
object-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
plugin-typesChrome Soporte completo 40Edge Soporte completo 15Firefox Sin soporte No
Notas
Sin soporte No
Notas
Notas See bug 1045899.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 10WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile Sin soporte NoFirefox Android Sin soporte NoOpera Android ? Safari iOS Soporte completo 9.3Samsung Internet Android Soporte completo Si
referrer
DeprecatedNo estándar
Chrome Sin soporte 33 — 56Edge Sin soporte NoFirefox Sin soporte 37 — 62IE Sin soporte NoOpera Sin soporte ? — 43Safari Sin soporte NoWebView Android Sin soporte 37 — 56Chrome Android Sin soporte 33 — 56Edge Mobile Sin soporte NoFirefox Android Sin soporte 37 — 62Opera Android Sin soporte ? — 43Safari iOS Sin soporte NoSamsung Internet Android Soporte completo Si
report-sample
Experimental
Chrome Soporte completo 59Edge ? Firefox ? IE ? Opera Soporte completo 46Safari ? WebView Android Soporte completo 59Chrome Android Soporte completo 59Edge Mobile ? Firefox Android ? Opera Android Soporte completo 46Safari iOS ? Samsung Internet Android Soporte completo 7.0
report-toChrome Sin soporte NoEdge Sin soporte NoFirefox Sin soporte NoIE Sin soporte NoOpera Sin soporte NoSafari Sin soporte NoWebView Android Sin soporte NoChrome Android Sin soporte NoEdge Mobile Sin soporte NoFirefox Android Sin soporte NoOpera Android Sin soporte NoSafari iOS Sin soporte NoSamsung Internet Android Sin soporte No
report-uri
Deprecated
Chrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
require-sri-for
Experimental
Chrome Soporte completo 54Edge Sin soporte NoFirefox Soporte completo 49
Deshabilitado
Soporte completo 49
Deshabilitado
Deshabilitado From version 49: this feature is behind the security.csp.experimentalEnabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE Sin soporte NoOpera Soporte completo 41Safari Sin soporte NoWebView Android Soporte completo 54Chrome Android Soporte completo 54Edge Mobile Sin soporte NoFirefox Android Soporte completo 49
Deshabilitado
Soporte completo 49
Deshabilitado
Deshabilitado From version 49: this feature is behind the security.csp.experimentalEnabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Soporte completo 41Safari iOS Sin soporte NoSamsung Internet Android Soporte completo 6.0
sandboxChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 50IE Soporte completo 10Opera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 50Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
script-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
strict-dynamicChrome Soporte completo 52Edge Sin soporte NoFirefox Soporte completo 52IE Sin soporte NoOpera Soporte completo 39Safari Sin soporte NoWebView Android Soporte completo 52Chrome Android Soporte completo 52Edge Mobile Sin soporte NoFirefox Android Sin soporte NoOpera Android Soporte completo 39Safari iOS Sin soporte NoSamsung Internet Android Soporte completo 6.0
style-srcChrome Soporte completo 25Edge Soporte completo 14Firefox Soporte completo 23IE Sin soporte NoOpera Soporte completo 15Safari Soporte completo 7WebView Android Soporte completo SiChrome Android Soporte completo SiEdge Mobile ? Firefox Android Soporte completo 23Opera Android ? Safari iOS Soporte completo 7.1Samsung Internet Android Soporte completo Si
upgrade-insecure-requestsChrome Soporte completo 43Edge Sin soporte No
Notas
Sin soporte No
Notas
Notas Under consideration for future release.
Firefox Soporte completo 42IE Sin soporte NoOpera Soporte completo 30Safari Soporte completo 10.1WebView Android Soporte completo 43Chrome Android Soporte completo 43Edge Mobile Sin soporte NoFirefox Android Soporte completo 42Opera Android Soporte completo 30Safari iOS Soporte completo 10.3Samsung Internet Android Soporte completo 4.0
worker-srcChrome Soporte completo 59
Notas
Soporte completo 59
Notas
Notas Chrome 59 and higher skips the deprecated child-src directive.
Edge Sin soporte NoFirefox Soporte completo 58IE Sin soporte NoOpera Soporte completo 48Safari Sin soporte NoWebView Android Soporte completo 59
Notas
Soporte completo 59
Notas
Notas Chrome 59 and higher skips the deprecated child-src directive.
Chrome Android Soporte completo 59
Notas
Soporte completo 59
Notas
Notas Chrome 59 and higher skips the deprecated child-src directive.
Edge Mobile Sin soporte NoFirefox Android Soporte completo 58Opera Android Soporte completo 48Safari iOS Sin soporte NoSamsung Internet Android Soporte completo 7.0

Leyenda

Soporte completo  
Soporte completo
Sin soporte  
Sin soporte
Compatibility unknown  
Compatibility unknown
Experimental. Esperar que el comportamiento cambie en el futuro.
Experimental. Esperar que el comportamiento cambie en el futuro.
No estandar . Esperar poco soporte entre navegadores.
No estandar . Esperar poco soporte entre navegadores.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
Ver notas de implementación.
Ver notas de implementación.
El usuario debe de habilitar explícitamente esta característica.
El usuario debe de habilitar explícitamente esta característica.

A specific incompatibility exists in some versions of the Safari web browser, whereby if a Content Security Policy header is set, but not a Same Origin header, the browser will block self-hosted content and off-site content, and incorrectly report that this is due to a the Content Security Policy not allowing the content.

See also

Etiquetas y colaboradores del documento

Colaboradores en esta página: vk496, CarlosRomeroVera
Última actualización por: vk496,