JavaScriptを安全に実行するためのnonce導入法
Webサイトでは不特定多数の人たちがサービスに触れます。その結果、悪意を持ったユーザによってWebページを改ざんされたり、不用意なJavaScriptを実行したりするリスクが発生します。
運営側で予期していないJavaScriptの実行を制限するのに使えるのがnonceです。CSP(コンテンツセキュリティポリシー)によって実行できるJavaScriptを制限できます。
仕組み
JavaScriptのnonceはクライアントサイドだけでは実装できません。まずHTMLを出力する際にレスポンスヘッダーにてnonceを出力する必要があります。以下はnode/Expressで実装した場合です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const uuidv4 = require('uuid/v4'); | |
nonce = uuidv4(); | |
res.setHeader('Content-Security-Policy', `script-src 'nonce-${nonce}' 'strict-dynamic'`) |
nonceは nonce-
という文字列ではじまっている必要があります。
HTML側
HTML側ではそのnonce(今度はnonce-は不要です)をscriptタグのnonce要素として出力します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
alert('Unsafe JavaScript'); | |
</script> | |
<script nonce="<%= nonce %>"> | |
alert('Safe JavaScript'); | |
</script> |
例えば上記のように記述されていた場合、Unsafe JavaScriptというアラートは出ません。
開発者コンソールで見ると、Unsafeの方はCSPエラーが出ています。
このようにして実行できるJavaScriptを制御できます。なお、nonceは常にユニークである必要があるので、uuidを使ったり、ランダムな文字列を生成するライブラリと組み合わせて使うのがいいでしょう。
コメントは受け付けていません。