Content Security Policy (CSP)란 무엇이며 XSS를 방어하는 방법은?
CSP Level 3 마스터 가이드: 지시문 문법, 엄격한 논스(nonce) 적용, 해시 검증 및 제로 트러스트 보안 헤더 구성.
Web Protocols & Security Architecture Research
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
DirectivesThe fundamental fallback directive governing all unspecified resource types (scripts, images, fonts, styles).
Cryptographic Nonces
NoncesSingle-use random tokens generated per-request and passed in both the CSP header and `<script nonce="...">` tags.
strict-dynamic
ModernCSPCSP Level 3 directive allowing a trusted script with a valid nonce to load subsequent child scripts without domain allowlists.
frame-ancestors
ClickjackingReplaces legacy `X-Frame-Options` by declaring which parent origins are allowed to embed the page in iframes.
report-to / report-uri
TelemetrySpecifies 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.
Server Generates Nonce
For every incoming HTTP request, backend generates a high-entropy random base64 string.
const nonce = crypto.randomBytes(16).toString("base64");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';HTML Template Rendering
Server attaches the identical nonce attribute to authorized script tags in HTML markup.
<script nonce="${nonce}" src="/app.js"></script>Browser Evaluation
Browser compares script tag nonce against header value; matches proceed, mismatches trigger violations.
Match: Execute script. Mismatch or Missing: Drop & Log Violation.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)
httpContent-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
javascriptimport 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를 방어하는 방법은?을 사용하는 이유와 구성
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.
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를 방어하는 방법은? 구현 시 자주 발생하는 실수와 오해
영향도: 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.
영향도: 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.
영향도: 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()`.
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.
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
발생 증상 및 오류 징후: 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'`
Content Security Policy (CSP)란 무엇이며 XSS를 방어하는 방법은?에 대한 자주 묻는 질문
Q:What is the difference between CSP Nonce and CSP Hash?
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?
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.
추천 관련 개발자 도구
100% 브라우저 메모리 실행
용어사전
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]W3CPrimary SpecificationW3C CSP Level 3 • Section 2 & 3Verified Primary SourceTechnical 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.”Source URI: https://www.w3.org/TR/CSP3/ - [2]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Strict CSP & XSS MitigationVerified Primary SourceTechnical Claim Supported:
Authoritative security guide for strict CSP deployment using per-request cryptographic nonces and strict-dynamic to neutralize Reflected and Stored XSS.
- [3]MDNDeveloper Authority (MDN)MDN Web Docs • CSP Directives ReferenceVerified Primary SourceTechnical Claim Supported:
Reference documentation for browser implementation of CSP directives including script-src, frame-ancestors, object-src, and report-to.
관련 기술 생태계 및 다음 학습 단계
추천 관련 개발자 도구
관련 기술 아티클
관련 기술 질문
개발자 표준 규격 및 레퍼런스
다음 학습 단계
Content Security Policy (CSP) Hands-On Lab
Step into the interactive lab to defend a vulnerable DOM application with strict CSP nonces.