■はじめに
* クロスサイト・スクリプティング(XSS)の一環として、 jQuery / JavaScript でのサニタイジング(エスケープ)を調べてみた
補足:用語について
* クロスサイト・スクリプティング/サニタイジング(Sanitizing)について、以下の関連記事を参照のこと。http://blogs.yahoo.co.jp/dk521123/35715410.html
■jQueryを使える場合
案1:text()を利用する
* jQueryの「xxxx.text(【値】)を利用する
サンプル
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <script src="">http://code.jquery.com/jquery-1.10.1.min.js"> </head> <body> <form> <div id="sanitizingOff">サニタイジングなし</div> <div id="sanitizingOn">サニタイジング済み</div> Input data:<input id="textValue" type="text" size="50" value="<s>Hello World!</s>"> <input id="fire" type="button" value="click me!"> </form> <script type="text/javascript"> $("#fire").click(function(event){ var textValue = document.getElementById("textValue").value; // サニタイジングなし document.getElementById("sanitizingOff").innerHTML = textValue; // サニタイジング済み escape("#sanitizingOn", textValue); }); function escape(targetId, targetValue) { if (targetValue === null || targetValue === undefined) { targetValue = ""; } $(targetId).text(targetValue).html(); } </script> </body> </html>
■jQueryが使えない(JavaScriptのみ)場合
案2:replace()を利用する
* 「xxxx.replace(【値】)で地道に実装。
サンプル
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> </head> <body> <form> <div id="sanitizingOff">サニタイジングなし</div> <div id="sanitizingOn">サニタイジング済み</div> Input data:<input id="textValue" type="text" size="50" value="<s>Hello World!</s>"> <input id="fire" type="button" value="click me!" onclick="sampleCode()"> </form> <script type="text/javascript"> function sampleCode() { var textValue = document.getElementById("textValue").value; // サニタイジングなし document.getElementById("sanitizingOff").innerHTML = textValue; // サニタイジング済み document.getElementById("sanitizingOn").innerHTML = escape(textValue); } function escape(targetValue) { if (targetValue === null || targetValue === undefined) { return ""; } return String(targetValue) .replace(/&/g, "&") .replace(/"/g, """) .replace(/'/g, "'") .replace(/`/g, "`") .replace(/</g, "<") .replace(/>/g, ">"); } </script> </body> </html>
参考文献
http://b.0218.jp/20131021184513.htmlhttp://iwb.jp/jquery-javascript-html-escape/