问题描述
我正在开发一个博客评论包,我想让用户使用 Markdown 发布一些代码.
我正在使用 symfony2、TWIG 和 KNPMarkdownBundle 进行解析
I am working on a blog comment bundle and I would like to let user post some code using Markdown.
I am working with symfony2, TWIG and KNPMarkdownBundle for parsing
{{ post.content|markdown }}
实际上,内容是很好的降价解析(<code>
<p>
...)但是如果我的内容中有一些 HTML 代码,例如:
Actually, the content is well markdown parsed (<code>
<p>
...) but if I have some HTML code in my content like :
Some content
``` <script>alert("hello world");</script> ```
代码没有转义,我有一条警告消息.请有人解释一下我该如何处理 XSS 问题?(foo|raw
和 foo|escape
正在破坏解析)
The code is not escaped and I have a alert message.Please can someone explain how can I deal with XSS issues ? (foo|raw
and foo|escape
are breaking parsing)
推荐答案
我刚好遇到了这个问题,但是由于strip_tags
不足以保护attributes标签中的值,所以我将提交我的回答.
I just happened to have this problem, but since strip_tags
is not enough to protect values in the attributes tag, I will submit my answer.
我正在使用 HTML Purifier 来删除所有不需要的 HTML 元素和属性.打开命令控制台并执行以下命令进行安装.
I'm using HTML Purifier to remove all unwanted HTML elements and attributes. Open a command console and execute the following command to install it.
$ composer require ezyang/htmlpurifier "^4.6"
然后您可以创建自己的 Twig 扩展:
Then you can create your own Twig extension:
namespace AcmeBundleTwig;
class HTMLPurifierExtension extends Twig_Extension
{
public function getFilters()
{
return array(
new Twig_SimpleFilter('html_purifier', array($this, 'purify'), array('is_safe' => array('html'))),
);
}
public function purify($text)
{
$elements = array(
'p',
'br',
'small',
'strong', 'b',
'em', 'i',
'strike',
'sub', 'sup',
'ins', 'del',
'ol', 'ul', 'li',
'h1', 'h2', 'h3',
'dl', 'dd', 'dt',
'pre', 'code', 'samp', 'kbd',
'q', 'blockquote', 'abbr', 'cite',
'table', 'thead', 'tbody', 'th', 'tr', 'td',
'a[href|target|rel|id]',
'img[src|title|alt|width|height|style]'
);
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', implode(',', $elements));
$purifier = new HTMLPurifier($config);
return $purifier->purify($text);
}
public function getName()
{
return 'html_purifier';
}
}
打开 services.yml
并将扩展注册为服务:
Open services.yml
and register the extension as a service:
services:
acme.html_purifier_extension:
class: AcmeBundleTwigHTMLPurifierExtension
public: false
tags:
- { name: twig.extension }
现在你可以使用它了
{{ post.content|markdown|html_purifier }}
这篇关于使用 TWIG Markdown 转义 HTML 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!