security.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import hashlib
  2. import hmac
  3. import os
  4. import posixpath
  5. import secrets
  6. import typing as t
  7. if t.TYPE_CHECKING:
  8. pass
  9. SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  10. DEFAULT_PBKDF2_ITERATIONS = 260000
  11. _os_alt_seps: t.List[str] = list(
  12. sep for sep in [os.path.sep, os.path.altsep] if sep is not None and sep != "/"
  13. )
  14. def gen_salt(length: int) -> str:
  15. """Generate a random string of SALT_CHARS with specified ``length``."""
  16. if length <= 0:
  17. raise ValueError("Salt length must be positive")
  18. return "".join(secrets.choice(SALT_CHARS) for _ in range(length))
  19. def _hash_internal(method: str, salt: str, password: str) -> t.Tuple[str, str]:
  20. """Internal password hash helper. Supports plaintext without salt,
  21. unsalted and salted passwords. In case salted passwords are used
  22. hmac is used.
  23. """
  24. if method == "plain":
  25. return password, method
  26. salt = salt.encode("utf-8")
  27. password = password.encode("utf-8")
  28. if method.startswith("pbkdf2:"):
  29. if not salt:
  30. raise ValueError("Salt is required for PBKDF2")
  31. args = method[7:].split(":")
  32. if len(args) not in (1, 2):
  33. raise ValueError("Invalid number of arguments for PBKDF2")
  34. method = args.pop(0)
  35. iterations = int(args[0] or 0) if args else DEFAULT_PBKDF2_ITERATIONS
  36. return (
  37. hashlib.pbkdf2_hmac(method, password, salt, iterations).hex(),
  38. f"pbkdf2:{method}:{iterations}",
  39. )
  40. if salt:
  41. return hmac.new(salt, password, method).hexdigest(), method
  42. return hashlib.new(method, password).hexdigest(), method
  43. def generate_password_hash(
  44. password: str, method: str = "pbkdf2:sha256", salt_length: int = 16
  45. ) -> str:
  46. """Hash a password with the given method and salt with a string of
  47. the given length. The format of the string returned includes the method
  48. that was used so that :func:`check_password_hash` can check the hash.
  49. The format for the hashed string looks like this::
  50. method$salt$hash
  51. This method can **not** generate unsalted passwords but it is possible
  52. to set param method='plain' in order to enforce plaintext passwords.
  53. If a salt is used, hmac is used internally to salt the password.
  54. If PBKDF2 is wanted it can be enabled by setting the method to
  55. ``pbkdf2:method:iterations`` where iterations is optional::
  56. pbkdf2:sha256:80000$salt$hash
  57. pbkdf2:sha256$salt$hash
  58. :param password: the password to hash.
  59. :param method: the hash method to use (one that hashlib supports). Can
  60. optionally be in the format ``pbkdf2:method:iterations``
  61. to enable PBKDF2.
  62. :param salt_length: the length of the salt in letters.
  63. """
  64. salt = gen_salt(salt_length) if method != "plain" else ""
  65. h, actual_method = _hash_internal(method, salt, password)
  66. return f"{actual_method}${salt}${h}"
  67. def check_password_hash(pwhash: str, password: str) -> bool:
  68. """Check a password against a given salted and hashed password value.
  69. In order to support unsalted legacy passwords this method supports
  70. plain text passwords, md5 and sha1 hashes (both salted and unsalted).
  71. Returns `True` if the password matched, `False` otherwise.
  72. :param pwhash: a hashed string like returned by
  73. :func:`generate_password_hash`.
  74. :param password: the plaintext password to compare against the hash.
  75. """
  76. if pwhash.count("$") < 2:
  77. return False
  78. method, salt, hashval = pwhash.split("$", 2)
  79. return hmac.compare_digest(_hash_internal(method, salt, password)[0], hashval)
  80. def safe_join(directory: str, *pathnames: str) -> t.Optional[str]:
  81. """Safely join zero or more untrusted path components to a base
  82. directory to avoid escaping the base directory.
  83. :param directory: The trusted base directory.
  84. :param pathnames: The untrusted path components relative to the
  85. base directory.
  86. :return: A safe path, otherwise ``None``.
  87. """
  88. if not directory:
  89. # Ensure we end up with ./path if directory="" is given,
  90. # otherwise the first untrusted part could become trusted.
  91. directory = "."
  92. parts = [directory]
  93. for filename in pathnames:
  94. if filename != "":
  95. filename = posixpath.normpath(filename)
  96. if (
  97. any(sep in filename for sep in _os_alt_seps)
  98. or os.path.isabs(filename)
  99. or filename == ".."
  100. or filename.startswith("../")
  101. ):
  102. return None
  103. parts.append(filename)
  104. return posixpath.join(*parts)