kohanaのテスト12-13・・・XSS攻撃対策に HTML Purifier を導入する
TinyMCE はテキストモードで編集すると HTML エスケープしてくれるので、問題ありませんが、HTML モードですと <script > タグなんかそのまんまポストしてしまいます。また、ブラウザの jabascript を使わない設定にすれば、テキストボックスがダイレクトに現れるわけですから、書いたまんまポストされます。
従って、サーバー側で XSS 攻撃対策が必須です。ということで、今日は悪意のある HTML を綺麗にしてくれる HTML Purifier を導入します。
HTML Purifier を導入する
・ HTML Purifier のサイトからダウンロードして解凍します。
・中にある library フォルダを htdocs/includes/の下に配置します。
・フォルダ名を htmlpurifier に変更します。
・kohana のブートストラップファイルにオートローダーを記述します。
・kohana/application/bootstrap.php に追加
/** * Enable HTMLpurifier autoloading */ $path = $_SERVER['DOCUMENT_ROOT'].'/includes'; ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . $path); require_once 'htmlpurifier/HTMLPurifier.auto.php';
コントローラーを書き換える
準備が整ったら HTML Purifier の使い方は簡単です。
・kohana/application/classes/controller/test12/postnew.php
<?php defined('SYSPATH') OR die('No direct access allowed.'); class Controller_Test12_postnew extends Controller { public function action_index() { $loginuser = Auth_Wplogin::instance()->get_user(); if (!$loginuser) $this->request->redirect('test12'); $user_ID = Auth_Wplogin::instance()->user_ID($loginuser); $model = Model::factory('test12_posts'); if (isset($_POST['post_title'])) { $post = Validation::factory($_POST) ->rule('post_title', 'not_empty', array(':value', 'タイトル')) ->rule('post_title', 'max_length', array(':value', 100)) ->rule('content', 'not_empty', array(':value', '記事')) ->rule('content', 'max_length', array(':value', 10000)); $posts = $post->data(); if ($post->check()) { $config = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($config); $content = $purifier->purify($posts['content']); $post_array = array( 'post_author' => $user_ID, 'post_title' => $posts['post_title'], 'post_content' => $content, ); $model->postnew($post_array); $this->request->redirect('test12'); } $errors = $post->errors('test12'); $post_title = HTML::chars($posts['post_title']); $content = $posts['content']; } else { $errors = ''; $post_title = ""; $content = ""; } $view = view::factory('test12/postnew/postnew'); $view->errors = $errors; $view->head02 = view::factory('test12/postnew/head02'); $view->adminmenu = view::factory('test12/postnew/adminmenu'); $view->help = view::factory('test12/postnew/help'); $view->screen_option = view::factory('test12/postnew/screen_option'); $view->form_1 = view::factory('test12/postnew/form_1'); $view->form_1->post_title = $post_title; $view->form_1->content = $content; $view->form_2 = view::factory('test12/postnew/form_2'); $view->wpadminbar = view::factory('test12/postnew/wpadminbar'); $view->wpadminbar->loginuser = $loginuser; $view->form_3 = view::factory('test12/postnew/form_3'); $view->fullscreen = view::factory('test12/postnew/fullscreen'); $this->response->body($view); } } ?>
動作試験
例えば、こんなの
<script type="text/javascript" language="javascript">window.alert("このサイトにはXSS攻撃に対する脆弱性があります。\n開発メンバーに連絡して下さい。");</script>
を送ってきたとしても、HTML Purifier が綺麗に抹消してくれます。