过滤、存储到数据库并输出文本区域的文本? Zend 框架 2.3.5

Filtering, storing into database and output textarea's text? Zend Framework 2.3.5

各位,

我有一个文本区域。我需要将其文本存储到数据库 Mysql 中并输出,但输出必须是安全的并保留换行符。

存储之前我使用 InputFilter 验证:

       $inputFilter = new InputFilter();
       $inputFilter->add(array(
             'name'     => 'Description',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name'    => 'StringLength',
                     'options' => array(
                         'encoding' => 'UTF-8',
                         'min'      => 1,
                         'max'      => 30000,
                     ),
                 ),
             ),

         ));

存储文本输出后,我使用:

echo nl2br(strip_tags($Description));

strip_tags 用于防止 XSS 攻击,nl2br 用于保留断行。 那么,它安全吗?我已尝试保存

"hi, how are yoy? <a href="www.hackered.com"> hackered </a>"

进入数据库的文本是:

"hi, how are yoy? hackered"

我尝试将第一个短语直接存储到数据库中,输出如上。看起来很安全。

这种方法安全吗?有一些方法安全吗? 我有这个疑问,因为在 Zend Filter 参考中它说:

Warning

Zend\Filter\StripTags is potentially unsecure

Be warned that Zend\Filter\StripTags should only be used to strip all available tags.

Using Zend\Filter\StripTags to make your site secure by stripping some unwanted tags will lead to unsecure and dangerous code.

Zend\Filter\StripTags must not be used to prevent XSS attacks. This filter is no replacement for using Tidy or HtmlPurifier.

http://framework.zend.com/manual/current/en/modules/zend.filter.set.html#striptags

非常感谢

我认为你说得对:

There are some methods much secure? I have this doubt because into Zend Filter reference it says:

Zend\Filter\StripTags must not be used to prevent XSS attacks

确定 Zend\InputFilter 是让您提高应用程序安全性的重要组成部分之一。 然而,它被认为是一种错误的策略来防止和阻止 XSS 攻击。

Zend\InputFilter: this component takes care of scanning input to escape or remove illegal strings (HTML elements or filesystem paths), as well as transforming it to meet formatting requirements (stripping whitespace and newlines or changing string case).

Zend Framework 提供的专门用于阻止 XSS 攻击的组件是 Zend\Escaper。它提供了五种方法来转义输出,具体取决于输出将出现在呈现页面中的位置。 HTML 页面内容、HTML 元素属性、脚本元素、样式元素和 URI 中的 escaping/encoding 内容存在方法。

Zend\Escaper : this component offers a way to escape output and defend from XSS and related vulnerabilities by introducing contextual escaping based on peer-reviewed rules.

这些是Zend\Escaper提供的转义方法:

  • escapeHtml:转义 HTML 正文上下文的字符串。
  • escapeHtmlAttr:转义 HTML 属性上下文的字符串。
  • escapeJs:为 Javascript 上下文转义字符串。
  • escapeCss:为 CSS 上下文转义字符串。
  • escapeUrl:转义 URI 或参数上下文的字符串。

您还可以参考文档 Zend Escaper Theory of Operation 了解每种方法的用法。

请看这个article on web application security with ZF2, particularly this section : Blunting XSS attacks with output escaping