LoginSignup
8
6

More than 5 years have passed since last update.

Content Security Policy (CSP)

Posted at

概要

CSPを使用する事でXSS攻撃の軽減、検出(レポーティング機能を利用する事で)が可能

CSPの使用方法

下記のいずれかの方法でCSPを有効化できる
- Content-Security-PolicyヘッダをHTTPレスポンスで返す
- metaタグ指定

レスポンスヘッダーでの指定

ポリシーを適用させる

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

ポリシーを適用はせず、違反を報告させる

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

metaタグでの指定

<meta http-equiv="Content-Security-Policy" content="<policy-directive>">

Policy directive

個々のdirectiveは下記を参照。
https://developer.mozilla.org/ja/docs/Web/HTTP/Headers/Content-Security-Policy

Policy directive 説明
Fetch directive リソースのタイプ毎にロードする制限をかけられる.default-srcは対応するリソースのポリシーが指定されてない場合に適用される.ソースの指定方法
Document directives baseの属性やプラグインの種類等を制限
Navigation directive formのポスト先やiframeのソース等の制限
Reporting directives ポリシー違反のレポート方法を指定

その他

block-all-mixed-content

  • HTTPS時のHTTPコンテンツの読み込みを防ぐ
  • 常時HTTPS化の際にレポーティング機能との組み合わせで問題のあるリンクを見つけるのに役に立つ

require-sri-for

  • scriptとstyleに対してsriを強制する

upgrade-insecure-requests

  • HTTPのアクセスをHTTPSに強制する

使用例

自ドメインのリソースのみ読み込みを許可する

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

自ドメインと指定したドメインのみの読み込みを許可する

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

ReadOnlyを利用したレポートティングの例

指定したレスポンスヘッダ

Content-Security-Policy-Report-Only: default-src 'self'; report-uri http://localhost:8080/report

画像ポリシーに違反した場合のレポート

{
    "csp-report": {
        "document-uri": "http://localhost:8080/img.html",
        "referrer": "",
        "violated-directive": "img-src",
        "effective-directive": "img-src",
        "original-policy": "default-src 'self'; report-uri http://localhost:8080/report",
        "disposition": "report",
        "blocked-uri": "http://placehold.it/350x150",
        "status-code": 200
    }
}

スクリプトポリシーに違反した場合のレポート

{
    "csp-report": {
        "document-uri": "http://localhost:8080/script.html",
        "referrer": "http://localhost:8080/",
        "violated-directive": "script-src",
        "effective-directive": "script-src",
        "original-policy": "default-src 'self'; report-uri http://localhost:8080/report",
        "disposition": "report",
        "blocked-uri": "https://code.jquery.com/jquery-3.2.1.min.js",
        "status-code": 200
    }
}

参考サイト

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6