diff --git a/monkey/monkey_island/cc/server_utils/file_utils.py b/monkey/monkey_island/cc/server_utils/file_utils.py index 225fb8732..6a474355a 100644 --- a/monkey/monkey_island/cc/server_utils/file_utils.py +++ b/monkey/monkey_island/cc/server_utils/file_utils.py @@ -3,3 +3,10 @@ import os def expand_path(path: str) -> str: return os.path.expandvars(os.path.expanduser(path)) + + +def has_expected_permissions(path: str, expected_permissions: int) -> bool: + file_mode = os.stat(path).st_mode + file_permissions = file_mode & 0o777 + + return file_permissions == expected_permissions diff --git a/monkey/monkey_island/cc/services/utils/file_handling.py b/monkey/monkey_island/cc/services/utils/file_handling.py index 114405647..e6c4839d2 100644 --- a/monkey/monkey_island/cc/services/utils/file_handling.py +++ b/monkey/monkey_island/cc/services/utils/file_handling.py @@ -1,6 +1,7 @@ import os from common.utils.exceptions import InsecurePermissionsError +from monkey_island.cc.server_utils.file_utils import has_expected_permissions def ensure_file_existence(file: str) -> None: @@ -9,14 +10,7 @@ def ensure_file_existence(file: str) -> None: def ensure_file_permissions(file: str) -> None: - if not file_has_expected_permissions(path=file, expected_permissions="0o400"): + if not has_expected_permissions(path=file, expected_permissions="0o400"): raise InsecurePermissionsError( f"{file} has insecure permissions. Required permissions: 400. Exiting." ) - - -def file_has_expected_permissions(path: str, expected_permissions: str) -> bool: - file_mode = os.stat(path).st_mode - file_permissions = oct(file_mode & 0o777) - - return file_permissions == expected_permissions diff --git a/monkey/tests/unit_tests/monkey_island/cc/server_utils/test_file_utils.py b/monkey/tests/unit_tests/monkey_island/cc/server_utils/test_file_utils.py index cff716135..79409ba7a 100644 --- a/monkey/tests/unit_tests/monkey_island/cc/server_utils/test_file_utils.py +++ b/monkey/tests/unit_tests/monkey_island/cc/server_utils/test_file_utils.py @@ -1,5 +1,7 @@ import os +import pytest + from monkey_island.cc.server_utils import file_utils @@ -15,3 +17,28 @@ def test_expand_vars(patched_home_env): expected_path = os.path.join(patched_home_env, "test") assert file_utils.expand_path(input_path) == expected_path + + +@pytest.mark.skipif(os.name != "posix", reason="Tests Posix (not Windows) permissions.") +def test_has_expected_permissions_true(tmpdir): + file_name = f"{tmpdir}/test" + + create_empty_file(file_name) + os.chmod(file_name, 0o754) + + assert file_utils.has_expected_permissions(file_name, 0o754) + + +@pytest.mark.skipif(os.name != "posix", reason="Tests Posix (not Windows) permissions.") +def test_has_expected_permissions_false(tmpdir): + file_name = f"{tmpdir}/test" + + create_empty_file(file_name) + os.chmod(file_name, 0o755) + + assert not file_utils.has_expected_permissions(file_name, 0o700) + + +def create_empty_file(file_name): + with open(file_name, "w"): + pass