pathutils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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_path_component(path):
  36. """Checks if path is a single component of a path and is safe to join"""
  37. if not path:
  38. return False
  39. head, _ = posixpath.split(path)
  40. if head:
  41. return False
  42. if path in (".", ".."):
  43. return False
  44. return True
  45. def is_safe_filesystem_path_component(path):
  46. """Checks if path is a single component of a local filesystem path
  47. and is safe to join"""
  48. if not path:
  49. return False
  50. drive, _ = os.path.splitdrive(path)
  51. if drive:
  52. return False
  53. head, _ = os.path.split(path)
  54. if head:
  55. return False
  56. if path in (os.curdir, os.pardir):
  57. return False
  58. return True
  59. def path_to_filesystem(path, base_folder):
  60. """Converts path to a local filesystem path relative to base_folder
  61. in a secure manner or raises ValueError."""
  62. sane_path = sanitize_path(path).strip("/")
  63. safe_path = base_folder
  64. if not sane_path:
  65. return safe_path
  66. for part in sane_path.split("/"):
  67. if not is_safe_filesystem_path_component(part):
  68. log.LOGGER.debug("Can't translate path safely to filesystem: %s",
  69. path)
  70. raise ValueError("Unsafe path")
  71. safe_path = os.path.join(safe_path, part)
  72. return safe_path