FreedomBox/plinth/__main__.py
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

156 lines
4.5 KiB
Python

#!/usr/bin/python3
# SPDX-License-Identifier: AGPL-3.0-or-later
import argparse
import logging
import sys
from . import __version__
from . import app as app_module
from . import (cfg, frontpage, glib, log, menu, module_loader, setup,
web_framework, web_server)
precedence_commandline_arguments = ["server_dir", "develop"]
logger = logging.getLogger(__name__)
def parse_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description='Core functionality and web interface for FreedomBox',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# TODO: server_dir is actually a url prefix; use a better variable name
parser.add_argument('--server_dir', default=None,
help='web server path under which to serve')
parser.add_argument(
'--develop', action='store_true', default=None,
help=('run Plinth *insecurely* from current folder; '
'enable auto-reloading and debugging options'))
parser.add_argument('--setup', default=False, nargs='*',
help='run setup tasks on all essential apps and exit')
parser.add_argument(
'--setup-no-install', default=False, nargs='*',
help='run setup tasks without installing packages and exit')
parser.add_argument('--list-dependencies', default=False, nargs='*',
help='list package dependencies for essential modules')
parser.add_argument('--list-apps', default=False, nargs='*',
help='list apps')
return parser.parse_args()
def run_setup_and_exit(app_ids, allow_install=True):
"""Run setup on all essential apps and exit."""
error_code = 0
try:
setup.run_setup_on_apps(app_ids, allow_install)
except Exception:
error_code = 1
sys.exit(error_code)
def list_dependencies(app_ids):
"""List dependencies for all essential apps and exit."""
error_code = 0
try:
if app_ids:
setup.list_dependencies(app_ids=app_ids)
else:
setup.list_dependencies(essential=True)
except Exception as exception:
logger.error('Error listing dependencies - %s', exception)
error_code = 1
sys.exit(error_code)
def list_apps(apps_type):
"""List all/essential/optional apps and exit."""
for app in app_module.App.list():
is_essential = app.info.is_essential
if 'essential' in apps_type and not is_essential:
continue
if 'optional' in apps_type and is_essential:
continue
print(f'{app.app_id}')
sys.exit()
def adapt_config(arguments):
"""Give commandline arguments precedence over config entries"""
for argument_name in precedence_commandline_arguments:
argument_value = getattr(arguments, argument_name)
if argument_value is not None:
setattr(cfg, argument_name, argument_value)
def on_web_server_stop():
"""Stop all other threads since web server is trying to exit."""
setup.stop()
glib.stop()
def main():
"""Initialize and start the application"""
arguments = parse_arguments()
cfg.read()
if arguments.develop:
# Use the config in the current working directory
cfg.read_file(cfg.get_develop_config_path())
adapt_config(arguments)
if arguments.list_dependencies is not False:
log.default_level = 'ERROR'
module_loader.load_modules()
app_module.apps_init()
list_dependencies(arguments.list_dependencies)
if arguments.list_apps is not False:
log.default_level = 'ERROR'
module_loader.load_modules()
app_module.apps_init()
list_apps(arguments.list_apps)
log.init()
web_framework.init()
web_framework.post_init()
logger.info('FreedomBox Service (Plinth) version - %s', __version__)
for config_file in cfg.config_files:
logger.info('Configuration loaded from file - %s', config_file)
logger.info('Script prefix - %s', cfg.server_dir)
module_loader.include_urls()
menu.init()
module_loader.load_modules()
app_module.apps_init()
app_module.apps_post_init()
frontpage.add_custom_shortcuts()
if arguments.setup is not False:
run_setup_and_exit(arguments.setup, allow_install=True)
if arguments.setup_no_install is not False:
run_setup_and_exit(arguments.setup_no_install, allow_install=False)
setup.run_setup_in_background()
glib.run()
web_server.init()
web_server.run(on_web_server_stop)
if __name__ == '__main__':
main()