security.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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.altsep] if sep is not None and sep != "/"
  11. )
  12. # https://chrisdenton.github.io/omnipath/Special%20Dos%20Device%20Names.html
  13. _windows_device_files = {
  14. "AUX",
  15. "CON",
  16. "CONIN$",
  17. "CONOUT$",
  18. *(f"COM{c}" for c in "123456789¹²³"),
  19. *(f"LPT{c}" for c in "123456789¹²³"),
  20. "NUL",
  21. "PRN",
  22. }
  23. def gen_salt(length: int) -> str:
  24. """Generate a random string of SALT_CHARS with specified ``length``."""
  25. if length <= 0:
  26. raise ValueError("Salt length must be at least 1.")
  27. return "".join(secrets.choice(SALT_CHARS) for _ in range(length))
  28. def _hash_internal(method: str, salt: str, password: str) -> tuple[str, str]:
  29. method, *args = method.split(":")
  30. salt_bytes = salt.encode()
  31. password_bytes = password.encode()
  32. # Security note: If the method contains args, they came from a stored,
  33. # trusted hash previously generated by generate_password_hash. An attacker
  34. # who could modify them can already compromise the entire application.
  35. if method == "scrypt":
  36. if not args:
  37. n = 2**15
  38. r = 8
  39. p = 1
  40. else:
  41. try:
  42. n, r, p = map(int, args)
  43. except ValueError:
  44. raise ValueError("'scrypt' takes 3 arguments.") from None
  45. maxmem = 132 * n * r * p # ideally 128, but some extra seems needed
  46. return (
  47. hashlib.scrypt(
  48. password_bytes, salt=salt_bytes, n=n, r=r, p=p, maxmem=maxmem
  49. ).hex(),
  50. f"scrypt:{n}:{r}:{p}",
  51. )
  52. elif method == "pbkdf2":
  53. len_args = len(args)
  54. if len_args == 0:
  55. hash_name = "sha256"
  56. iterations = DEFAULT_PBKDF2_ITERATIONS
  57. elif len_args == 1:
  58. hash_name = args[0]
  59. iterations = DEFAULT_PBKDF2_ITERATIONS
  60. elif len_args == 2:
  61. hash_name = args[0]
  62. iterations = int(args[1])
  63. else:
  64. raise ValueError("'pbkdf2' takes 2 arguments.")
  65. return (
  66. hashlib.pbkdf2_hmac(
  67. hash_name, password_bytes, salt_bytes, iterations
  68. ).hex(),
  69. f"pbkdf2:{hash_name}:{iterations}",
  70. )
  71. else:
  72. raise ValueError(f"Invalid hash method '{method}'.")
  73. def generate_password_hash(
  74. password: str, method: str = "scrypt", salt_length: int = 16
  75. ) -> str:
  76. """Securely hash a password for storage. A password can be compared to a stored hash
  77. using :func:`check_password_hash`.
  78. The following methods are supported:
  79. - ``scrypt``, the default. The parameters are ``n``, ``r``, and ``p``, the default
  80. is ``scrypt:32768:8:1``. See :func:`hashlib.scrypt`.
  81. - ``pbkdf2``, less secure. The parameters are ``hash_method`` and ``iterations``,
  82. the default is ``pbkdf2:sha256:600000``. See :func:`hashlib.pbkdf2_hmac`.
  83. Default parameters may be updated to reflect current guidelines, and methods may be
  84. deprecated and removed if they are no longer considered secure. To migrate old
  85. hashes, you may generate a new hash when checking an old hash, or you may contact
  86. users with a link to reset their password.
  87. :param password: The plaintext password.
  88. :param method: The key derivation function and parameters.
  89. :param salt_length: The number of characters to generate for the salt.
  90. .. versionchanged:: 3.1
  91. The default iterations for pbkdf2 was increased to 1,000,000.
  92. .. versionchanged:: 2.3
  93. Scrypt support was added.
  94. .. versionchanged:: 2.3
  95. The default iterations for pbkdf2 was increased to 600,000.
  96. .. versionchanged:: 2.3
  97. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  98. """
  99. salt = gen_salt(salt_length)
  100. h, actual_method = _hash_internal(method, salt, password)
  101. return f"{actual_method}${salt}${h}"
  102. def check_password_hash(pwhash: str, password: str) -> bool:
  103. """Securely check that the given stored password hash, previously generated using
  104. :func:`generate_password_hash`, matches the given password.
  105. Methods may be deprecated and removed if they are no longer considered secure. To
  106. migrate old hashes, you may generate a new hash when checking an old hash, or you
  107. may contact users with a link to reset their password.
  108. :param pwhash: The hashed password.
  109. :param password: The plaintext password.
  110. .. versionchanged:: 2.3
  111. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  112. """
  113. try:
  114. method, salt, hashval = pwhash.split("$", 2)
  115. except ValueError:
  116. return False
  117. return hmac.compare_digest(_hash_internal(method, salt, password)[0], hashval)
  118. def safe_join(directory: str, *untrusted: str) -> str | None:
  119. """Safely join zero or more untrusted path components to a trusted base
  120. directory to avoid escaping the base directory. Return ``None`` if the path
  121. is not safe.
  122. The untrusted path is assumed to be from/for a URL, such as for serving
  123. files. Therefore, it should only use the forward slash ``/`` path separator,
  124. and will be joined using that separator. On Windows, the backslash ``\\``
  125. separator is not allowed.
  126. This only considers the path name, it does not validate if it does or does
  127. not exist, if it is a symlink, or other properties of the file or
  128. filesystem. It's up to the application to ensure that the contents of
  129. ``directory`` can be trusted.
  130. On Windows, special device names such as ``CON`` and ``NUL`` are not
  131. allowed, as this is used for serving files with :func:`.send_from_directory`
  132. and those files will hang when read.
  133. NTFS alternate data streams (ADS) like ``filename:stream`` are
  134. allowed. :func:`.secure_filename` will remove the ``:`` when saving.
  135. :param directory: The trusted base directory.
  136. :param untrusted: The untrusted path components relative to the
  137. base directory.
  138. :return: A safe path, otherwise ``None``.
  139. .. versionchanged:: 3.1.9
  140. Special device names with empty ADS stream markers are not allowed on
  141. Windows.
  142. .. versionchanged:: 3.1.6
  143. Special device names in multi-segment paths are not allowed on Windows.
  144. .. versionchanged:: 3.1.5
  145. More special device names, regardless of extension or trailing spaces,
  146. are not allowed on Windows.
  147. .. versionchanged:: 3.1.4
  148. Special device names are not allowed on Windows.
  149. """
  150. if not directory:
  151. # Ensure we end up with ./path if directory="" is given,
  152. # otherwise the first untrusted part could become trusted.
  153. directory = "."
  154. parts = [directory]
  155. for part in untrusted:
  156. if not part:
  157. continue
  158. part = posixpath.normpath(part)
  159. if (
  160. os.path.isabs(part)
  161. # ntpath.isabs doesn't catch this
  162. or part.startswith("/")
  163. or part == ".."
  164. or part.startswith("../")
  165. or any(sep in part for sep in _os_alt_seps)
  166. or (
  167. os.name == "nt"
  168. and any(
  169. p.partition(":")[0].partition(".")[0].strip().upper()
  170. in _windows_device_files
  171. for p in part.split("/")
  172. )
  173. )
  174. ):
  175. return None
  176. parts.append(part)
  177. return posixpath.join(*parts)