Djangoにおけるパスワード管理

パスワード管理は一般的に、不必要に再発明されるべきではないものです。Djangoはユーザーのパスワードを管理するための安全で柔軟なツールセットを提供するよう努めています。このドキュメントでは、Djangoがパスワードを保存する方法、ストレージハッシュの設定方法、およびハッシュされたパスワードを扱ういくつかのユーティリティについて説明します。

参考

ユーザーが強力なパスワードを使ったとしても、攻撃者が通信経路上において盗聴をおこなう可能性があります。パスワード(または他の機密データ)がプレーンなHTTP接続で送信されないように、 HTTPS を使用してください。なぜなら、HTTPはパスワードスニッフィングに対して脆弱であるからです。

Djangoのパスワード保存方法

DjangoはデフォルトでPBKDF2を利用した、柔軟なパスワード保存システムを提供します。

The password attribute of a User object is a string in this format:

<algorithm>$<iterations>$<salt>$<hash>

これらはユーザーのパスワードを保存するためのコンポーネントで、ハッシュアルゴリズム、アルゴリズムのイテレーション回数(ワークファクター)、ランダムなソルト、そして結果のパスワードハッシュをドル記号($)で区切ったものです。このアルゴリズムは、Djangoが使用できる数多くの一方向ハッシュ、またはパスワード保存アルゴリズム(下記参照)の一つです。イテレーションはハッシュに対してアルゴリズムが実行された回数を表します。ソルトは使用されたランダムシードで、ハッシュは一方向ハッシュ関数の実行結果です。

デフォルトでは、Djangoは NIST が推奨するパスワードストレッチングメカニズムである PBKDF2 アルゴリズムと SHA256 ハッシュを使用します。これはほとんどのユーザーに十分有効なはずです。非常に安全で、クラックするのに膨大な計算時間を必要とします。

ただし、要件に応じて、異なるアルゴリズムを使用することも、一部のセキュリティ状況に合わせてカスタムアルゴリズムを使用することもできます。繰り返しますが、ほとんどのユーザーはこれを行う必要はありません。よくわからない場合、おそらくそうしないほうが良いです。もしそうする場合は、こちらをお読みください:

Djangoは PASSWORD_HASHERS 設定に基づき、使用するアルゴリズムを選択します。これは、Djangoインストールがサポートするハッシュアルゴリズムクラスのリストです。このリストの最初のエントリ(つまり、 settings.PASSWORD_HASHERS[0] )がパスワードの保存に使用され、他の全てのエントリは、既に存在するパスワードの検証に使用できる有効性検証ハッシャです。つまり、他のアルゴリズムを使用したい場合は PASSWORD_HASHERS を修正して、使用したいアルゴリズムをリストの最初にする必要があります。

デフォルトでの PASSWORD_HASHERS

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.ScryptPasswordHasher',
]

これは、Djangoは PBKDF2 を使用して全てのパスワードを保存しますが、PBKDF2SHA1、 argon2 、および bcrypt で保存されたパスワードのチェックもサポートすることを意味しています。

次のいくつかのセクションでは、高度なユーザーがこの設定を変更するための一般的な方法について説明します。

Using Argon2 with Django

Argon2 is the winner of the 2015 Password Hashing Competition, a community organized open competition to select a next generation hashing algorithm. It's designed not to be easier to compute on custom hardware than it is to compute on an ordinary CPU.

Argon2 is not the default for Django because it requires a third-party library. The Password Hashing Competition panel, however, recommends immediate use of Argon2 rather than the other algorithms supported by Django.

To use Argon2 as your default storage algorithm, do the following:

  1. Install the argon2-cffi library. This can be done by running python -m pip install django[argon2], which is equivalent to python -m pip install argon2-cffi (along with any version requirement from Django's setup.cfg).

  2. Modify PASSWORD_HASHERS to list Argon2PasswordHasher first. That is, in your settings file, you'd put:

    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.Argon2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
        'django.contrib.auth.hashers.ScryptPasswordHasher',
    ]
    

    Keep and/or add any entries in this list if you need Django to upgrade passwords.

Using bcrypt with Django

Bcrypt is a popular password storage algorithm that's specifically designed for long-term password storage. It's not the default used by Django since it requires the use of third-party libraries, but since many people may want to use it Django supports bcrypt with minimal effort.

To use Bcrypt as your default storage algorithm, do the following:

  1. Install the bcrypt library. This can be done by running python -m pip install django[bcrypt], which is equivalent to python -m pip install bcrypt (along with any version requirement from Django's setup.cfg).

  2. Modify PASSWORD_HASHERS to list BCryptSHA256PasswordHasher first. That is, in your settings file, you'd put:

    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
        'django.contrib.auth.hashers.Argon2PasswordHasher',
        'django.contrib.auth.hashers.ScryptPasswordHasher',
    ]
    

    Keep and/or add any entries in this list if you need Django to upgrade passwords.

That's it -- now your Django install will use Bcrypt as the default storage algorithm.

Using scrypt with Django

New in Django 4.0.

scrypt is similar to PBKDF2 and bcrypt in utilizing a set number of iterations to slow down brute-force attacks. However, because PBKDF2 and bcrypt do not require a lot of memory, attackers with sufficient resources can launch large-scale parallel attacks in order to speed up the attacking process. scrypt is specifically designed to use more memory compared to other password-based key derivation functions in order to limit the amount of parallelism an attacker can use, see RFC 7914 for more details.

To use scrypt as your default storage algorithm, do the following:

  1. Modify PASSWORD_HASHERS to list ScryptPasswordHasher first. That is, in your settings file:

    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.ScryptPasswordHasher',
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
        'django.contrib.auth.hashers.Argon2PasswordHasher',
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    ]
    

    Keep and/or add any entries in this list if you need Django to upgrade passwords.

注釈

scrypt requires OpenSSL 1.1+.

Increasing the salt entropy

New in Django 3.2.

Most password hashes include a salt along with their password hash in order to protect against rainbow table attacks. The salt itself is a random value which increases the size and thus the cost of the rainbow table and is currently set at 128 bits with the salt_entropy value in the BasePasswordHasher. As computing and storage costs decrease this value should be raised. When implementing your own password hasher you are free to override this value in order to use a desired entropy level for your password hashes. salt_entropy is measured in bits.

Implementation detail

Due to the method in which salt values are stored the salt_entropy value is effectively a minimum value. For instance a value of 128 would provide a salt which would actually contain 131 bits of entropy.

Increasing the work factor

PBKDF2 and bcrypt

The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of hashing. This deliberately slows down attackers, making attacks against hashed passwords harder. However, as computing power increases, the number of iterations needs to be increased. We've chosen a reasonable default (and will increase it with each release of Django), but you may wish to tune it up or down, depending on your security needs and available processing power. To do so, you'll subclass the appropriate algorithm and override the iterations parameter (use the rounds parameter when subclassing a bcrypt hasher). For example, to increase the number of iterations used by the default PBKDF2 algorithm:

  1. Create a subclass of django.contrib.auth.hashers.PBKDF2PasswordHasher:

    from django.contrib.auth.hashers import PBKDF2PasswordHasher
    
    class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
        """
        A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
        """
        iterations = PBKDF2PasswordHasher.iterations * 100
    

    Save this somewhere in your project. For example, you might put this in a file like myproject/hashers.py.

  2. Add your new hasher as the first entry in PASSWORD_HASHERS:

    PASSWORD_HASHERS = [
        'myproject.hashers.MyPBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
        'django.contrib.auth.hashers.Argon2PasswordHasher',
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
        'django.contrib.auth.hashers.ScryptPasswordHasher',
    ]
    

That's it -- now your Django install will use more iterations when it stores passwords using PBKDF2.

注釈

bcrypt rounds is a logarithmic work factor, e.g. 12 rounds means 2 ** 12 iterations.

Argon2

Argon2 has three attributes that can be customized:

  1. time_cost controls the number of iterations within the hash.
  2. memory_cost controls the size of memory that must be used during the computation of the hash.
  3. parallelism controls how many CPUs the computation of the hash can be parallelized on.

The default values of these attributes are probably fine for you. If you determine that the password hash is too fast or too slow, you can tweak it as follows:

  1. Choose parallelism to be the number of threads you can spare computing the hash.
  2. Choose memory_cost to be the KiB of memory you can spare.
  3. Adjust time_cost and measure the time hashing a password takes. Pick a time_cost that takes an acceptable time for you. If time_cost set to 1 is unacceptably slow, lower memory_cost.

memory_cost interpretation

The argon2 command-line utility and some other libraries interpret the memory_cost parameter differently from the value that Django uses. The conversion is given by memory_cost == 2 ** memory_cost_commandline.

scrypt

New in Django 4.0.

scrypt has four attributes that can be customized:

  1. work_factor controls the number of iterations within the hash.
  2. block_size
  3. parallelism controls how many threads will run in parallel.
  4. maxmem limits the maximum size of memory that can be used during the computation of the hash. Defaults to 0, which means the default limitation from the OpenSSL library.

We've chosen reasonable defaults, but you may wish to tune it up or down, depending on your security needs and available processing power.

Estimating memory usage

The minimum memory requirement of scrypt is:

work_factor * 2 * block_size * 64

so you may need to tweak maxmem when changing the work_factor or block_size values.

パスワードの更新

ユーザーがログインする際、もしそのパスワードが推奨されるアルゴリズム以外で保存されていた場合、Djangoは自動で推奨されるアルゴリズムへ更新します。つまり、Djangoの古いインストールでも、ユーザーのログイン時に自動的にセキュリティが強化され、新しい(より良い)保存アルゴリズムが開発されるたびに切り替えることができるということです。

However, Django can only upgrade passwords that use algorithms mentioned in PASSWORD_HASHERS, so as you upgrade to new systems you should make sure never to remove entries from this list. If you do, users using unmentioned algorithms won't be able to upgrade. Hashed passwords will be updated when increasing (or decreasing) the number of PBKDF2 iterations, bcrypt rounds, or argon2 attributes.

データベース上の全てのパスワードがデフォルトのハッシュアルゴリズムでエンコードされていない場合、デフォルト以外のアルゴリズムでエンコードされたパスワードを持つユーザーと、存在しないユーザー(デフォルトのハッシュアルゴリズムが実行されます)に対するログインリクエストにかかる時間の差に起因する、ユーザー列挙型タイミング攻撃に対して脆弱になる可能性があることに注意してください。 古いパスワードハッシュの更新 によりこれを軽減できます。

Password upgrading without requiring a login

If you have an existing database with an older, weak hash such as MD5 or SHA1, you might want to upgrade those hashes yourself instead of waiting for the upgrade to happen when a user logs in (which may never happen if a user doesn't return to your site). In this case, you can use a "wrapped" password hasher.

For this example, we'll migrate a collection of SHA1 hashes to use PBKDF2(SHA1(password)) and add the corresponding password hasher for checking if a user entered the correct password on login. We assume we're using the built-in User model and that our project has an accounts app. You can modify the pattern to work with any algorithm or with a custom user model.

First, we'll add the custom hasher:

accounts/hashers.py
from django.contrib.auth.hashers import (
    PBKDF2PasswordHasher, SHA1PasswordHasher,
)


class PBKDF2WrappedSHA1PasswordHasher(PBKDF2PasswordHasher):
    algorithm = 'pbkdf2_wrapped_sha1'

    def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
        return super().encode(sha1_hash, salt, iterations)

    def encode(self, password, salt, iterations=None):
        _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
        return self.encode_sha1_hash(sha1_hash, salt, iterations)

The data migration might look something like:

accounts/migrations/0002_migrate_sha1_passwords.py
from django.db import migrations

from ..hashers import PBKDF2WrappedSHA1PasswordHasher


def forwards_func(apps, schema_editor):
    User = apps.get_model('auth', 'User')
    users = User.objects.filter(password__startswith='sha1$')
    hasher = PBKDF2WrappedSHA1PasswordHasher()
    for user in users:
        algorithm, salt, sha1_hash = user.password.split('$', 2)
        user.password = hasher.encode_sha1_hash(sha1_hash, salt)
        user.save(update_fields=['password'])


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0001_initial'),
        # replace this with the latest migration in contrib.auth
        ('auth', '####_migration_name'),
    ]

    operations = [
        migrations.RunPython(forwards_func),
    ]

Be aware that this migration will take on the order of several minutes for several thousand users, depending on the speed of your hardware.

Finally, we'll add a PASSWORD_HASHERS setting:

mysite/settings.py
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'accounts.hashers.PBKDF2WrappedSHA1PasswordHasher',
]

Include any other hashers that your site uses in this list.

Included hashers

The full list of hashers included in Django is:

[
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.ScryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
    'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
]

The corresponding algorithm names are:

  • pbkdf2_sha256
  • pbkdf2_sha1
  • argon2
  • bcrypt_sha256
  • bcrypt
  • scrypt
  • sha1
  • md5
  • unsalted_sha1
  • unsalted_md5
  • crypt

Writing your own hasher

If you write your own password hasher that contains a work factor such as a number of iterations, you should implement a harden_runtime(self, password, encoded) method to bridge the runtime gap between the work factor supplied in the encoded password and the default work factor of the hasher. This prevents a user enumeration timing attack due to difference between a login request for a user with a password encoded in an older number of iterations and a nonexistent user (which runs the default hasher's default number of iterations).

Taking PBKDF2 as example, if encoded contains 20,000 iterations and the hasher's default iterations is 30,000, the method should run password through another 10,000 iterations of PBKDF2.

If your hasher doesn't have a work factor, implement the method as a no-op (pass).

Manually managing a user's password

The django.contrib.auth.hashers module provides a set of functions to create and validate hashed passwords. You can use them independently from the User model.

check_password(password, encoded)

If you'd like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user's password field in the database to check against, and returns True if they match, False otherwise.

make_password(password, salt=None, hasher='default')

Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text (string or bytes). Optionally, you can provide a salt and a hashing algorithm to use, if you don't want to use the defaults (first entry of PASSWORD_HASHERS setting). See Included hashers for the algorithm name of each hasher. If the password argument is None, an unusable password is returned (one that will never be accepted by check_password()).

is_password_usable(encoded_password)

Returns False if the password is a result of User.set_unusable_password().

パスワードの妥当性検証

Users often choose poor passwords. To help mitigate this problem, Django offers pluggable password validation. You can configure multiple password validators at the same time. A few validators are included in Django, but you can write your own as well.

各パスワードのバリデータは、ユーザーに要件の説明文を与え、指定されたパスワードの妥当性検証を行い、要件を満たしていない場合はエラーメッセージを返し、必要に応じて設定されたパスワードを受信します。バリデータは、それらの挙動を微調整するオプション設定を持つこともできます。

Validation is controlled by the AUTH_PASSWORD_VALIDATORS setting. The default for the setting is an empty list, which means no validators are applied. In new projects created with the default startproject template, a set of validators is enabled by default.

By default, validators are used in the forms to reset or change passwords and in the createsuperuser and changepassword management commands. Validators aren't applied at the model level, for example in User.objects.create_user() and create_superuser(), because we assume that developers, not users, interact with Django at that level and also because model validation doesn't automatically run as part of creating models.

注釈

パスワードの妥当性検証は多くの脆弱なパスワードの形式が使用されることを防ぎます。しかしながら、パスワードが全てのバリデータを通過するという事実は、強力なパスワードであることを保証するわけではありません。最も先進的なパスワードのバリデータでさえ検出できない、パスワードを弱めうる多くの要素があります。

パスワードの妥当性検証を有効にする

パスワードの妥当性検証は AUTH_PASSWORD_VALIDATORS で構成されます:

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 9,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

本例では組み込みの4つ全てのバリデータを有効化します。

  • UserAttributeSimilarityValidator は、パスワードとユーザの属性との類似性をチェックします。
  • MinimumLengthValidator, which checks whether the password meets a minimum length. This validator is configured with a custom option: it now requires the minimum length to be nine characters, instead of the default eight.
  • CommonPasswordValidator, which checks whether the password occurs in a list of common passwords. By default, it compares to an included list of 20,000 common passwords.
  • NumericPasswordValidator は、パスワードが全体的に数値ではないかをチェックします。

For UserAttributeSimilarityValidator and CommonPasswordValidator, we're using the default settings in this example. NumericPasswordValidator has no settings.

The help texts and any errors from password validators are always returned in the order they are listed in AUTH_PASSWORD_VALIDATORS.

Included validators

Django includes four validators:

class MinimumLengthValidator(min_length=8)

Validates whether the password meets a minimum length. The minimum length can be customized with the min_length parameter.

class UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)

Validates whether the password is sufficiently different from certain attributes of the user.

The user_attributes parameter should be an iterable of names of user attributes to compare to. If this argument is not provided, the default is used: 'username', 'first_name', 'last_name', 'email'. Attributes that don't exist are ignored.

The maximum allowed similarity of passwords can be set on a scale of 0.1 to 1.0 with the max_similarity parameter. This is compared to the result of difflib.SequenceMatcher.quick_ratio(). A value of 0.1 rejects passwords unless they are substantially different from the user_attributes, whereas a value of 1.0 rejects only passwords that are identical to an attribute's value.

Changed in Django 2.2.26:

The max_similarity parameter was limited to a minimum value of 0.1.

class CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)

Validates whether the password is not a common password. This converts the password to lowercase (to do a case-insensitive comparison) and checks it against a list of 20,000 common password created by Royce Williams.

The password_list_path can be set to the path of a custom file of common passwords. This file should contain one lowercase password per line and may be plain text or gzipped.

class NumericPasswordValidator

Validates whether the password is not entirely numeric.

Integrating validation

There are a few functions in django.contrib.auth.password_validation that you can call from your own forms or other code to integrate password validation. This can be useful if you use custom forms for password setting, or if you have API calls that allow passwords to be set, for example.

validate_password(password, user=None, password_validators=None)

Validates a password. If all validators find the password valid, returns None. If one or more validators reject the password, raises a ValidationError with all the error messages from the validators.

The user object is optional: if it's not provided, some validators may not be able to perform any validation and will accept any password.

password_changed(password, user=None, password_validators=None)

Informs all validators that the password has been changed. This can be used by validators such as one that prevents password reuse. This should be called once the password has been successfully changed.

For subclasses of AbstractBaseUser, the password field will be marked as "dirty" when calling set_password() which triggers a call to password_changed() after the user is saved.

password_validators_help_texts(password_validators=None)

Returns a list of the help texts of all validators. These explain the password requirements to the user.

password_validators_help_text_html(password_validators=None)

Returns an HTML string with all help texts in an <ul>. This is helpful when adding password validation to forms, as you can pass the output directly to the help_text parameter of a form field.

get_password_validators(validator_config)

Returns a set of validator objects based on the validator_config parameter. By default, all functions use the validators defined in AUTH_PASSWORD_VALIDATORS, but by calling this function with an alternate set of validators and then passing the result into the password_validators parameter of the other functions, your custom set of validators will be used instead. This is useful when you have a typical set of validators to use for most scenarios, but also have a special situation that requires a custom set. If you always use the same set of validators, there is no need to use this function, as the configuration from AUTH_PASSWORD_VALIDATORS is used by default.

The structure of validator_config is identical to the structure of AUTH_PASSWORD_VALIDATORS. The return value of this function can be passed into the password_validators parameter of the functions listed above.

Note that where the password is passed to one of these functions, this should always be the clear text password - not a hashed password.

Writing your own validator

If Django's built-in validators are not sufficient, you can write your own password validators. Validators have a fairly small interface. They must implement two methods:

  • validate(self, password, user=None): validate a password. Return None if the password is valid, or raise a ValidationError with an error message if the password is not valid. You must be able to deal with user being None - if that means your validator can't run, return None for no error.
  • get_help_text(): provide a help text to explain the requirements to the user.

Any items in the OPTIONS in AUTH_PASSWORD_VALIDATORS for your validator will be passed to the constructor. All constructor arguments should have a default value.

Here's a basic example of a validator, with one optional setting:

from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _

class MinimumLengthValidator:
    def __init__(self, min_length=8):
        self.min_length = min_length

    def validate(self, password, user=None):
        if len(password) < self.min_length:
            raise ValidationError(
                _("This password must contain at least %(min_length)d characters."),
                code='password_too_short',
                params={'min_length': self.min_length},
            )

    def get_help_text(self):
        return _(
            "Your password must contain at least %(min_length)d characters."
            % {'min_length': self.min_length}
        )

You can also implement password_changed(password, user=None), which will be called after a successful password change. That can be used to prevent password reuse, for example. However, if you decide to store a user's previous passwords, you should never do so in clear text.