2012-08-09 22:25:35 +08:00
|
|
|
import base64
|
2013-03-26 23:44:26 +08:00
|
|
|
import binascii
|
2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
2011-12-23 11:53:56 +08:00
|
|
|
import hashlib
|
2013-07-29 21:50:58 +08:00
|
|
|
import importlib
|
2016-02-14 04:09:46 +08:00
|
|
|
import warnings
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.signals import setting_changed
|
|
|
|
from django.dispatch import receiver
|
|
|
|
from django.utils.crypto import (
|
|
|
|
constant_time_compare, get_random_string, pbkdf2,
|
|
|
|
)
|
2014-01-21 04:15:14 +08:00
|
|
|
from django.utils.module_loading import import_string
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_noop as _
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2013-06-19 02:02:00 +08:00
|
|
|
UNUSABLE_PASSWORD_PREFIX = '!' # This will never be a valid encoded hash
|
|
|
|
UNUSABLE_PASSWORD_SUFFIX_LENGTH = 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX
|
2012-05-01 02:35:04 +08:00
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def is_password_usable(encoded):
|
2018-03-21 05:19:27 +08:00
|
|
|
"""
|
|
|
|
Return True if this password wasn't generated by
|
|
|
|
User.set_unusable_password(), i.e. make_password(None).
|
|
|
|
"""
|
|
|
|
return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
def check_password(password, encoded, setter=None, preferred='default'):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Return a boolean of whether the raw password matches the three
|
2011-12-23 11:53:56 +08:00
|
|
|
part encoded digest.
|
|
|
|
|
|
|
|
If setter is specified, it'll be called when you need to
|
|
|
|
regenerate the password.
|
|
|
|
"""
|
2013-07-04 01:13:47 +08:00
|
|
|
if password is None or not is_password_usable(encoded):
|
2011-12-23 11:53:56 +08:00
|
|
|
return False
|
|
|
|
|
|
|
|
preferred = get_hasher(preferred)
|
2018-03-21 05:19:27 +08:00
|
|
|
try:
|
|
|
|
hasher = identify_hasher(encoded)
|
|
|
|
except ValueError:
|
|
|
|
# encoded is gibberish or uses a hasher that's no longer installed.
|
|
|
|
return False
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
hasher_changed = hasher.algorithm != preferred.algorithm
|
|
|
|
must_update = hasher_changed or preferred.must_update(encoded)
|
2011-12-23 11:53:56 +08:00
|
|
|
is_correct = hasher.verify(password, encoded)
|
2016-02-14 04:09:46 +08:00
|
|
|
|
|
|
|
# If the hasher didn't change (we don't protect against enumeration if it
|
|
|
|
# does) and the password should get updated, try to close the timing gap
|
|
|
|
# between the work factor of the current encoded password and the default
|
|
|
|
# work factor.
|
|
|
|
if not is_correct and not hasher_changed and must_update:
|
|
|
|
hasher.harden_runtime(password, encoded)
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
if setter and is_correct and must_update:
|
2012-06-06 16:53:16 +08:00
|
|
|
setter(password)
|
2011-12-23 11:53:56 +08:00
|
|
|
return is_correct
|
|
|
|
|
|
|
|
|
|
|
|
def make_password(password, salt=None, hasher='default'):
|
|
|
|
"""
|
|
|
|
Turn a plain-text password into a hash for database storage
|
|
|
|
|
2017-01-25 04:31:57 +08:00
|
|
|
Same as encode() but generate a new random salt. If password is None then
|
|
|
|
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
|
|
|
|
which disallows logins. Additional random string reduces chances of gaining
|
|
|
|
access to staff or superuser accounts. See ticket #20079 for more info.
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
2013-06-18 00:06:26 +08:00
|
|
|
if password is None:
|
2013-06-19 02:02:00 +08:00
|
|
|
return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
|
2020-03-26 20:23:32 +08:00
|
|
|
if not isinstance(password, (bytes, str)):
|
|
|
|
raise TypeError(
|
|
|
|
'Password must be a string or bytes, got %s.'
|
|
|
|
% type(password).__qualname__
|
|
|
|
)
|
2011-12-23 11:53:56 +08:00
|
|
|
hasher = get_hasher(hasher)
|
2018-01-04 07:52:12 +08:00
|
|
|
salt = salt or hasher.salt()
|
2011-12-23 11:53:56 +08:00
|
|
|
return hasher.encode(password, salt)
|
|
|
|
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache()
|
2014-11-19 04:45:12 +08:00
|
|
|
def get_hashers():
|
2011-12-23 11:53:56 +08:00
|
|
|
hashers = []
|
2014-11-19 04:45:12 +08:00
|
|
|
for hasher_path in settings.PASSWORD_HASHERS:
|
|
|
|
hasher_cls = import_string(hasher_path)
|
|
|
|
hasher = hasher_cls()
|
2011-12-23 11:53:56 +08:00
|
|
|
if not getattr(hasher, 'algorithm'):
|
|
|
|
raise ImproperlyConfigured("hasher doesn't specify an "
|
2014-11-19 04:45:12 +08:00
|
|
|
"algorithm name: %s" % hasher_path)
|
2011-12-23 11:53:56 +08:00
|
|
|
hashers.append(hasher)
|
2014-11-19 04:45:12 +08:00
|
|
|
return hashers
|
|
|
|
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache()
|
2014-11-19 04:45:12 +08:00
|
|
|
def get_hashers_by_algorithm():
|
|
|
|
return {hasher.algorithm: hasher for hasher in get_hashers()}
|
|
|
|
|
|
|
|
|
|
|
|
@receiver(setting_changed)
|
|
|
|
def reset_hashers(**kwargs):
|
|
|
|
if kwargs['setting'] == 'PASSWORD_HASHERS':
|
|
|
|
get_hashers.cache_clear()
|
|
|
|
get_hashers_by_algorithm.cache_clear()
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
def get_hasher(algorithm='default'):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Return an instance of a loaded password hasher.
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2017-01-25 04:31:57 +08:00
|
|
|
If algorithm is 'default', return the default hasher. Lazily import hashers
|
|
|
|
specified in the project's settings file if needed.
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
|
|
|
if hasattr(algorithm, 'algorithm'):
|
|
|
|
return algorithm
|
|
|
|
|
|
|
|
elif algorithm == 'default':
|
2014-11-19 04:45:12 +08:00
|
|
|
return get_hashers()[0]
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
else:
|
2014-11-19 04:45:12 +08:00
|
|
|
hashers = get_hashers_by_algorithm()
|
|
|
|
try:
|
|
|
|
return hashers[algorithm]
|
|
|
|
except KeyError:
|
2011-12-23 11:53:56 +08:00
|
|
|
raise ValueError("Unknown password hashing algorithm '%s'. "
|
|
|
|
"Did you specify it in the PASSWORD_HASHERS "
|
|
|
|
"setting?" % algorithm)
|
|
|
|
|
|
|
|
|
2012-06-06 17:06:33 +08:00
|
|
|
def identify_hasher(encoded):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Return an instance of a loaded password hasher.
|
2012-06-06 17:06:33 +08:00
|
|
|
|
2017-01-25 04:31:57 +08:00
|
|
|
Identify hasher algorithm by examining encoded hash, and call
|
|
|
|
get_hasher() to return hasher. Raise ValueError if
|
2012-06-06 17:06:33 +08:00
|
|
|
algorithm cannot be identified, or if hasher is not loaded.
|
|
|
|
"""
|
2013-02-26 03:01:57 +08:00
|
|
|
# Ancient versions of Django created plain MD5 passwords and accepted
|
|
|
|
# MD5 passwords with an empty salt.
|
2013-02-02 18:57:25 +08:00
|
|
|
if ((len(encoded) == 32 and '$' not in encoded) or
|
2013-02-02 19:13:32 +08:00
|
|
|
(len(encoded) == 37 and encoded.startswith('md5$$'))):
|
2012-06-06 17:06:33 +08:00
|
|
|
algorithm = 'unsalted_md5'
|
2013-02-26 03:01:57 +08:00
|
|
|
# Ancient versions of Django accepted SHA1 passwords with an empty salt.
|
|
|
|
elif len(encoded) == 46 and encoded.startswith('sha1$$'):
|
|
|
|
algorithm = 'unsalted_sha1'
|
2012-06-06 17:06:33 +08:00
|
|
|
else:
|
|
|
|
algorithm = encoded.split('$', 1)[0]
|
|
|
|
return get_hasher(algorithm)
|
|
|
|
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
def mask_hash(hash, show=6, char="*"):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Return the given hash, with only the first ``show`` number shown. The
|
2011-12-23 11:53:56 +08:00
|
|
|
rest are masked with ``char`` for security reasons.
|
|
|
|
"""
|
|
|
|
masked = hash[:show]
|
|
|
|
masked += char * len(hash[show:])
|
|
|
|
return masked
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BasePasswordHasher:
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
|
|
|
Abstract base class for password hashers
|
|
|
|
|
|
|
|
When creating your own hasher, you need to override algorithm,
|
|
|
|
verify(), encode() and safe_summary().
|
|
|
|
|
|
|
|
PasswordHasher objects are immutable.
|
|
|
|
"""
|
|
|
|
algorithm = None
|
|
|
|
library = None
|
|
|
|
|
|
|
|
def _load_library(self):
|
|
|
|
if self.library is not None:
|
|
|
|
if isinstance(self.library, (tuple, list)):
|
|
|
|
name, mod_path = self.library
|
|
|
|
else:
|
2013-08-05 00:17:10 +08:00
|
|
|
mod_path = self.library
|
2011-12-23 11:53:56 +08:00
|
|
|
try:
|
|
|
|
module = importlib.import_module(mod_path)
|
2013-06-14 22:19:53 +08:00
|
|
|
except ImportError as e:
|
|
|
|
raise ValueError("Couldn't load %r algorithm library: %s" %
|
|
|
|
(self.__class__.__name__, e))
|
2011-12-23 11:53:56 +08:00
|
|
|
return module
|
2013-06-14 22:19:53 +08:00
|
|
|
raise ValueError("Hasher %r doesn't specify a library attribute" %
|
|
|
|
self.__class__.__name__)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def salt(self):
|
2017-01-25 04:31:57 +08:00
|
|
|
"""Generate a cryptographically secure nonce salt in ASCII."""
|
2020-03-11 16:47:43 +08:00
|
|
|
# 12 returns a 71-bit value, log_2((26+26+10)^12) =~ 71 bits
|
|
|
|
return get_random_string(12)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def verify(self, password, encoded):
|
2017-01-25 04:31:57 +08:00
|
|
|
"""Check if the given password is correct."""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def encode(self, password, salt):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Create an encoded database value.
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
The result is normally formatted as "algorithm$salt$hash" and
|
|
|
|
must be fewer than 128 characters.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method')
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
|
|
|
"""
|
|
|
|
Return a decoded database value.
|
|
|
|
|
|
|
|
The result is a dictionary and should contain `algorithm`, `hash`, and
|
|
|
|
`salt`. Extra keys can be algorithm specific like `iterations` or
|
|
|
|
`work_factor`.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError(
|
|
|
|
'subclasses of BasePasswordHasher must provide a decode() method.'
|
|
|
|
)
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
def safe_summary(self, encoded):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Return a summary of safe values.
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
The result is a dictionary and will be used where the password field
|
|
|
|
must be displayed to construct a safe representation of the password.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method')
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2013-09-25 02:52:20 +08:00
|
|
|
def must_update(self, encoded):
|
|
|
|
return False
|
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
"""
|
|
|
|
Bridge the runtime gap between the work factor supplied in `encoded`
|
|
|
|
and the work factor suggested by this hasher.
|
|
|
|
|
|
|
|
Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
|
|
|
|
`self.iterations` is 30000, this method should run password through
|
|
|
|
another 10000 iterations of PBKDF2. Similar approaches should exist
|
|
|
|
for any hasher that has a work factor. If not, this method should be
|
|
|
|
defined as a no-op to silence the warning.
|
|
|
|
"""
|
|
|
|
warnings.warn('subclasses of BasePasswordHasher should provide a harden_runtime() method')
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
class PBKDF2PasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
|
|
|
Secure password hashing using the PBKDF2 algorithm (recommended)
|
|
|
|
|
2015-02-21 05:37:03 +08:00
|
|
|
Configured to use PBKDF2 + HMAC + SHA256.
|
2011-12-23 11:53:56 +08:00
|
|
|
The result is a 64 byte binary string. Iterations may be changed
|
|
|
|
safely but you must rename the algorithm if you change SHA256.
|
|
|
|
"""
|
|
|
|
algorithm = "pbkdf2_sha256"
|
2020-05-04 18:19:16 +08:00
|
|
|
iterations = 260000
|
2011-12-23 11:53:56 +08:00
|
|
|
digest = hashlib.sha256
|
|
|
|
|
|
|
|
def encode(self, password, salt, iterations=None):
|
2013-06-18 00:06:26 +08:00
|
|
|
assert password is not None
|
2011-12-23 11:53:56 +08:00
|
|
|
assert salt and '$' not in salt
|
2018-01-04 07:52:12 +08:00
|
|
|
iterations = iterations or self.iterations
|
2011-12-23 11:53:56 +08:00
|
|
|
hash = pbkdf2(password, salt, iterations, digest=self.digest)
|
2012-08-11 06:18:33 +08:00
|
|
|
hash = base64.b64encode(hash).decode('ascii').strip()
|
2011-12-23 11:53:56 +08:00
|
|
|
return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
|
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
2011-12-23 11:53:56 +08:00
|
|
|
algorithm, iterations, salt, hash = encoded.split('$', 3)
|
|
|
|
assert algorithm == self.algorithm
|
2020-04-07 04:14:17 +08:00
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'hash': hash,
|
|
|
|
'iterations': int(iterations),
|
|
|
|
'salt': salt,
|
|
|
|
}
|
|
|
|
|
|
|
|
def verify(self, password, encoded):
|
|
|
|
decoded = self.decode(encoded)
|
|
|
|
encoded_2 = self.encode(password, decoded['salt'], decoded['iterations'])
|
2011-12-23 11:53:56 +08:00
|
|
|
return constant_time_compare(encoded, encoded_2)
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('iterations'): decoded['iterations'],
|
|
|
|
_('salt'): mask_hash(decoded['salt']),
|
|
|
|
_('hash'): mask_hash(decoded['hash']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2013-09-25 02:52:20 +08:00
|
|
|
def must_update(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
|
|
|
return decoded['iterations'] != self.iterations
|
2013-09-25 02:52:20 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
|
|
|
extra_iterations = self.iterations - decoded['iterations']
|
2016-02-14 04:09:46 +08:00
|
|
|
if extra_iterations > 0:
|
2020-04-07 04:14:17 +08:00
|
|
|
self.encode(password, decoded['salt'], extra_iterations)
|
2016-02-14 04:09:46 +08:00
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
|
|
|
|
"""
|
|
|
|
Alternate PBKDF2 hasher which uses SHA1, the default PRF
|
|
|
|
recommended by PKCS #5. This is compatible with other
|
|
|
|
implementations of PBKDF2, such as openssl's
|
|
|
|
PKCS5_PBKDF2_HMAC_SHA1().
|
|
|
|
"""
|
|
|
|
algorithm = "pbkdf2_sha1"
|
|
|
|
digest = hashlib.sha1
|
|
|
|
|
|
|
|
|
2015-12-26 20:14:07 +08:00
|
|
|
class Argon2PasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
|
|
|
Secure password hashing using the argon2 algorithm.
|
|
|
|
|
|
|
|
This is the winner of the Password Hashing Competition 2013-2015
|
|
|
|
(https://password-hashing.net). It requires the argon2-cffi library which
|
|
|
|
depends on native C code and might cause portability issues.
|
|
|
|
"""
|
|
|
|
algorithm = 'argon2'
|
|
|
|
library = 'argon2'
|
|
|
|
|
|
|
|
time_cost = 2
|
2020-06-17 14:07:10 +08:00
|
|
|
memory_cost = 102400
|
|
|
|
parallelism = 8
|
2015-12-26 20:14:07 +08:00
|
|
|
|
|
|
|
def encode(self, password, salt):
|
|
|
|
argon2 = self._load_library()
|
2020-06-17 13:46:45 +08:00
|
|
|
params = self.params()
|
2015-12-26 20:14:07 +08:00
|
|
|
data = argon2.low_level.hash_secret(
|
2018-02-02 01:36:21 +08:00
|
|
|
password.encode(),
|
|
|
|
salt.encode(),
|
2020-06-17 13:46:45 +08:00
|
|
|
time_cost=params.time_cost,
|
|
|
|
memory_cost=params.memory_cost,
|
|
|
|
parallelism=params.parallelism,
|
|
|
|
hash_len=params.hash_len,
|
|
|
|
type=params.type,
|
2015-12-26 20:14:07 +08:00
|
|
|
)
|
2016-08-04 22:57:37 +08:00
|
|
|
return self.algorithm + data.decode('ascii')
|
2015-12-26 20:14:07 +08:00
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
|
|
|
argon2 = self._load_library()
|
|
|
|
algorithm, rest = encoded.split('$', 1)
|
|
|
|
assert algorithm == self.algorithm
|
|
|
|
params = argon2.extract_parameters('$' + rest)
|
|
|
|
variety, *_, salt, hash = rest.split('$')
|
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'hash': hash,
|
|
|
|
'memory_cost': params.memory_cost,
|
|
|
|
'parallelism': params.parallelism,
|
|
|
|
'salt': salt,
|
|
|
|
'time_cost': params.time_cost,
|
|
|
|
'variety': variety,
|
|
|
|
'version': params.version,
|
|
|
|
}
|
|
|
|
|
2015-12-26 20:14:07 +08:00
|
|
|
def verify(self, password, encoded):
|
|
|
|
argon2 = self._load_library()
|
2016-04-22 19:26:41 +08:00
|
|
|
algorithm, rest = encoded.split('$', 1)
|
2015-12-26 20:14:07 +08:00
|
|
|
assert algorithm == self.algorithm
|
|
|
|
try:
|
2020-06-17 13:46:45 +08:00
|
|
|
return argon2.PasswordHasher().verify('$' + rest, password)
|
2015-12-26 20:14:07 +08:00
|
|
|
except argon2.exceptions.VerificationError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('variety'): decoded['variety'],
|
|
|
|
_('version'): decoded['version'],
|
|
|
|
_('memory cost'): decoded['memory_cost'],
|
|
|
|
_('time cost'): decoded['time_cost'],
|
|
|
|
_('parallelism'): decoded['parallelism'],
|
|
|
|
_('salt'): mask_hash(decoded['salt']),
|
|
|
|
_('hash'): mask_hash(decoded['hash']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2015-12-26 20:14:07 +08:00
|
|
|
|
|
|
|
def must_update(self, encoded):
|
2020-06-17 13:46:45 +08:00
|
|
|
algorithm, rest = encoded.split('$', 1)
|
2015-12-26 20:14:07 +08:00
|
|
|
assert algorithm == self.algorithm
|
2016-04-22 19:26:41 +08:00
|
|
|
argon2 = self._load_library()
|
2020-06-17 13:46:45 +08:00
|
|
|
current_params = argon2.extract_parameters('$' + rest)
|
|
|
|
new_params = self.params()
|
|
|
|
# Set salt_len to the salt_len of the current parameters because salt
|
|
|
|
# is explicitly passed to argon2.
|
|
|
|
new_params.salt_len = current_params.salt_len
|
|
|
|
return current_params != new_params
|
2015-12-26 20:14:07 +08:00
|
|
|
|
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
# The runtime for Argon2 is too complicated to implement a sensible
|
|
|
|
# hardening algorithm.
|
|
|
|
pass
|
|
|
|
|
2020-06-17 13:46:45 +08:00
|
|
|
def params(self):
|
|
|
|
argon2 = self._load_library()
|
|
|
|
# salt_len is a noop, because we provide our own salt.
|
|
|
|
return argon2.Parameters(
|
2020-06-17 14:07:10 +08:00
|
|
|
type=argon2.low_level.Type.ID,
|
2020-06-17 13:46:45 +08:00
|
|
|
version=argon2.low_level.ARGON2_VERSION,
|
|
|
|
salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH,
|
|
|
|
hash_len=argon2.DEFAULT_HASH_LENGTH,
|
|
|
|
time_cost=self.time_cost,
|
|
|
|
memory_cost=self.memory_cost,
|
|
|
|
parallelism=self.parallelism,
|
|
|
|
)
|
|
|
|
|
2015-12-26 20:14:07 +08:00
|
|
|
|
2013-03-26 23:44:26 +08:00
|
|
|
class BCryptSHA256PasswordHasher(BasePasswordHasher):
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
|
|
|
Secure password hashing using the bcrypt algorithm (recommended)
|
|
|
|
|
|
|
|
This is considered by many to be the most secure algorithm but you
|
2013-05-14 11:39:50 +08:00
|
|
|
must first install the bcrypt library. Please be warned that
|
2011-12-23 11:53:56 +08:00
|
|
|
this library depends on native C code and might cause portability
|
|
|
|
issues.
|
|
|
|
"""
|
2013-03-26 23:44:26 +08:00
|
|
|
algorithm = "bcrypt_sha256"
|
|
|
|
digest = hashlib.sha256
|
2013-05-14 11:39:50 +08:00
|
|
|
library = ("bcrypt", "bcrypt")
|
2011-12-23 11:53:56 +08:00
|
|
|
rounds = 12
|
|
|
|
|
|
|
|
def salt(self):
|
|
|
|
bcrypt = self._load_library()
|
2016-01-02 19:44:06 +08:00
|
|
|
return bcrypt.gensalt(self.rounds)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def encode(self, password, salt):
|
|
|
|
bcrypt = self._load_library()
|
2018-02-02 01:36:21 +08:00
|
|
|
password = password.encode()
|
2016-02-12 00:57:12 +08:00
|
|
|
# Hash the password prior to using bcrypt to prevent password
|
|
|
|
# truncation as described in #20138.
|
2013-03-26 23:44:26 +08:00
|
|
|
if self.digest is not None:
|
2017-01-26 02:59:25 +08:00
|
|
|
# Use binascii.hexlify() because a hex encoded bytestring is str.
|
2018-02-02 01:36:21 +08:00
|
|
|
password = binascii.hexlify(self.digest(password).digest())
|
2013-03-26 23:44:26 +08:00
|
|
|
|
|
|
|
data = bcrypt.hashpw(password, salt)
|
2018-02-02 01:36:21 +08:00
|
|
|
return "%s$%s" % (self.algorithm, data.decode('ascii'))
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
|
|
|
algorithm, empty, algostr, work_factor, data = encoded.split('$', 4)
|
|
|
|
assert algorithm == self.algorithm
|
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'algostr': algostr,
|
|
|
|
'checksum': data[22:],
|
|
|
|
'salt': data[:22],
|
|
|
|
'work_factor': int(work_factor),
|
|
|
|
}
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
def verify(self, password, encoded):
|
|
|
|
algorithm, data = encoded.split('$', 1)
|
|
|
|
assert algorithm == self.algorithm
|
2018-02-02 01:36:21 +08:00
|
|
|
encoded_2 = self.encode(password, data.encode('ascii'))
|
2016-02-14 04:09:46 +08:00
|
|
|
return constant_time_compare(encoded, encoded_2)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('work factor'): decoded['work_factor'],
|
|
|
|
_('salt'): mask_hash(decoded['salt']),
|
|
|
|
_('checksum'): mask_hash(decoded['checksum']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2015-02-27 03:04:24 +08:00
|
|
|
def must_update(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
|
|
|
return decoded['work_factor'] != self.rounds
|
2015-02-27 03:04:24 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
_, data = encoded.split('$', 1)
|
|
|
|
salt = data[:29] # Length of the salt in bcrypt.
|
|
|
|
rounds = data.split('$')[2]
|
|
|
|
# work factor is logarithmic, adding one doubles the load.
|
|
|
|
diff = 2**(self.rounds - int(rounds)) - 1
|
|
|
|
while diff > 0:
|
2018-02-02 01:36:21 +08:00
|
|
|
self.encode(password, salt.encode('ascii'))
|
2016-02-14 04:09:46 +08:00
|
|
|
diff -= 1
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2013-03-26 23:44:26 +08:00
|
|
|
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
|
|
|
|
"""
|
|
|
|
Secure password hashing using the bcrypt algorithm
|
|
|
|
|
|
|
|
This is considered by many to be the most secure algorithm but you
|
2013-05-14 11:39:50 +08:00
|
|
|
must first install the bcrypt library. Please be warned that
|
2013-03-26 23:44:26 +08:00
|
|
|
this library depends on native C code and might cause portability
|
|
|
|
issues.
|
|
|
|
|
|
|
|
This hasher does not first hash the password which means it is subject to
|
2018-02-26 22:12:46 +08:00
|
|
|
bcrypt's 72 bytes password truncation. Most use cases should prefer the
|
|
|
|
BCryptSHA256PasswordHasher.
|
2013-03-26 23:44:26 +08:00
|
|
|
"""
|
|
|
|
algorithm = "bcrypt"
|
|
|
|
digest = None
|
|
|
|
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
class SHA1PasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
|
|
|
The SHA1 password hashing algorithm (not recommended)
|
|
|
|
"""
|
|
|
|
algorithm = "sha1"
|
|
|
|
|
|
|
|
def encode(self, password, salt):
|
2013-06-18 00:06:26 +08:00
|
|
|
assert password is not None
|
2011-12-23 11:53:56 +08:00
|
|
|
assert salt and '$' not in salt
|
2018-02-02 01:36:21 +08:00
|
|
|
hash = hashlib.sha1((salt + password).encode()).hexdigest()
|
2011-12-23 11:53:56 +08:00
|
|
|
return "%s$%s$%s" % (self.algorithm, salt, hash)
|
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
2011-12-23 11:53:56 +08:00
|
|
|
algorithm, salt, hash = encoded.split('$', 2)
|
|
|
|
assert algorithm == self.algorithm
|
2020-04-07 04:14:17 +08:00
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'hash': hash,
|
|
|
|
'salt': salt,
|
|
|
|
}
|
|
|
|
|
|
|
|
def verify(self, password, encoded):
|
|
|
|
decoded = self.decode(encoded)
|
|
|
|
encoded_2 = self.encode(password, decoded['salt'])
|
2011-12-23 11:53:56 +08:00
|
|
|
return constant_time_compare(encoded, encoded_2)
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('salt'): mask_hash(decoded['salt'], show=2),
|
|
|
|
_('hash'): mask_hash(decoded['hash']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
pass
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
class MD5PasswordHasher(BasePasswordHasher):
|
2012-03-01 04:12:16 +08:00
|
|
|
"""
|
|
|
|
The Salted MD5 password hashing algorithm (not recommended)
|
|
|
|
"""
|
|
|
|
algorithm = "md5"
|
|
|
|
|
|
|
|
def encode(self, password, salt):
|
2013-06-18 00:06:26 +08:00
|
|
|
assert password is not None
|
2012-03-01 04:12:16 +08:00
|
|
|
assert salt and '$' not in salt
|
2018-02-02 01:36:21 +08:00
|
|
|
hash = hashlib.md5((salt + password).encode()).hexdigest()
|
2012-03-01 04:12:16 +08:00
|
|
|
return "%s$%s$%s" % (self.algorithm, salt, hash)
|
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
2012-03-01 04:12:16 +08:00
|
|
|
algorithm, salt, hash = encoded.split('$', 2)
|
|
|
|
assert algorithm == self.algorithm
|
2020-04-07 04:14:17 +08:00
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'hash': hash,
|
|
|
|
'salt': salt,
|
|
|
|
}
|
|
|
|
|
|
|
|
def verify(self, password, encoded):
|
|
|
|
decoded = self.decode(encoded)
|
|
|
|
encoded_2 = self.encode(password, decoded['salt'])
|
2012-03-01 04:12:16 +08:00
|
|
|
return constant_time_compare(encoded, encoded_2)
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('salt'): mask_hash(decoded['salt'], show=2),
|
|
|
|
_('hash'): mask_hash(decoded['hash']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2012-03-01 04:12:16 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
pass
|
|
|
|
|
2012-03-01 04:12:16 +08:00
|
|
|
|
2013-02-26 03:01:57 +08:00
|
|
|
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Very insecure algorithm that you should *never* use; store SHA1 hashes
|
2013-02-26 03:01:57 +08:00
|
|
|
with an empty salt.
|
|
|
|
|
|
|
|
This class is implemented because Django used to accept such password
|
|
|
|
hashes. Some older Django installs still have these values lingering
|
|
|
|
around so we need to handle and upgrade them properly.
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
2013-02-26 03:01:57 +08:00
|
|
|
algorithm = "unsalted_sha1"
|
|
|
|
|
|
|
|
def salt(self):
|
|
|
|
return ''
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2013-02-26 03:01:57 +08:00
|
|
|
def encode(self, password, salt):
|
|
|
|
assert salt == ''
|
2018-02-02 01:36:21 +08:00
|
|
|
hash = hashlib.sha1(password.encode()).hexdigest()
|
2013-02-26 03:01:57 +08:00
|
|
|
return 'sha1$$%s' % hash
|
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
|
|
|
assert encoded.startswith('sha1$$')
|
|
|
|
return {
|
|
|
|
'algorithm': self.algorithm,
|
|
|
|
'hash': encoded[6:],
|
|
|
|
'salt': None,
|
|
|
|
}
|
|
|
|
|
2013-02-26 03:01:57 +08:00
|
|
|
def verify(self, password, encoded):
|
|
|
|
encoded_2 = self.encode(password, '')
|
|
|
|
return constant_time_compare(encoded, encoded_2)
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('hash'): mask_hash(decoded['hash']),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2013-02-26 03:01:57 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
pass
|
|
|
|
|
2013-02-26 03:01:57 +08:00
|
|
|
|
|
|
|
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
|
|
|
Incredibly insecure algorithm that you should *never* use; stores unsalted
|
|
|
|
MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an
|
|
|
|
empty salt.
|
|
|
|
|
|
|
|
This class is implemented because Django used to store passwords this way
|
|
|
|
and to accept such password hashes. Some older Django installs still have
|
|
|
|
these values lingering around so we need to handle and upgrade them
|
|
|
|
properly.
|
2011-12-23 11:53:56 +08:00
|
|
|
"""
|
2012-03-01 04:12:16 +08:00
|
|
|
algorithm = "unsalted_md5"
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def salt(self):
|
|
|
|
return ''
|
|
|
|
|
|
|
|
def encode(self, password, salt):
|
2013-02-26 03:01:57 +08:00
|
|
|
assert salt == ''
|
2018-02-02 01:36:21 +08:00
|
|
|
return hashlib.md5(password.encode()).hexdigest()
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2020-04-07 04:14:17 +08:00
|
|
|
def decode(self, encoded):
|
|
|
|
return {
|
|
|
|
'algorithm': self.algorithm,
|
|
|
|
'hash': encoded,
|
|
|
|
'salt': None,
|
|
|
|
}
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
def verify(self, password, encoded):
|
2013-02-02 18:57:25 +08:00
|
|
|
if len(encoded) == 37 and encoded.startswith('md5$$'):
|
|
|
|
encoded = encoded[5:]
|
2011-12-23 11:53:56 +08:00
|
|
|
encoded_2 = self.encode(password, '')
|
|
|
|
return constant_time_compare(encoded, encoded_2)
|
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('hash'): mask_hash(decoded['hash'], show=3),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2011-12-23 11:53:56 +08:00
|
|
|
|
2016-02-14 04:09:46 +08:00
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
pass
|
|
|
|
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
class CryptPasswordHasher(BasePasswordHasher):
|
|
|
|
"""
|
|
|
|
Password hashing using UNIX crypt (not recommended)
|
|
|
|
|
|
|
|
The crypt module is not supported on all platforms.
|
|
|
|
"""
|
|
|
|
algorithm = "crypt"
|
|
|
|
library = "crypt"
|
|
|
|
|
|
|
|
def salt(self):
|
|
|
|
return get_random_string(2)
|
|
|
|
|
|
|
|
def encode(self, password, salt):
|
|
|
|
crypt = self._load_library()
|
|
|
|
assert len(salt) == 2
|
2020-04-07 04:14:17 +08:00
|
|
|
hash = crypt.crypt(password, salt)
|
|
|
|
assert hash is not None # A platform like OpenBSD with a dummy crypt module.
|
2011-12-23 11:53:56 +08:00
|
|
|
# we don't need to store the salt, but Django used to do this
|
2020-04-07 04:14:17 +08:00
|
|
|
return '%s$%s$%s' % (self.algorithm, '', hash)
|
|
|
|
|
|
|
|
def decode(self, encoded):
|
|
|
|
algorithm, salt, hash = encoded.split('$', 2)
|
|
|
|
assert algorithm == self.algorithm
|
|
|
|
return {
|
|
|
|
'algorithm': algorithm,
|
|
|
|
'hash': hash,
|
|
|
|
'salt': salt,
|
|
|
|
}
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def verify(self, password, encoded):
|
|
|
|
crypt = self._load_library()
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
|
|
|
data = crypt.crypt(password, decoded['hash'])
|
|
|
|
return constant_time_compare(decoded['hash'], data)
|
2011-12-23 11:53:56 +08:00
|
|
|
|
|
|
|
def safe_summary(self, encoded):
|
2020-04-07 04:14:17 +08:00
|
|
|
decoded = self.decode(encoded)
|
2019-02-05 19:22:08 +08:00
|
|
|
return {
|
2020-04-07 04:14:17 +08:00
|
|
|
_('algorithm'): decoded['algorithm'],
|
|
|
|
_('salt'): decoded['salt'],
|
|
|
|
_('hash'): mask_hash(decoded['hash'], show=3),
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2016-02-14 04:09:46 +08:00
|
|
|
|
|
|
|
def harden_runtime(self, password, encoded):
|
|
|
|
pass
|