From 28bafc59aaece9e51d9b5d25b69f8e67a8bf4ebb Mon Sep 17 00:00:00 2001 From: Semgrep Autofix Date: Tue, 17 Mar 2026 07:00:32 +0000 Subject: [PATCH] Fix path traversal vulnerability in actions.py using secure_filename Sanitize user-supplied filename to prevent path traversal attacks in the `/message` endpoint. ## Changes - Added import for `werkzeug.utils.secure_filename` - Applied `secure_filename()` to sanitize `filename_param` before constructing the file path - Replaced string concatenation with `Path` operator for cleaner path construction ## Why The `filename_param` parameter was taken directly from user input without validation. An attacker could supply a malicious filename like `../../etc/passwd` to write files outside the intended `data/{user_id}/` directory. Using `secure_filename()` strips path separators and other dangerous characters, ensuring the file is always written within the intended directory. ## Semgrep Finding Details The application builds a file path from potentially untrusted data, which can lead to a path traversal vulnerability. An attacker can manipulate the path which the application uses to access files. If the application does not validate user input and sanitize file paths, sensitive files such as configuration or user data can be accessed, potentially creating or overwriting files. In Flask apps, consider using the Werkzeug util `werkzeug.utils.secure_filename()` to sanitize paths and filenames. @267212124 requested Semgrep Assistant generate this pull request to fix [a finding](https://semgrep.dev/orgs/studentsca023_personal_org/findings/722169011) from the detection rule [python.flask.file.tainted-path-traversal-stdlib-flask.tainted-path-traversal-stdlib-flask](https://semgrep.dev/r/python.flask.file.tainted-path-traversal-stdlib-flask.tainted-path-traversal-stdlib-flask). --- flask_webgoat/actions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flask_webgoat/actions.py b/flask_webgoat/actions.py index 8cf5bbf4..f75e57eb 100644 --- a/flask_webgoat/actions.py +++ b/flask_webgoat/actions.py @@ -4,6 +4,7 @@ import subprocess from flask import Blueprint, request, jsonify, session +from werkzeug.utils import secure_filename bp = Blueprint("actions", __name__) @@ -29,10 +30,9 @@ def log_entry(): if not user_dir_path.exists(): user_dir_path.mkdir() - filename = filename_param + ".txt" - path = Path(user_dir + "/" + filename) + filename = secure_filename(filename_param) + ".txt" + path = Path(user_dir) / filename with path.open("w", encoding="utf-8") as open_file: - # vulnerability: Directory Traversal open_file.write(text_param) return jsonify({"success": True})