Skip to content

Commit

Permalink
Sanitize logging untrusted filenames
Browse files Browse the repository at this point in the history
  • Loading branch information
ajinabraham committed Nov 28, 2024
1 parent c29144a commit 8a5ea49
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
12 changes: 12 additions & 0 deletions mobsf/MobSF/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
12 changes: 9 additions & 3 deletions mobsf/StaticAnalyzer/views/common/shared_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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)
Expand Down

0 comments on commit 8a5ea49

Please sign in to comment.