security.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. from __future__ import annotations
  2. import hashlib
  3. import hmac
  4. import os
  5. import posixpath
  6. import secrets
  7. SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  8. DEFAULT_PBKDF2_ITERATIONS = 1_000_000
  9. _os_alt_seps: list[str] = list(
  10. sep for sep in [os.sep, os.path.altsep] if sep is not None and sep != "/"
  11. )
  12. def gen_salt(length: int) -> str:
  13. """Generate a random string of SALT_CHARS with specified ``length``."""
  14. if length <= 0:
  15. raise ValueError("Salt length must be at least 1.")
  16. return "".join(secrets.choice(SALT_CHARS) for _ in range(length))
  17. def _hash_internal(method: str, salt: str, password: str) -> tuple[str, str]:
  18. method, *args = method.split(":")
  19. salt_bytes = salt.encode()
  20. password_bytes = password.encode()
  21. if method == "scrypt":
  22. if not args:
  23. n = 2**15
  24. r = 8
  25. p = 1
  26. else:
  27. try:
  28. n, r, p = map(int, args)
  29. except ValueError:
  30. raise ValueError("'scrypt' takes 3 arguments.") from None
  31. maxmem = 132 * n * r * p # ideally 128, but some extra seems needed
  32. return (
  33. hashlib.scrypt(
  34. password_bytes, salt=salt_bytes, n=n, r=r, p=p, maxmem=maxmem
  35. ).hex(),
  36. f"scrypt:{n}:{r}:{p}",
  37. )
  38. elif method == "pbkdf2":
  39. len_args = len(args)
  40. if len_args == 0:
  41. hash_name = "sha256"
  42. iterations = DEFAULT_PBKDF2_ITERATIONS
  43. elif len_args == 1:
  44. hash_name = args[0]
  45. iterations = DEFAULT_PBKDF2_ITERATIONS
  46. elif len_args == 2:
  47. hash_name = args[0]
  48. iterations = int(args[1])
  49. else:
  50. raise ValueError("'pbkdf2' takes 2 arguments.")
  51. return (
  52. hashlib.pbkdf2_hmac(
  53. hash_name, password_bytes, salt_bytes, iterations
  54. ).hex(),
  55. f"pbkdf2:{hash_name}:{iterations}",
  56. )
  57. else:
  58. raise ValueError(f"Invalid hash method '{method}'.")
  59. def generate_password_hash(
  60. password: str, method: str = "scrypt", salt_length: int = 16
  61. ) -> str:
  62. """Securely hash a password for storage. A password can be compared to a stored hash
  63. using :func:`check_password_hash`.
  64. The following methods are supported:
  65. - ``scrypt``, the default. The parameters are ``n``, ``r``, and ``p``, the default
  66. is ``scrypt:32768:8:1``. See :func:`hashlib.scrypt`.
  67. - ``pbkdf2``, less secure. The parameters are ``hash_method`` and ``iterations``,
  68. the default is ``pbkdf2:sha256:600000``. See :func:`hashlib.pbkdf2_hmac`.
  69. Default parameters may be updated to reflect current guidelines, and methods may be
  70. deprecated and removed if they are no longer considered secure. To migrate old
  71. hashes, you may generate a new hash when checking an old hash, or you may contact
  72. users with a link to reset their password.
  73. :param password: The plaintext password.
  74. :param method: The key derivation function and parameters.
  75. :param salt_length: The number of characters to generate for the salt.
  76. .. versionchanged:: 3.1
  77. The default iterations for pbkdf2 was increased to 1,000,000.
  78. .. versionchanged:: 2.3
  79. Scrypt support was added.
  80. .. versionchanged:: 2.3
  81. The default iterations for pbkdf2 was increased to 600,000.
  82. .. versionchanged:: 2.3
  83. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  84. """
  85. salt = gen_salt(salt_length)
  86. h, actual_method = _hash_internal(method, salt, password)
  87. return f"{actual_method}${salt}${h}"
  88. def check_password_hash(pwhash: str, password: str) -> bool:
  89. """Securely check that the given stored password hash, previously generated using
  90. :func:`generate_password_hash`, matches the given password.
  91. Methods may be deprecated and removed if they are no longer considered secure. To
  92. migrate old hashes, you may generate a new hash when checking an old hash, or you
  93. may contact users with a link to reset their password.
  94. :param pwhash: The hashed password.
  95. :param password: The plaintext password.
  96. .. versionchanged:: 2.3
  97. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  98. """
  99. try:
  100. method, salt, hashval = pwhash.split("$", 2)
  101. except ValueError:
  102. return False
  103. return hmac.compare_digest(_hash_internal(method, salt, password)[0], hashval)
  104. def safe_join(directory: str, *pathnames: str) -> str | None:
  105. """Safely join zero or more untrusted path components to a base
  106. directory to avoid escaping the base directory.
  107. :param directory: The trusted base directory.
  108. :param pathnames: The untrusted path components relative to the
  109. base directory.
  110. :return: A safe path, otherwise ``None``.
  111. """
  112. if not directory:
  113. # Ensure we end up with ./path if directory="" is given,
  114. # otherwise the first untrusted part could become trusted.
  115. directory = "."
  116. parts = [directory]
  117. for filename in pathnames:
  118. if filename != "":
  119. filename = posixpath.normpath(filename)
  120. if (
  121. any(sep in filename for sep in _os_alt_seps)
  122. or os.path.isabs(filename)
  123. # ntpath.isabs doesn't catch this on Python < 3.11
  124. or filename.startswith("/")
  125. or filename == ".."
  126. or filename.startswith("../")
  127. ):
  128. return None
  129. parts.append(filename)
  130. return posixpath.join(*parts)