100% ブラウザ内完結計算 • サーバーログ完全ゼロ • 即時実行
Curious Techie開発者ツールボックス
CSP10分で読める•日本語 Edition100% クライアントサイド実行

Content Security Policy (CSP) の仕組みとXSS完全防御手法

CSP Level 3のディレクティブ構文、暗号学的ナンス(nonce)による厳格な保護、ハッシュ検証、ゼロトラストHTTPヘッダーの設計。

CT
Curious-Techie Engineering Team認証著者

Web Protocols & Security Architecture Research

公開日:
•
更新日:
•10分で読める
査読者: Curious-Techie Architecture Peer Review Group
主要な疑問 • 即時アーキテクチャ回答

Content Security Policy (CSP) の仕組みとXSS完全防御手法

TL;DR — 設計・エンジニアリングの要点

  • CSPは、ブラウザが読み込み・実行可能なスクリプトやリソースの配信元を制限するHTTPレスポンスヘッダーです。
  • クロスサイトスクリプティング(XSS)および悪意あるデータインジェクションに対する最強の防御策です。
  • 最新のCSP Level 3では、ドメインホワイトリストではなく暗号学的ナンス (nonce) やハッシュ値による厳格な制限を推奨します。
  • frame-ancestors 'none' は、従来の X-Frame-Options を置き換えてクリックジャッキングを防ぎます。
  • 本番適用前の検証には Content-Security-Policy-Report-Only ヘッダーを活用します。
// 基本概念

中核概念とアーキテクチャ構造

default-src

Directives

The fundamental fallback directive governing all unspecified resource types (scripts, images, fonts, styles).

Cryptographic Nonces

Nonces

Single-use random tokens generated per-request and passed in both the CSP header and `<script nonce="...">` tags.

strict-dynamic

ModernCSP

CSP Level 3 directive allowing a trusted script with a valid nonce to load subsequent child scripts without domain allowlists.

frame-ancestors

Clickjacking

Replaces legacy `X-Frame-Options` by declaring which parent origins are allowed to embed the page in iframes.

report-to / report-uri

Telemetry

Specifies an endpoint where the browser dispatches JSON violation reports whenever a policy breach is detected.

処理プロセス • 実行シーケンス

Content Security Policy (CSP) の仕組みとXSS完全防御手法の動作原理と仕組み

直接の回答:

When the browser receives an HTTP response containing a `Content-Security-Policy` header, its security manager parses the directive list into a memory policy tree. As the HTML parser encounters external resources or inline scripts, it queries the policy engine. If an inline script lacks a matching cryptographic nonce or SHA-256 hash, or if an image originates from an unlisted host, the browser blocks execution immediately and posts a JSON violation report.

1

Server Generates Nonce

For every incoming HTTP request, backend generates a high-entropy random base64 string.

const nonce = crypto.randomBytes(16).toString("base64");
2

Header Injection

Server sends CSP header binding the nonce to script-src and setting default restrictions.

Content-Security-Policy: default-src 'self'; script-src 'nonce-${nonce}' 'strict-dynamic';
3

HTML Template Rendering

Server attaches the identical nonce attribute to authorized script tags in HTML markup.

<script nonce="${nonce}" src="/app.js"></script>
4

Browser Evaluation

Browser compares script tag nonce against header value; matches proceed, mismatches trigger violations.

Match: Execute script. Mismatch or Missing: Drop & Log Violation.
5

Violation Reporting

Browser transmits structured JSON report to configured report-to endpoint for observability.

POST /csp-reports {"csp-report": {"blocked-uri": "eval", "violated-directive": "script-src"}}
実装コード例 • ベストプラクティス

Content Security Policy (CSP) の仕組みとXSS完全防御手法の実務における実装方法

Google-Recommended Strict Nonce-Based CSP (Level 3)

http
Content-Security-Policy: 
  default-src 'self'; 
  script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa' 'strict-dynamic' https: 'unsafe-inline'; 
  style-src 'self' 'unsafe-inline'; 
  object-src 'none'; 
  base-uri 'self'; 
  frame-ancestors 'none';

エンジニアリング詳細: The modern gold standard: `'strict-dynamic'` trusts scripts loaded by nonced scripts; `'unsafe-inline'` is ignored by modern browsers when a nonce is present, providing backwards compatibility for legacy browsers.

Express.js Implementation using Helmet Middleware

javascript
import express from "express";
import helmet from "helmet";
import crypto from "crypto";

const app = express();

// Generate cryptographic nonce per-request
app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString("base64");
  next();
});

app.use((req, res, next) => {
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`, "'strict-dynamic'"],
      objectSrc: ["'none'"],
      baseUri: ["'self'"],
      upgradeInsecureRequests: [],
    },
  })(req, res, next);
});

エンジニアリング詳細: Generates a unique 128-bit cryptographic nonce on every request and injects it into both Helmet CSP and template response locals.

本番環境アーキテクチャ • 実用ケース

本番環境でのContent Security Policy (CSP) の仕組みとXSS完全防御手法の適用理由と構成

Healthcare & Patient Portals (HIPAA Compliance)

Preventing malicious third-party tag managers or browser extensions from exfiltrating medical records.

Locking down `connect-src` and `form-action` strictly to internal API domains so stolen data cannot be transmitted to external servers.

High-Volume E-Commerce Platforms (Magecart Defense)

Stopping e-skimming attacks where compromised third-party scripts steal checkout credit card details.

Using strict CSP `script-src` and `connect-src` restrictions to block unauthorized external script injection at checkout steps.

アンチパターンと回避策

Content Security Policy (CSP) の仕組みとXSS完全防御手法でよくある設計上の過ちと誤解

アンチパターン: Using `unsafe-inline` in `script-src` without a nonce or hash

影響: Allows any injected `<script>evil()</script>` payload to run, rendering CSP almost entirely ineffective against XSS.

推奨される修正策: Migrate inline JavaScript to external files or supply cryptographic nonces on all script tags.

アンチパターン: Omitting `object-src 'none'` from your policy

影響: Enables attackers to inject malicious Flash, Java, or PDF plugin objects that bypass script execution filters.

推奨される修正策: Always include `object-src 'none';` explicitly in every CSP policy.

アンチパターン: Deploying a strict blocking CSP directly to production without testing in Report-Only mode

影響: Inadvertently breaks legitimate analytics, payment gateways, or customer widgets, causing severe site outages.

推奨される修正策: Deploy first using `Content-Security-Policy-Report-Only` for 1-2 weeks; analyze violation logs before enforcing.

脅威モデル分析 • 攻撃ベクトル

Content Security Policy (CSP) の仕組みとXSS完全防御手法のセキュリティ上のリスクと脆弱性

DOM-Based Cross-Site Scripting (DOM XSS)

OWASP Top 10 Injection / CWE-79

脆弱性: Application passes untrusted input into execution sinks like `eval()`, `setTimeout(string)`, or `new Function()`.

防御・緩和策: Omit `'unsafe-eval'` from CSP; combine with `require-trusted-types-for 'script'` to enforce safe type-checked DOM sinks.

Base Tag Hijacking (Base-URI Manipulation)

CWE-444 Inconsistent Interpretation

脆弱性: Attacker injects `<base href="https://attacker.com">`, forcing all relative script URLs to load from the attacker’s domain.

防御・緩和策: Always specify `base-uri 'self'` or `base-uri 'none'`.
診断ワークフロー • 根本原因解決

Content Security Policy (CSP) の仕組みとXSS完全防御手法のエラー診断とトラブルシューティング

発生症状とエラーの兆候: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'"

根本原因の技術的分析:
  • Inline script tags (`<script>...</script>`) present in HTML without nonce or hash
  • HTML event handlers (`onclick="..."`) used in markup
本番環境検証済み修正手順: Refactor inline event handlers to `addEventListener`; attach `nonce="..."` matching the CSP header to the script tag.

発生症状とエラーの兆候: Refused to connect to "https://analytics.vendor.com" because it violates directive: "default-src 'self'"

根本原因の技術的分析:
  • `connect-src` is missing from CSP and fell back to `default-src 'self'`
本番環境検証済み修正手順: Add `connect-src 'self' https://analytics.vendor.com` to the CSP header.
技術ナレッジベース • 即時回答

Content Security Policy (CSP) の仕組みとXSS完全防御手法に関するよくある質問

Q:What is the difference between CSP Nonce and CSP Hash?

直接の回答:A nonce is a dynamic random token generated per request and placed on `<script nonce="...">`. A hash is a static SHA-256 digest of the script’s exact textual content, ideal for static sites where the HTML cannot be dynamically generated per request.

Nonces require a dynamic backend server (Node, Go, Python) to generate fresh random values on each page load. Static sites (JAMstack, Astro static builds) use SHA-256 hashes (`'sha256-xyz'`) calculated from the script contents.

Q:Does Content Security Policy completely eliminate XSS?

直接の回答:No single tool completely eliminates all vulnerabilities, but a strict CSP drastically limits the blast radius of XSS by preventing injected code execution and blocking unauthorized network exfiltration.

CSP cannot prevent logic flaws or server-side template injection before HTML generation, but it stops the attacker’s payload from executing in the browser or contacting outside command-and-control servers.

セクション 12 • 対話型ユーティリティ

おすすめの関連開発者ツール

100% クライアントサイド実行

Companion Interactive Tool100% Client-Side Execution

Test & Verify with CSP (Content Security Policy) Generator

Build secure Content-Security-Policy headers visually with nonce and hash.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with Security Headers Checker

Audit HSTS, CSP, X-Frame-Options, and OWASP recommended web headers.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with SRI (Subresource Integrity) Hash Generator

Generate sha384 and sha256 integrity hashes for CDN scripts and styles.

用語集

CSP
Content Security Policy: HTTP header defining approved resource origins for the browser.
Nonce
Number used once: A cryptographically random token ensuring script legitimacy.
Directive
A specific CSP policy rule targeting a resource category (e.g. script-src, img-src).
Authoritative Sourcing & Verification

References & Primary Sources

Every source below directly substantiates technical statements and protocol behaviors explained in Content Security Policy (CSP) の仕組みとXSS完全防御手法. Curious-Techie prioritizes official Internet standards (IETF RFCs, W3C Recommendations, WHATWG specifications) and established security bodies (OWASP, NIST). Zero sponsored or secondary links.

  1. [1]W3CPrimary SpecificationW3C CSP Level 3 • Section 2 & 3
    Verified Primary Source
    Technical Claim Supported:

    Normative specification for Content-Security-Policy HTTP headers, directive fallback inheritance from default-src, and cryptographic nonce/hash-based script execution.

    “A server can specify a policy for a resource that the user agent will enforce, restricting the execution of scripts, stylesheets, and embedded frames.”
  2. [2]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Strict CSP & XSS Mitigation
    Verified Primary Source
    Technical Claim Supported:

    Authoritative security guide for strict CSP deployment using per-request cryptographic nonces and strict-dynamic to neutralize Reflected and Stored XSS.

  3. [3]MDNDeveloper Authority (MDN)MDN Web Docs • CSP Directives Reference
    Verified Primary Source
    Technical Claim Supported:

    Reference documentation for browser implementation of CSP directives including script-src, frame-ancestors, object-src, and report-to.