mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-01-21 07:55:00 +00:00
- 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>
146 lines
4.0 KiB
Python
146 lines
4.0 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""
|
|
Setup logging for the application.
|
|
"""
|
|
|
|
import importlib
|
|
import logging
|
|
import logging.config
|
|
import warnings
|
|
|
|
from . import cfg
|
|
|
|
default_level = None
|
|
|
|
|
|
class ColoredFormatter(logging.Formatter):
|
|
"""Print parts of log message in color."""
|
|
codes = {
|
|
'black': 30,
|
|
'red': 31,
|
|
'green': 32,
|
|
'yellow': 33,
|
|
'blue': 34,
|
|
'magenta': 35,
|
|
'cyan': 36,
|
|
'white': 37,
|
|
'bright_black': 90,
|
|
'bright_red': 91,
|
|
'bright_green': 92,
|
|
'bright_yellow': 93,
|
|
'bright_blue': 94,
|
|
'bright_magenta': 95,
|
|
'bright_cyan': 96,
|
|
'bright_white': 97
|
|
}
|
|
|
|
level_colors = {
|
|
'DEBUG': 'bright_black',
|
|
'INFO': 'bright_white',
|
|
'WARNING': 'bright_yellow',
|
|
'ERROR': 'red',
|
|
'CRITICAL': 'bright_red'
|
|
}
|
|
|
|
def wrap_color(self, string, color=None):
|
|
"""Return a string wrapped in terminal escape codes for coloring."""
|
|
if not color:
|
|
return string
|
|
|
|
return '\x1b[{}m'.format(self.codes[color]) + string + '\x1b[0m'
|
|
|
|
def format(self, record):
|
|
"""Format a record into a string"""
|
|
record_name = '{:<20}'.format(record.name)
|
|
record.colored_name = self.wrap_color(record_name, 'bright_blue')
|
|
|
|
level_color = self.level_colors.get(record.levelname, None)
|
|
level_name = '{:>8}'.format(record.levelname)
|
|
record.colored_levelname = self.wrap_color(level_name, level_color)
|
|
return super().format(record)
|
|
|
|
|
|
def _capture_warnings():
|
|
"""Capture all warnings include deprecation warnings."""
|
|
# Capture all Python warnings such as deprecation warnings
|
|
logging.captureWarnings(True)
|
|
|
|
# Log all deprecation warnings when in develop mode
|
|
if cfg.develop:
|
|
warnings.filterwarnings('default', '', DeprecationWarning)
|
|
warnings.filterwarnings('default', '', PendingDeprecationWarning)
|
|
warnings.filterwarnings('default', '', ImportWarning)
|
|
|
|
|
|
def action_init():
|
|
"""Initialize logging for action scripts."""
|
|
_capture_warnings()
|
|
|
|
logging.config.dictConfig(get_configuration())
|
|
|
|
|
|
def init():
|
|
"""Setup the logging framework."""
|
|
import cherrypy
|
|
|
|
# Remove default handlers and let the log message propagate to root logger.
|
|
for cherrypy_logger in [cherrypy.log.error_log, cherrypy.log.access_log]:
|
|
for handler in list(cherrypy_logger.handlers):
|
|
cherrypy_logger.removeHandler(handler)
|
|
|
|
_capture_warnings()
|
|
|
|
|
|
def setup_cherrypy_static_directory(app):
|
|
"""Hush output from cherrypy static file request logging.
|
|
|
|
Static file serving logs are hardly useful.
|
|
"""
|
|
app.log.access_log.propagate = False
|
|
app.log.error_log.propagate = False
|
|
|
|
|
|
def get_configuration():
|
|
"""Return the main python logging module configuration."""
|
|
configuration = {
|
|
'version': 1,
|
|
'disable_existing_loggers': False,
|
|
'formatters': {
|
|
'color': {
|
|
'()': 'plinth.log.ColoredFormatter',
|
|
'format': '{colored_levelname} {colored_name} {message}',
|
|
'style': '{'
|
|
}
|
|
},
|
|
'handlers': {
|
|
'console': {
|
|
'class': 'logging.StreamHandler',
|
|
'formatter': 'color'
|
|
}
|
|
},
|
|
'root': {
|
|
'handlers': ['console'],
|
|
'level': default_level or ('DEBUG' if cfg.develop else 'INFO')
|
|
},
|
|
'loggers': {
|
|
'django.db.backends': {
|
|
'level': 'INFO' # Set to 'DEBUG' to log database queries
|
|
},
|
|
'axes': {
|
|
'level': 'INFO' # Too verbose during DEBUG
|
|
}
|
|
}
|
|
}
|
|
|
|
try:
|
|
importlib.import_module('systemd.journal')
|
|
except ModuleNotFoundError:
|
|
pass
|
|
else:
|
|
configuration['handlers']['journal'] = {
|
|
'class': 'systemd.journal.JournalHandler'
|
|
}
|
|
configuration['root']['handlers'].append('journal')
|
|
|
|
return configuration
|