修复 Freemarker 模板注入漏洞

在不进行依赖版本升级,同时避免对已有类进行重写,可以参考下列处理:

Configuration在配置类FreeMarkerConfigurer中使用,在配置类的bean初始化方法afterPropertiesSet中,若Configuration还未设置,则使用createConfiguration方法创建Configuration.
在这里插入图片描述
SpringBoot自动配置FreeMarkerConfigurer,如下图所示:
在这里插入图片描述
其使用了@ConditionalOnMissingBean(FreeMarkerConfig.class),故可以使用我们自己定义的FreeMarkerConfigurer,通过自定义的FreeMarkerConfigurer中配置对应的Configuration,解决Freemarker 模板注入漏洞.

自定义配置FreeMarkerConfigurer代码示例如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, FreeMarkerConfigurer.class})
public class FreeMarkerServletWebConfigurer {
    private final FreeMarkerProperties properties;

    public FreeMarkerServletWebConfigurer(FreeMarkerProperties properties) {
        this.properties = properties;
    }

    protected void applyProperties(FreeMarkerConfigurationFactory factory) {
        factory.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());
        factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
        factory.setDefaultEncoding(this.properties.getCharsetName());
        Properties settings = new Properties();
        settings.put("recognize_standard_file_extensions", "true");
        settings.putAll(this.properties.getSettings());
        factory.setFreemarkerSettings(settings);
    }

    @Bean
    FreeMarkerConfigurer freeMarkerConfigurer() throws IOException, TemplateException {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        freemarker.template.Configuration configuration = configurer.createConfiguration();
        // 通过设置TemplateClassResolver.SAFER_RESOLVER避免注入漏洞.
        configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
        configurer.setConfiguration(configuration);
        applyProperties(configurer);
        return configurer;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值