From 74b105657ffbd1d1de80455f03446c3bbf30d1f5 Mon Sep 17 00:00:00 2001
From: Mark Thomas <markt@apache.org>
Date: Wed, 20 Jan 2021 13:28:57 +0000
Subject: [PATCH] Use consistent approach for sub-directory checking

---
 .../catalina/servlets/DefaultServlet.java     |  3 +-
 .../apache/catalina/session/FileStore.java    |  4 +-
 .../catalina/startup/ContextConfig.java       |  3 +-
 .../apache/catalina/startup/ExpandWar.java    | 21 +++-----
 .../apache/catalina/startup/HostConfig.java   |  5 +-
 java/org/apache/catalina/util/FileUtil.java   | 50 +++++++++++++++++++
 webapps/docs/changelog.xml                    |  4 ++
 7 files changed, 71 insertions(+), 19 deletions(-)
 create mode 100644 java/org/apache/catalina/util/FileUtil.java
 
 
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/servlets/DefaultServlet.java
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/java/org/apache/catalina/servlets/DefaultServlet.java
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/servlets/DefaultServlet.java
@@ -61,6 +61,7 @@ import javax.xml.transform.stream.Stream
 
 import org.apache.catalina.Globals;
 import org.apache.catalina.connector.RequestFacade;
+import org.apache.catalina.util.FileUtil;
 import org.apache.catalina.core.ApplicationFilterFactory;
 import org.apache.catalina.util.RequestUtil;
 import org.apache.catalina.util.ServerInfo;
@@ -1701,7 +1702,7 @@ public class DefaultServlet
 
         // First check that the resulting path is under the provided base
         try {
-            if (!candidate.getCanonicalPath().startsWith(base.getCanonicalPath())) {
+            if (!(new FileUtil(base)).isParentOf(candidate)) {
                 return null;
             }
         } catch (IOException ioe) {
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/session/FileStore.java
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/java/org/apache/catalina/session/FileStore.java
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/session/FileStore.java
@@ -32,6 +32,7 @@ import org.apache.catalina.Context;
 import org.apache.catalina.Globals;
 import org.apache.catalina.Loader;
 import org.apache.catalina.Session;
+import org.apache.catalina.util.FileUtil;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.util.res.StringManager;
@@ -400,9 +401,10 @@ public final class FileStore extends Sto
 
         String filename = id + FILE_EXT;
         File file = new File(storageDir, filename);
+        FileUtil storageDirUtil = new FileUtil(storageDir);
 
         // Check the file is within the storage directory
-        if (!file.getCanonicalPath().startsWith(storageDir.getCanonicalPath())) {
+        if (!storageDirUtil.isParentOf(file)) {
             log.warn(sm.getString("fileStore.invalid", file.getPath(), id));
             return null;
         }
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ContextConfig.java
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ContextConfig.java
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ContextConfig.java
@@ -49,6 +49,7 @@ import org.apache.catalina.deploy.Filter
 import org.apache.catalina.deploy.LoginConfig;
 import org.apache.catalina.deploy.SecurityConstraint;
 import org.apache.catalina.util.StringManager;
+import org.apache.catalina.util.FileUtil;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.util.descriptor.DigesterFactory;
@@ -912,7 +913,7 @@ public class ContextConfig implements Li
             }
         }
 
-        if (docBase.startsWith(canonicalAppBase.getPath() + File.separatorChar)) {
+        if ((new FileUtil(canonicalAppBase)).isParentOf(docBase)) {
             docBase = docBase.substring(canonicalAppBase.getPath().length());
             docBase = docBase.replace(File.separatorChar, '/');
             if (docBase.startsWith("/")) {
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ExpandWar.java
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ExpandWar.java
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/ExpandWar.java
@@ -32,6 +32,7 @@ import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 
 import org.apache.catalina.Host;
+import org.apache.catalina.util.FileUtil;
 import org.apache.catalina.util.StringManager;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
@@ -136,10 +137,7 @@ public class ExpandWar {
             throw new IOException(sm.getString("expandWar.createFailed", docBase));
 
         // Expand the WAR into the new document base directory
-        String canonicalDocBasePrefix = docBase.getCanonicalPath();
-        if (!canonicalDocBasePrefix.endsWith(File.separator)) {
-            canonicalDocBasePrefix += File.separator;
-        }
+        FileUtil docBaseUtil = new FileUtil(docBase);
         JarURLConnection juc = (JarURLConnection) war.openConnection();
         juc.setUseCaches(false);
         JarFile jarFile = null;
@@ -152,12 +150,13 @@ public class ExpandWar {
                 JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
                 String name = jarEntry.getName();
                 File expandedFile = new File(docBase, name);
-                if (!expandedFile.getCanonicalPath().startsWith(
-                        canonicalDocBasePrefix)) {
+                if (!docBaseUtil.isParentOf(expandedFile)) {
                     // Trying to expand outside the docBase
                     // Throw an exception to stop the deployment
                     throw new IllegalArgumentException(
-                            sm.getString("expandWar.illegalPath",war, name));
+                            sm.getString("expandWar.illegalPath",war, name,
+                                    expandedFile.getCanonicalPath(),
+                                    docBaseUtil.getCanonicalPath()));
                 }
                 int last = name.lastIndexOf('/');
                 if (last >= 0) {
@@ -241,10 +240,7 @@ public class ExpandWar {
         File docBase = new File(appBase, pathname);
 
         // Calculate the document base directory
-        String canonicalDocBasePrefix = docBase.getCanonicalPath();
-        if (!canonicalDocBasePrefix.endsWith(File.separator)) {
-            canonicalDocBasePrefix += File.separator;
-        }
+        FileUtil docBaseUtil = new FileUtil(docBase);
         JarURLConnection juc = (JarURLConnection) war.openConnection();
         juc.setUseCaches(false);
         JarFile jarFile = null;
@@ -255,12 +251,13 @@ public class ExpandWar {
                 JarEntry jarEntry = jarEntries.nextElement();
                 String name = jarEntry.getName();
                 File expandedFile = new File(docBase, name);
-                if (!expandedFile.getCanonicalPath().startsWith(
-                        canonicalDocBasePrefix)) {
+                if (!docBaseUtil.isParentOf(expandedFile)) {
                     // Entry located outside the docBase
                     // Throw an exception to stop the deployment
                     throw new IllegalArgumentException(
-                            sm.getString("expandWar.illegalPath",war, name));
+                            sm.getString("expandWar.illegalPath",war, name,
+                                    expandedFile.getCanonicalPath(),
+                                    docBaseUtil.getCanonicalPath()));
                 }
             }
         } catch (IOException e) {
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/HostConfig.java
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/HostConfig.java
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/startup/HostConfig.java
@@ -41,6 +41,7 @@ import javax.management.ObjectName;
 
 import org.apache.catalina.Container;
 import org.apache.catalina.Context;
+import org.apache.catalina.util.FileUtil;
 import org.apache.catalina.Engine;
 import org.apache.catalina.Host;
 import org.apache.catalina.Lifecycle;
@@ -656,8 +657,8 @@ public class HostConfig
                     docBase = new File(appBase(), context.getDocBase());
                 }
                 // If external docBase, register .xml as redeploy first
-                if (!docBase.getCanonicalPath().startsWith(
-                        appBase().getAbsolutePath() + File.separator)) {
+                FileUtil appBaseUtil = new FileUtil(appBase());
+                if (!appBaseUtil.isParentOf(docBase)) {
                     isExternal = true;
                     deployedApp.redeployResources.put
                         (contextXml.getAbsolutePath(), new Long(contextXml.lastModified()));
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/util/FileUtil.java
===================================================================
--- /dev/null
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/java/org/apache/catalina/util/FileUtil.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.catalina.util;
+
+import java.io.File;
+import java.io.IOException;
+
+public class FileUtil {
+
+    private final String canonicalPath;
+
+    public FileUtil(File f) throws IOException {
+        String path = f.getCanonicalPath();
+        if (!path.endsWith(File.pathSeparator)) {
+            path += File.pathSeparatorChar;
+        }
+
+        canonicalPath = path;
+    }
+
+
+    public String getCanonicalPath() {
+        return canonicalPath;
+    }
+
+
+    public boolean isParentOf(File child) throws IOException {
+        return isParentOf(child.getCanonicalPath());
+    }
+
+
+    public boolean isParentOf(String childPath) {
+        return childPath.startsWith(canonicalPath);
+    }
+}                         
Index: tomcat6-6.0.53/apache-tomcat-6.0.53-src/webapps/docs/changelog.xml
===================================================================
--- tomcat6-6.0.53.orig/apache-tomcat-6.0.53-src/webapps/docs/changelog.xml
+++ tomcat6-6.0.53/apache-tomcat-6.0.53-src/webapps/docs/changelog.xml
@@ -6863,6 +6863,10 @@
   </subsection>
   <subsection name="Catalina">
     <changelog>
+      <scode>
+        Test for one directory being a sub-directory of another in a consistent
+        way. (markt)
+      </scode>
       <add>
         <bug>64871</bug>: Log a warning if Tomcat blocks access to a file
         because it uses symlinks. (markt)
