pathutils.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # This file is part of Radicale Server - Calendar Server
  2. #
  3. # This library is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This library is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  15. """
  16. Helper functions for working with paths.
  17. """
  18. import os
  19. import posixpath
  20. from . import log
  21. def sanitize_path(path):
  22. """Make path absolute with leading slash to prevent access to other data.
  23. Preserve a potential trailing slash.
  24. """
  25. trailing_slash = "/" if path.endswith("/") else ""
  26. path = posixpath.normpath(path)
  27. new_path = "/"
  28. for part in path.split("/"):
  29. if not part or part in (".", ".."):
  30. continue
  31. new_path = posixpath.join(new_path, part)
  32. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  33. return new_path + trailing_slash
  34. def is_safe_path_component(path):
  35. """Check if path is a single component of a POSIX path.
  36. Check that the path is safe to join too.
  37. """
  38. if not path:
  39. return False
  40. if posixpath.split(path)[0]:
  41. return False
  42. if path in (".", ".."):
  43. return False
  44. return True
  45. def is_safe_filesystem_path_component(path):
  46. """Check if path is a single component of a filesystem path.
  47. Check that the path is safe to join too.
  48. """
  49. if not path:
  50. return False
  51. drive, _ = os.path.splitdrive(path)
  52. if drive:
  53. return False
  54. head, _ = os.path.split(path)
  55. if head:
  56. return False
  57. if path in (os.curdir, os.pardir):
  58. return False
  59. return True
  60. def path_to_filesystem(path, base_folder):
  61. """Convert path to a local filesystem path relative to base_folder.
  62. Conversion is done in a secure manner, or raises ``ValueError``.
  63. """
  64. sane_path = sanitize_path(path).strip("/")
  65. safe_path = base_folder
  66. if not sane_path:
  67. return safe_path
  68. for part in sane_path.split("/"):
  69. if not is_safe_filesystem_path_component(part):
  70. log.LOGGER.debug(
  71. "Can't translate path safely to filesystem: %s", path)
  72. raise ValueError("Unsafe path")
  73. safe_path = os.path.join(safe_path, part)
  74. return safe_path