Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8259637

java.io.File.getCanonicalPath() returns different values for same path

    XMLWordPrintable

    Details

    • Subcomponent:
    • CPU:
      x86_64
    • OS:
      linux_ubuntu

      Description

      ADDITIONAL SYSTEM INFORMATION :
      Ubuntu 18.04
      JDK 8
      JDK 11

      A DESCRIPTION OF THE PROBLEM :
      When using getCanonicalPath() function I've noticed that if I put a directory name in the middle of the path I want to canonicalize, it's possible to get a canonical path starting with /../

      This may lead to confussion to users when using getCanonicalPath function if they use it to validate paths, since users would never assume a canonical path can start with /../

      Imagine I want to avoid someone could read anything under /etc folder in my system within a java application, and I create a filter which reads a path entered by the user, let's say ../../../../../etc/hosts and canonicalize it to check if starts with "/etc". If the user input is /../../../../../a/../../etc/hosts, getCanonicalPath funtion will return /../etc/hosts, which won't match my filter and would allow the user to read my /etc/hosts file.

      I really think it's assumed by everybody that a Canonical Path will never contain ".." so I don't understand this weird behaviour in the getCanonicalPath function

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      String path = "/../../../../../a/../../etc/hosts";
      String canPath = new File(path).getCanonicalPath();
      System.out.println(canPath);

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      /etc/hosts
      ACTUAL -
      /../etc/hosts

      ---------- BEGIN SOURCE ----------
      import java.io.File;
      import java.io.IOException;

      public class CanonicalTest {
          public static void main(String args[])
          {
              try {
                  String path = "/../../../../../a/../../etc/hosts";
                  String canPath = new File(path).getCanonicalPath();
                  System.out.println(canPath);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Activity

            People

            Assignee:
            bpb Brian Burkhalter
            Reporter:
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated: