{"title":"Segurança no Django","version":"6.1","locale":"pt-br","docname":"topics/security","url":"/pt-br/6.1/topics/security/","canonical":"https://djangodocs.dev/pt-br/6.1/topics/security/","summary":"Este documento é uma visão geral sobre as funcionalidades de segurança do Django. Ele inclui dicas de segurança para sites desenvolvidos em Django. Real-world…","html":"<h1>Segurança no Django<a class=\"heading-anchor\" href=\"#security-in-django\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Este documento é uma visão geral sobre as funcionalidades de segurança do Django. Ele inclui dicas de segurança para sites desenvolvidos em Django.</p>\n<aside class=\"admonition-real-world-security admonition\">\n<p class=\"admonition-title\">Real-world security</p>\n<p>Django’s web security implementations have been designed with security for\nreal-world applications in mind. Django is a general-purpose web\napplication framework, and its defaults reflect this - they will not be the\nbest solution for every particular case. Special cases deserve special\nattention to their needs.</p>\n<p>Web security requires a multi-layered approach. Securing only a single\nvector does not make a site secure overall, nor does a single apparent\nweakness necessarily compromise the entire site. This should be borne in\nmind particularly when assessing individual points in security audits.</p>\n</aside>\n<section id=\"always-sanitize-user-input\">\n<span id=\"sanitize-user-input\"></span><h2>Always sanitize user input<a class=\"heading-anchor\" href=\"#always-sanitize-user-input\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The golden rule of web application security is to never trust user-controlled\ndata. Hence, all user input should be sanitized before being used in your\napplication. See the <a class=\"reference internal\" href=\"/pt-br/6.1/topics/forms/\"><span class=\"doc\">forms documentation</span></a> for\ndetails on validating user inputs in Django.</p>\n</section>\n<section id=\"cross-site-scripting-xss-protection\">\n<span id=\"cross-site-scripting\"></span><h2>Cross-site scripting (XSS) protection<a class=\"heading-anchor\" href=\"#cross-site-scripting-xss-protection\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>In a cross-site scripting attack, malicious code in the form of a client-side\nscript is injected into another user’s web browser, where it will be executed.</p>\n<p>This is typically done by:</p>\n<ul class=\"simple\">\n<li><p>storing the malicious script in the database where it will be retrieved and\npresented to other users in their browsers, or</p></li>\n<li><p>getting users to click a link which will cause the attacker’s JavaScript to\nbe executed by the user’s browser.</p></li>\n</ul>\n<p>Cross-site scripting attacks can originate from any untrusted source of data,\nincluding cookies or web services, if the data are not adequately sanitized\nbefore being published in a page.</p>\n<p>Django templates provide protection against the majority of cross-site\nscripting attacks by <a class=\"reference internal\" href=\"/pt-br/6.1/ref/templates/language/#automatic-html-escaping\"><span class=\"std std-ref\">automatically escaping characters that represent a\nrisk</span></a> (that is, HTML characters that could be\n<em>interpreted</em> by the browser to malicious effect are instead safely\n<em>displayed</em>).</p>\n<p>However, the extent of this protection and its limitations should be\nunderstood.</p>\n<p>Ambiguity between the developer’s intention and how the browser interprets\nHTML can expose the client to unintended code execution. Suppose that a\ndeveloper creates:</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Text code\"><code>&lt;style class={{ var }}&gt;...&lt;/style&gt;\n</code></pre></div>\n<p>where <code class=\"docutils literal notranslate\"><span class=\"pre\">var</span></code> is expected to contain something like <code class=\"docutils literal notranslate\"><span class=\"pre\">'class1'</span></code>. If <code class=\"docutils literal notranslate\"><span class=\"pre\">var</span></code>\nwere set to <code class=\"docutils literal notranslate\"><span class=\"pre\">'class1</span> <span class=\"pre\">onmouseover=javascript:func()'</span></code> though, this could\nresult in unauthorized JavaScript execution due to differences in how browsers\nwill interpret this imperfect HTML.</p>\n<p>Explicit template design, in which the quotes are not left to the variable to\nprovide:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">style</span> <span class=\"na\">class</span><span class=\"o\">=</span><span class=\"s\">&quot;</span><span class=\"cp\">{{</span> <span class=\"nv\">var</span> <span class=\"cp\">}}</span><span class=\"s\">&quot;</span><span class=\"p\">&gt;</span><span class=\"o\">...</span><span class=\"p\">&lt;/</span><span class=\"nt\">style</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>would eliminate this possibility.</p>\n<p>It is also important to be particularly careful when using the <code class=\"docutils literal notranslate\"><span class=\"pre\">is_safe</span></code>\nattribute with custom template tags, the <a class=\"reference internal\" href=\"/pt-br/6.1/ref/templates/builtins/#std-templatefilter-safe\"><code class=\"xref std std-tfilter docutils literal notranslate\"><span class=\"pre\">safe</span></code></a> template tag,\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/utils/#module-django.utils.safestring\" title=\"django.utils.safestring: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">mark_safe</span></code></a>, and when autoescape is turned off.</p>\n<p>Django’s built-in escaping is intended to protect HTML output. If you are using\nthe template system to output something other than HTML, the characters and\nstrings that require escaping might be entirely different.</p>\n<p>Additionally, be very careful when storing HTML in the database, especially\nwhen that HTML is retrieved and displayed. Unless the HTML is guaranteed to\ncome from a trusted source - user input is <em>not</em> a trusted source - stored HTML\nshould be checked and sanitized, preferably on input as well as output.</p>\n</section>\n<section id=\"cross-site-request-forgery-csrf-protection\">\n<h2>Cross-site request forgery (CSRF) protection<a class=\"heading-anchor\" href=\"#cross-site-request-forgery-csrf-protection\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Ataques de solicitações forjadas entre sites, na sigla em inglês, CSRF, permitem que um usuário malicioso execute ações usando as credenciais de outro usuário sem o seu consentimento ou conhecimento.</p>\n<p>O Django já possui proteção embutida contra a maioria dos tipos de ataques CSRF, contanto que você a tenha <a class=\"reference internal\" href=\"/pt-br/6.1/howto/csrf/#using-csrf\"><span class=\"std std-ref\">habilitado e usado</span></a> onde apropriado. Porém, assim como em qualquer outra técnica de mitigação, existem limitações. Por exemplo, é possível desabilitar o módulo CSRF globalmente ou para views em particular. Você só deve fazer isso se você souber o que você está fazendo. Existem outras <a class=\"reference internal\" href=\"/pt-br/6.1/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">limitações</span></a> se o seu site tiver subdomínios que estão fora do seu controle.</p>\n<p><a class=\"reference internal\" href=\"/pt-br/6.1/ref/csrf/#how-csrf-works\"><span class=\"std std-ref\">CSRF protection works</span></a> by checking for a secret in each\nPOST request. This ensures that a malicious user cannot “replay” a form POST to\nyour website and have another logged-in user unwittingly submit that form. The\nmalicious user would have to know the secret, which is user specific (using a\ncookie).</p>\n<p>Quando implantado com <a class=\"reference internal\" href=\"#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a>, <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> irá verificar se o referido cabeçalho HTTP está configurado para uma URL na mesma origem (incluindo subdomínio e porta). Como o HTTPS fornece segurança adicional, é imperativo garantir que as conexões utilizem HTTPS quando disponível redirecionando requisições de conexões inseguras e usando HSTS nos browsers suportados.</p>\n<p>Tenha cuidado ao marcar views com o decorator <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_exempt</span></code> a não ser que isso seja absolutamente necessário.</p>\n</section>\n<section id=\"sql-injection-protection\">\n<span id=\"id1\"></span><h2>Proteção contra SQL injection<a class=\"heading-anchor\" href=\"#sql-injection-protection\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>SQL injection é um tipo de ataque onde o usuário malicioso consegue executar código SQL arbitrário em um banco de dados. Isso pode resultar em registros sendo deletados ou vazamento de dados.</p>\n<p>Django’s querysets are protected from SQL injection since their queries are\nconstructed using query parameterization. A query’s SQL code is defined\nseparately from the query’s parameters. Since parameters may be user-provided\nand therefore unsafe, they are escaped by the underlying database driver.</p>\n<p>Django also gives developers power to write <a class=\"reference internal\" href=\"/pt-br/6.1/topics/db/sql/#executing-raw-queries\"><span class=\"std std-ref\">raw queries</span></a> or execute <a class=\"reference internal\" href=\"/pt-br/6.1/topics/db/sql/#executing-custom-sql\"><span class=\"std std-ref\">custom sql</span></a>.\nThese capabilities should be used sparingly and you should always be careful to\nproperly escape any parameters that the user can control. In addition, you\nshould exercise caution when using\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/models/querysets/#django.db.models.query.QuerySet.extra\" title=\"django.db.models.query.QuerySet.extra\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">extra()</span></code></a> and\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/models/expressions/#django.db.models.expressions.RawSQL\" title=\"django.db.models.expressions.RawSQL\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RawSQL</span></code></a>.</p>\n</section>\n<section id=\"clickjacking-protection\">\n<h2>Proteção contra Clickjacking<a class=\"heading-anchor\" href=\"#clickjacking-protection\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Clickjacking, ou roubo de click, é um tipo de ataque onde um site malicioso embrulha outro site dentro de um frame. Esse ataque pode resultar em um usuário desavisado sendo levado a fazer ações não intencionadas no site alvo.</p>\n<p>O Django possui <a class=\"reference internal\" href=\"/pt-br/6.1/ref/clickjacking/#clickjacking-prevention\"><span class=\"std std-ref\">proteção contra clickjacking</span></a> no form do middleware <a class=\"reference internal\" href=\"/pt-br/6.1/ref/middleware/#django.middleware.clickjacking.XFrameOptionsMiddleware\" title=\"django.middleware.clickjacking.XFrameOptionsMiddleware\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">X-Frame-Options</span> <span class=\"pre\">middleware</span></code></a> que em um browser com suporte pode prevenir um site de ser renderizado dentro de um frame. É possível desabilitar a proteção por view ou configurar o valor exato a ser enviado no cabeçalho.</p>\n<p>O middleware é fortemente recomendado para qualquer site que não precise ter suas páginas envolvidas em um frame por sites de terceiros, ou que só precise permitir isso para uma pequena seção do site.</p>\n</section>\n<section id=\"ssl-https\">\n<span id=\"security-recommendation-ssl\"></span><h2>SSL/HTTPS<a class=\"heading-anchor\" href=\"#ssl-https\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>É sempre melhor para segurança implantar o seu site usando HTTPS. Sem isso, é possível para redes de usuários mal intencionados farejar credenciais de autenticação ou qualquer outra informação transferida entre o cliente e o servidor, e em alguns casos – <strong>invasores ativos na rede</strong> – alterarem dados que foram enviados em qualquer direção.</p>\n<p>Se você quiser a proteção que o HTTPS provê, e o habilitou no seu servidor, existem mais alguns passos adicionais que você pode precisar:</p>\n<ul>\n<li><p>Se necessário, ativar <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_PROXY_SSL_HEADER</span></code></a>, certificando-se que você entendeu completamente os avisos mencionados lá. Falhar ao fazer isso pode resultar em vulnerabilidades de CSRF, e falhar em fazer isso corretamente podem ainda ser perigoso!</p></li>\n<li><p>Ativar <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_SSL_REDIRECT</span></code></a> configurando para <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>, de modo que as requisições via HTTP sejam redirecionadas para HTTPS.</p>\n<p>Please note the caveats under <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_PROXY_SSL_HEADER</span></code></a>. For the\ncase of a reverse proxy, it may be easier or more secure to configure the\nmain web server to do the redirect to HTTPS.</p>\n</li>\n<li><p>Utilize cookies ‘seguros’.</p>\n<p>Se um browser conecta inicialmente via HTTP, o que é o padrão na maioria dos browsers, é possível que cookies existentes sejam vazados. Por essa razão, você deve ativar os settings <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SESSION_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SESSION_COOKIE_SECURE</span></code></a> e <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SECURE</span></code></a> para <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>. Isso instrui o browser a só enviar os cookies em conexões sobre HTTPS. Repare que isso significa que as sessões não irão funcionar sobre HTTP (o que não é um problema se você está redirecionando todo o seu tráfego HTTP para HTTPS).</p>\n</li>\n<li><p>Utilize <a class=\"reference internal\" href=\"/pt-br/6.1/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP Strict Transport Security</span></a> (HSTS)</p>\n<p>HSTS is an HTTP header that informs a browser that all future connections to\na particular site should always use HTTPS. Combined with redirecting requests\nover HTTP to HTTPS, this will ensure that connections always enjoy the added\nsecurity of SSL provided one successful connection has occurred. HSTS may\neither be configured with <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_SECONDS</span></code></a>,\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a>, and\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_PRELOAD</span></code></a>, or on the web server.</p>\n</li>\n</ul>\n</section>\n<section id=\"host-header-validation\">\n<span id=\"host-headers-virtual-hosting\"></span><h2>Validação do cabeçalho Host<a class=\"heading-anchor\" href=\"#host-header-validation\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django uses the <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header provided by the client to construct URLs in\ncertain cases. While these values are sanitized to prevent cross-site scripting\nattacks, a fake <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> value can be used for cross-site request forgery,\ncache poisoning attacks, and poisoning links in emails.</p>\n<p>Because even seemingly-secure web server configurations are susceptible to fake\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> headers, Django validates <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> headers against the\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a> setting in the\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">django.http.HttpRequest.get_host()</span></code></a> method.</p>\n<p>This validation only applies via <a class=\"reference internal\" href=\"/pt-br/6.1/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">get_host()</span></code></a>;\nif your code accesses the <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header directly from <code class=\"docutils literal notranslate\"><span class=\"pre\">request.META</span></code> you\nare bypassing this security protection.</p>\n<p>Para mais detalhes veja a documentação completa do setting <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a>.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Aviso</p>\n<p>Versões prévias deste documento recomendavam configurar o seu web server para garantir que ele valide cabeçalhos HTTP <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> recebidos. Embora isso ainda seja recomendado, em vários web servers comuns uma configuração que parece validar o cabeçalho <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> pode na verdade não fazer isso. Por exemplo, mesmo se o Apache estiver configurado de modo que o seu site Django seja fornecido de um host virtual não padrão com o <code class=\"docutils literal notranslate\"><span class=\"pre\">ServerName`</span> <span class=\"pre\">configurado,</span> <span class=\"pre\">ainda</span> <span class=\"pre\">é</span> <span class=\"pre\">possível</span> <span class=\"pre\">para</span> <span class=\"pre\">uma</span> <span class=\"pre\">requisição</span> <span class=\"pre\">HTTP</span> <span class=\"pre\">corresponder</span> <span class=\"pre\">a</span> <span class=\"pre\">esse</span> <span class=\"pre\">host</span> <span class=\"pre\">virtual</span> <span class=\"pre\">e</span> <span class=\"pre\">fornecer</span> <span class=\"pre\">um</span> <span class=\"pre\">cabeçalho</span> <span class=\"pre\">``Host</span></code> falso. Assim, O Django agora exige que você ative explicitamente o setting <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a> ao invés de confiar na configuração do web server.</p>\n</aside>\n<p>Adicionalmente, o Django requer que você ative explicitamente o suporte para o cabeçalho <code class=\"docutils literal notranslate\"><span class=\"pre\">X-Forwarded-Host</span></code> (através do setting <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-USE_X_FORWARDED_HOST\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">USE_X_FORWARDED_HOST</span></code></a>) se a sua configuração exigir ele.</p>\n</section>\n<section id=\"referrer-policy\">\n<h2>Referrer policy<a class=\"heading-anchor\" href=\"#referrer-policy\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Browsers use the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header as a way to send information to a site\nabout how users got there. By setting a <em>Referrer Policy</em> you can help to\nprotect the privacy of your users, restricting under which circumstances the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header is set. See <a class=\"reference internal\" href=\"/pt-br/6.1/ref/middleware/#referrer-policy\"><span class=\"std std-ref\">the referrer policy section of the\nsecurity middleware reference</span></a> for details.</p>\n</section>\n<section id=\"cross-origin-opener-policy\">\n<h2>Cross-origin opener policy<a class=\"heading-anchor\" href=\"#cross-origin-opener-policy\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The cross-origin opener policy (COOP) header allows browsers to isolate a\ntop-level window from other documents by putting them in a different context\ngroup so that they cannot directly interact with the top-level window. If a\ndocument protected by COOP opens a cross-origin popup window, the popup’s\n<code class=\"docutils literal notranslate\"><span class=\"pre\">window.opener</span></code> property will be <code class=\"docutils literal notranslate\"><span class=\"pre\">null</span></code>. COOP protects against cross-origin\nattacks. See <a class=\"reference internal\" href=\"/pt-br/6.1/ref/middleware/#cross-origin-opener-policy\"><span class=\"std std-ref\">the cross-origin opener policy section of the security\nmiddleware reference</span></a> for details.</p>\n</section>\n<section id=\"session-security\">\n<h2>Session security<a class=\"heading-anchor\" href=\"#session-security\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>De forma similiar as :ref:` limitações CSRF &lt;csrf-limitations&gt;` requerendo que o deploy de um site seja feito de modo que usuários não tenham acesso a quaisquer subdomínios, o módulo <a class=\"reference internal\" href=\"/pt-br/6.1/topics/http/sessions/#module-django.contrib.sessions\" title=\"django.contrib.sessions: Provides session management for Django projects.\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">django.contrib.sessions</span></code></a> também tem limitações. Veja <a class=\"reference internal\" href=\"/pt-br/6.1/topics/http/sessions/#topics-session-security\"><span class=\"std std-ref\">a seção de segurança do guia que fala sobre sessions</span></a> para mais detalhes.</p>\n</section>\n<section id=\"user-uploaded-content\">\n<span id=\"user-uploaded-content-security\"></span><h2>Conteúdo carregado por upload de usuários<a class=\"heading-anchor\" href=\"#user-uploaded-content\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p>Considere  <a class=\"reference internal\" href=\"/pt-br/6.1/howto/static-files/deployment/#staticfiles-from-cdn\"><span class=\"std std-ref\">servir arquivos estáticos de um serviço na nuvem ou através de uma CDN</span></a> para evitar alguns desses problemas.</p>\n</aside>\n<ul>\n<li><p>If your site accepts file uploads, it is strongly advised that you limit\nthese uploads in your web server configuration to a reasonable\nsize in order to prevent denial of service (DOS) attacks. In Apache, this\ncan be easily set using the <a class=\"reference external\" href=\"https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody\">LimitRequestBody</a> directive. You should not rely\nsolely on <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DATA_UPLOAD_MAX_MEMORY_SIZE</span></code></a>\nnor <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-FILE_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">FILE_UPLOAD_MAX_MEMORY_SIZE</span></code></a>.</p></li>\n<li><p>Se você estiver fornecendo os seus próprios arquivos estáticos, certifique-se de que handlers como o <code class=\"docutils literal notranslate\"><span class=\"pre\">mod_php</span></code>, que são capazes de executar arquivos estáticos como código, estejam desabilitados. Você não quer que usuários sejam capazes de executar código arbitrário através do upload e solicitação de um arquivo especialmente criado.</p></li>\n<li><p>A manipulação de envio de mídia no Django expõe algumas vulnerabilidades quando esta mídia é servida de maneiras que não seguem as melhores práticas de segurança. Especificamente, um arquivo HTML pode ser enviado como imagem se o arquivo contiver  um cabeçalho PNG válido seguido por um HTML malicioso. Este arquivo irá passar a validação da biblioteca <a class=\"reference internal\" href=\"/pt-br/6.1/ref/models/fields/#django.db.models.ImageField\" title=\"django.db.models.ImageField\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">ImageField</span></code></a> que o Django usa para processar imagem (Pillow). Quando este arquivo é subsequentemente mostrado para um usuário, ele pode ser mostrado como HTML dependendo do tipo de configuração do seu servidor web.</p>\n<p>Não existe solução à prova de balas a nível de framework para validar com segurança todos os uploads de arquivos de usuários, entretanto, existem mais alguns passos que você pode dar para mitigar esses ataques:</p>\n<ol class=\"arabic simple\">\n<li><p>Uma classe de ataques pode ser prevenida servindo sempre conteúdo proveniente de uploads de um domínio de primeiro nível ou de um domínio de segundo nível. Isso previne qualquer vulnerabilidade bloqueada por proteções do tipo <a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Same-origin_policy\">same-origin policy</a> tais como CSS. Por exemplo, se o seu site está hospedado em <code class=\"docutils literal notranslate\"><span class=\"pre\">example.com</span></code>, você vai querer fornecer conteúdo proveniente de uploads (o setting <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-MEDIA_URL\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MEDIA_URL</span></code></a>) de algo como <code class=\"docutils literal notranslate\"><span class=\"pre\">usercontent-example.com</span></code>. <em>Não</em> basta apenas fornecer conteúdo de um subdomínio como <code class=\"docutils literal notranslate\"><span class=\"pre\">usercontent.example.com</span></code>.</p></li>\n<li><p>Beyond this, applications may choose to define a list of allowable\nfile extensions for user uploaded files and configure the web server\nto only serve such files.</p></li>\n</ol>\n</li>\n</ul>\n</section>\n<section id=\"form-submissions\">\n<h2>Form Submissions<a class=\"heading-anchor\" href=\"#form-submissions\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<ul class=\"simple\">\n<li><p>Form submissions containing files are not limited by\n<a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DATA_UPLOAD_MAX_MEMORY_SIZE</span></code></a>. Under ASGI, the entire request may be\nspooled to disk before any file size validation is performed. It is strongly\nadvised that you limit the maximum request body size in your web server\nconfiguration to prevent denial of service (DOS) attacks.</p></li>\n</ul>\n</section>\n<section id=\"content-security-policy\">\n<span id=\"security-csp\"></span><h2>Content Security Policy<a class=\"heading-anchor\" href=\"#content-security-policy\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"version-note version-added\" data-version=\"6.0\">\n<p class=\"version-note-title\">New in Django 6.0</p></aside>\n<p>Content Security Policy (CSP) is a browser security mechanism that helps\nprotect web applications against attacks such as cross-site scripting (XSS) and\nother content injection attacks.</p>\n<p>CSP allows web applications to define which sources of content are trusted,\ninstructing the browser to load, execute, or render resources only from those\nsources. This effectively creates an allowlist of content origins, reducing the\nrisk of malicious code execution.</p>\n<p>Key benefits of enabling CSP include:</p>\n<ol class=\"arabic simple\">\n<li><p>Mitigating XSS attacks by blocking inline scripts and restricting external\nscript loading.</p></li>\n<li><p>Controlling which external resources (e.g., images, fonts, stylesheets) can\nbe loaded.</p></li>\n<li><p>Preventing unwanted framing of your site to protect against clickjacking.</p></li>\n<li><p>Reporting violations to a specified endpoint, enabling monitoring and\ndebugging.</p></li>\n</ol>\n<p>For configuration instructions, see the <a class=\"reference internal\" href=\"/pt-br/6.1/howto/csp/#csp-config\"><span class=\"std std-ref\">Using CSP</span></a>\ndocumentation, and refer to the <a class=\"reference internal\" href=\"/pt-br/6.1/ref/csp/#csp-overview\"><span class=\"std std-ref\">CSP overview</span></a> for details\non directives and settings.</p>\n<section id=\"limitations-and-considerations\">\n<h3>Limitations and considerations<a class=\"heading-anchor\" href=\"#limitations-and-considerations\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>While CSP is a powerful security mechanism, it’s important to understand its\nlimitations and implications, particularly when used in Django:</p>\n<ul class=\"simple\">\n<li><p>Policy exclusion risks: Avoid excluding specific paths or responses from\nCSP protection. Due to the browser’s same-origin policy, a vulnerability on\nan unprotected page (e.g., one allowing arbitrary script injection) may be\nleveraged to attack protected pages. Excluding <em>any</em> route can significantly\nweaken the site’s overall CSP protection.</p></li>\n<li><p>Performance overhead: Although typically negligible, CSP adds some processing\noverhead. Nonce generation involves secure randomness for each applicable\nrequest. For high-traffic applications or resource-constrained environments,\nmeasure the performance impact accordingly.</p></li>\n<li><p>Browser support: While CSP Levels 1 and 2 are widely supported, newer\ndirectives (CSP Level 3+) or complex policy behaviors may vary across\nbrowsers. Test your policy across the environments you intend to support.</p></li>\n</ul>\n<p>Despite these limitations, CSP remains an important and recommended security\nlayer for web applications. Understanding its constraints will help you design\na more effective and reliable deployment.</p>\n</section>\n</section>\n<section id=\"additional-security-topics\">\n<span id=\"id2\"></span><h2>Tópicos adicionais de segurança<a class=\"heading-anchor\" href=\"#additional-security-topics\"><span class=\"visually-hidden\">Link para este cabeçalho</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>While Django provides good security protection out of the box, it is still\nimportant to properly deploy your application and take advantage of the\nsecurity protection of the web server, operating system and other components.</p>\n<ul class=\"simple\">\n<li><p>Make sure that your Python code is outside of the web server’s root. This\nwill ensure that your Python code is not accidentally served as plain text\n(or accidentally executed).</p></li>\n<li><p>Tome cuidado com qualquer <a class=\"reference internal\" href=\"/pt-br/6.1/ref/models/fields/#file-upload-security\"><span class=\"std std-ref\">arquivo originado de uploads de usuários</span></a>.</p></li>\n<li><p>Django does not throttle requests to authenticate users. To protect against\nbrute-force attacks against the authentication system, you may consider\ndeploying a Django plugin or web server module to throttle these requests.</p></li>\n<li><p>Keep your <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECRET_KEY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECRET_KEY</span></code></a>, and <a class=\"reference internal\" href=\"/pt-br/6.1/ref/settings/#std-setting-SECRET_KEY_FALLBACKS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECRET_KEY_FALLBACKS</span></code></a> if in\nuse, secret.</p></li>\n<li><p>É uma boa idéia limitar a acessibilidade de seu sistema de cache e banco de dados, utilizando um firewall.</p></li>\n<li><p>Dê uma olhada no <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>Top 10 <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">`</span></a>_ do “Projeto Aberto de Segurança de Aplicações Web”, em inglês Open Web Application Security Project (OWASP), que identifica algumas vulnerabilidades comuns em aplicações web. Embora o Django tenha ferramentas para solucionar alguns desses problemas, outros problemas devem ser resolvidos no design do seu projeto.</p></li>\n<li><p>Mozilla discusses various topics regarding <a class=\"reference external\" href=\"https://infosec.mozilla.org/guidelines/web_security.html\">web security</a>. Their\npages also include security principles that apply to any system.</p></li>\n</ul>\n</section>","rootId":"security-in-django","toc":[{"title":"Always sanitize user input","anchor":"always-sanitize-user-input","children":[]},{"title":"Cross-site scripting (XSS) protection","anchor":"cross-site-scripting-xss-protection","children":[]},{"title":"Cross-site request forgery (CSRF) protection","anchor":"cross-site-request-forgery-csrf-protection","children":[]},{"title":"Proteção contra SQL injection","anchor":"sql-injection-protection","children":[]},{"title":"Proteção contra Clickjacking","anchor":"clickjacking-protection","children":[]},{"title":"SSL/HTTPS","anchor":"ssl-https","children":[]},{"title":"Validação do cabeçalho Host","anchor":"host-header-validation","children":[]},{"title":"Referrer policy","anchor":"referrer-policy","children":[]},{"title":"Cross-origin opener policy","anchor":"cross-origin-opener-policy","children":[]},{"title":"Session security","anchor":"session-security","children":[]},{"title":"Conteúdo carregado por upload de usuários","anchor":"user-uploaded-content","children":[]},{"title":"Form Submissions","anchor":"form-submissions","children":[]},{"title":"Content Security Policy","anchor":"content-security-policy","children":[{"title":"Limitations and considerations","anchor":"limitations-and-considerations","children":[]}]},{"title":"Tópicos adicionais de segurança","anchor":"additional-security-topics","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Usando o Django","url":"/pt-br/6.1/topics/"}],"prev":{"docname":"topics/pagination","title":"Pagination","url":"/pt-br/6.1/topics/pagination/"},"next":{"docname":"topics/performance","title":"Performance e otimização","url":"/pt-br/6.1/topics/performance/"},"formats":{"html":"/pt-br/6.1/topics/security/","markdown":"/pt-br/6.1/topics/security.md","json":"/pt-br/6.1/topics/security.json"},"source":"https://github.com/django/django/blob/stable/6.1.x/docs/topics/security.txt","official":"https://docs.djangoproject.com/pt-br/6.1/topics/security/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}