feat: enhance logging by removing sensitive information and cleaning up debug messages

This commit is contained in:
Théophile Diot 2024-12-05 14:33:15 +01:00
parent 996299893b
commit 6be20b6189
No known key found for this signature in database
GPG key ID: FA995104A0BA376A
4 changed files with 5 additions and 158 deletions

View file

@ -20,8 +20,7 @@ def login_page():
fail = False
if request.method == "POST" and "username" in request.form and "password" in request.form:
LOGGER.debug(request.form)
LOGGER.warning(f"Login attempt from {request.remote_addr} with username \"{request.form['username']}\"")
LOGGER.warning(f"Login attempt from {request.remote_addr}")
ui_user = DB.get_ui_user(username=request.form["username"])
if ui_user and ui_user.username == request.form["username"] and ui_user.check_password(request.form["password"]):

View file

@ -582,150 +582,3 @@ def custom_plugin_page(plugin: str):
is_metrics=is_metrics_on,
pre_render=pre_render,
)
# @plugins.route("/plugins/<plugin>", methods=["GET", "POST"])
# @login_required
# def custom_plugin(plugin: str):
# if not PLUGIN_ID_RX.match(plugin):
# return error_message("Invalid plugin id, (must be between 1 and 64 characters, only letters, numbers, underscores and hyphens)"), 400
# # Case we ware looking for a plugin template
# # We need to check if a page exists, and if it does, we need to check if the plugin is activated and metrics are on
# if request.method == "GET":
# # Check plugin's page
# page = DB.get_plugin_page(plugin)
# if not page:
# return error_message("The plugin does not have a page"), 404
# tmp_page_dir = TMP_DIR.joinpath("ui", "page", str(uuid4()))
# tmp_page_dir.mkdir(parents=True, exist_ok=True)
# with tar_open(fileobj=BytesIO(page), mode="r:gz") as tar_file:
# tar_file.extractall(tmp_page_dir)
# tmp_page_dir = tmp_page_dir.joinpath("ui")
# LOGGER.debug(f"Plugin {plugin} page extracted successfully")
# # Case template, prepare data
# plugins = BW_CONFIG.get_plugins()
# plugin_id = None
# curr_plugin = {}
# is_used = False
# use_key = False
# is_metrics_on = False
# context = "multisite"
# for plug in plugins:
# if plug["id"] == plugin:
# plugin_id = plug["id"]
# curr_plugin = plug
# break
# # Case no plugin found
# if plugin_id is None:
# return error_message("Plugin not found"), 404
# config = DB.get_config()
# # Check if we are using metrics
# for service in config.get("SERVER_NAME", "").split(" "):
# # specific case
# if config.get(f"{service}_USE_METRICS", "yes") != "no":
# is_metrics_on = True
# break
# # Check if the plugin is used
# # Here we have specific cases for some plugins
# # {plugin_id: [[setting_name, setting_false], ...]}
# specific_cases = {
# "limit": [["USE_LIMIT_REQ", "no"], ["USE_LIMIT_CONN", "no"]],
# "misc": [["DISABLE_DEFAULT_SERVER", "no"], ["ALLOWED_METHODS", ""]],
# "modsecurity": [["USE_MODSECURITY", "no"]],
# "realip": [["USE_REALIP", "no"]],
# "reverseproxy": [["USE_REVERSE_PROXY", "no"]],
# "selfsigned": [["GENERATE_SELF_SIGNED_SSL", "no"]],
# "letsencrypt": [["AUTO_LETS_ENCRYPT", "no"]],
# "country": [["BLACKLIST_COUNTRY", ""], ["WHITELIST_COUNTRY", ""]],
# }
# # specific cases
# for key, data in curr_plugin["settings"].items():
# # specific cases
# if plugin_id in specific_cases:
# use_key = "SPECIFIC"
# context = data["context"]
# break
# # default case (one USE_)
# if key.upper().startswith("USE_"):
# use_key = key
# context = data["context"]
# break
# # Case USE_<NAME>, it means show only if used by one service
# if context == "global":
# if plugin_id in specific_cases:
# for key in specific_cases[plugin_id]:
# setting_name = key[0]
# setting_false = key[1]
# if config.get(setting_name, setting_false) != setting_false:
# is_used = True
# break
# if config.get(use_key, "no") != "no":
# is_used = True
# if context == "multisite":
# for service in config.get("SERVER_NAME", "").split(" "):
# # specific case
# if plugin_id in specific_cases:
# for key in specific_cases[plugin_id]:
# setting_name = key[0]
# setting_false = key[1]
# if config.get(f"{service}_{setting_name}", setting_false) != setting_false:
# is_used = True
# break
# # general case
# if config.get(f"{service}_{use_key}", "no") != "no":
# is_used = True
# break
# # Get prerender from action.py
# pre_render = run_action(plugin, "pre_render", tmp_dir=tmp_page_dir)
# return render_template(
# # deepcode ignore Ssti: We trust the plugin template
# Environment(
# loader=FileSystemLoader((tmp_page_dir.as_posix() + "/", join(sep, "usr", "share", "bunkerweb", "ui", "templates") + "/")),
# autoescape=select_autoescape(["html"]),
# ).from_string(tmp_page_dir.joinpath("template.html").read_text(encoding="utf-8")),
# current_endpoint=plugin,
# plugin=curr_plugin,
# pre_render=pre_render,
# is_used=is_used,
# is_metrics=is_metrics_on,
# **current_app.jinja_env.globals,
# )
# rmtree(TMP_DIR.joinpath("ui", "page"), ignore_errors=True)
# action_result = run_action(plugin)
# if isinstance(action_result, Response):
# LOGGER.info(f"Plugin {plugin} action executed successfully")
# return action_result
# # case error
# if action_result["status"] == "ko":
# return error_message(action_result["message"]), action_result["code"]
# LOGGER.info(f"Plugin {plugin} action executed successfully")
# if request.content_type == "application/x-www-form-urlencoded":
# return redirect(f"{url_for('plugins.plugins_page')}/{plugin}", code=303)
# return jsonify({"message": "ok", "data": action_result["data"]}), 200

View file

@ -91,7 +91,6 @@ def on_starting(server):
def set_secure_permissions(file_path: Path):
"""Set file permissions to 600 (owner read/write only)."""
file_path.chmod(S_IRUSR | S_IWUSR)
LOGGER.info(f"Permissions set to 600 for {file_path}")
# * Handle Flask secret
try:
@ -137,8 +136,8 @@ def on_starting(server):
file.write(current_env_hash)
set_secure_permissions(FLASK_SECRET_HASH_FILE)
LOGGER.info(f"Flask secret securely stored in {FLASK_SECRET_FILE}.")
LOGGER.info(f"Flask secret hash stored in {FLASK_SECRET_HASH_FILE} for change detection.")
LOGGER.info("Flask secret securely stored.")
LOGGER.info("Flask secret hash stored for change detection.")
except Exception as e:
LOGGER.critical(f"An error occurred while handling the Flask secret: {e}")
exit(1)
@ -201,8 +200,8 @@ def on_starting(server):
file.write(current_env_hash)
set_secure_permissions(TOTP_HASH_FILE)
LOGGER.info(f"TOTP secrets securely stored in {TOTP_SECRETS_FILE}.")
LOGGER.info(f"TOTP environment hash stored in {TOTP_HASH_FILE} for change detection.")
LOGGER.info("TOTP secrets securely stored.")
LOGGER.info("TOTP environment hash stored for change detection.")
except Exception as e:
LOGGER.critical(f"An error occurred while handling TOTP secrets: {e}")
exit(1)
@ -254,7 +253,6 @@ def on_starting(server):
if err:
LOGGER.error(f"Couldn't update the admin user in the database: {err}")
LOGGER.debug(f"Admin user: {ADMIN_USER}")
if env_admin_username or env_admin_password:
override_admin_creds = getenv("OVERRIDE_ADMIN_CREDS", "no").lower() == "yes"
if ADMIN_USER["method"] == "manual" or override_admin_creds:

View file

@ -491,9 +491,6 @@ def set_columns_preferences():
except BaseException:
return Response(status=400, response=dumps({"message": "Bad request"}), content_type="application/json")
LOGGER.debug(f"Setting columns preferences for {table_name}: {columns_preferences}")
LOGGER.debug(f"Default columns preferences for {table_name}: {COLUMNS_PREFERENCES_DEFAULTS.get(table_name, {})}")
if (
DB.readonly
or table_name not in COLUMNS_PREFERENCES_DEFAULTS