[Cakephp] XSS対策としてSanitizeを使ってみる

生のSQLを使わずに、find、readを使用している場合の「SQLインジェクション」は、Cakephp側で対応するので、だいたい大丈夫だと思われる。

XSS対策

参考:hijiriworld Web

■HTMLタグのみを除去する

[cakephp2.5.5]
AppController.php

App::uses('Sanitize', 'Utility');
class AppController extends Controller {
(略)
  public function __sanitize() {
    $this->data = Sanitize::clean($this->data, array('remove_html' => true, 'encode' => true, 'escape' => false));
  }
}

各controllerのaddやeditでpost、putチェック後にsanitizeする

public function add() {
  if ($this->request->is('post')) {
    $this->__sanitize();
    (略)
  }
}

Viewでも

echo h(xxxxxx);

■SanitizeするとDBエラーが出る

Database connection "Mysql" is missing, or could not be created.

参考:Use Sanitize::clean without Database connection at CakePHP 2.3 – Stack Overflow

Sanitizeのオプションに

'escape' => false

を入れる。

Sanitizeの仕様みたいですが、escapeが無いとdatabase.phpの「$default」設定を見に行くようです。
なので、本番環境は「$production」とかにしてDB設定を分けている場合は、escapeを入れないとMysqlエラーになります。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)