{"title":"Django におけるセキュリティ","version":"6.0","locale":"ja","docname":"topics/security","url":"/ja/6.0/topics/security/","canonical":"https://djangodocs.dev/ja/6.0/topics/security/","summary":"このドキュメントは、Django のセキュリティ機能の概要です。Django を利用したサイトを安全なものにするためのヒントを説明します。","html":"<h1>Django におけるセキュリティ<a class=\"heading-anchor\" href=\"#security-in-django\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>このドキュメントは、Django のセキュリティ機能の概要です。Django を利用したサイトを安全なものにするためのヒントを説明します。</p>\n<section id=\"always-sanitize-user-input\">\n<span id=\"sanitize-user-input\"></span><h2>ユーザーの入力は常にサニタイズしてください<a class=\"heading-anchor\" href=\"#always-sanitize-user-input\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Web アプリケーションのセキュリティにおける黄金律は、「ユーザーが制御できるデータを決して信用しないこと」です。そのため、アプリケーション内で使用する前に、すべてのユーザー入力は必ずサニタイズ（無害化）する必要があります。Django におけるユーザー入力の検証については、 <a class=\"reference internal\" href=\"/ja/6.0/topics/forms/\"><span class=\"doc\">フォームに関するドキュメント</span></a> を参照してください。</p>\n</section>\n<section id=\"cross-site-scripting-xss-protection\">\n<span id=\"cross-site-scripting\"></span><h2>クロス・サイト・スクリプティング (XSS) の防御<a class=\"heading-anchor\" href=\"#cross-site-scripting-xss-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>XSS 攻撃はあるユーザーに対してクライアント用のスクリプトを別のユーザーのブラウザに読み込ませることを可能にしてしまいます。この攻撃は通常他のユーザーに対して選択・表示を行うデータベース内に悪意のあるスクリプトを保存させる、あるいは攻撃者の JavaScript がブラウザで実行されるリンクをユーザーにクリックさせることでなされます。しかしながら、XSS 攻撃はページを読み込む前に十分なサニタイズを行っていなければ、信頼できないクッキーやウェブ・サービスのようなデータが発生の原因となることがあります。</p>\n<p>Django のテンプレートを用いる事で多数の XSS 攻撃に対抗できます。しかしながら、それがどのような防御策が用意でき、またその利用に際する制限について知ることが重要になります。</p>\n<p>Django は HTML に対して特に危険とみなされる <a class=\"reference internal\" href=\"/ja/6.0/ref/templates/language/#automatic-html-escaping\"><span class=\"std std-ref\">特定の文字列のエスケープ</span></a> を行います。この防御によってユーザーは大半の悪意のある入力から守られますが、いつも簡単で容易に利用できる訳ではありません。たとえば、次に示す例では防御がなされません。</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>もし <code class=\"docutils literal notranslate\">var</code> の値が <code class=\"docutils literal notranslate\">'class1 onmouseover=javascript:func()'</code> にセットされた場合、不完全な HTML をそのブラウザがどのようにレンダリングするかによっては、許可されていない Javascript を実行させる事になります。(このケースであれば属性値のクオートを行えば対処できます)</p>\n<p>カスタム・テンプレート・タグと共に <code class=\"docutils literal notranslate\">is_safe</code> を用いたり、 <a class=\"reference internal\" href=\"/ja/6.0/ref/templates/builtins/#std-templatefilter-safe\"><code class=\"xref std std-tfilter docutils literal notranslate\">safe</code></a> テンプレートタグや、 <a class=\"reference internal\" href=\"/ja/6.0/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\">mark_safe</code></a> の利用に加えてオートエスケープが無効化されている場合十分な注意を払う必要があります。</p>\n<p>ここまでの内容に加えて、HTML 以外を出力するのにテンプレートシステムを利用している場合、完全に別のエスケープすべき文字や単語が存在するかもしれません。</p>\n<p>HTML をデータベース内に収集、特にその HTML が選択・表示される場合は十分な注意を払う必要があります。</p>\n</section>\n<section id=\"cross-site-request-forgery-csrf-protection\">\n<h2>クロス・サイト・リクエスト・フォージェリ(CSRF)の防御<a class=\"heading-anchor\" href=\"#cross-site-request-forgery-csrf-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>CSRF 攻撃は悪意ある利用者が、あるユーザーが自身で持っている情報や承認を用いずに、そのユーザーの認証情報での処理を発生させてしまう攻撃です。</p>\n<p>Django は大半の CSRF 攻撃に対応したビルトインの防御機構を備え、適切な所で <a class=\"reference internal\" href=\"/ja/6.0/howto/csrf/#using-csrf\"><span class=\"std std-ref\">有効化して利用できます</span></a> 。しかしながら、いかなる緩和策にも制限が存在します。たとえば、CSRF モジュールをグローバルにあるいは特定のビューだけ無効化できます。これは自身が何をしているのか理解している場合のみ行うべきです。もしあなたのサイト内に管理対象外のサブドメインが存在すればそこにも <a class=\"reference internal\" href=\"/ja/6.0/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">制限</span></a> が存在します。</p>\n<p><a class=\"reference internal\" href=\"/ja/6.0/ref/csrf/#how-csrf-works\"><span class=\"std std-ref\">CSRF 対策</span></a> は各 POST リクエスト内の秘密情報を確認することで機能します。悪意あるユーザーは、フォームの POST を別のログイン中のユーザーが気づかない間に「リプレイ」して、フォームを送信させようとします。これを実行するには秘密情報を知っている必要がありますが、秘密情報は（クッキーを用いて）ユーザーごとに固有なので、簡単に取得することはできません。これにより、フォームの POST の「リプレイ」を防ぐことができます。</p>\n<p><a class=\"reference internal\" href=\"#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a> でデプロイした場合、<code class=\"docutils literal notranslate\">CsrfViewMiddleware</code> は HTTP referer ヘッダが (サブドメインとポートを含め) 同一オリジンの URL にセットされているかをチェックします。HTTPS では強化されたセキュリティを利用できるため、可能な限り安全でないコネクションのリクエストを転送したり、サポートされたブラウザでは HSTS を使用するなどして HTTPS コネクションを使用することが不可欠です。</p>\n<p>どうしても必要という場合を除いて、 <code class=\"docutils literal notranslate\">csrf_exempt</code> デコレータでビューをマークする際には十分注意してください。</p>\n</section>\n<section id=\"sql-injection-protection\">\n<span id=\"id1\"></span><h2>SQL injectionへの防御<a class=\"heading-anchor\" href=\"#sql-injection-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>SQL injectionは、悪意ある攻撃者がデータベース任意のSQLコードを実行する攻撃です。これによって、レコードが削除されたり、情報が漏洩する可能性があります。</p>\n<p>Djangoのクエリセットは、クエリのパラメータ化によってクエリを構成するため、SQL injectionから守られています。クエリのSQLコードはそのクエリのパラメータとは独立に定義されています。パラメータはユーザが指定するものも有り、安全ではないので、低レイヤのデータベースドライバーによってエスケープされます。</p>\n<p>Djangoは開発者に、<a class=\"reference internal\" href=\"/ja/6.0/topics/db/sql/#executing-raw-queries\"><span class=\"std std-ref\">素のクエリを実行する</span></a> または <a class=\"reference internal\" href=\"/ja/6.0/topics/db/sql/#executing-custom-sql\"><span class=\"std std-ref\">カスタムSQLを実行する</span></a> 力も与えています。これらの機能は慎重に使用すべきであり、ユーザーが制御できるパラメータを適切にエスケープすることを常に注意すべきです。さらに、<a class=\"reference internal\" href=\"/ja/6.0/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\">extra()</code></a> や <a class=\"reference internal\" href=\"/ja/6.0/ref/models/expressions/#django.db.models.expressions.RawSQL\" title=\"django.db.models.expressions.RawSQL\"><code class=\"xref py py-class docutils literal notranslate\">RawSQL</code></a> を使用する際には注意が必要です。</p>\n</section>\n<section id=\"clickjacking-protection\">\n<h2>クリックジャッキング (Clickjacking) に対する防御<a class=\"heading-anchor\" href=\"#clickjacking-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>クリックジャッキング (Clickjacking) は、悪意のあるサイトが他のサイトをフレームの中に表示するタイプの攻撃です。攻撃の結果、疑いのないユーザーが騙されてターゲットのサイトに対して意図しない操作を行ってしまいます。</p>\n<p>Djangoは <a class=\"reference internal\" href=\"/ja/6.0/ref/clickjacking/#clickjacking-prevention\"><span class=\"std std-ref\">クリックジャッキング保護</span></a> の仕組みを <a class=\"reference internal\" href=\"/ja/6.0/ref/middleware/#django.middleware.clickjacking.XFrameOptionsMiddleware\" title=\"django.middleware.clickjacking.XFrameOptionsMiddleware\"><code class=\"xref py py-mod docutils literal notranslate\">X-Frame-Options ミドルウェア</code></a> で提供しています。サポートしているブラウザではサイトをフレーム内で描画しないようにします。この保護はビュー単位で無効化できます。あるいは、固定的にヘッダーの値を送信できます。</p>\n<p>サードパーティのサイト上でページをフレーム内に表示する必要がないか、もし合ったとしてもごく少数のセクションしかないようなあらゆるサイトは、このミドルウェアを使用することを強く推奨します。</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 to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>セキュリティの観点から、サイトを HTTPS の下でデプロイするのは常に良い選択です。HTTPS がなければ、悪意のあるネットワークユーザーが、クライアント・サーバー間で通信される認証情報やその他あらゆる情報を盗み見たり、場合によっては、<strong>積極的な</strong> ネットワーク攻撃者がどちらの方向でもデータ書き換えが可能になってしまいます。</p>\n<p>HTTPS による保護をサーバー上で有効にするためには、多少の追加作業が必要になります:</p>\n<ul>\n<li><p>必要な場合は、関連する注意点を完全に理解した上で、<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a> をセットしてください。この設定に失敗すると、CSRF の脆弱性の原因となり、大変な危険につながりかねません！</p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_REDIRECT</code></a> を <code class=\"docutils literal notranslate\">True</code> にセットして、HTTP によるリクエストが HTTPS にリダイレクトされるようにしてください。</p>\n<p><a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a> の注意点を確認してください。リバースプロキシの場合、メインのウェブサーバーを HTTPS にリダイレクトするよう設定した方が簡単で安全かもしれません。</p>\n</li>\n<li><p>'安全な' クッキーを使用してください。</p>\n<p>ブラウザが最初 HTTP で通信した場合 (これはブラウザのデフォルトの動作です)、既存のクッキーが誰でも見える状態になっている可能性があります。そのため、<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SESSION_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\">SESSION_COOKIE_SECURE</code></a> と <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_SECURE</code></a> を <code class=\"docutils literal notranslate\">True</code> にセットする必要があります。これにより、ブラウザは HTTPS コネクションによるクッキーを送信するようになります。これは、セッションが HTTP では動作せず、 CSRF 保護が HTTP によって受け入れられたあらゆる POST データを防止することを意味します (ただし、HTTP 通信を HTTPS にリダイレクトするよう設定しておけば問題ありません)。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"/ja/6.0/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP Strict Transport Security</span></a> (HSTS) を使用してください。</p>\n<p>HSTS は HTTP ヘッダで、特定のサイトに対する以降のコネクションが常に HTTPS を使うことをブラウザに伝えるものです。HTTP から HTTPS にリクエストをリダイレクトさせることと合わせて、コネクションが 1 つ成功したときに提供される SSL の安全性を担保します。 HSTS は、<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_SECONDS</code></a>、<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_INCLUDE_SUBDOMAINS</code></a>, と <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_PRELOAD</code></a>、もしくはウェブサーバ上のどれかで設定されます。</p>\n</li>\n</ul>\n</section>\n<section id=\"host-header-validation\">\n<span id=\"host-headers-virtual-hosting\"></span><h2>Host ヘッダーの検証<a class=\"heading-anchor\" href=\"#host-header-validation\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django はいくつかのケースで、URL を組み立てるためにクライアントから送られてきた <code class=\"docutils literal notranslate\">Host</code> ヘッダーを使用します。<code class=\"docutils literal notranslate\">Host</code> ヘッダーの値は、クロス サイト スクリプティング (XSS) 攻撃を回避するためにサニタイズされますが、それでもまだ偽の <code class=\"docutils literal notranslate\">Host</code> 値はクロス サイト リクエスト フォージェリ (CSRF) やキャッシュポイズニング攻撃、メールアドレス内のリンクへのポイズニング等に使用されます。</p>\n<p>Because even seemingly-secure web server configurations are susceptible to fake\n<code class=\"docutils literal notranslate\">Host</code> headers, Django validates <code class=\"docutils literal notranslate\">Host</code> headers against the\n<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a> setting in the\n<a class=\"reference internal\" href=\"/ja/6.0/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\">django.http.HttpRequest.get_host()</code></a> method.</p>\n<p>This validation only applies via <a class=\"reference internal\" href=\"/ja/6.0/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\">get_host()</code></a>;\nif your code accesses the <code class=\"docutils literal notranslate\">Host</code> header directly from <code class=\"docutils literal notranslate\">request.META</code> you\nare bypassing this security protection.</p>\n<p>より詳しい情報については、<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a> ドキュメントをご覧ください。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>以前のドキュメントでは、外部から渡される <code class=\"docutils literal notranslate\">Host</code> ヘッダーを検証して正しい値にするようにウェブサーバーを設定することを推奨していました。これはまだ推奨されますが、多くの一般的なウェブサーバーは <code class=\"docutils literal notranslate\">Host</code> ヘッダーを正しく検証するように設定できません。例えば、Apacheがそのように設定されたとしても、あなたのDjangoサイトが <code class=\"docutils literal notranslate\">ServerName</code> に設定された非デフォルトの仮想ホストを扱うようにApacheに設定された場合、その仮想ホスト名に一致するような偽の <code class=\"docutils literal notranslate\">Host</code> ヘッダーを与えたHTTPリクエストを作れます。したがって、ウェブサーバー設定にたよるだけでなく、Djangoの <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a> に明示的に設定する必要があります。</p>\n</aside>\n<p>さらに、Djangoでは <code class=\"docutils literal notranslate\">X-Forwarded-Host</code> ヘッダーのサポートを使いたければ ( <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-USE_X_FORWARDED_HOST\"><code class=\"xref std std-setting docutils literal notranslate\">USE_X_FORWARDED_HOST</code></a> 設定で)明示的に有効にする必要があります。</p>\n</section>\n<section id=\"referrer-policy\">\n<h2>リファラ ポリシー<a class=\"heading-anchor\" href=\"#referrer-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>ブラウザは <code class=\"docutils literal notranslate\">Referer</code> ヘッダーを、ユーザーがどのようにしてそのサイトにたどり着いたかについての情報をサイトに送信する手段として使用します。 <em>Referrer Policy</em> を設定することで、どのような状況で <code class=\"docutils literal notranslate\">Referer</code> ヘッダが設定されるかを制限し、ユーザーのプライバシーを守ることができます。詳しくは <a class=\"reference internal\" href=\"/ja/6.0/ref/middleware/#referrer-policy\"><span class=\"std std-ref\">セキュリティミドルウェアのリファレンス</span></a> のリファラポリシーのセクションを参照してください。</p>\n</section>\n<section id=\"cross-origin-opener-policy\">\n<h2>クロスオリジン・オープナー・ポリシー<a class=\"heading-anchor\" href=\"#cross-origin-opener-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>クロスオリジンオープナーポリシー（COOP）ヘッダーは、ブラウザがトップレベルウィンドウを他のドキュメントから隔離し、異なるコンテキストグループに配置することを可能にします。これにより、それらがトップレベルウィンドウと直接的にやり取りすることができなくなります。COOPで保護されたドキュメントがクロスオリジンのポップアップウィンドウを開いた場合、ポップアップの <code class=\"docutils literal notranslate\">window.opener</code> プロパティは <code class=\"docutils literal notranslate\">null</code> になります。COOPはクロスオリジン攻撃から保護します。詳細については、 <a class=\"reference internal\" href=\"/ja/6.0/ref/middleware/#cross-origin-opener-policy\"><span class=\"std std-ref\">セキュリティミドルウェアリファレンスのクロスオリジンオープナーポリシーのセクション</span></a> を参照してください。</p>\n</section>\n<section id=\"session-security\">\n<h2>セッションのセキュリティ<a class=\"heading-anchor\" href=\"#session-security\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p><a class=\"reference internal\" href=\"/ja/6.0/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">CSRF limitation</span></a> が、信頼できないユーザがサブドメインにアクセスできないようにサイトを配置することを要求しているのと同様に、 <a class=\"reference internal\" href=\"/ja/6.0/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\">django.contrib.sessions</code></a> にも制限があります。詳細は <a class=\"reference internal\" href=\"/ja/6.0/topics/http/sessions/#topics-session-security\"><span class=\"std std-ref\">セッション・トピックガイドのセキュリティに関するセクション</span></a> を参照してください。</p>\n</section>\n<section id=\"user-uploaded-content\">\n<span id=\"user-uploaded-content-security\"></span><h2>ユーザーがアップロードしたコンテンツ<a class=\"heading-anchor\" href=\"#user-uploaded-content\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>以下に説明する問題を回避するには <a class=\"reference internal\" href=\"/ja/6.0/howto/static-files/deployment/#staticfiles-from-cdn\"><span class=\"std std-ref\">クラウドサービスやCDNから静的ファイルを配信する</span></a> ことを検討してください。</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=\"/ja/6.0/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">DATA_UPLOAD_MAX_MEMORY_SIZE</code></a>\nnor <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-FILE_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">FILE_UPLOAD_MAX_MEMORY_SIZE</code></a>.</p></li>\n<li><p>独自の静的ファイルを提供している場合は、Apache の <code class=\"docutils literal notranslate\">mod_php</code> のような、静的ファイルをコードとして実行するハンドラが無効になっていることを確認してください。特別に細工されたファイルをアップロードしてリクエストすることで、ユーザが任意のコードを実行できるようになるのは望ましくありません。</p></li>\n<li><p>Django のメディアアップロード処理には、セキュリティのベストプラクティスに従わない方法でメディアが提供された場合、いくつかの脆弱性があります。具体的には、有効な PNG ヘッダの後に悪意のある HTML が続く場合、HTML ファイルを画像としてアップロードできます。このファイルは、 Django が <a class=\"reference internal\" href=\"/ja/6.0/ref/models/fields/#django.db.models.ImageField\" title=\"django.db.models.ImageField\"><code class=\"xref py py-class docutils literal notranslate\">ImageField</code></a> の画像処理 (Pillow) に使っているライブラリの検証を通過します。このファイルがユーザに表示されるとき、 Web サーバの種類や設定によっては HTML として表示されるかもしれません。</p>\n<p>フレームワークレベルですべてのユーザーがアップロードしたファイルの内容を安全に検証するための完璧な技術的な解決策はありません。ただし、これらの攻撃を緩和できるいくつかの手順があります:</p>\n<ol class=\"arabic simple\">\n<li><p>ある種の攻撃は、ユーザがアップロードしたコンテンツを常に異なるトップレベルまたはセカンドレベルドメインから提供することで防ぐことができます。これにより、クロスサイトスクリプティングのような <a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Same-origin_policy\">same-origin policy</a> の保護によってブロックされる攻撃を防ぐことができます。例えば、あなたのサイトが <code class=\"docutils literal notranslate\">example.com</code> で運営されている場合、アップロードされたコンテンツ（<a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-MEDIA_URL\"><code class=\"xref std std-setting docutils literal notranslate\">MEDIA_URL</code></a> 設定）は <code class=\"docutils literal notranslate\">usercontent-example.com</code> のようなドメインから提供されることが望ましいです。 <code class=\"docutils literal notranslate\">usercontent.example.com</code> のようなサブドメインからコンテンツを提供するだけでは十分ではありません。</p></li>\n<li><p>さらに、アプリケーションは、ユーザーがアップロードしたファイルに対して許可されるファイル拡張子のリストを定義し、そのようなファイルのみを提供するように Web サーバーを設定することもできます。</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 to this heading</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=\"/ja/6.0/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">DATA_UPLOAD_MAX_MEMORY_SIZE</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 to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"version-note version-added\" data-version=\"6.0\" role=\"note\">\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=\"/ja/6.0/howto/csp/#csp-config\"><span class=\"std std-ref\">Using CSP</span></a>\ndocumentation, and refer to the <a class=\"reference internal\" href=\"/ja/6.0/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 to this heading</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>その他のセキュリティトピック<a class=\"heading-anchor\" href=\"#additional-security-topics\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django は、「箱から出してすぐに」優れたセキュリティ保護を提供しますが、アプリケーションを適切にデプロイし、Web サーバやオペレーティングシステム、その他のコンポーネントのセキュリティ保護を利用することが重要です。</p>\n<ul class=\"simple\">\n<li><p>PythonコードがWebサーバのルートの外にあることを確認してください。こうすることで、Pythonコードが誤ってプレーンテキストとして提供されない（あるいは誤って実行されない）ようになります。</p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/6.0/ref/models/fields/#file-upload-security\"><span class=\"std std-ref\">ユーザがアップロードしたファイル</span></a> には注意してください。</p></li>\n<li><p>Djangoはユーザーを認証するためのリクエストの制限を行いません。認証システムへの総当たり攻撃から保護するためには、これらのリクエストを制限するためのDjangoプラグインやWebサーバーモジュールを導入することを検討してください。</p></li>\n<li><p>あなたの <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECRET_KEY\"><code class=\"xref std std-setting docutils literal notranslate\">SECRET_KEY</code></a> と <a class=\"reference internal\" href=\"/ja/6.0/ref/settings/#std-setting-SECRET_KEY_FALLBACKS\"><code class=\"xref std std-setting docutils literal notranslate\">SECRET_KEY_FALLBACKS</code></a> を秘密にしておいてください。</p></li>\n<li><p>ファイアウォールを使用して、キャッシュシステムとデータベースへのアクセスを制限することをお勧めします。</p></li>\n<li><p>Open Web Application Security Project (OWASP) の <a class=\"reference external\" href=\"https://owasp.org/Top10/\">Top 10 list</a> を見てください。OWASP は、Web アプリケーションによくある脆弱性をいくつか挙げています。Django には、いくつかの問題に対処するためのツールがありますが、それ以外はプロジェクトの設計で考慮する必要があります。</p></li>\n<li><p>Mozilla は <a class=\"reference external\" href=\"https://infosec.mozilla.org/guidelines/web_security.html\">web security</a> に関する様々なトピックについて議論しています。彼らのページには、どのようなシステムにも適用できるセキュリティの原則も含まれています。</p></li>\n</ul>\n</section>","rootId":"security-in-django","toc":[{"title":"ユーザーの入力は常にサニタイズしてください","anchor":"always-sanitize-user-input","children":[]},{"title":"クロス・サイト・スクリプティング (XSS) の防御","anchor":"cross-site-scripting-xss-protection","children":[]},{"title":"クロス・サイト・リクエスト・フォージェリ(CSRF)の防御","anchor":"cross-site-request-forgery-csrf-protection","children":[]},{"title":"SQL injectionへの防御","anchor":"sql-injection-protection","children":[]},{"title":"クリックジャッキング (Clickjacking) に対する防御","anchor":"clickjacking-protection","children":[]},{"title":"SSL/HTTPS","anchor":"ssl-https","children":[]},{"title":"Host ヘッダーの検証","anchor":"host-header-validation","children":[]},{"title":"リファラ ポリシー","anchor":"referrer-policy","children":[]},{"title":"クロスオリジン・オープナー・ポリシー","anchor":"cross-origin-opener-policy","children":[]},{"title":"セッションのセキュリティ","anchor":"session-security","children":[]},{"title":"ユーザーがアップロードしたコンテンツ","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":"その他のセキュリティトピック","anchor":"additional-security-topics","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/6.0/topics/"}],"prev":{"docname":"topics/pagination","title":"ページ分割 (Pagination)","url":"/ja/6.0/topics/pagination/"},"next":{"docname":"topics/performance","title":"パフォーマンスと最適化","url":"/ja/6.0/topics/performance/"},"formats":{"html":"/ja/6.0/topics/security/","markdown":"/ja/6.0/topics/security.md","json":"/ja/6.0/topics/security.json"},"source":"https://github.com/django/django/blob/stable/6.0.x/docs/topics/security.txt","official":"https://docs.djangoproject.com/ja/6.0/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"]}