View Javadoc

1   package com.atlassian.core.util.zip;
2   
3   import com.google.common.annotations.VisibleForTesting;
4   import org.apache.commons.lang.StringUtils;
5   
6   /**
7    * Utilities to cleanup file path
8    *
9    * @since v4.6.13
10   */
11  class FilePathUtils
12  {
13      /**
14       * Returns the sanitised path (protection against path traversal attacks JDEV-24536, JDEV-24537)
15       *
16       * @param path string to sanitise
17       */
18      @VisibleForTesting
19      static String stripSlashes(final String path)
20      {
21          String result = path;
22          result = result.replaceAll("\\\\", "/");// Replaces all backslashes with slashes
23          result = result.replaceAll("(/)+", "/"); // Replaces multiple slashes with a single slash
24          result = result.replaceAll("(\\.){2,}+/", ""); // Replaces 2 and more (e.g. ../) dots followed by a slash
25          result = result.replaceAll("(\\./)", ""); // Replaces current directories (./)
26          if (StringUtils.startsWith(result, "/"))
27          {
28              result = StringUtils.substring(result, 1);
29          }
30          if (StringUtils.endsWith(result, "/"))
31          {
32              result = StringUtils.substring(result, 0, result.length() - 1);
33          }
34          return result;
35      }
36  }