django-two-factor-auth icon indicating copy to clipboard operation
django-two-factor-auth copied to clipboard

Cookie validation raises BadSignature error after major Django upgrade

Open webjunkie opened this issue 6 months ago • 1 comments

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

  • Django version: Upgrade from 3x to 4x
  • django-otp version: 1.1.4
  • django-two-factor-auth version: 1.14.0

webjunkie avatar Dec 15 '23 11:12 webjunkie