Content-Security-Policy

O cabeçalho de resposta HTTP Content-Security-Policy permite aos administradores do site, ter controle sobre os recursos que o agente de usuário é permitido carregar para uma certa página. Com algumas pequenas exceções, políticas majoritariamente envolvem especificar as origens do servidor e pontos de acessos dos scripts. Isso ajuda contra ataques de scripting entre sites (XSS).

Para mais informações, veja o artigo introdutório em Política de Segurança de Conteúdo (Content Security Policy)(CSP).

Tipo de cabeçalho Response header
Forbidden header name não

Sintaxe

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

Diretivas

Fetch directives

Diretivas de busca (Fetch directives) controlam as localizações dos quais certos tipos de recursos podem ser carregados.

Lista de Diretivas de busca de Política de Segurança de Conteúdo (CSP)

child-src
Define uma origem válida para web workers e contextos aninhados de navegação carregados usando elementos como <frame> e <iframe>.

Ao invés de child-src, os autores que querem regular contextos de navegação aninhadas e trabalhores devem usar as diretivas frame-src e worker-src, respectivamente.

connect-src
Restringe a URL que pode ser carregada usando interfaces de script.
default-src
Funciona como recuo para a outra fetch directives.
font-src
Especifica origens válidas para as fontes de letras carregadas usando @font-face.
frame-src
Especifica origens válidas para carregamento de contextos de navegação aninhados usando elementos como <frame> e <iframe>.
img-src
Especifica origens válidas para imagens e ícones.
manifest-src
Especifica origens válidas dos arquivos de manifesto da aplicação.
media-src
Especifica origens válidas para carregar dados de media usando os elementos <audio> , <video> e <track>.
object-src
Especifica origens válidas para os elementos <object>, <embed>, e <applet>.
Elementos controlados por object-src sejam talvez considerados elementos HTML legados e não estão recebendo novas funcionalidades padrão (como os atributos de segurança sandbox ou allow para <iframe>). Sendo assim é recomendado restringir o uso desta diretiva (e.g. colocar explicitamente object-src 'none' se possível).
prefetch-src
Especifica origens válidas para serem pré-carregadas ou pré-renderizadas.
script-src
Especifica origens válidas para JavaScript.
script-src-elem
Especifica origens válidas para elementos JavaScript <script>.
script-src-attr
Especifica origens válidas para handlers de eventos JavaScript inline.
style-src
Especifica origens válidas para arquivos de estilo.
style-src-elem
Especifica origens válidas para elementos de estilo <style> e elementos <link> com rel="stylesheet".
style-src-attr
Especifica origens válidas para estilos dentro de linha aplicados a elementos DOM individuais.
worker-src
Especifica origens válidas para scripts Worker, SharedWorker, ou ServiceWorker.

Document directives

As diretivas de Documento governam as propriedades de um documento ou ambiente worker (trabalhador) para qual a política se aplica.

Lista de diretivas de Documento da Política de Segurança de Conteúdo

base-uri
Restringe as URLs que podem ser usadas em um elemento <base> do documento.
plugin-types
Restringe o conjunto de plugins que podem ser embutidos em um documento limitando pelos tipos de conteúdos que podem ser carregados.
sandbox
Habilita o sandbox para um recurso requisitado similar ao atributo sandbox de <iframe>.

Diretivas de Navegação governam para qual localização um usuário pode navegar ou submeter um formulário para, por exemplo.

Lista de diretivas de Navegação da Política de Segurança de Conteúdo

form-action
Restringe as URLs que podem ser usadas como alvo para as submissões de um formulário para um dado contexto.
frame-ancestors
Especifica pais válidos que podem embutir uma página usando <frame>, <iframe>, <object>, <embed>, ou <applet>.
navigate-to
Restringe as URLs para qual um documento pode iniciar navegação quaisquer sejam os motivos, incluindo <form> (se form-action não for especificado), <a>, window.location, window.open, etc.

Reporting directives

Diretivas de Relatório controlam o processo de reportar as violações CSP. Veja também o cabeçalho Content-Security-Policy-Report-Only.

Lista de Diretivas de Relatório da Política de Segurança de Conteúdo

report-uri
Instrui ao agente de usuário para reportar tentativas de violaçnao de Política de Segurança de Conteúdo. Esses relatórios de violação consistem de documentos JSON enviados por requisição HTTP POST para uma URI especificada.

Apesar da diretiva report-to tem a inteção de trocar a diretiva depreciada report-uri, report-to não é suportado na maioria dos navegadores ainda. Então para compatibilidade com os navegadores atuais enquanto adiciona a compatibilidade com report-to, você pode especificar ambos report-uri e report-to:

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

Em navegadores que suportam report-to, a diretiva report-uri será ignorada.

report-to
Dispara um SecurityPolicyViolationEvent.

Outras diretivas

block-all-mixed-content
Previne carregamento de quaisquer recursos usando HTTP quando a página é carregada usando HTTPS.
referrer
Era usado para especificar informação no cabeçalho de referência (sic) para links fora da página. Ao invés disso, use o cabeçalho Referrer-Policy.
require-sri-for
Obriga o uso de SRI para scripts ou estilos na página.
require-trusted-types-for
Impõe Trusted Types (Tipos confiáveis) em coletores de eventos (vide: Sink (Computing)) para evitar injeção de DOM XSS.
trusted-types
Usado para especificar uma lista branca de políticas Trusted Types (Tipos confiáveis) (Tipos confiáveis permitem aplicações travarem injeções DOM XSS em coletores de eventos (sinks) para aceitarem somente valores tipados não falsificáveis no lugar de strings.
upgrade-insecure-requests
Instrui o usuário de agente a tratar todas as URLs inseguras de um site (aquelas servidas através do HTTP) a serem trocadas por URLs seguras (aqueles servidas através de HTTPS). Essa diretiva tem como foco sites com grande número de URLs inseguras e legadas que precisam ser reescritas.

CSP em workers(trabalhadores)

Workers (trabalhadores) em geral não são governados pela política de segurança de conteúdo do documento (ou trabalhador pai) que os criou. Para especificar uma política de segurança de conteúdo para um trabalhador, coloque um cabeçalho de resposta Content-Security-Policy para a requisição que pediu o script do trabalhador em si.

A exceção à isso é se o script original do trabalhador é um identificador único global (por exemplo, se a URL tem um esquema de dados ou blob). Neste caso, o trabalhador herda a política de segurança de conteúdo do documento ou trabalhador que o criou.

Múltiplas políticas de segurança de conteúdo

CSP permite múltiplas políticas sendo especificadas para um recurso, através dos cabeçalhos Content-Security-Policy, Content-Security-Policy-Report-Only e do elemento <meta>.

Você pode usar o cabeçalho Content-Security-Policy mais de uma vez como no exemplo abaixo. Preste atenção a diretiva connect-src aqui. Mesmo que a segunda política permitiria a conexão, a primeira política contém connect-src 'none'. Adicionando políticas adicionais podem somente restringir as capacidades do recurso protegido, o que significa que não haverá conexão permitida e, como política mais restrita, connect-src 'none' é imposto.

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/

Exemplos

Exemplo: Desabilitar inline/eval inseguros, permitindo somente carregamento de conteúdos (imagens, fontes de letras, scripts, etc.) através do HTTPS:

// cabeçalho
Content-Security-Policy: default-src https:

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

Exemplo: Site pré-existente que usa muito código dentro de linha para corrigir mas quer assegurar que os recursos são carregador somente através de HTTPS e desabilita plugins:

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

Exemplo: Não implemente a política acima ainda, ao invés disso, somente reporte as violações que podem ter ocorrido:

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

Veja as Mozilla Web Security Guidelines para mais exemplos.

Especificações

Especificação Status Comentários
Content Security Policy Level 3 Rascunho atual Adiciona manifest-src, navigate-to, report-to, strict-dynamic, worker-src. Desdeprecia frame-src. Deprecia report-uri em favor de report-to.
Mixed Content Candidata a Recomendação Adiciona block-all-mixed-content.
Subresource Integrity Recomendação Adiciona require-sri-for.
Upgrade Insecure Requests Candidata a Recomendação Adiciona upgrade-insecure-requests.
Content Security Policy Level 2 Recomendação Adiciona base-uri, child-src, form-action, frame-ancestors, plugin-types, referrer, and report-uri. Deprecia frame-src.
Content Security Policy 1.0 Obsoleto Define connect-src, default-src, font-src, frame-src, img-src, media-src, object-src, report-uri, sandbox, script-src, e style-src.

Compatibilidade de navegador

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Content-Security-PolicyChrome Full support 25
Full support 25
Full support 14
Alternate Name
Alternate Name Uses the non-standard name: X-Webkit-CSP
Edge Full support 14Firefox Full support 23
Full support 23
Full support 4
Alternate Name
Alternate Name Uses the non-standard name: X-Content-Security-Policy
IE Full support 10
Notes Alternate Name
Full support 10
Notes Alternate Name
Notes Only supporting 'sandbox' directive.
Alternate Name Uses the non-standard name: X-Content-Security-Policy
Opera Full support 15Safari Full support 7
Full support 7
Full support 6
Alternate Name
Alternate Name Uses the non-standard name: X-Webkit-CSP
WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android Full support YesSafari iOS Full support 7
Full support 7
Full support 5.1
Notes
Notes X-Webkit-CSP
Samsung Internet Android Full support Yes
base-uriChrome Full support 40Edge Full support 79Firefox Full support 35IE No support NoOpera Full support 27Safari Full support 10WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 35Opera Android ? Safari iOS Full support 9.3Samsung Internet Android Full support Yes
block-all-mixed-contentChrome Full support YesEdge Full support ≤79Firefox Full support 48IE No support NoOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 48Opera Android ? Safari iOS ? Samsung Internet Android Full support Yes
child-srcChrome Full support 40Edge Full support 15Firefox Full support 45IE No support NoOpera Full support 27Safari Full support 10WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 45Opera Android ? Safari iOS Full support 9.3Samsung Internet Android Full support Yes
connect-srcChrome Full support 25Edge Full support 14Firefox Full support 23
Notes
Full support 23
Notes
Notes Prior to Firefox 50, ping attributes of <a> elements weren't covered by connect-src.
IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
default-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
font-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
form-actionChrome Full support 40Edge Full support 15Firefox Full support 36IE No support NoOpera Full support 27Safari Full support 10WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 36Opera Android ? Safari iOS Full support 9.3Samsung Internet Android Full support Yes
frame-ancestorsChrome Full support 40Edge Full support 15Firefox Full support 33
Notes
Full support 33
Notes
Notes Before Firefox 58, frame-ancestors is ignored in Content-Security-Policy-Report-Only.
IE No support NoOpera Full support 26Safari Full support 10WebView Android ? Chrome Android Full support YesFirefox Android Full support 33
Notes
Full support 33
Notes
Notes Before Firefox for Android 58, frame-ancestors is ignored in Content-Security-Policy-Report-Only.
Opera Android ? Safari iOS Full support 9.3Samsung Internet Android Full support Yes
frame-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
img-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
manifest-srcChrome Full support YesEdge Full support 79Firefox Full support 41IE No support NoOpera Full support YesSafari No support NoWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 41Opera Android ? Safari iOS No support NoSamsung Internet Android Full support Yes
media-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
<meta> element supportChrome Full support YesEdge Full support ≤18Firefox Full support 45IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 45Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
navigate-to
Experimental
Chrome No support NoEdge No support NoFirefox No support NoIE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support No
object-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
plugin-typesChrome Full support 40Edge Full support 15Firefox No support No
Notes
No support No
Notes
Notes See bug 1045899.
IE No support NoOpera Full support 27Safari Full support 10WebView Android Full support YesChrome Android Full support YesFirefox Android No support NoOpera Android ? Safari iOS Full support 9.3Samsung Internet Android Full support Yes
prefetch-src
Experimental
Chrome No support No
Notes
No support No
Notes
Notes See bug 801561.
Edge No support No
Notes
No support No
Notes
Notes See bug 801561.
Firefox No support No
Notes
No support No
Notes
Notes See bug 1457204.
IE No support NoOpera No support NoSafari No support No
Notes
No support No
Notes
Notes See bug 185070.
WebView Android No support No
Notes
No support No
Notes
Notes See bug 801561.
Chrome Android No support No
Notes
No support No
Notes
Notes See bug 801561.
Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1457204.
Opera Android No support NoSafari iOS No support No
Notes
No support No
Notes
Notes See bug 185070.
Samsung Internet Android No support No
referrer
DeprecatedNon-standard
Chrome No support 33 — 56Edge No support NoFirefox No support 37 — 62IE No support NoOpera No support ? — 43Safari No support NoWebView Android No support 4.4.3 — 56Chrome Android No support 33 — 56Firefox Android No support 37 — 62Opera Android No support ? — 43Safari iOS No support NoSamsung Internet Android No support 2.0 — 6.0
report-sample
Experimental
Chrome Full support 59Edge Full support ≤79Firefox ? IE ? Opera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support 59Firefox Android ? Opera Android Full support 43Safari iOS ? Samsung Internet Android Full support 7.0
report-toChrome Full support 70Edge Full support 79Firefox No support NoIE No support NoOpera No support NoSafari No support NoWebView Android Full support 70Chrome Android Full support 70Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android Full support 10.0
report-uri
Deprecated
Chrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
require-sri-for
ExperimentalDeprecatedNon-standard
Chrome Full support 54Edge Full support 79Firefox No support 49 — 68
Disabled
No support 49 — 68
Disabled
Disabled From version 49 until version 68 (exclusive): this feature is behind the security.csp.experimentalEnabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 41Safari No support NoWebView Android Full support 54Chrome Android Full support 54Firefox Android No support 49 — 68
Disabled
No support 49 — 68
Disabled
Disabled From version 49 until version 68 (exclusive): 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 Full support 41Safari iOS No support NoSamsung Internet Android Full support 6.0
sandboxChrome Full support 25Edge Full support 14Firefox Full support 50IE Full support 10Opera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 50Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
script-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
script-src-attr
Experimental
Chrome Full support 75Edge Full support 79Firefox No support No
Notes
No support No
Notes
Notes See bug 1529337.
IE No support NoOpera Full support 62Safari No support NoWebView Android Full support 75Chrome Android Full support 75Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1529337.
Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
script-src-elem
Experimental
Chrome Full support 75Edge Full support 79Firefox No support No
Notes
No support No
Notes
Notes See bug 1529337.
IE No support NoOpera Full support 62Safari No support NoWebView Android Full support 75Chrome Android Full support 75Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1529337.
Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
strict-dynamicChrome Full support 52Edge Full support 79Firefox Full support 52IE No support NoOpera Full support 39Safari No support NoWebView Android Full support 52Chrome Android Full support 52Firefox Android No support NoOpera Android Full support 41Safari iOS No support NoSamsung Internet Android Full support 6.0
style-srcChrome Full support 25Edge Full support 14Firefox Full support 23IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 23Opera Android ? Safari iOS Full support 7Samsung Internet Android Full support Yes
style-src-attr
Experimental
Chrome Full support 75Edge Full support 79Firefox No support No
Notes
No support No
Notes
Notes See bug 1529338.
IE No support NoOpera Full support 62Safari No support NoWebView Android Full support 75Chrome Android Full support 75Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1529338.
Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
style-src-elem
Experimental
Chrome Full support 75Edge Full support 79Firefox No support No
Notes
No support No
Notes
Notes See bug 1529338.
IE No support NoOpera Full support 62Safari No support NoWebView Android Full support 75Chrome Android Full support 75Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1529338.
Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
trusted-types
Experimental
Chrome ?
?
No support 73 — 76
Disabled
Disabled From version 73 until version 76 (exclusive): this feature is behind the #enable-experimental-productivity-features preference (needs to be set to Enabled). To change preferences in Chrome, visit chrome://flags.
Edge ? Firefox No support NoIE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android ?
?
No support 73 — 76
Disabled
Disabled From version 73 until version 76 (exclusive): this feature is behind the #enable-experimental-productivity-features preference (needs to be set to Enabled). To change preferences in Chrome, visit chrome://flags.
Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support No
unsafe-hashesChrome Full support 69Edge Full support 79Firefox No support No
Notes
No support No
Notes
Notes See bug 1343950.
IE No support NoOpera Full support 56Safari No support NoWebView Android Full support 69Chrome Android Full support 69Firefox Android No support NoOpera Android Full support 48Safari iOS No support NoSamsung Internet Android No support No
upgrade-insecure-requestsChrome Full support 43Edge Full support 17Firefox Full support 42IE No support NoOpera Full support 30Safari Full support 10.1WebView Android Full support 43Chrome Android Full support 43Firefox Android Full support 42Opera Android Full support 30Safari iOS Full support 10.3Samsung Internet Android Full support 4.0
Worker supportChrome Full support YesEdge Full support ≤79Firefox Full support 50IE No support NoOpera ? Safari Full support 10WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 50Opera Android ? Safari iOS Full support 10Samsung Internet Android Full support Yes
worker-srcChrome Full support 59
Notes
Full support 59
Notes
Notes Chrome 59 and higher skips the deprecated child-src directive.
Edge Full support 79Firefox Full support 58IE No support NoOpera Full support 48Safari No support NoWebView Android Full support 59
Notes
Full support 59
Notes
Notes Chrome 59 and higher skips the deprecated child-src directive.
Chrome Android Full support 59
Notes
Full support 59
Notes
Notes Chrome 59 and higher skips the deprecated child-src directive.
Firefox Android Full support 58Opera Android Full support 45Safari iOS No support NoSamsung Internet Android Full support 7.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.
Uses a non-standard name.
Uses a non-standard name.

Veja também