Fixed a race condition for linux secure directory creation, by setting dir permissions on creation.

This commit is contained in:
VakarisZ 2021-06-10 11:44:50 +03:00
parent 2fc726dc78
commit 36e0309409
3 changed files with 7 additions and 18 deletions

View File

@ -1,7 +0,0 @@
import os
import stat
def set_perms_to_owner_only(path: str):
# Read, write, and execute by owner
os.chmod(path, stat.S_IRWXU)

View File

@ -9,24 +9,24 @@ def is_windows_os() -> bool:
if is_windows_os(): if is_windows_os():
import monkey_island.cc.environment.windows_permissions as windows_permissions import monkey_island.cc.environment.windows_permissions as windows_permissions
else:
import monkey_island.cc.environment.linux_permissions as linux_permissions # noqa: E402
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
def create_secure_directory(path: str, create_parent_dirs: bool): def create_secure_directory(path: str, create_parent_dirs: bool):
if not os.path.isdir(path): if not os.path.isdir(path):
create_directory(path, create_parent_dirs) _create_secure_directory(path, create_parent_dirs)
set_secure_permissions(path) set_secure_permissions(path)
def create_directory(path: str, create_parent_dirs: bool): def _create_secure_directory(path: str, create_parent_dirs: bool):
try: try:
if create_parent_dirs: if create_parent_dirs:
os.makedirs(path) # Don't split directory creation and permission setting
# because it will temporarily create an accessible directory which anyone can use.
os.makedirs(path, mode=0o700)
else: else:
os.mkdir(path) os.mkdir(path, mode=0o700)
except Exception as ex: except Exception as ex:
LOG.error( LOG.error(
f'Could not create a directory at "{path}" (maybe environmental variables could not be ' f'Could not create a directory at "{path}" (maybe environmental variables could not be '
@ -39,8 +39,6 @@ def set_secure_permissions(dir_path: str):
try: try:
if is_windows_os(): if is_windows_os():
windows_permissions.set_perms_to_owner_only(folder_path=dir_path) windows_permissions.set_perms_to_owner_only(folder_path=dir_path)
else:
linux_permissions.set_perms_to_owner_only(path=dir_path)
except Exception as ex: except Exception as ex:
LOG.error(f"Permissions could not be set successfully for {dir_path}: {str(ex)}") LOG.error(f"Permissions could not be set successfully for {dir_path}: {str(ex)}")
raise ex raise ex

View File

@ -8,9 +8,7 @@ from monkey_island.cc.environment.utils import create_secure_directory, is_windo
@pytest.fixture @pytest.fixture
def test_path_nested(tmpdir): def test_path_nested(tmpdir):
nested_path = "test1/test2/test3" path = os.path.join(tmpdir, "test1", "test2", "test3")
path = os.path.join(tmpdir, nested_path)
return path return path