CodeQL 文档

服务器端模板注入

ID: java/server-side-template-injection
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-1336
   - external/cwe/cwe-094
Query suites:
   - java-code-scanning.qls
   - java-security-extended.qls
   - java-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当用户输入以不安全的方式嵌入到模板的代码中时,就会发生模板注入。攻击者可以使用本机模板语法将恶意有效负载注入到模板中,然后在服务器端执行该有效负载。这允许攻击者在服务器的上下文中运行任意代码。

建议

要解决此问题,请确保不将不受信任的输入用作模板代码的一部分。如果应用程序要求不允许这样做,请使用沙箱环境,其中禁止访问不安全的属性和方法。

示例

在以下示例中,不受信任的 HTTP 参数 code 用作 Velocity 模板字符串。这会导致远程代码执行。

@Controller
public class VelocitySSTI {

	@GetMapping(value = "bad")
	public void bad(HttpServletRequest request) {
		Velocity.init();

		String code = request.getParameter("code");

		VelocityContext context = new VelocityContext();

		context.put("name", "Velocity");
		context.put("project", "Jakarta");

		StringWriter w = new StringWriter();
		// evaluate( Context context, Writer out, String logTag, String instring )
		Velocity.evaluate(context, w, "mystring", code);
	}
}

在下一个示例中,通过使用固定的模板字符串 s 避免了这个问题。由于在这种情况下,模板代码不受攻击者控制,因此此解决方案可以防止执行不受信任的代码。

@Controller
public class VelocitySSTI {

	@GetMapping(value = "good")
	public void good(HttpServletRequest request) {
		Velocity.init();
		VelocityContext context = new VelocityContext();

		context.put("name", "Velocity");
		context.put("project", "Jakarta");

		String s = "We are using $project $name to render this.";
		StringWriter w = new StringWriter();
		Velocity.evaluate(context, w, "mystring", s);
		System.out.println(" string : " + w);
	}
}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私