Improper limitation of a pathname to a restricted directory ('Path Traversal')

ID

scala.file.scala_file_rule_filenameutils

Severity

low

Resource

File

Language

Scala

Description

A file is opened to read its content. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read.

Rationale

A file is opened to read its content. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read.

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

def main(args: Array[String]): Unit = {
  val maliciousPath = "/test%00/././../../././secret/note.cfg\u0000example.jpg"
  testPath(maliciousPath)
}

@throws[IOException]
private def testPath(maliciousPath: String): Unit = {
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  val path = normalize(maliciousPath)
  System.out.println("Expected:" + path + " -> Actual:" + canonical(path))
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  val extension = getExtension(maliciousPath)
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  System.out.println("Expected:" + extension + " -> Actual:" + getExtension(canonical(path)))
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  val isExt = isExtension(maliciousPath, "jpg")
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  System.out.println("Expected:" + isExt + " -> Actual:" + isExtension(canonical(path), "jpg"))
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  val name = getName(maliciousPath)
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  System.out.println("Expected:" + name + " -> Actual:" + getName(canonical(name)))
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  val baseName = getBaseName(maliciousPath)
  // VULNERABLE: Improper limitation of a pathname to a restricted directory ('Path Traversal')
  System.out.println("Expected:" + baseName + " -> Actual:" + getBaseName(canonical(baseName)))
}

Remediation

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

Configuration

This detector does not need any configuration.

References