简体   繁体   English

树枝逃逸('js')symfony2

[英]twig escape('js') symfony2

Let's say I have article with content (content has html tags).. so:假设我有文章内容(内容有 html 标签)..所以:

{{article.content|raw}}

and it looks good.看起来不错。

Problem is if user adds script tags - So I try doing问题是如果用户添加脚本标签 - 所以我尝试做

{{article.content|raw|e('js')}}

and it escapes all.. I mean html and so on..它逃脱了所有..我的意思是html等等..

I get double escaped text, I don't have any html tags any more, they all are escaped.. is it some kind of twig bug or what?我得到了双重转义文本,我不再有任何 html 标签,它们都被转义了..是某种树枝虫还是什么?

example: I have "<p>test</p>"示例:我有"<p>test</p>"

with {{article.content|raw}} I will see "test" with {{article.content|raw|e('js')}} I will see "\\x3Cp\\x3Etestas\\x3C\\x2Fp\\" .使用{{article.content|raw}}我会看到 "test" 使用{{article.content|raw|e('js')}}我会看到"\\x3Cp\\x3Etestas\\x3C\\x2Fp\\" So what's wrong?那么怎么了? I know I can escape script tags on server side, but I am so interested in knowing what's wrong with my approach..我知道我可以在服务器端转义脚本标签,但我很想知道我的方法有什么问题..

You have the wrong tool for the job using the escape filter.您使用转义过滤器的工作使用了错误的工具。 With what you have written, the "raw" filter does nothing and the escape escapes the string you are outputting so that it will be suitable for inclusion as data inside a Javascript section of your output.使用您编写的内容,“原始”过滤器不执行任何操作,转义符会转义您输出的字符串,以便将其作为数据包含在输出的 Javascript 部分中。

What you are looking for is an XSS filter like HtmlPurifier .您正在寻找的是像HtmlPurifier这样的 XSS 过滤器。 Once you have used composer or direct installation to include an XSS filter in your project, you can then write a custom filter for Twig that will filter out XSS vectors like script tags etc. and leave you with a variable safe to output via the raw filter.一旦你使用 composer 或直接安装在你的项目中包含一个 XSS 过滤器,你就可以为 Twig 编写一个自定义过滤器,它会过滤掉脚本标签等 XSS 向量,并为你留下一个变量,可以通过原始过滤器安全输出.

Tested in https://twigfiddle.com/https://twigfiddle.com/ 中测试

{{'<p>test</p><script>const me = "hi"</script>'|raw}}
{{'<p>test</p><script>const me = "hi"</script>'|e('js')}}
{{'<p>test</p><script>const me = "hi"</script>'|e('html')}}
{{'<p>test</p><script>const me = "hi"</script>'|e('html_attr')}}
{{'<p>test</p><script>const me = "hi"</script>'|striptags}}
{{'<p>test</p><script>const me = "hi"</script>'|striptags|raw}}

/*
<p>test</p><script>const me = "hi"</script>
\u003Cp\u003Etest\u003C\/p\u003E\u003Cscript\u003Econst\u0020me\u0020\u003D\u0020\u0022hi\u0022\u003C\/script\u003E
&lt;p&gt;test&lt;/p&gt;&lt;script&gt;const me = &quot;hi&quot;&lt;/script&gt;
&lt;p&gt;test&lt;&#x2F;p&gt;&lt;script&gt;const&#x20;me&#x20;&#x3D;&#x20;&quot;hi&quot;&lt;&#x2F;script&gt;
testconst me = &quot;hi&quot;
testconst me = "hi"
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM