# CSP 檢測及設定 ###### tags: `CSP` `資安` ## 概要 CSP 全稱為 Content-Security-Policy(內容安全策略),是X-Frame-Options 的加強板,因為配置需要花較多心思處理,所以這邊著重在配置。 下面的配置僅為經驗,當作參考,每個網站的配置不一定都相同。 ## 檢測及開發工具 * CSP Evaluator [CSP Evaluator](https://csp-evaluator.withgoogle.com/)可以檢測是否設定成功及開發 CSP * 開發環境配置 `haproxy` 或是 `nginx` 這邊強烈建議在開發環境中自行建立 haproxy 或是 nginx 服務,因為在設定 CSP 過程中非常容易造成服務異常 ## 事前準備 ### 產出 nonce 值 以linux 為例,可以使用`sha256sum`產出 ```shell ❯ echo -n "password" | sha256sum 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8 - ``` 取其中一段字就可以了,例如: 047151d0e56f 。之後 `haproxy` 或是 `nginx` 與 網站程式碼 都需要用相同的 `nonce值` ### 調查會引入網站資源的 URL 為了防止跨網域攻擊,CSP 採用嚴謹的白名單配置。所以請先調查設定目標網展有引用哪些外部網站資源,外部資源如: `https://www.google-analytics.com` 等等 ## 設定方式 ### 程式碼 在網站專案中所有的`<script>`、`<style>` 都需要加入 `nonce` 元素 ```html <html> <head> <script nonce="047151d0e56f"> ... </script> <style nonce="047151d0e56f"> ... </style> </head> </html> ``` ### nginx 設定 nginx.confg ``` add_header Content-Security-Policy "script-src 'unsafe-inline' 'strict-dynamic' 'nonce-047151d0e56f' https://domain1 https://domain2 ;object-src 'none';base-uri 'none';" ``` ### haproxy 設定 haproxy.cfg ``` http-response set-header Content-Security-Policy "script-src 'unsafe-inline' 'strict-dynamic' 'nonce-047151d0e56f' 'unsafe-inline' https://domain1 https://domain2";"object-src 'none'";"base-uri 'none'"; ``` ## 特別的問題 * a 作為返回歷史紀錄功能失效 原始出現的程式如下 ```html <a title="返回" href="javascript:history.back();"> ``` 解決方式 ```html <a title="返回" href="#"> <script id="idVal" nonce="15d6c15b0f00a08"> document.getElementById('idVal').onclick = function () { window.history.back(); } </script> ``` ## 參考資料 [Content-Security-Policy - HTTP Headers 的資安議題 (2)](https://devco.re/blog/2014/04/08/security-issues-of-http-headers-2-content-security-policy/) [Using a nonce with CSP](https://content-security-policy.com/nonce/) [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) [Active Content-Security-Policy (CSP) and Rails :back link](https://stackoverflow.com/questions/38099220/active-content-security-policy-csp-and-rails-back-link)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up