CSP レポート

Content Security Policy 違反をブラウザがサーバーに自動報告し、XSS やデータ漏洩を検知する仕組み

セキュリティ

CSP レポートとは

CSP レポートは、Content Security Policy (CSP) に違反するリソースの読み込みやスクリプトの実行をブラウザが検知し、指定したエンドポイントに自動報告する仕組みである。XSS 攻撃の試行、意図しない外部リソースの読み込み、サードパーティスクリプトの不正な動作を検知できる。

基本的な設定

Content-Security-Policy: default-src 'self'; script-src 'self'; report-uri /csp-report

ブラウザが CSP 違反を検知すると、以下の JSON を /csp-report に POST する。

{
  "csp-report": {
    "document-uri": "https://example.com/page",
    "violated-directive": "script-src 'self'",
    "blocked-uri": "https://evil.com/malicious.js",
    "original-policy": "default-src 'self'; script-src 'self'",
    "disposition": "enforce"
  }
}

Report-Only モード

CSP を本番に導入する際、いきなり enforce (ブロック) すると、正当なリソースまでブロックしてサイトが壊れるリスクがある。Content-Security-Policy-Report-Only ヘッダーを使えば、違反を報告するだけでブロックしない。

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; report-uri /csp-report
  1. Report-Only で CSP を設定し、違反レポートを収集
  2. レポートを分析し、正当なリソースを CSP に追加
  3. 違反が十分に減ったら、enforce モードに切り替え

Reporting API v2

report-uri は非推奨になりつつあり、新しい Reporting API (report-to) への移行が進んでいる。

Content-Security-Policy: default-src 'self'; report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://example.com/csp-report"

レポートの分析ポイント

フィールド 確認すべきこと
blocked-uri 不正な外部ドメインか、正当なリソースか
violated-directive どの CSP ディレクティブに違反したか
document-uri どのページで発生したか
disposition enforce (ブロック済み) か report (報告のみ) か

大量のレポートが発生する場合、blocked-uri でグルーピングし、頻度の高い違反から対処する。

CSP レポートの背景や設計思想は関連書籍に詳しい。

関連用語