Content Security Policy 是一種使用標(biāo)題或 meta 元素來限制或批準(zhǔn)加載到指定網(wǎng)站上的內(nèi)容的策略。 這是一個(gè)廣受支持的安全標(biāo)準(zhǔn),所有網(wǎng)站運(yùn)營者都應(yīng)該對這些標(biāo)準(zhǔn)了然于心。
使用 CSP 通過說明允許或不允許的規(guī)則為 Web 網(wǎng)站增加了一層保護(hù)。 這些規(guī)則有助于防御內(nèi)容注入和跨站點(diǎn)腳本 (XSS) 攻擊,這是 OWASP 的十大 Web 應(yīng)用程序安全風(fēng)險(xiǎn)中的兩個(gè)。
當(dāng)攻擊者能夠通過注入惡意代碼來破壞未受保護(hù)的網(wǎng)站時(shí),就會(huì)發(fā)生 XSS 攻擊。 當(dāng)用戶嘗試與站點(diǎn)交互時(shí),惡意腳本會(huì)在用戶的瀏覽器中執(zhí)行,從而使攻擊者能夠訪問受害者與站點(diǎn)的交互,例如登錄信息等。
CSP 將阻止大多數(shù)腳本注入攻擊的發(fā)生,因?yàn)樗梢栽O(shè)置為將 JavaScript 限制為僅從受信任的位置加載。
本文介紹一些基于 frame-src
這個(gè) Directive 的各種測試用例。 作為容器,定義 iframe 的 web 應(yīng)用,監(jiān)聽在 3000 端口:wechat 文件夾下
嵌入了另一個(gè)網(wǎng)頁,監(jiān)聽在 3002 端口,Jerrylist 文件夾下面:
如果 Jerrylist 文件夾下的 csp html 里沒有聲明任何 csp 相關(guān)的 Directive(通過 meta 標(biāo)簽),則 iframe 工作正常:
源代碼:
<html> <head> <meta http-equiv="Content-Security-Policy" content="frame-src 'self'"> </head> <h1>Parent</h1> <iframe src="http://localhost:3002/csp"></iframe></html>
測試結(jié)果:
Refused to frame 'http://localhost:3002/' because it violates the following Content Security Policy directive: "frame-src 'self'".
iframe 加載失?。?/p>
<html> <head> <meta http-equiv="Content-Security-Policy" content="frame-src 'http://localhost:3002'"> </head> <h1>Parent</h1> <iframe src="http://localhost:3002/csp"></iframe></html>
錯(cuò)誤消息:
The source list for the Content Security Policy directive 'frame-src' contains an invalid source: ''http://localhost:3002''. It will be ignored. 11:25:37.549 localhost/:6 Refused to frame 'http://localhost:3002/' because it violates the following Content Security Policy directive: "frame-src 'none'".
iframe 加載失?。?/p>
改成 *
的話,又重新工作了:
下列代碼也工作:
<html> <head> <meta http-equiv="Content-Security-Policy" content="frame-src http://localhost:3002/csp"> </head> <h1>Parent</h1> <iframe src="http://localhost:3002/csp"></iframe></html>
下列代碼也工作:
<html> <head> <meta http-equiv="Content-Security-Policy" content="frame-src http://localhost:*/csp"> </head> <h1>Parent</h1> <iframe src="http://localhost:3002/csp"></iframe></html>
下列代碼也工作: