|
| 1 | +== How to fix it in Groovy |
| 2 | + |
| 3 | +=== Code examples |
| 4 | + |
| 5 | +==== Noncompliant code example |
| 6 | + |
| 7 | +The following code example is vulnerable to a Server-Side Template Injection |
| 8 | +attack because it builds a template string from a user input without control or |
| 9 | +sanitation. |
| 10 | + |
| 11 | +[source,kotlin,diff-id=21,diff-type=noncompliant] |
| 12 | +---- |
| 13 | +import groovy.text.markup.MarkupTemplateEngine |
| 14 | +import groovy.text.markup.TemplateConfiguration |
| 15 | +
|
| 16 | +@Controller |
| 17 | +class ExampleController { |
| 18 | + @GetMapping("/example") |
| 19 | + fun example(@RequestParam("title") title: String): String { |
| 20 | + val templateString = "h1('$title')" |
| 21 | + val config = TemplateConfiguration() |
| 22 | + val engine = MarkupTemplateEngine(config) |
| 23 | + val template = engine.createTemplate(templateString) // Noncompliant |
| 24 | + val out = template.make() |
| 25 | + return out.toString() |
| 26 | + } |
| 27 | +} |
| 28 | +---- |
| 29 | + |
| 30 | +==== Compliant solution |
| 31 | + |
| 32 | +[source,kotlin,diff-id=21,diff-type=compliant] |
| 33 | +---- |
| 34 | +import groovy.text.markup.MarkupTemplateEngine |
| 35 | +import groovy.text.markup.TemplateConfiguration |
| 36 | +
|
| 37 | +@Controller |
| 38 | +class ExampleController { |
| 39 | + @GetMapping("/example") |
| 40 | + fun example(@RequestParam("title") title: String): String { |
| 41 | + val templateString = "h1(title)" |
| 42 | +
|
| 43 | + val ctx = mutableMapOf<String, Any>() |
| 44 | + ctx["title"] = title |
| 45 | +
|
| 46 | + val config = TemplateConfiguration() |
| 47 | + val engine = MarkupTemplateEngine(config) |
| 48 | + val template = engine.createTemplate(templateString) |
| 49 | + val out: Writable = template.make(ctx) |
| 50 | + return out.toString() |
| 51 | + } |
| 52 | +} |
| 53 | +---- |
| 54 | + |
| 55 | +=== How does this work? |
| 56 | + |
| 57 | +The compliant code example uses a template binding to pass user information to |
| 58 | +the template. The rendering engine then ensures that this tainted data is |
| 59 | +processed in a way that will not change the template semantics. |
0 commit comments