Twig:允许 HTML,但转义脚本 [英] Twig: Allow HTML, but escape script
问题描述
我正在调查我的应用程序可能存在的 XSS
攻击向量.
I am investigating a possible XSS
attack vector for my application.
我有什么:
- FormType 与单个
textarea
字段.通常这个字段可以包含html
标签. Twig
模板,用于呈现插入的数据.
- FormType with a single
textarea
field. Normally this field can containhtml
tags. Twig
template that renders the data inserted.
我使用该表单插入以下内容:
I use that form to insert the following content:
<b>Some valid HTML text</b>
<script type="text/javascript">alert("XSS")</script>
查看该数据需要转义.在转义数据方面,我熟悉的策略很少.
Viewing that data would require escaping. I am familiar with few strategies when it comes to escaping the data.
1) raw
过滤器:完全禁用转义 -> 引入可能的 XSS
1) raw
filter: Completely disables escaping -> introduces possible XSS
2) e
过滤器:
html
风味输出:<b>一些有效的 HTML 文本</b><script type="text/javascript">alert("XSS")</script>
js
风味输出:x3Cbx3ESomex20validx20HTMLx20textx3Cx2Fbx3Ex0Dx0Ax3Cscriptx20typex3Dx22textx2Fjavascriptx22x3Ealertx28x22XSSx22x29x3Cx2Fscriptx3E
html
flavor outputs:<b>Some valid HTML text</b> <script type="text/javascript">alert("XSS")</script>
js
flavor outputs:x3Cbx3ESomex20validx20HTMLx20textx3Cx2Fbx3Ex0Dx0Ax3Cscriptx20typex3Dx22textx2Fjavascriptx22x3Ealertx28x22XSSx22x29x3Cx2Fscriptx3E
3) {{ var|striptags('<br>')|raw }}
,输出:一些有效的 HTML 文本 alert("XSS")
3) {{ var|striptags('<br>')|raw }}
, outputs: Some valid HTML text alert("XSS")
这个工作,但不知何故我不喜欢它.我宁愿寻找黑名单解决方案,而不是白名单.
This one works, but somehow I don't like it. I am rather looking for a black-list solution, not white-list.
现在的问题是:
是否有任何其他转义策略允许 html
标签但像 e("js")
过滤器那样转义 <script>
标签?
Is there any other escaping strategy that allows html
tags but escapes <script>
tag like e("js")
filter does?
我应该在表单提交期间还是在 Twig
呈现期间杀死"脚本?
Should I "kill" the script during the form submission or during the Twig
rendering?
推荐答案
我建议添加一个符合您需求的新 Twig 过滤器.
I would suggest adding a new Twig filter that fits your needs.
它应该看起来像
{{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 :)
这篇关于Twig:允许 HTML,但转义脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!