Twig: Allow HTML, but escape script

后端 未结 1 1564
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 04:27

I am investigating a possible XSS attack vector for my application.

What I have:

  • FormType with a single textarea field. Normally
相关标签:
1条回答
  • 2021-01-22 05:21

    I would suggest adding a new Twig filter that fits your needs.

    It should look something like

    {{var | filter_black_listed() }}
    

    and in the filter logic you add something like

    class FilterBlackListedExtension extends \Twig_Extension
    {
        private $blacklistedTags = ['script', 'p'];
    
        public function getFilters()
        {
            return array(
                new \Twig_SimpleFilter('filter_black_listed', array($this, 'htmlFilter')),
            );
        }
    
        public function htmlFilter($html)
        {
            foreach ($this->blacklistedTags as $tag) {
                preg_replace('/(<' . $tag . '>)(.*)(<\/' . $tag . '>)/g', '', $html);
            }
    
            return $html; // maybe even apply the raw filter also afterwards.
        }
    
        public function getName()
        {
            return 'filter_black_listed_extension';
        }
    }
    

    let me know if you don't manage to make this work :)

    0 讨论(0)
提交回复
热议问题