48 lines
1.6 KiB
Plaintext
48 lines
1.6 KiB
Plaintext
== How to fix it in Groovy
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
The following code example is vulnerable to a Server-Side Template Injection
|
|
attack because it builds a template string from a user input without control or
|
|
sanitation.
|
|
|
|
[source,java,diff-id=21,diff-type=noncompliant]
|
|
----
|
|
@GetMapping("/example")
|
|
public String example(@RequestParam("title") String title) throws CompilationFailedException, ClassNotFoundException, IOException {
|
|
String templateString = "h1('" + title + "')";
|
|
TemplateConfiguration config = new TemplateConfiguration();
|
|
MarkupTemplateEngine engine = new MarkupTemplateEngine(config);
|
|
Template template = engine.createTemplate(templateString); // Noncompliant
|
|
Writable out = template.make();
|
|
return out.toString();
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=21,diff-type=compliant]
|
|
----
|
|
@GetMapping("/example")
|
|
public String example(@RequestParam("title") String title) throws CompilationFailedException, ClassNotFoundException, IOException {
|
|
String templateString = "h1(title)";
|
|
|
|
Map<String, Object> ctx = new HashMap<>();
|
|
ctx.put("title", title);
|
|
|
|
TemplateConfiguration config = new TemplateConfiguration();
|
|
MarkupTemplateEngine engine = new MarkupTemplateEngine(config);
|
|
Template template = engine.createTemplate(templateString);
|
|
Writable out = template.make(ctx);
|
|
return out.toString();
|
|
}
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
The compliant code example uses a template binding to pass user information to
|
|
the template. The rendering engine then ensures that this tainted data is
|
|
processed in a way that will not change the template semantics.
|