バックエンド向けContent Security Policy(CSP)
バックエンドの設定がContent Security Policy(CSP)に与える影響と、XSSなどのクライアントサイド攻撃を軽減する方法を理解します。
「バックエンド向けContent Security Policy(CSP)」はCoddyKit上の無料Secure Coding & OWASP Top 10 for Backendレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSecure Coding & OWASP Top 10 for Backend学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Secure Coding & OWASP Top 10 for Backendコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Backend's Role in CSP
Welcome to Content Security Policy (CSP) for Backend! You might think CSP is just for frontend developers, but the backend plays a crucial role.
CSP is a security standard that helps prevent client-side attacks like Cross-Site Scripting (XSS). It does this by telling the browser which resources (scripts, styles, images) it's allowed to load and execute.
The backend is responsible for delivering these rules to the browser.
How Backend Delivers CSP
The backend delivers CSP rules to the browser using a special HTTP response header called Content-Security-Policy. When the browser receives this header, it enforces the rules defined within it.
This means your backend application directly controls the security policy for your frontend. Let's see how a backend might set this header.
Setting the CSP Header
In a backend application, you'd typically add the CSP header to your HTTP response. This example simulates a backend sending a basic CSP header.
The default-src 'self' directive allows resources only from the same origin as the document.
public class BackendCspExample {
public static void main(String[] args) {
System.out.println("HTTP/1.1 200 OK");
System.out.println("Content-Type: text/html");
System.out.println("Content-Security-Policy: default-src 'self';");
System.out.println("");
System.out.println("<!-- Your secure HTML content goes here -->");
}
}Key CSP Directives for Backend
As a backend developer, you'll often define directives that control various resource types. Some common ones include:
script-src: Specifies valid sources for JavaScript.style-src: Specifies valid sources for stylesheets.img-src: Specifies valid sources for images.connect-src: Restricts URLs that can be loaded using scripting interfaces (e.g., AJAX, WebSockets).
Each directive can have multiple allowed sources, like 'self', https://example.com, or 'unsafe-inline' (generally to be avoided).
Mitigating Inline Scripts with Nonces
One common XSS attack vector is injecting inline scripts. CSP can block these, but sometimes inline scripts are necessary.
The backend can generate a unique, cryptographically secure nonce (Number Used Once) for each request. This nonce is added to both the CSP header and the allowed inline <script> tags.
Backend Nonce Generation
Here's how a backend can generate a nonce. This nonce is then included in the Content-Security-Policy header (e.g., script-src 'nonce-YOUR_NONCE_HERE') and rendered into the HTML script tag.
The browser will only execute inline scripts that have a matching nonce attribute.
import java.util.Base64;
import java.security.SecureRandom;
public class NonceGenerator {
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
byte[] nonceBytes = new byte[16]; // 16 bytes for a good nonce
random.nextBytes(nonceBytes);
String nonce = Base64.getEncoder().encodeToString(nonceBytes);
System.out.println("Generated Nonce: " + nonce);
System.out.println("\nUse this in your CSP header:");
System.out.println("Content-Security-Policy: script-src 'self' 'nonce-" + nonce + "';");
System.out.println("\nAnd in your HTML:");
System.out.println("<script nonce=\"" + nonce + "\">alert('Hello!');</script>");
}
}CSP Reporting: `report-to`
CSP isn't just about blocking; it's also about visibility. The backend can specify a reporting endpoint using the report-to directive (or older report-uri).
If a browser violates the CSP (e.g., tries to load a script from an unauthorized source), it will send a JSON report to this backend endpoint. Your backend can then log and analyze these reports to detect potential attacks or policy misconfigurations.
Integrating CSP with Frameworks
Modern backend frameworks often provide convenient ways to manage CSP headers without manually concatenating strings.
- Spring Security (Java): Has dedicated configurations for HTTP security headers, including CSP.
- Helmet (Node.js/Express): A middleware that helps secure Express apps by setting various HTTP headers, including CSP.
- Django (Python): Can set CSP headers via middleware or specific libraries.
These tools simplify implementation and help ensure best practices.
CSP for XSS Prevention (Backend View)
From a backend perspective, correctly configured CSP adds a powerful layer of defense against XSS. Even if an attacker manages to inject malicious content into your HTML, CSP can prevent the browser from executing it.
By controlling the Content-Security-Policy header, your backend dictates what content is safe, significantly reducing the impact of client-side vulnerabilities.
CSP Header Challenge
Consider a backend service that needs to allow scripts only from its own domain and from cdn.example.com. Which CSP header directive would best achieve this?
Recap: Backend & CSP
You've learned that Content Security Policy (CSP) is a critical security layer delivered by the backend via the Content-Security-Policy HTTP header.
- Backend sets CSP headers to control resource loading.
- Directives like
script-srcdefine allowed sources. - Nonces are backend-generated tokens to safely allow specific inline scripts.
- Backend can collect violation reports via
report-to. - Frameworks simplify CSP implementation.
By actively managing CSP, backend developers significantly enhance their application's defense against client-side attacks like XSS.
よくある質問
「バックエンド向けContent Security Policy(CSP)」レッスンは無料ですか?
はい。「バックエンド向けContent Security Policy(CSP)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Secure Coding & OWASP Top 10 for Backendコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Secure Coding & OWASP Top 10 for Backendコースには全4レッスンが含まれています。
「バックエンド向けContent Security Policy(CSP)」で何を学びますか?
バックエンドの設定がContent Security Policy(CSP)に与える影響と、XSSなどのクライアントサイド攻撃を軽減する方法を理解します。 ブラウザで直接実行するハンズオンコードでSecure Coding & OWASP Top 10 for Backendを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Secure Coding & OWASP Top 10 for Backendを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSecure Coding & OWASP Top 10 for Backendは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「バックエンド向けContent Security Policy(CSP)」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSecure Coding & OWASP Top 10 for Backendレッスンでコードを書いて実行できますか?
はい。すべてのSecure Coding & OWASP Top 10 for Backendレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 高度なSQLiおよびNoSQLiの手法
- 包括的な入力検証戦略
- バックエンド向けContent Security Policy(CSP)
- コマンドインジェクションとLDAPインジェクションの防止