Mas*_*iri 10 java xss freemarker escaping
在Freemarker模板中,我们可以使用escape指令自动将转义应用于包含块内的所有插值:
<#escape x as x?html>
<#-- name is escaped as html -->
Hallo, ${name}
</#escape>
Run Code Online (Sandbox Code Playgroud)
有没有办法以编程方式实现类似的效果,定义应用于模板中所有插值的默认转义,包括那些转义外转义?
谢谢.
详细说明Attila的答案:你可以使用像这样的类,然后像这样包装你的模板加载器:
final TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), templatePath) {
/**
* Replaces the normal template reader with something that changes the default
* escaping to HTML as to avoid XSS attacks.
*/
@Override
public Reader getReader(Object templateSource, String encoding) throws IOException {
return new WrappingReader(super.getReader(templateSource, encoding), "<#escape x as x?html>", "</#escape>");
}
};
Run Code Online (Sandbox Code Playgroud)
如果您在添加的部分中不包含换行符,则不会出现行编号问题.但是,您无法使用此方法使用<#ftl>/[#ftl].
从 2.3.24 开始,每个模板都有一个关联的freemarker.core.OutputFormat对象,该对象指定${...}(and #{...}) 是否以及如何转义。OuputFormat对于 HTML,XML 和 RTF 是开箱即用的,但您也可以定义自己的格式。当选定的OutputFormat默认转义时,您可以像 那样显式防止转义${foo?no_esc}。
有多种方法可以将模板与OutputFormat您想要的相关联。对于 HTML 和 XML 转义,建议的方法是将recognize_standard_file_extensions配置设置设置为true,然后使用ftlhHTML 的文件扩展名和ftlxXML 模板的文件扩展名。您还可以OutputFormat使用该设置,根据任意模板名称(模板路径)模式将 -s 关联到模板template_configurers。最后同样重要的是,您可以全局设置默认输出格式,例如configuration.setOutputFormat(HTMLOutputFormat.INSTANCE). 您还可以将模板顶部的输出格式覆盖为<#ftl output_format='HTML'>,但应该很少使用。
相关文档页面:http://freemarker.org/docs/dgui_misc_autoescaping.html,http : //freemarker.org/docs/pgui_config_outputformatsautoesc.html
有一个解决方案,尽管它并不完全微不足道。您可以创建一个特殊的 TemplateLoader 来包装其他模板加载器,并在模板源文本的序言中注入 <#escape x as x?html> ,并添加为它的尾声。
明显的缺点: - 第一行中的列号将被丢弃 - 如果您的模板以 <#ftl> 声明开头,则需要在其后插入 <#escape> 。
| 归档时间: |
|
| 查看次数: |
10527 次 |
| 最近记录: |