def testMemory(self): pwr_sid = self.pwr_sid admin_sid = self.admin_sid sd1 = win32security.SECURITY_DESCRIPTOR() sd2 = win32security.SECURITY_DESCRIPTOR() sd3 = win32security.SECURITY_DESCRIPTOR() dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_READ, pwr_sid) if admin_sid is not None: dacl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, admin_sid) sd4 = win32security.SECURITY_DESCRIPTOR() sacl = win32security.ACL() if admin_sid is not None: sacl.AddAuditAccessAce(win32security.ACL_REVISION, win32con.DELETE, admin_sid, 1, 1) sacl.AddAuditAccessAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, pwr_sid, 1, 1) for x in range(0, 200000): if admin_sid is not None: sd1.SetSecurityDescriptorOwner(admin_sid, 0) sd2.SetSecurityDescriptorGroup(pwr_sid, 0) sd3.SetSecurityDescriptorDacl(1, dacl, 0) sd4.SetSecurityDescriptorSacl(1, sacl, 0)
def restore_access(filepath): win32security.SetNamedSecurityInfo( filepath, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION | win32security.UNPROTECTED_SACL_SECURITY_INFORMATION, None, None, win32security.ACL(), win32security.ACL())
def setup_sacl(user_group_sid): """ Without this setup, the single user server will likely fail with either Error 0x0000142 or ExitCode -1073741502. This sets up access for the given user to the WinSta (Window Station) and Desktop objects. """ # Set access rights to window station h_win_sta = win32service.OpenWindowStation( "winsta0", False, win32con.READ_CONTROL | win32con.WRITE_DAC) # Get security descriptor by winsta0-handle sec_desc_win_sta = win32security.GetUserObjectSecurity( h_win_sta, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION | win32con.GROUP_SECURITY_INFORMATION) # Get DACL from security descriptor dacl_win_sta = sec_desc_win_sta.GetSecurityDescriptorDacl() if dacl_win_sta is None: # Create DACL if not exisiting dacl_win_sta = win32security.ACL() # Add ACEs to DACL for specific user group dacl_win_sta.AddAccessAllowedAce(win32security.ACL_REVISION_DS, GENERIC_ACCESS, user_group_sid) dacl_win_sta.AddAccessAllowedAce(win32security.ACL_REVISION_DS, WINSTA_ALL, user_group_sid) # Set modified DACL for winsta0 win32security.SetSecurityInfo(h_win_sta, win32security.SE_WINDOW_OBJECT, win32security.DACL_SECURITY_INFORMATION, None, None, dacl_win_sta, None) # Set access rights to desktop h_desktop = win32service.OpenDesktop( "default", 0, False, win32con.READ_CONTROL | win32con.WRITE_DAC | win32con.DESKTOP_WRITEOBJECTS | win32con.DESKTOP_READOBJECTS) # Get security descriptor by desktop-handle sec_desc_desktop = win32security.GetUserObjectSecurity( h_desktop, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION | win32con.GROUP_SECURITY_INFORMATION) # Get DACL from security descriptor dacl_desktop = sec_desc_desktop.GetSecurityDescriptorDacl() if dacl_desktop is None: #create DACL if not exisiting dacl_desktop = win32security.ACL() # Add ACEs to DACL for specific user group dacl_desktop.AddAccessAllowedAce(win32security.ACL_REVISION_DS, GENERIC_ACCESS, user_group_sid) dacl_desktop.AddAccessAllowedAce(win32security.ACL_REVISION_DS, DESKTOP_ALL, user_group_sid) # Set modified DACL for desktop win32security.SetSecurityInfo(h_desktop, win32security.SE_WINDOW_OBJECT, win32security.DACL_SECURITY_INFORMATION, None, None, dacl_desktop, None)
def setUp(self): testutils.change_priv(win32security.SE_SECURITY_NAME, True) self.filehandle, self.filename = tempfile.mkstemp() dacl = win32security.ACL() dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, 0, ntsecuritycon.FILE_READ_DATA, everyone) sacl = win32security.ACL() sacl.AddAuditAccessAce(win32security.ACL_REVISION_DS, ntsecuritycon.FILE_READ_DATA, everyone, 1, 1) win32security.SetNamedSecurityInfo( self.filename, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION, None, None, dacl, sacl)
def acl(dlp_file="acl.csv"): dlp_file = pd.read_csv(dlp_file) directory = ps.get('folder_protect', 'folder') + '/' for row in range(0, len(dlp_file)): if dlp_file['tags'][row] == 'confidential': # function to get and set ACL access_info = win32security.GetFileSecurity(directory + dlp_file['filename'][row], win32security.DACL_SECURITY_INFORMATION) # function to get owner info of a file owner_info = win32security.GetFileSecurity(directory + dlp_file['filename'][row], win32security.OWNER_SECURITY_INFORMATION) # lookup for SID of user everyone, domain, type = win32security.LookupAccountName("", "Everyone") admins, domain, type = win32security.LookupAccountName("", "Administrators") owner_sid = owner_info.GetSecurityDescriptorOwner() # set permission dacl = win32security.ACL() dacl.AddAccessDeniedAce(win32security.ACL_REVISION, con.SECURITY_NULL_RID, everyone) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, owner_sid) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins) # EXECUTE ORDER 66!!! access_info.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(directory + dlp_file['filename'][row], win32security.DACL_SECURITY_INFORMATION, access_info) print("File %s is now protected." % dlp_file['filename'][row]) elif dlp_file['tags'][row] == 'public': # function to get and set ACL access_info = win32security.GetFileSecurity(directory + dlp_file['filename'][row], win32security.DACL_SECURITY_INFORMATION) # function to get owner info of a file owner_info = win32security.GetFileSecurity(directory + dlp_file['filename'][row], win32security.OWNER_SECURITY_INFORMATION) # lookup for SID of user everyone, domain, type = win32security.LookupAccountName("", "Everyone") admins, domain, type = win32security.LookupAccountName("", "Administrators") owner_sid = owner_info.GetSecurityDescriptorOwner() # set permission dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, everyone) # EXECUTE ORDER 66!!! access_info.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(directory + dlp_file['filename'][row], win32security.DACL_SECURITY_INFORMATION, access_info)
def _generate_dacl(user_sid, mode): analysis = _analyze_mode(mode) # Get standard accounts from "well-known" sid # See the list here: # https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems system = win32security.ConvertStringSidToSid('S-1-5-18') admins = win32security.ConvertStringSidToSid('S-1-5-32-544') everyone = win32security.ConvertStringSidToSid('S-1-1-0') # New dacl, without inherited permissions dacl = win32security.ACL() # If user is already system or admins, any ACE defined here would be superseded by # the full control ACE that will be added after. if user_sid not in [system, admins]: # Handle user rights user_flags = _generate_windows_flags(analysis['user']) if user_flags: dacl.AddAccessAllowedAce(win32security.ACL_REVISION, user_flags, user_sid) # Handle everybody rights everybody_flags = _generate_windows_flags(analysis['all']) if everybody_flags: dacl.AddAccessAllowedAce(win32security.ACL_REVISION, everybody_flags, everyone) # Handle administrator rights full_permissions = _generate_windows_flags({'read': True, 'write': True, 'execute': True}) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, full_permissions, system) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, full_permissions, admins) return dacl
def GetACLObj(acl): security_obj = win32security.ACL() for x in range(len(acl)): ace = acl[x] ACL.SetACE(security_obj, ace['account_id'], ace['mask_bits'], ace['type'], ace['inherit_bits']) return security_obj
def set_file_readable(filename): import win32api import win32security import ntsecuritycon as con WinBuiltinUsersSid = 27 # not exported by win32security. according to WELL_KNOWN_SID_TYPE enumeration from http://msdn.microsoft.com/en-us/library/windows/desktop/aa379650%28v=vs.85%29.aspx users = win32security.CreateWellKnownSid(WinBuiltinUsersSid) WinBuiltinAdministratorsSid = 26 # not exported by win32security. according to WELL_KNOWN_SID_TYPE enumeration from http://msdn.microsoft.com/en-us/library/windows/desktop/aa379650%28v=vs.85%29.aspx admins = win32security.CreateWellKnownSid(WinBuiltinAdministratorsSid) user, domain, type = win32security.LookupAccountName( "", win32api.GetUserName()) sd = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, users) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION, sd)
def copyfileAndPermissions( source, destination ): ## uses shutil, stat, and os to copy preserving permissions shutil.copyfile(source, destination) if platform.system() == 'Windows': everyone, domain, type = win32security.LookupAccountName( "", "Everyone") admins, domain, type = win32security.LookupAccountName( "", "Administrators") user, domain, type = win32security.LookupAccountName( "", win32api.GetUserName()) sd = win32security.GetFileSecurity( destination, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.GENERIC_EXECUTE, everyone) dacl.AddAccessAllowedAce( win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE | con.GENERIC_EXECUTE, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(destination, win32security.DACL_SECURITY_INFORMATION, sd) else: runCmdAndHideOutput('chmod 755 ' + destination) ## my wonderful hack O_o
def make_data_folder(folder, allow_add_file=False): try: os.makedirs(folder) except: pass # Set inheritance flags flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE # Set permissions on this folder so that it isn't viewable by students sd = win32security.GetFileSecurity(folder, win32security.DACL_SECURITY_INFORMATION) # Create the blank DACL and add our ACE's dacl = win32security.ACL() #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ, EVERYONE) # Setup a folder where sshot running as the student can add pics, but can't delete/modify anythin if allow_add_file == True: dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ADD_FILE, EVERYONE) #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_WRITE, CURRENT_USER) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS) #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, ADMINISTRATORS) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER) #dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, SYSTEM_USER) # Set our ACL sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity( folder, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
def AddACL(username, folder): try: account_sid = (win32security.LookupAccountName(None, username))[0] everyone = win32security.LookupAccountName("", "Everyone")[0] system = win32security.LookupAccountName("", "System")[0] creator = win32security.LookupAccountName("", "CREATOR OWNER")[0] domain_admins = win32security.LookupAccountName("", "Domain Admins")[0] wolfbyte = win32security.LookupAccountName(None, "wolfbyte")[0] devon = win32security.LookupAccountName(None, "devon.dieffenbach")[0] dacl = win32security.ACL() dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, ntsecuritycon.FILE_ALL_ACCESS, account_sid) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 2032127, system) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 19, 2032127, domain_admins) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 2032127, wolfbyte) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 19, 2032127, devon) dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 2031616, creator) sd = win32security.GetFileSecurity( folder, win32security.DACL_SECURITY_INFORMATION) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(folder, win32security.DACL_SECURITY_INFORMATION, sd) except Exception as er: cprint("AddACL exception %s on %s" % (type(er).__name__, folder))
def change_acl_for_delete(path): """Zaps the SECURITY_DESCRIPTOR's DACL on a directory entry that is tedious to delete. This function is a heavy hammer. It discards the SECURITY_DESCRIPTOR and creates a new one with only one DACL set to user:FILE_ALL_ACCESS. Used as last resort. """ STANDARD_RIGHTS_REQUIRED = 0xf0000 SYNCHRONIZE = 0x100000 FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff import win32security user, _domain, _type = win32security.LookupAccountName( '', getpass.getuser()) sd = win32security.SECURITY_DESCRIPTOR() sd.Initialize() sd.SetSecurityDescriptorOwner(user, False) dacl = win32security.ACL() dacl.Initialize() dacl.AddAccessAllowedAce( win32security.ACL_REVISION_DS, FILE_ALL_ACCESS, user) sd.SetSecurityDescriptorDacl(1, dacl, 0) # Note that this assumes the object is either owned by the current user or # its group or that the current ACL permits this. Otherwise it will silently # fail. win32security.SetFileSecurity( fs.extend(path), win32security.DACL_SECURITY_INFORMATION, sd) # It's important to also look for the read only bit after, as it's possible # the set_read_only() call to remove the read only bit had silently failed # because there was no DACL for the user. if not (os.stat(path).st_mode & stat.S_IWUSR): os.chmod(path, 0777)
def win32_restrict_file_to_user(fname): """Secure a windows file to read-only access for the user. Follows guidance from win32 library creator: http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html This method should be executed against an already generated file which has no secrets written to it yet. Parameters ---------- fname : unicode The path to the file to secure """ import win32api import win32security import ntsecuritycon as con # everyone, _domain, _type = win32security.LookupAccountName("", "Everyone") admins = win32security.CreateWellKnownSid(win32security.WinBuiltinAdministratorsSid) user, _domain, _type = win32security.LookupAccountName("", win32api.GetUserName()) sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL() # dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, everyone) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION, sd)
def chown(path, user, group): ''' Chown a file, pass the file the desired user and group CLI Example:: salt '*' file.chown c:\\temp\\test.txt myusername administrators ''' # I think this function isn't working correctly yet sd = win32security.GetFileSecurity (path, win32security.DACL_SECURITY_INFORMATION) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': err += 'User does not exist\n' if gid == '': err += 'Group does not exist\n' if not os.path.exists(path): err += 'File not found' if err: return err dacl = win32security.ACL () dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, win32security.GetBinarySid(uid)) dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, win32security.GetBinarySid(gid)) sd.SetSecurityDescriptorDacl (1, dacl, 0) return win32security.SetFileSecurity (path, win32security.DACL_SECURITY_INFORMATION, sd)
def test_access_inputfile_failed(): with open(input_file_example['input_file'], 'w') as fp: fp.write('test') if sys.platform == "win32": sd = win32security.GetFileSecurity( input_file_example['input_file'], win32security.DACL_SECURITY_INFORMATION) everyone, domain, type = win32security.LookupAccountName( "", "Everyone") dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_WRITE, everyone) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(input_file_example['input_file'], win32security.DACL_SECURITY_INFORMATION, sd) else: os.chmod(input_file_example['input_file'], 0o222) with pytest.raises(mm.ValidationError): ArgSchemaParser(input_data=input_file_example, schema_type=BasicInputFile, args=[]) os.remove(input_file_example['input_file'])
def change_acl_for_delete_win(path): """Zaps the SECURITY_DESCRIPTOR's DACL on a directory entry that is tedious to delete. This function is a heavy hammer. It discards the SECURITY_DESCRIPTOR and creates a new one with only one DACL set to user:FILE_ALL_ACCESS. Used as last resort. """ assert isinstance(path, unicode), path STANDARD_RIGHTS_REQUIRED = 0xf0000 SYNCHRONIZE = 0x100000 FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff import win32security user, _domain, _type = win32security.LookupAccountName( '', getpass.getuser()) sd = win32security.SECURITY_DESCRIPTOR() sd.Initialize() sd.SetSecurityDescriptorOwner(user, False) dacl = win32security.ACL() dacl.Initialize() dacl.AddAccessAllowedAce(win32security.ACL_REVISION_DS, FILE_ALL_ACCESS, user) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
def test_acl_PyACL(self): dacl = win32security.ACL() dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, 0, ntsecuritycon.FILE_READ_DATA, everyone) acl = _acls.acl(dacl).pyobject() assert dacl.GetAceCount() == 1 assert dacl.GetAce(0) == ((win32security.ACCESS_ALLOWED_ACE_TYPE, 0), ntsecuritycon.FILE_READ_DATA, everyone)
def chmod(path, mode): # get the ugo out of the dacl Everyone,_,_ = win32security.LookupAccountName("", "Everyone") User,Group = None,None import pwd sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() for index in xrange(dacl.GetAceCount()): _,_,sid = dacl.GetAce(index) name,domain,sidtype = win32security.LookupAccountSid(None,sid) # figure out the account type if sidtype == ntsecuritycon.SidTypeUser and User is None: User = sid if sidtype == ntsecuritycon.SidTypeGroup and Group is None: Group = sid continue # default to Guest if User is None: User,_,_ = win32security.LookupAccountName("", "Guest") # find the first group associated with User if Group is None: name,domain,_ = win32security.LookupAccountSid(None,User) acct = pwd.Query.ByName(domain,name) Group = pwd.Query.Group(acct)['user_sid'] # generate ACL from mode dacl = win32security.ACL() res = 0 if mode & stat.S_IXOTH: res |= ntsecuritycon.FILE_GENERIC_EXECUTE if mode & stat.S_IWOTH: res |= ntsecuritycon.FILE_GENERIC_WRITE if mode & stat.S_IROTH: res |= ntsecuritycon.FILE_GENERIC_READ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, res, Everyone) res = 0 if mode & stat.S_IXGRP: res |= ntsecuritycon.FILE_GENERIC_EXECUTE if mode & stat.S_IWGRP: res |= ntsecuritycon.FILE_GENERIC_WRITE if mode & stat.S_IRGRP: res |= ntsecuritycon.FILE_GENERIC_READ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, res, Group) res = 0 if mode & stat.S_IXUSR: res |= ntsecuritycon.FILE_GENERIC_EXECUTE if mode & stat.S_IWUSR: res |= ntsecuritycon.FILE_GENERIC_WRITE if mode & stat.S_IRUSR: res |= ntsecuritycon.FILE_GENERIC_READ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, res, User) sd.SetSecurityDescriptorDacl(1, dacl, 0) res = win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd) return -1 if res == 0 else 0
def set_read_only(self) : sd = win32security.GetFileSecurity (self.path, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL () # Everyone read only dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.GENERIC_READ, self.everyone) sd.SetSecurityDescriptorDacl (1, dacl, 0) win32security.SetFileSecurity (self.path, win32security.DACL_SECURITY_INFORMATION, sd)
def _deny_access(fh): import win32security import ntsecuritycon as con user, _, _ = win32security.LookupAccountName("", win32api.GetUserName()) dacl = win32security.ACL() dacl.AddAccessDeniedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user) win32security.SetSecurityInfo(fh, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None)
def remove_access(path=r"software\winsys"): hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, path, 0, win32con.READ_CONTROL | win32con.WRITE_DAC) dacl = win32security.ACL() win32security.SetSecurityInfo( hKey, win32security.SE_REGISTRY_KEY, win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION, None, None, dacl, None)
def test_Security_set_sacl_empty(self): s = security.security() s.sacl = [] assert len(s.sacl) == 0 assert s.pyobject().GetSecurityDescriptorSacl().GetAceCount() == 0 sd = win32security.SECURITY_DESCRIPTOR() acl = win32security.ACL() sd.SetSecurityDescriptorSacl(1, acl, 0) assert equal(sd, s)
def __init__(self, obj_name=None, obj_type='file'): ''' Either load the DACL from the passed object or create an empty DACL. If `obj_name` is not passed, an empty DACL is created. Args: obj_name (str): The full path to the object. If None, a blank DACL will be created obj_type (Optional[str]): The type of object. Returns: obj: A DACL object Usage: .. code-block:: python # Create an Empty DACL dacl = Dacl(obj_type=obj_type) # Load the DACL of the named object dacl = Dacl(obj_name, obj_type) ''' # Validate obj_type if obj_type.lower() not in self.obj_type: raise SaltInvocationError( 'Invalid "obj_type" passed: {0}'.format(obj_type)) self.dacl_type = obj_type.lower() if obj_name is None: self.dacl = win32security.ACL() else: if self.dacl_type in ['registry', 'registry32']: obj_name = self.get_reg_name(obj_name) sd = win32security.GetNamedSecurityInfo( obj_name, self.obj_type[self.dacl_type], self.element['dacl']) self.dacl = sd.GetSecurityDescriptorDacl() if self.dacl is None: self.dacl = win32security.ACL()
def setUpSACL(self): sacl = win32security.ACL() sid, _, _ = win32security.LookupAccountName(None, win32api.GetUserName()) sacl.AddAuditAccessAceEx( win32security.ACL_REVISION_DS, win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE, ntsecuritycon.FILE_ALL_ACCESS, sid, 1, 1) win32security.SetNamedSecurityInfo( self.TEST_ROOT, win32security.SE_FILE_OBJECT, win32security.SACL_SECURITY_INFORMATION, None, None, None, sacl)
def tearDown (self): hKey = win32api.RegOpenKeyEx (win32con.HKEY_CURRENT_USER, r"Software\winsys", 0, win32con.READ_CONTROL|win32con.WRITE_DAC) dacl = win32security.ACL () sid, _, _ = win32security.LookupAccountName (None, win32api.GetUserName ()) dacl.AddAccessAllowedAce (win32security.ACL_REVISION_DS, win32con.KEY_ALL_ACCESS, sid) win32security.SetSecurityInfo ( hKey, win32security.SE_REGISTRY_KEY, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, dacl, None ) remove_key (win32con.HKEY_CURRENT_USER, r"Software\winsys")
def auditFile(fileName, auditVal): # # Find the SIDs for Everyone, the Admin group and the current user # everyone, domain, type = win32security.LookupAccountName("", "Everyone") admins, domain, type = win32security.LookupAccountName( "", "Administrators") user, domain, type = win32security.LookupAccountName( "", win32api.GetUserName()) # # Touch the file and use CACLS to show its default permissions # (which will probably be: Admins->Full; Owner->Full; Everyone->Read) # open(fileName, "w").close() show_cacls(fileName) # # Find the DACL part of the Security Descriptor for the file # sd = win32security.GetFileSecurity(fileName, win32security.DACL_SECURITY_INFORMATION) # # Create a blank DACL and add the three ACEs we want # We will completely replace the original DACL with # this. Obviously you might want to alter the original # instead. # # Read : 1179785 # Write : 1179926 # Execute : 1179808 # Read | Write: 1180063 # Read | Execute: 1179817 # Write | Execute: 1180086 # Full: 2032639 # dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, auditVal, everyone) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, auditVal, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, auditVal, admins) # # Put our new DACL into the Security Descriptor, # update the file with the updated SD, and use # CACLS to show what's what. # sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(fileName, win32security.DACL_SECURITY_INFORMATION, sd) show_cacls(fileName)
def test_Security_add_to_dacl_simple(): administrator = security.principal("Administrator") s = security.security() s.dacl = [] s.dacl.append(("Administrator", "F", "ALLOW")) sd = win32security.SECURITY_DESCRIPTOR() dacl = win32security.ACL() dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, security.DACE.FLAGS, ntsecuritycon.GENERIC_ALL, administrator.pyobject()) sd.SetSecurityDescriptorDacl(1, dacl, 0) assert equal(sd, s)
def test_Security_add_to_sacl_simple(): administrator = security.principal("Administrator") s = security.security() s.sacl = [] s.sacl.append(("Administrator", "F", "SUCCESS")) sd = win32security.SECURITY_DESCRIPTOR() sacl = win32security.ACL() sacl.AddAuditAccessAceEx(win32security.ACL_REVISION_DS, security.SACE.FLAGS, ntsecuritycon.GENERIC_ALL, administrator.pyobject(), 1, 0) sd.SetSecurityDescriptorSacl(1, sacl, 0) assert equal(sd, s)
def set_share(self) : sd = win32security.GetFileSecurity (self.path, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL () # Every one can read only dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.GENERIC_READ, self.everyone) #This user will have full access dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.user) sd.SetSecurityDescriptorDacl (1, dacl, 0) win32security.SetFileSecurity (self.path, win32security.DACL_SECURITY_INFORMATION, sd)
def grantEveryoneFilePermission(self, dirpath, filepath=""): """Grant full control to the group I{Everyone} in this folder and all sub-folders This function grants full control to the Windows group I{Everyone} for files in the C{dirpath} its sub-folders. If a C{filepath} is specified, only the permissions of a specific file are updated. @type dirpath: string @param dirpath: The full path of the folder for which these permissions are set @type filepath: string @param filepath: The full path to a specific file. """ # Execute command only on NTFS filesystem. Otherwise pass silently fullpath = os.path.abspath(dirpath) driveLetter = os.path.splitdrive(fullpath)[0] if not self.isNTFSVolume(driveLetter): pylabs.q.logger.log( "Skipped file permissions update - filesystem for [%s] is not NTFS" % dirpath, 6) return def _grantFile(fileName, securityDescriptor): '''Set security on a file''' pylabs.q.logger.log( "granting all access to everyone on %s" % fileName, 6) win32security.SetFileSecurity( fileName, win32security.DACL_SECURITY_INFORMATION, securityDescriptor) def _grantDir(dirpath, securityDescriptor): '''Set security on a folder''' for dir in pylabs.q.system.fs.listDirsInDir(dirpath): _grantDir(dir, securityDescriptor) for file in pylabs.q.system.fs.listFilesInDir(dirpath): _grantFile(file, securityDescriptor) win32security.SetFileSecurity( dirpath, win32security.DACL_SECURITY_INFORMATION, securityDescriptor) # create the security descriptor sd = win32security.SECURITY_DESCRIPTOR() # fill it: everyone = win32security.ConvertStringSidToSid('S-1-1-0') acl = win32security.ACL(128) acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, everyone) sd.SetSecurityDescriptorDacl(1, acl, 0) if filepath == "": # it's a dir _grantDir(dirpath, sd) else: _grantFile(os.path.join(dirpath, filepath), sd)