Island: Add logging to DirectoryFileStorageService

This commit is contained in:
Mike Salvatore 2022-04-26 19:54:12 -04:00
parent 4ddcd5e9a8
commit e8e879091d
1 changed files with 9 additions and 0 deletions

View File

@ -1,3 +1,4 @@
import logging
import shutil import shutil
from pathlib import Path from pathlib import Path
from typing import BinaryIO from typing import BinaryIO
@ -7,6 +8,8 @@ from monkey_island.cc.server_utils.file_utils import create_secure_directory
from . import FileRetrievalError, IFileStorageService from . import FileRetrievalError, IFileStorageService
logger = logging.getLogger(__name__)
class DirectoryFileStorageService(IFileStorageService): class DirectoryFileStorageService(IFileStorageService):
""" """
@ -30,6 +33,7 @@ class DirectoryFileStorageService(IFileStorageService):
def save_file(self, unsafe_file_name: str, file_contents: BinaryIO): def save_file(self, unsafe_file_name: str, file_contents: BinaryIO):
safe_file_path = self._get_safe_file_path(unsafe_file_name) safe_file_path = self._get_safe_file_path(unsafe_file_name)
logger.debug(f"Saving file contents to {safe_file_path}")
with open(safe_file_path, "wb") as dest: with open(safe_file_path, "wb") as dest:
shutil.copyfileobj(file_contents, dest) shutil.copyfileobj(file_contents, dest)
@ -37,14 +41,17 @@ class DirectoryFileStorageService(IFileStorageService):
safe_file_path = self._get_safe_file_path(unsafe_file_name) safe_file_path = self._get_safe_file_path(unsafe_file_name)
try: try:
logger.debug(f"Opening {safe_file_path}")
return open(safe_file_path, "rb") return open(safe_file_path, "rb")
except OSError as err: except OSError as err:
logger.error(err)
raise FileRetrievalError(f"Failed to retrieve file {safe_file_path}: {err}") from err raise FileRetrievalError(f"Failed to retrieve file {safe_file_path}: {err}") from err
def delete_file(self, unsafe_file_name: str): def delete_file(self, unsafe_file_name: str):
safe_file_path = self._get_safe_file_path(unsafe_file_name) safe_file_path = self._get_safe_file_path(unsafe_file_name)
try: try:
logger.debug(f"Deleting {safe_file_path}")
safe_file_path.unlink() safe_file_path.unlink()
except FileNotFoundError: except FileNotFoundError:
pass pass
@ -58,8 +65,10 @@ class DirectoryFileStorageService(IFileStorageService):
if self._storage_directory.resolve() not in safe_file_path.parents: if self._storage_directory.resolve() not in safe_file_path.parents:
raise ValueError(f"The file named {unsafe_file_name} can not be safely retrieved") raise ValueError(f"The file named {unsafe_file_name} can not be safely retrieved")
logger.debug(f"Unsafe file name {unsafe_file_name} sanitized: {safe_file_path}")
return safe_file_path return safe_file_path
def delete_all_files(self): def delete_all_files(self):
for file in get_all_regular_files_in_directory(self._storage_directory): for file in get_all_regular_files_in_directory(self._storage_directory):
logger.debug(f"Deleting {file}")
file.unlink() file.unlink()