Extract file checking activities

This commit is contained in:
Shreya 2021-06-07 13:14:31 +05:30
parent d740173f79
commit 53a126482f
3 changed files with 28 additions and 19 deletions

View File

@ -0,0 +1,22 @@
import os
from common.utils.exceptions import InsecurePermissionsError
def ensure_file_existence(file: str) -> None:
if not os.path.exists(file):
raise FileNotFoundError(f"File not found at {file}. Exiting.")
def ensure_file_permissions(file: str) -> None:
if not file_has_sufficient_permissions(path=file, required_permissions="0o400"):
raise InsecurePermissionsError(
f"{file} has insecure permissions. Required permissions: r--------. Exiting."
)
def file_has_sufficient_permissions(path: str, required_permissions: str) -> bool:
file_mode = os.stat(path).st_mode
file_permissions = oct(file_mode & 0o777)
return file_permissions == required_permissions

View File

@ -1,8 +0,0 @@
import os
def has_sufficient_permissions(path: str, required_permissions: str) -> bool:
file_mode = os.stat(path).st_mode
file_permissions = oct(file_mode & 0o777)
return file_permissions == required_permissions

View File

@ -1,8 +1,9 @@
import logging
import os
from common.utils.exceptions import InsecurePermissionsError
from monkey_island.cc.services.utils.file_permissions import has_sufficient_permissions
from monkey_island.cc.services.utils.file_handling import (
ensure_file_existence,
ensure_file_permissions,
)
from monkey_island.cc.setup.island_config_options import IslandConfigOptions
logger = logging.getLogger(__name__)
@ -12,15 +13,9 @@ def setup_certificate(config_options: IslandConfigOptions) -> (str, str):
crt_path = config_options.crt_path
key_path = config_options.key_path
# check paths
for file in [crt_path, key_path]:
if not os.path.exists(file):
raise FileNotFoundError(f"File not found at {file}. Exiting.")
if not has_sufficient_permissions(path=file, required_permissions="0o400"):
raise InsecurePermissionsError(
f"{file} has insecure permissions. Required permissions: r--------. Exiting."
)
ensure_file_existence(file)
ensure_file_permissions(file)
logger.info(f"Using certificate path: {crt_path}, and key path: {key_path}.")