security.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 = 600000
  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 = salt.encode()
  20. password = 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(password, salt=salt, n=n, r=r, p=p, maxmem=maxmem).hex(),
  34. f"scrypt:{n}:{r}:{p}",
  35. )
  36. elif method == "pbkdf2":
  37. len_args = len(args)
  38. if len_args == 0:
  39. hash_name = "sha256"
  40. iterations = DEFAULT_PBKDF2_ITERATIONS
  41. elif len_args == 1:
  42. hash_name = args[0]
  43. iterations = DEFAULT_PBKDF2_ITERATIONS
  44. elif len_args == 2:
  45. hash_name = args[0]
  46. iterations = int(args[1])
  47. else:
  48. raise ValueError("'pbkdf2' takes 2 arguments.")
  49. return (
  50. hashlib.pbkdf2_hmac(hash_name, password, salt, iterations).hex(),
  51. f"pbkdf2:{hash_name}:{iterations}",
  52. )
  53. else:
  54. raise ValueError(f"Invalid hash method '{method}'.")
  55. def generate_password_hash(
  56. password: str, method: str = "scrypt", salt_length: int = 16
  57. ) -> str:
  58. """Securely hash a password for storage. A password can be compared to a stored hash
  59. using :func:`check_password_hash`.
  60. The following methods are supported:
  61. - ``scrypt``, the default. The parameters are ``n``, ``r``, and ``p``, the default
  62. is ``scrypt:32768:8:1``. See :func:`hashlib.scrypt`.
  63. - ``pbkdf2``, less secure. The parameters are ``hash_method`` and ``iterations``,
  64. the default is ``pbkdf2:sha256:600000``. See :func:`hashlib.pbkdf2_hmac`.
  65. Default parameters may be updated to reflect current guidelines, and methods may be
  66. deprecated and removed if they are no longer considered secure. To migrate old
  67. hashes, you may generate a new hash when checking an old hash, or you may contact
  68. users with a link to reset their password.
  69. :param password: The plaintext password.
  70. :param method: The key derivation function and parameters.
  71. :param salt_length: The number of characters to generate for the salt.
  72. .. versionchanged:: 2.3
  73. Scrypt support was added.
  74. .. versionchanged:: 2.3
  75. The default iterations for pbkdf2 was increased to 600,000.
  76. .. versionchanged:: 2.3
  77. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  78. """
  79. salt = gen_salt(salt_length)
  80. h, actual_method = _hash_internal(method, salt, password)
  81. return f"{actual_method}${salt}${h}"
  82. def check_password_hash(pwhash: str, password: str) -> bool:
  83. """Securely check that the given stored password hash, previously generated using
  84. :func:`generate_password_hash`, matches the given password.
  85. Methods may be deprecated and removed if they are no longer considered secure. To
  86. migrate old hashes, you may generate a new hash when checking an old hash, or you
  87. may contact users with a link to reset their password.
  88. :param pwhash: The hashed password.
  89. :param password: The plaintext password.
  90. .. versionchanged:: 2.3
  91. All plain hashes are deprecated and will not be supported in Werkzeug 3.0.
  92. """
  93. try:
  94. method, salt, hashval = pwhash.split("$", 2)
  95. except ValueError:
  96. return False
  97. return hmac.compare_digest(_hash_internal(method, salt, password)[0], hashval)
  98. def safe_join(directory: str, *pathnames: str) -> str | None:
  99. """Safely join zero or more untrusted path components to a base
  100. directory to avoid escaping the base directory.
  101. :param directory: The trusted base directory.
  102. :param pathnames: The untrusted path components relative to the
  103. base directory.
  104. :return: A safe path, otherwise ``None``.
  105. """
  106. if not directory:
  107. # Ensure we end up with ./path if directory="" is given,
  108. # otherwise the first untrusted part could become trusted.
  109. directory = "."
  110. parts = [directory]
  111. for filename in pathnames:
  112. if filename != "":
  113. filename = posixpath.normpath(filename)
  114. if (
  115. any(sep in filename for sep in _os_alt_seps)
  116. or os.path.isabs(filename)
  117. or filename == ".."
  118. or filename.startswith("../")
  119. ):
  120. return None
  121. parts.append(filename)
  122. return posixpath.join(*parts)