cajaプロジェクトJsHtmlSanitizerを使ってみた
google-cajaプロジェクトは、Ajaxを多用するようなクロスドメインなサイトのセキュリティの問題を解決するためのライブラリを開発しているプロジェクトです。
OpenSocialエンジンであるApache-Shindigにも含まれて居ます。どちらかというと派生プロジェクト?
サニタイズの処理を整理するにあたって、自分でコーディングするのはバグの元なので、cajaプロジェクトのhtml-sanitizer.jsを利用を検討してみることにします。
cajaプロジェクトはソースコードのみ配布されていますので、SVNリポジトリからチェックアウトします。
$ svn checkout http://google-caja.googlecode.com/svn/trunk/
html-sanitizer-minified.jsを生成するためにantを実行します。
$ ant MinifiedJs
以下のファイルができます。
ant-lib/com/google/caja/plugin/html-sanitizer-minified.js
サニタイズ処理が必要なページには、上記のjsファイルを追加します。
サニタイズは、html_sanitize関数を利用します。
html_sanitize(htmlSnippet, urlTransformer, nameIdClassTransformer)
引数は以下の通りです。
- htmlSnippet: サニタイズするHTML文字列を指定します。
- urlTransformer: htmlSnippetに指定したHTML内の各URLごとに呼ばれるコールバック関数を指定します。特定のドメインのURLのみサニタイズする場合などに利用します。
- nameIdClassTransformer: 各HTML要素のid、name、class属性を検証するためのコールバック関数です。
以下、サンプルのHTMLです。
<html> <head> <script src="html-sanitizer-minified.js"></script> <script> function urlX(url) {if(/^https?:\/\//.test(url)) {return url }} function idX(id) { return id } function load(){ document.getElementById('sanitize').innerHTML = html_sanitize('<b>hello</b><img src="./debug.gif"><img src="http://www.infoscoop.org/infoscoop_H60.gif"><a href="javascript:alert(0)"><script src="http://dfd"><\/script>', urlX, idX); document.getElementById('no_sanitize').innerHTML ='<b>hello</b><img src="./debug.gif"><img src="http://www.infoscoop.org/infoscoop_H60.gif"><a href="javascript:alert(0)"><script src="http://dfd"><\/script>'; } </script> </head> <body onload="load()"> <div><span>with sanitize:</span><span id="sanitize"></span></div> <div><span>without sanitize:</span><span id="no_sanitize"></span></div> </body> </html>
結果は以下のようになります。
サニタイズあり:
<B>hello</B><IMG /><IMG src="http://www.infoscoop.org/infoscoop_H60.gif" /><A></A>