jazzband / django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
MIT License
1.68k stars 443 forks source link

Cookie validation raises BadSignature error after major Django upgrade #686

Open webjunkie opened 10 months ago

webjunkie commented 10 months ago

Expected Behavior

After a major Django version upgrade, existing two-factor authentication cookies should continue to be valid until their expiration.

Current Behavior

After a major Django version upgrade, existing two-factor authentication cookies are invalidated due to the change in the user's password hash. This happens because Django updates the password hash on login if the hash iteration count changes with the new version. Consequently, the hash used in the two-factor authentication cookies, which relies on the user's password hash, no longer matches, causing cookie validation to fail with a BadSignature exception when using validate_remember_device_cookie directly. While views in django-two-factor-auth itself catch this exception, implementations using validate_remember_device_cookie directly might not. In our case, the user is presented with an error and no way to continue.

Possible Solution

One potential solution is to just return false on the cookie validation, as signature mismatches might not be due to malicious behavior, but also due to upgrades or even in general due to other changes in how the hashing is done.

Steps to Reproduce

  1. Implement two-factor authentication using django-two-factor-auth in a Django project.
  2. Login and generate a two-factor authentication cookie with the current Django version. Then log out.
  3. Upgrade to a newer major version of Django where the password hash iteration count changes.
  4. Log in and attempt to validate the previously generated two-factor authentication cookie using validate_remember_device_cookie.

Context

This issue leads to an inconvenient user experience, as in our case users are forced to clear their cookies after a Django upgrade. It affects the seamless usage of two-factor authentication in Django applications.

Your Environment

moggers87 commented 7 months ago

I don't think the current behaviour is bug. The doc string of validate_remember_device_cookie could be clearer though