diff --git a/mobsf/MobSF/security.py b/mobsf/MobSF/security.py index 02e884839..36984a5fe 100644 --- a/mobsf/MobSF/security.py +++ b/mobsf/MobSF/security.py @@ -228,3 +228,15 @@ def sanitize_filename(filename): # Remove leading and trailing underscores safe_filename = safe_filename.strip('_') return safe_filename + + +def sanitize_for_logging(filename: str, max_length: int = 255) -> str: + """Sanitize a filename to prevent log injection.""" + # Remove newline, carriage return, and other risky characters + filename = filename.replace('\n', '_').replace('\r', '_').replace('\t', '_') + + # Allow only safe characters (alphanumeric, underscore, dash, and period) + filename = re.sub(r'[^a-zA-Z0-9._-]', '_', filename) + + # Truncate filename to the maximum allowed length + return filename[:max_length] diff --git a/mobsf/StaticAnalyzer/views/common/shared_func.py b/mobsf/StaticAnalyzer/views/common/shared_func.py index 0157d67cc..e47b35bef 100755 --- a/mobsf/StaticAnalyzer/views/common/shared_func.py +++ b/mobsf/StaticAnalyzer/views/common/shared_func.py @@ -20,6 +20,9 @@ from django.http import HttpResponseRedirect from mobsf.MobSF import settings +from mobsf.MobSF.security import ( + sanitize_for_logging, +) from mobsf.MobSF.utils import ( EMAIL_REGEX, STRINGS_REGEX, @@ -122,7 +125,8 @@ def unzip(checksum, app_path, ext_path): # Skip encrypted files if fileinfo.flag_bits & 0x1: - msg = f'Skipping encrypted file {fileinfo.filename}' + msg = ('Skipping encrypted file ' + f'{sanitize_for_logging(fileinfo.filename)}') logger.warning(msg) continue @@ -138,7 +142,8 @@ def unzip(checksum, app_path, ext_path): # Handle Zip Slip if is_path_traversal(file_path): - msg = f'Zip slip detected. skipped extracting {file_path}' + msg = ('Zip slip detected. skipped extracting' + f' {sanitize_for_logging(file_path)}') logger.error(msg) continue @@ -156,7 +161,8 @@ def unzip(checksum, app_path, ext_path): try: zipptr.extract(file_path, ext_path) except Exception: - logger.warning('Failed to extract %s', file_path) + logger.warning( + 'Failed to extract %s', sanitize_for_logging(file_path)) except Exception as exp: msg = f'Unzipping Error - {str(exp)}' logger.error(msg)