2017-06-29 39 views
0

CakePHP的版本是3.4.xcakephp3-如何做xss过滤?我使用

我有十几形式更在我的CakePHP 3应用程序。我想为所有窗体实现xss过滤。在不更改所有表单函数的情况下,最简单的方法是什么?

我在一个答案中读到,为了在视图中消毒,我们应该使用CakePHP的便利函数h($ string),它将使XSS的所有尝试都完全无害。

我试过这个,但是id没有解决。

enter image description here

的\ src \模板\用户\ view.ctp

<p><span>Address</span>: <?= h($user->address) ?></p> 

是否有数据保存到数据库之前执行跨站脚本过滤的方法吗?

我的控制器功能(这CakePHP的出炉对我来说)添加一个新用户和他的信息

的\ src \控制器\ UsersController.php

public function add(){ 
    $this->viewBuilder()->setLayout('admin') ; 
    $user = $this->Users->newEntity(); 
    if ($this->request->is('post')) { 
     $user = $this->Users->patchEntity($user, $this->request->getData()); 
     if ($this->Users->save($user)) { 
      $this->Flash->success(__('The user has been saved.')); 

      return $this->redirect(['action' => 'index']); 
     } 
     $this->Flash->error(__('The user could not be saved. Please, try again.')); 
    } 
    $groups = $this->Users->Groups->find('list', ['limit' => 200]); 
    $this->set(compact('user', 'groups')); 
    $this->set('_serialize', ['user']); 
} 

的\ src \型号\ Table \ UsersTable.php

public function beforeSave(Event $event) 
{ 
    $entity = $event->getData('entity'); 

    if ($entity->isNew()) { 
     $hasher = new DefaultPasswordHasher(); 

     // Generate an API 'token' 
     $entity->api_key_plain = sha1(Text::uuid()); 

     // Bcrypt the token so BasicAuthenticate can check 
     // it during login. 
     $entity->api_key = $hasher->hash($entity->api_key_plain); 
    } 
    return true; 
} 

谢谢!

+0

怎么'H()'不适合你?从你的屏幕截图看来,它似乎已经编码了有害脚本标记,以便它不会运行。便利功能不会去除内容,只是确保它被正确编码,以防止用户输入注入可能有害的代码。 – drmonkeyninja

+1

但脚本标记正在保存在数据库中。这就是我想要阻止的。 @drmonkeyninja – Annabelle

+0

我不相信这是你可以直接用CakePHP做的事情。您可能需要查看'beforeSave'中手动剥离标签,查看接受的答案:https://stackoverflow.com/questions/7130867/remove-script-tag-from-html-content。 – drmonkeyninja

回答

0

您可以使用赋值函数方法在用户实体类:

class User extends Entity 
{  
    protected function _setAddress($value) { 
     return strip_tags($value); 
    } 
} 

使用这种突变基因,你可以保存到数据库每次,当实体更新或创建之前修改输入数据。有关增变器的更多信息:https://book.cakephp.org/3.0/en/orm/entities.html#accessors-mutators

您也可以使用其他方式,但是我在此之前写过。如果你想使用,你应该测试这个代码。使用$entity->getDirty()方法,我们可以得到所有修改的字段,并更改Table::beforeSave()方法,它们的值:

public function beforeSave($event) 
{ 
    $entity = $event->getData('entity'); 

    $modified = $entity->getDirty(); 
    foreach((array) $modified as $v) { 
     if(isset($entity->{$v})) { 
      $entity->{$v} = strip_tags($entity->{$v}); 
     } 
    } 

    return true; 
}  
+0

调用未定义的方法Cake \ Event \ Event :: getData()@Dariusz Majchrzak – Annabelle

+0

[*](https://api.cakephp.org/3.4/function-h.html) *输出**而不是在保存时剥离一些标签? [破碎的HTML会通过这个](http://php.net/manual/en/function.strip-tags.php#refsect1-function.strip-tags-notes) – Sevvlor

+0

@AnnaBelle cakephp的哪个版本? –