Web安全之Content Security Policy(CSP 內(nèi)容安全策略)詳解
什么是Content Security Policy(CSP)
Content Security Policy是一種網(wǎng)頁安全策略,現(xiàn)代瀏覽器使用它來增強(qiáng)網(wǎng)頁的安全性??梢酝ㄟ^Content Security Policy來限制哪些資源(如JavaScript、CSS、圖像等)可以被加載,從哪些url加載。
CSP 本質(zhì)上是白名單機(jī)制,開發(fā)者明確告訴瀏覽器哪些外部資源可以加載和執(zhí)行,可以從哪些url加載資源。
CSP最初被設(shè)計(jì)用來減少跨站點(diǎn)腳本攻擊(XSS),該規(guī)范的后續(xù)版本還可以防止其他形式的攻擊,如點(diǎn)擊劫持。
啟用CSP的兩種方法
啟用CSP的方法有兩種,第一種是通過設(shè)置一個(gè)HTTP響應(yīng)頭(HTTP response header) “Content-Security-Policy”,第二種是通過HTML標(biāo)簽<meta>設(shè)置,例如:
除了Content-Security-Policy外,還有一個(gè)Content-Security-Policy-Report-Only字段,表示不執(zhí)行限制選項(xiàng),只是記錄違反限制的行為,必須與report-uri值選項(xiàng)配合使用,例如:
CSP指令介紹
Content-Security-Policy值由一個(gè)或多個(gè)指令組成,多個(gè)指令用分號分隔。
csp資源加載項(xiàng)限制指令如下:
上述指令對應(yīng)的值如下:
Source Value | Example | Description |
* | img-src * | Wildcard, allows any URL except data: blob: filesystem: schemes. |
'none' | object-src 'none' | Prevents loading resources from any source. |
'self' | script-src 'self' | Allows loading resources from the same origin (same scheme, host and port). |
data: | img-src 'self' data: | Allows loading resources via the data scheme (eg Base64 encoded images). |
domain.example.com | img-src domain.example.com | Allows loading resources from the specified domain name. |
*.example.com | img-src *.example.com | Allows loading resources from any subdomain under example.com. |
img-src https://cdn.com | Allows loading resources only over HTTPS matching the given domain. | |
https: | img-src https: | Allows loading resources only over HTTPS on any domain. |
'unsafe-inline' | script-src 'unsafe-inline' | Allows use of inline source elements such as style attribute, onclick, or script tag bodies (depends on the context of the source it is applied to) and javascript: URIs |
'unsafe-eval' | script-src 'unsafe-eval' | Allows unsafe dynamic code evaluation such as JavaScript eval() |
'sha256-' | script-src 'sha256-xyz...' | Allows an inline script or CSS to execute if its hash matches the specified hash in the header. Currently supports SHA256, SHA384 or SHA512. CSP Level 2 |
'nonce-' | script-src 'nonce-rAnd0m' | Allows an inline script or CSS to execute if the script (eg: <script nonce="rAnd0m">) tag contains a nonce attribute matching the nonce specifed in the CSP header. The nonce should be a secure random string, and should not be reused. CSP Level 2 |
'strict-dynamic' | script-src 'strict-dynamic' | Enables an allowed script to load additional scripts via non-"parser-inserted" script elements (for example document.createElement('script'); is allowed). CSP Level 3 |
'unsafe-hashes' | script-src 'unsafe-hashes' 'sha256-abc...' | Allows you to enable scripts in event handlers (eg onclick). Does not apply to javascript: or inline <script> CSP Level 3 |
CSP URL限制指令如下:
CSP其它限制指令如下:
小結(jié)
CSP對于保護(hù)Web應(yīng)用程序的安全非常重要,可以幫助減少很多XSS類攻擊。需要注意的是,CSP只是一種安全策略,不能完全保證網(wǎng)站的安全性。因此,在使用CSP時(shí),還需要結(jié)合其他安全措施,如使用HTTPS、防火墻等,進(jìn)一步提高網(wǎng)站的安全性。