Sunil Mohan Adapa 770974c8ce
sso: Switch to django-axes >= 5.0
- Add explicit dependency on django-ipware >=3. django-axes >= 6 adds
only and optional dependency on django-ipware. Adding explicit dependency make
the behavior safer.

- Depend on django-axes >= 5 where the authentication backend and other features
are available. The new code won't work with older versions. The new approach
uses and authentication backend to deny access to the login form on lockout and
a middleware to redirect user to locked out form when limit of attempts have
been reached.

- Drop old code used for compatibility with django-axes 3.x.

- Suppress verbose and debug messages as django-axes is too chatty.

- Re-implment the CAPTCHA form entirely. In the old style, we have a login form
with CAPTCHA field. That would not work with the new django-axes authentication
middle. On submission of the form, auth.authenticate() will be called. This
call invokes various authentication backends include django-axes authentication
backend. This backend's behavior is to reject all authentication attempts when
the IP is listed in locked table. The new approach is to provide a simple
CAPTCHA form with just the CAPTCHA field. If the form is successfully
validated (correct CAPTCHA is provided), then the lock on the IP address is
reset. The user is then free to perform 3 more attempts to login.

- Update firstboot form to send the request parameter when using
auth.authenticate() method. This needed by Django axes' authentication method
which will be triggered.

Tests:

- Run tests on Debian Bookworm and Debian testing.

- Axes verbose messages and debug messages are not printed on the console when
running FreedomBox in debug mode.

- Only three invalid attempts are allowed at the login page. After the final
incorrect attempt, user is redirected to CAPTCHA page. Visiting the login page
using the URL works but entering the correct credentials still takes the user to
CAPTCHA page.

- CAPTCHA form appears as expected. Clicking the CAPTCHA images downloads the
audio file corresponding to the image. Incorrect CAPTCHA shows an error. Correct
CAPTCHA takes the user to login form where they are able to login with correct
credentials. Entering incorrect credentials 3 times will take the user again to
CAPTCHA page.

- Creating user account during firstboot works.

- Blocked IP address the IP of the client such as 10.42.0.1 and not the local IP
address 127.0.0.1 according the django-axes log messages. While one client IP
address is blocked, another IP is able to login to the same user account that
was attempted by the blocked client.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
2023-08-23 21:47:39 -04:00

98 lines
3.3 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Views for the Single Sign On app of FreedomBox."""
import logging
import os
import urllib
import axes.utils
from django import shortcuts
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.views import LoginView
from django.http import HttpResponseRedirect
from django.utils.translation import gettext as _
from django.views.decorators.http import require_POST
from django.views.generic.edit import FormView
from plinth import translation
from . import privileged
from .forms import AuthenticationForm, CaptchaForm
PRIVATE_KEY_FILE_NAME = 'privkey.pem'
SSO_COOKIE_NAME = 'auth_pubtkt'
KEYS_DIRECTORY = '/etc/apache2/auth-pubtkt-keys'
logger = logging.getLogger(__name__)
def set_ticket_cookie(user, response):
"""Generate and set a mod_auth_pubtkt as a cookie in the response."""
tokens = list(map(lambda g: g.name, user.groups.all()))
private_key_file = os.path.join(KEYS_DIRECTORY, PRIVATE_KEY_FILE_NAME)
ticket = privileged.generate_ticket(user.username, private_key_file,
tokens)
response.set_cookie(SSO_COOKIE_NAME, urllib.parse.quote(ticket))
return response
class SSOLoginView(LoginView):
"""View to login to FreedomBox and set a auth_pubtkt cookie.
Cookie will be used to provide Single Sign On for some other applications.
"""
redirect_authenticated_user = True
template_name = 'login.html'
form_class = AuthenticationForm
def dispatch(self, request, *args, **kwargs):
"""Handle a request and return a HTTP response."""
response = super().dispatch(request, *args, **kwargs)
if request.user.is_authenticated:
translation.set_language(request, response,
request.user.userprofile.language)
return set_ticket_cookie(request.user, response)
return response
class CaptchaView(FormView):
"""A simple form view with a CAPTCHA image.
When a user performs too many login attempts, they will no longer be able
to login with the typical login view. They will be redirected to this view.
On successfully solving the CAPTCHA in this form, their ability to use the
login form will be reset.
"""
template_name = 'captcha.html'
form_class = CaptchaForm
def form_valid(self, form):
"""Reset login attempts and redirect to login page."""
axes.utils.reset_request(self.request)
return shortcuts.redirect('users:login')
@require_POST
def logout(request):
"""Logout an authenticated user, remove SSO cookie and redirect to home."""
auth_logout(request)
response = shortcuts.redirect('index')
response.delete_cookie(SSO_COOKIE_NAME)
messages.success(request, _('Logged out successfully.'))
return response
def refresh(request):
"""Simulate cookie refresh - redirect logged in user with a new cookie."""
redirect_url = request.GET.get(REDIRECT_FIELD_NAME, '')
response = HttpResponseRedirect(redirect_url)
response.delete_cookie(SSO_COOKIE_NAME)
# Redirect with cookie doesn't work with 300 series
response.status_code = 200
return set_ticket_cookie(request.user, response)