pathutils.py 2.3 KB

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