Improper Control of Generation of Code ('Code Injection')
ID |
scala.templateinjection.scala_templateinjection_rule_templateinjection |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Templateinjection |
Language |
Scala |
Description
A malicious user in control of a template can run malicious code on the server-side. Velocity templates should be seen as scripts.
Rationale
A malicious user in control of a template can run malicious code on the server-side. Velocity templates should be seen as scripts.
The following code illustrates a vulnerable pattern detected by this rule:
// A template is a program in its own language, so a template chosen or written by the
// caller runs whatever that caller put in it.
class LetterRenderer {
@throws[FileNotFoundException]
def velocityFromAFile(supplied: String): Unit = {
Velocity.init
val values = new VelocityContext
values.put("recipient", "A. Nadie")
values.put("street", "Calle Mayor 1")
values.put("phone", "555-0100")
val source = new FileInputStream(supplied)
val rendered = new StringWriter
// VULNERABLE: Improper Control of Generation of Code ('Code Injection')
Velocity.evaluate(values, rendered, "letter", source.toString)
System.out.println(rendered.getBuffer.toString)
}
@throws[FileNotFoundException]
// A template written in the source is fixed, so there is nothing to inject into it.
@throws[FileNotFoundException]
def velocityFromAConstant(): Unit = {
val values = new VelocityContext
val rendered = new StringWriter
Velocity.evaluate(values, rendered, "letter", "Hola $recipient")
}
@throws[IOException]
@throws[TemplateException]
@throws[IOException]
def pebbleFromAFile(supplied: String): Unit = {
val engine = new PebbleEngine.Builder().build
var template: PebbleTemplate = null
try {
template = engine.getTemplate(supplied)
}
catch {
case e: PebbleException =>
e.printStackTrace
}
val values = new HashMap[String, Object]
values.put("recipient", "A. Nadie")
val rendered = new StringWriter
try template.evaluate(rendered, values)
catch {
case e: PebbleException =>
e.printStackTrace
}
val letter = rendered.toString
}
@throws[IOException]
@throws[PebbleException]
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.
References
-
OWASP Top 10 2025 - A05 : Injection.