Self hosted FLOSS fitness/workout, nutrition and weight tracker
Throttle wrong two-factor codes per user
Roland Geiderdeddce29f265
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 6b871fa2a..43758ba65 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -169,6 +169,9 @@ MIDDLEWARE = [# would never be created'wger.core.middleware.TimezoneMiddleware',+ # Blocks allauth's account pages while a trainer is logged in as a member+ 'wger.core.middleware.TrainerLoginMiddleware',+# Send an appropriate Header so search engines don't index pages'wger.utils.middleware.RobotsExclusionMiddleware','django.contrib.messages.middleware.MessageMiddleware',@@ -285,11 +288,11 @@ ACCOUNT_FORMS = {'reset_password': 'wger.core.forms.WgerResetPasswordForm',}-# django-axes handles login brute-force protection at the backend level (it-# wraps every authenticate() call, so it also covers the API login endpoints).-# Disable allauth's overlapping login throttles to avoid running two systems;-# the non-login limits (signup, password reset, ...) stay at allauth's defaults.-ACCOUNT_RATE_LIMITS = {'login_failed': None, 'login': None}+# Failed logins are throttled per key: per username for passwords and per user+# for second factor codes (allauth.mfa counts those under the same action, axes+# never sees them). No per-IP part, behind the reverse proxy every client has+# the same address. django-axes additionally locks out per IP.+ACCOUNT_RATE_LIMITS = {'login': None, 'login_failed': '5/300s/key'}## Two-factor authentication (allauth.mfa)diff --git a/wger/core/middleware.py b/wger/core/middleware.pyindex 429696f4e..8c42a4728 100644--- a/wger/core/middleware.py+++ b/wger/core/middleware.py@@ -24,6 +24,7 @@ from django.contrib.auth import (login,logout,)+from django.http import HttpResponseForbiddenfrom django.shortcuts import redirectfrom django.urls import reversefrom django.utils import timezone@@ -191,3 +192,30 @@ class TimezoneMiddleware:timezone.deactivate()return self.get_response(request)+++class TrainerLoginMiddleware:+ """+ Keeps a trainer logged in as a member out of allauth's account pages++ These change how the account is logged into or recovered (email, password,+ two-factor, social connections), which would outlive the trainer session.+ Logging out stays possible.+ """++ allowed_url_names = {'account_logout'}++ def __init__(self, get_response):+ self.get_response = get_response++ def __call__(self, request):+ return self.get_response(request)++ def process_view(self, request, view_func, view_args, view_kwargs):+ if not request.session.get('trainer.identity'):+ return None+ if request.resolver_match.url_name in self.allowed_url_names:+ return None+ if view_func.__module__.startswith('allauth.'):+ return HttpResponseForbidden()+ return Nonediff --git a/wger/core/templates/user/preferences.html b/wger/core/templates/user/preferences.htmlindex 8d599c2fe..f95e60ded 100644--- a/wger/core/templates/user/preferences.html+++ b/wger/core/templates/user/preferences.html@@ -19,48 +19,48 @@{% translate "Account & security" %}</div><div class="list-group list-group-flush">- <a href="{% url 'account_email' %}" class="list-group-item list-group-item-action">- <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>- <span class="{% fa_class 'envelope' %} me-2 text-muted"></span>- {% translate "Email address" %}- {% if email_verified %}- <small class="d-block ms-4 text-success">{% translate "Verified email" %}</small>- {% else %}- <small class="d-block ms-4 text-muted">{% translate "Unverified email" %}</small>- {% endif %}- </a>- {% if has_usable_password %}- <a href="{% url 'core:user:change-password' %}" class="list-group-item list-group-item-action">- <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>- <span class="{% fa_class 'key' %} me-2 text-muted"></span>- {% translate "Change password" %}- </a>- {% else %}- <a href="{% url 'account_set_password' %}" class="list-group-item list-group-item-action">+ {% if not trainer_identity %}+ <a href="{% url 'account_email' %}" class="list-group-item list-group-item-action"><span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>- <span class="{% fa_class 'key' %} me-2 text-muted"></span>- {% translate "Set password" %}+ <span class="{% fa_class 'envelope' %} me-2 text-muted"></span>+ {% translate "Email address" %}+ {% if email_verified %}+ <small class="d-block ms-4 text-success">{% translate "Verified email" %}</small>+ {% else %}+ <small class="d-block ms-4 text-muted">{% translate "Unverified email" %}</small>+ {% endif %}</a>- {% endif %}- <a href="{% url 'mfa_index' %}" class="list-group-item list-group-item-action">- <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>- <span class="{% fa_class 'shield-halved' %} me-2 text-muted"></span>- {% translate "Two-factor authentication" %}- {% if mfa_enabled %}- <span class="badge text-bg-success ms-1">{% translate "On" %}</span>+ {% if has_usable_password %}+ <a href="{% url 'core:user:change-password' %}" class="list-group-item list-group-item-action">+ <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>+ <span class="{% fa_class 'key' %} me-2 text-muted"></span>+ {% translate "Change password" %}+ </a>{% else %}- <span class="badge text-bg-secondary ms-1">{% translate "Off" %}</span>+ <a href="{% url 'account_set_password' %}" class="list-group-item list-group-item-action">+ <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>+ <span class="{% fa_class 'key' %} me-2 text-muted"></span>+ {% translate "Set password" %}+ </a>{% endif %}- </a>- {% get_providers as socialaccount_providers %}- {% if socialaccount_providers %}- <a href="{% url 'socialaccount_connections' %}" class="list-group-item list-group-item-action">+ <a href="{% url 'mfa_index' %}" class="list-group-item list-group-item-action"><span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>- <span class="{% fa_class 'link' %} me-2 text-muted"></span>- {% translate "Connected accounts" %}+ <span class="{% fa_class 'shield-halved' %} me-2 text-muted"></span>+ {% translate "Two-factor authentication" %}+ {% if mfa_enabled %}+ <span class="badge text-bg-success ms-1">{% translate "On" %}</span>+ {% else %}+ <span class="badge text-bg-secondary ms-1">{% translate "Off" %}</span>+ {% endif %}</a>- {% endif %}- {% if not trainer_identity %}+ {% get_providers as socialaccount_providers %}+ {% if socialaccount_providers %}+ <a href="{% url 'socialaccount_connections' %}" class="list-group-item list-group-item-action">+ <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>+ <span class="{% fa_class 'link' %} me-2 text-muted"></span>+ {% translate "Connected accounts" %}+ </a>+ {% endif %}<a href="{% url 'core:user:api-key' %}" class="list-group-item list-group-item-action"><span class="{% fa_class 'chevron-right' %} float-end text-muted"></span><span class="{% fa_class 'globe' %} me-2 text-muted"></span>diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.pyindex 06f0327b3..27f4bdcf8 100644--- a/wger/core/tests/test_apikey.py+++ b/wger/core/tests/test_apikey.py@@ -644,6 +644,15 @@ class ApiKeyTrainerLoginTestCase(WgerTestCase):self.assertEqual(response.status_code, 403)self.assertEqual(list_long_lived_sessions(self.member), [])+ def test_app_auth_handoff_does_not_issue_token(self):+ """+ The app handoff doesn't mint a long-lived refresh token for the member+ """+ response = self.client.get(reverse('core:user:app-auth-handoff'))+ self.assertEqual(response.status_code, 403)+ self.assertNotContains(response, 'token=', status_code=403)+ self.assertEqual(list_long_lived_sessions(self.member), [])+def test_jwt_sessions_can_not_be_revoked(self):"""The member's API sessions can't be revokeddiff --git a/wger/core/tests/test_axes.py b/wger/core/tests/test_axes.pyindex 59da5d0e3..3253f0bc8 100644--- a/wger/core/tests/test_axes.py+++ b/wger/core/tests/test_axes.py@@ -34,11 +34,10 @@ FAILURE_LIMIT = 3@override_settings(AXES_ENABLED=True, AXES_FAILURE_LIMIT=FAILURE_LIMIT)class AxesLockoutTestCase(WgerTestCase):"""- Tests the brute force protection+ Tests the per-IP brute force protection- allauth's own login rate limit is switched off (see settings_global), so- django-axes is the only thing standing between an attacker and unlimited- password guessing.+ allauth additionally throttles per username (see settings_global), the+ failure limit here stays below that."""def setUp(self):@@ -98,8 +97,7 @@ class AxesLockoutTestCase(WgerTestCase):def test_api_login_is_covered(self):"""- The API login endpoint has to be protected too, it is the reason- allauth's own rate limiting was switched off+ The API login endpoint has to be protected too"""for _ in range(FAILURE_LIMIT):self.api_login('wrong password')@@ -118,6 +116,7 @@ class AxesLockoutTestCase(WgerTestCase):self.assertFalse(response.wsgi_request.user.is_authenticated)+@override_settings(ACCOUNT_RATE_LIMITS={'login_failed': None})class AxesDisabledInTestsTestCase(WgerTestCase):"""The shared base test case switches axes off so the other tests can log indiff --git a/wger/core/tests/test_login_rate_limit.py b/wger/core/tests/test_login_rate_limit.pynew file mode 100644index 000000000..5ae672322--- /dev/null+++ b/wger/core/tests/test_login_rate_limit.py@@ -0,0 +1,137 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Standard Library+import json++# Django+from django.contrib.auth.models import User+from django.urls import reverse++# Third Party+from allauth.mfa.recovery_codes.internal.auth import RecoveryCodes+from allauth.mfa.totp.internal.auth import (+ TOTP,+ generate_totp_secret,+)++# wger+from wger.core.tests.base_testcase import WgerTestCase+++# allauth's per-user limit for wrong second factor codes+FAILURE_LIMIT = 5++WRONG_CODE = '000000'+++class MfaRateLimitTestCase(WgerTestCase):+ """+ Wrong second factor codes are throttled per user, on the web and the app+ """++ def setUp(self):+ super().setUp()+ user = User.objects.get(username='test')+ TOTP.activate(user, generate_totp_secret())+ self.recovery_code = RecoveryCodes.activate(user).get_unused_codes()[0]++ def web_login(self):+ response = self.client.post(+ reverse('core:user:login'),+ {'login': 'test', 'password': 'testtest'},+ )+ self.assertRedirects(response, reverse('mfa_authenticate'), fetch_redirect_response=False)++ def web_code(self, code: str):+ return self.client.post(reverse('mfa_authenticate'), {'code': code})++ def app_login(self) -> str:+ response = self.client.post(+ reverse('headless:app:account:login'),+ data=json.dumps({'username': 'test', 'password': 'testtest'}),+ content_type='application/json',+ )+ self.assertEqual(response.status_code, 401, response.content)+ return response.json()['meta']['session_token']++ def app_code(self, session_token: str, code: str):+ return self.client.post(+ reverse('headless:app:mfa:authenticate'),+ data=json.dumps({'code': code}),+ content_type='application/json',+ HTTP_X_SESSION_TOKEN=session_token,+ )++ def test_web_valid_code_after_a_few_typos(self):+ self.web_login()+ self.web_code(WRONG_CODE)+ self.web_code(WRONG_CODE)++ response = self.web_code(self.recovery_code)+ self.assertTrue(response.wsgi_request.user.is_authenticated)++ def test_web_valid_code_refused_after_the_limit(self):+ self.web_login()+ for _ in range(FAILURE_LIMIT):+ self.web_code(WRONG_CODE)++ response = self.web_code(self.recovery_code)+ self.assertFalse(response.wsgi_request.user.is_authenticated)++ def test_app_valid_code_after_a_few_typos(self):+ token = self.app_login()+ self.app_code(token, WRONG_CODE)+ self.app_code(token, WRONG_CODE)++ response = self.app_code(token, self.recovery_code)+ self.assertEqual(response.status_code, 200, response.content)++ def test_app_valid_code_refused_after_the_limit(self):+ token = self.app_login()+ for _ in range(FAILURE_LIMIT):+ self.app_code(token, WRONG_CODE)++ response = self.app_code(token, self.recovery_code)+ self.assertEqual(response.status_code, 400, response.content)+ self.assertEqual(response.json()['errors'][0]['code'], 'too_many_login_attempts')++ def test_limit_survives_a_new_login(self):+ """Opening a fresh login with the password does not reset the budget"""+ token = self.app_login()+ for _ in range(FAILURE_LIMIT):+ self.app_code(token, WRONG_CODE)++ response = self.app_code(self.app_login(), self.recovery_code)+ self.assertEqual(response.status_code, 400, response.content)+++class PasswordRateLimitTestCase(WgerTestCase):+ """+ Failed password logins are throttled per username, not per IP+ """++ def web_login(self, username: str, password: str):+ return self.client.post(+ reverse('core:user:login'),+ {'login': username, 'password': password},+ )++ def test_failures_for_one_user_do_not_block_others(self):+ """Behind the reverse proxy every client has the same IP"""+ for _ in range(10):+ self.web_login('admin', 'wrong password')++ response = self.web_login('test', 'testtest')+ self.assertTrue(response.wsgi_request.user.is_authenticated)diff --git a/wger/core/tests/test_trainer_login_account.py b/wger/core/tests/test_trainer_login_account.pynew file mode 100644index 000000000..4d0e2a0ab--- /dev/null+++ b/wger/core/tests/test_trainer_login_account.py@@ -0,0 +1,89 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Django+from django.contrib.auth.models import User+from django.urls import reverse++# Third Party+from allauth.account.models import EmailAddress++# wger+from wger.core.tests.base_testcase import WgerTestCase+++class TrainerLoginAccountManagementTestCase(WgerTestCase):+ """+ A trainer logged in as one of their members can't change the member's+ login or recovery settings+ """++ def setUp(self):+ super().setUp()+ self.member = User.objects.get(username='test')+ self.impersonate_member()++ def impersonate_member(self):+ self.user_login('trainer1')+ response = self.client.post(+ reverse('core:user:trainer-login', kwargs={'user_pk': self.member.pk})+ )+ self.assertEqual(response.status_code, 302)+ self.assertTrue(self.client.session.get('trainer.identity'))++ def test_email_page_is_not_shown(self):+ """+ The member's email management page is not rendered+ """+ response = self.client.get(reverse('account_email'))+ self.assertEqual(response.status_code, 403)++ def test_email_can_not_be_added(self):+ """+ No email address can be added to the member's account+ """+ email_before = self.member.email++ response = self.client.post(+ reverse('account_email'),+ {'email': '[email protected]', 'action_add': ''},+ )+ self.assertEqual(response.status_code, 403)+ self.assertFalse(EmailAddress.objects.filter(email='[email protected]').exists())+ self.member.refresh_from_db()+ self.assertEqual(self.member.email, email_before)++ def test_password_can_not_be_set(self):+ """+ A member without a usable password (social login) doesn't get one+ """+ self.member.set_unusable_password()+ self.member.save()+ self.impersonate_member()++ response = self.client.post(+ reverse('account_set_password'),+ {'password1': 'attacker-pass-123', 'password2': 'attacker-pass-123'},+ )+ self.assertEqual(response.status_code, 403)+ self.member.refresh_from_db()+ self.assertFalse(self.member.has_usable_password())++ def test_logout_still_works(self):+ """+ The session can still be ended+ """+ response = self.client.post(reverse('account_logout'))+ self.assertEqual(response.status_code, 302)+ self.assertNotIn('_auth_user_id', self.client.session)diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex 365fac272..cf76fa08a 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -595,6 +595,11 @@ def app_auth_handoff(request):itself. The value is treated as opaque but constrained to base64url charactersand a sane length to prevent abuse of the reflection."""++ # A trainer logged in as a member must not get credentials that outlive the session+ if request.session.get('trainer.identity'):+ return HttpResponseForbidden()+token = mint_long_lived_refresh_token(request.user,settings.HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN,