Improper Control of Generation of Code ('Code Injection')

ID

scala.script.scala_script_rule_spelview

Severity

high

Resource

Script

Language

Scala

Description

The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.

Rationale

The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.

The following code illustrates a vulnerable pattern detected by this rule:

abstract class SpelView(val template: String) extends View {
  var resolver: PlaceholderResolver
  final private val parser = new SpelExpressionParser()
  final private val context = new StandardEvaluationContext()

  this.context.addPropertyAccessor(new MapAccessor())
  this.resolver = (name: String) => {
      // VULNERABLE: Improper Control of Generation of Code ('Code Injection')
      val expression = parser.parseExpression(name) //BOOM!
      val value = expression.getValue(context)
      null
  }
  override def getContentType = "text/html"

  @throws[Exception]
  def render(model: java.util.Map[String, _], request: HttpServletRequest, response: HttpServletResponse): Unit = {
    val path = ServletUriComponentsBuilder.fromContextPath(request).build.getPath
    context.setRootObject(model)
    val helper = new PropertyPlaceholderHelper("${", "}")
    val result = helper.replacePlaceholders(template, resolver)
    response.setContentType(getContentType)
    response.getWriter.append(result)
  }
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

References