From b39440e871e9f25a6090cc7dd36eeadff3f46813 Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Sat, 19 Jun 2021 08:55:53 -0400 Subject: [PATCH] island: Return a fd instead of PyHandle during windows file creation Fixes #1252 --- monkey/monkey_island/cc/server_utils/file_utils.py | 9 +++++---- .../monkey_island/cc/server_utils/test_file_utils.py | 3 +-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/monkey/monkey_island/cc/server_utils/file_utils.py b/monkey/monkey_island/cc/server_utils/file_utils.py index 995501c09..1cda9a6d3 100644 --- a/monkey/monkey_island/cc/server_utils/file_utils.py +++ b/monkey/monkey_island/cc/server_utils/file_utils.py @@ -79,8 +79,7 @@ def _get_file_descriptor_for_new_secure_file_linux(path: str) -> int: def _get_file_descriptor_for_new_secure_file_windows(path: str) -> int: try: file_access = win32file.GENERIC_READ | win32file.GENERIC_WRITE - # subsequent open operations on the object will succeed only if read access is requested - file_sharing = win32file.FILE_SHARE_READ + file_sharing = win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE security_attributes = win32security.SECURITY_ATTRIBUTES() security_attributes.SECURITY_DESCRIPTOR = ( windows_permissions.get_security_descriptor_for_owner_only_perms() @@ -88,7 +87,7 @@ def _get_file_descriptor_for_new_secure_file_windows(path: str) -> int: file_creation = win32file.CREATE_NEW # fails if file exists file_attributes = win32file.FILE_FLAG_BACKUP_SEMANTICS - fd = win32file.CreateFile( + handle = win32file.CreateFile( path, file_access, file_sharing, @@ -98,7 +97,9 @@ def _get_file_descriptor_for_new_secure_file_windows(path: str) -> int: _get_null_value_for_win32(), ) - return fd + detached_handle = handle.Detach() + + return win32file._open_osfhandle(detached_handle, os.O_RDWR) except Exception as ex: LOG.error(f'Could not create a file at "{path}": {str(ex)}') 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 894f1e6b3..756c6452d 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 @@ -12,7 +12,6 @@ from monkey_island.cc.server_utils.file_utils import ( if is_windows_os(): import win32api - import win32file import win32security FULL_CONTROL = 2032127 @@ -125,7 +124,7 @@ def test_get_file_descriptor_for_new_secure_file__perm_linux(test_path): @pytest.mark.skipif(not is_windows_os(), reason="Tests Windows (not Posix) permissions.") def test_get_file_descriptor_for_new_secure_file__perm_windows(test_path): - win32file.CloseHandle(get_file_descriptor_for_new_secure_file(test_path)) + os.close(get_file_descriptor_for_new_secure_file(test_path)) acl, user_sid = _get_acl_and_sid_from_path(test_path)