Change data_dir permissions on Windows

This commit is contained in:
shreyamalviya 2021-05-18 23:32:44 +05:30 committed by Shreya
parent ff1e6bdb2c
commit a1beee95f3
2 changed files with 38 additions and 0 deletions

View File

@ -1,13 +1,46 @@
import os
import ntsecuritycon
import win32api
import win32con
import win32security
from monkey_island.cc.environment.os import is_windows_os
from monkey_island.cc.server_utils.consts import DEFAULT_DATA_DIR
def create_data_dir(data_dir: str) -> None:
if not os.path.isdir(data_dir):
os.makedirs(data_dir, mode=0o700)
if is_windows_os(): # `mode=0o700` doesn't work on Windows
set_data_dir_security_to_read_by_owner(data_dir_path=data_dir)
def create_default_data_dir() -> None:
if not os.path.isdir(DEFAULT_DATA_DIR):
os.mkdir(DEFAULT_DATA_DIR, mode=0o700)
if is_windows_os(): # `mode=0o700` doesn't work on Windows
set_data_dir_security_to_read_by_owner(data_dir_path=DEFAULT_DATA_DIR)
def set_data_dir_security_to_read_by_owner(data_dir_path: str) -> None:
user = get_user_pySID_object() # current user is newly created data dir's owner
security_descriptor = win32security.GetFileSecurity(
data_dir_path, win32security.DACL_SECURITY_INFORMATION
)
dacl = win32security.ACL()
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ, user)
security_descriptor.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetFileSecurity(
data_dir_path, win32security.DACL_SECURITY_INFORMATION, security_descriptor
)
def get_user_pySID_object():
# get current user's name
username = win32api.GetUserNameEx(win32con.NameSamCompatible)
# pySID object for the current user
user, _, _ = win32security.LookupAccountName("", username)
return user

View File

@ -0,0 +1,5 @@
import sys
def is_windows_os():
return sys.platform.startswith("win")