Link Search Menu Expand Document

Unrestricted File Upload in Scala

Vulnerable example

In the example below, the filename is user controlled. It could be possible to store the file in a different location from the one intended by the application. The logic does not perform checks on the file type, thus allowing any type of file to be uploaded.

def uploadFile(
  request: Request[MultipartFormData[TemporaryFile]],
  filename: String
): String = {
  request.body
    .file("file")
    .map { file =>
      val currentDirectory = new File(".").getCanonicalPath()
      file.ref.moveTo(new File(currentDirectory + s"/uploads/$filename"))

      // ...
    }
    .getOrElse {
      // ...
    }
}

Prevention

Ensure the user cannot manipulate the upload path, for example use java.io.File.getName() to obtain the file name, i.e., without additional path elements, and use this value to build the path. For example new File("../../../../file.ext").getName() yields file.ext.

val safeFilename = new File(filename).getName()
file.ref.moveTo(new File(currentDirectory + s"/uploads/$safeFilename"))

Also optionally implement a check based on the file contents, and also ensure all uploaded files are scanned with an antivirus solution.

References

OWASP - FileUpload