def _win_is_executable(path): if not os.path.isfile(path): return False security = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION) dacl = security.GetSecurityDescriptorDacl() mode = dacl.GetEffectiveRightsFromAcl({ 'TrusteeForm': win32security.TRUSTEE_IS_SID, 'TrusteeType': win32security.TRUSTEE_IS_USER, 'Identifier': _get_current_user(), }) return mode & ntsecuritycon.FILE_GENERIC_EXECUTE == ntsecuritycon.FILE_GENERIC_EXECUTE
def has_same_ownership(path1, path2): # type: (str, str) -> bool """ Return True if the ownership of two files given their respective path is the same. On Windows, ownership is checked against owner only, since files do not have a group owner. :param str path1: path to the first file :param str path2: path to the second file :return: True if both files have the same ownership, False otherwise :rtype: bool """ if POSIX_MODE: stats1 = os.stat(path1) stats2 = os.stat(path2) return (stats1.st_uid, stats1.st_gid) == (stats2.st_uid, stats2.st_gid) security1 = win32security.GetFileSecurity(path1, win32security.OWNER_SECURITY_INFORMATION) user1 = security1.GetSecurityDescriptorOwner() security2 = win32security.GetFileSecurity(path2, win32security.OWNER_SECURITY_INFORMATION) user2 = security2.GetSecurityDescriptorOwner() return user1 == user2
def __get_owner_windows(self): r""" Return the name of the owner of this file or directory. Follow symbolic links. Return a name of the form ``ur'DOMAIN\User Name'``; may be a group. .. seealso:: :attr:`owner` """ desc = win32security.GetFileSecurity( self, win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) return domain + u('\\') + account
def get_user(path): ''' Return the user that owns a given file CLI Example:: salt '*' file.get_user c:\\temp\\test.txt ''' secdesc = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = secdesc.GetSecurityDescriptorOwner() name, domain, account_type = win32security.LookupAccountSid( None, owner_sid) return name
def get_gid(path): ''' Return the id of the group that owns a given file CLI Example:: salt '*' file.get_gid c:\\temp\\test.txt ''' if not os.path.exists(path): return False secdesc = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = secdesc.GetSecurityDescriptorOwner() return win32security.ConvertSidToStringSid(owner_sid)
def checkDockerFolderPermissions(): print("\n[#] Checking permissions for C:\ProgramData\docker...") #if os.path.isfile('C:\ProgramData\docker'): f = win32security.GetFileSecurity( "C:\ProgramData\docker", win32security.OWNER_SECURITY_INFORMATION) (username, domain, sid_name_use) = win32security.LookupAccountSid( None, f.GetSecurityDescriptorOwner()) if username != 'Administrator': print( bcolors.WARNING + "Directory C:\\ProgramData\docker is not owned by Administrator" + bcolors.ENDC)
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 modify_file_permission_windows(): import win32security import ntsecuritycon user, domain, account_type = win32security.LookupAccountName( None, f"{platform.node()}\\{os.getlogin()}") sd = win32security.GetFileSecurity( path_to_file, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, user) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(path_to_file, win32security.DACL_SECURITY_INFORMATION, sd)
def get_group(path): ''' Return the group that owns a given file CLI Example:: salt '*' file.get_group c:\\temp\\test.txt ''' if not os.path.exists(path): return False secdesc = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = secdesc.GetSecurityDescriptorOwner() name, domain, type = win32security.LookupAccountSid(None, owner_sid) return name
def GetFileOwner(path): try: if platform.system() == 'Windows': # This only works if pywin32 is installed. # Try "pip install pypiwin32". import win32security as w32s fs = w32s.GetFileSecurity(path, w32s.OWNER_SECURITY_INFORMATION) sdo = fs.GetSecurityDescriptorOwner() name, domain, use = w32.LookupAccountSid(None, sdo) return "%s\\%s" % (domain, name) else: import pwd return pwd.getpwuid(os.stat(path).st_uid).pw_name except: return "<unknown>"
def get_ownership(path: str) -> Tuple[str, str, int]: """ Returns owner from Path :param path: (str) path to directory / file to check :return: (tuple) ('owner', 'group', 'privilege') """ try: sec_descriptor = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION) sid = sec_descriptor.GetSecurityDescriptorOwner() return win32security.LookupAccountSid(None, sid) except pywintypes.error as exc: # Let's raise OSError so we don't need to import pywintypes in parent module to catch the exception raise OSError('Cannot get owner of file: {0}. {1}'.format(path, exc))
def get_file_security(path, info): # Windows API call descriptor = win32security.GetFileSecurity(path, info) # Extract SDDL sddl = win32security.ConvertSecurityDescriptorToStringSecurityDescriptor( descriptor, win32security.SDDL_REVISION_1, win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION, ) return {"Sddl": sddl}
def is_private(path): """ Return True if `path` is accessible only by 'owner'. path: string Path to file or directory to check. .. note:: On Windows this requires the pywin32 extension. """ if not os.path.exists(path): return True # Nonexistent file is secure ;-) if sys.platform == 'win32': # pragma no cover if not HAVE_PYWIN32: return False # No way to know. # Find the SIDs for user and system. username = win32api.GetUserNameEx(win32con.NameSamCompatible) # Map Cygwin 'root' to 'Administrator'. Typically these are intended # to be identical, but /etc/passwd might configure them differently. if username.endswith('\\root'): username = username.replace('\\root', '\\Administrator') user, domain, type = win32security.LookupAccountName('', username) system, domain, type = win32security.LookupAccountName('', 'System') # Find the DACL part of the Security Descriptor for the file sd = win32security.GetFileSecurity( path, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() if dacl is None: logging.warning('is_private: No DACL for %r', path) return False # Happened on a user's XP system. # Verify the DACL contains just the two entries we expect. count = dacl.GetAceCount() if count != 2: return False for i in range(count): ace = dacl.GetAce(i) if ace[2] != user and ace[2] != system: return False return True else: return (os.stat(path).st_mode & 0077) == 0
def has_min_permissions(path, min_mode): # type: (str, int) -> bool """ Check if a file given its path has at least the permissions defined by the given minimal mode. On Windows, group permissions are ignored since files do not have a group owner. :param str path: path to the file to check :param int min_mode: the minimal permissions expected :return: True if the file matches the minimal permissions expectations, False otherwise :rtype: bool """ if POSIX_MODE: st_mode = os.stat(path).st_mode return st_mode == st_mode | min_mode # Resolve symlinks, to get a consistent result with os.stat on Linux, # that follows symlinks by default. path = realpath(path) # Get owner sid of the file security = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION) user = security.GetSecurityDescriptorOwner() dacl = security.GetSecurityDescriptorDacl() min_dacl = _generate_dacl(user, min_mode) for index in range(min_dacl.GetAceCount()): min_ace = min_dacl.GetAce(index) # On a given ACE, index 0 is the ACE type, 1 is the permission mask, and 2 is the SID. # See: http://timgolden.me.uk/pywin32-docs/PyACL__GetAce_meth.html mask = min_ace[1] user = min_ace[2] effective_mask = dacl.GetEffectiveRightsFromAcl({ 'TrusteeForm': win32security.TRUSTEE_IS_SID, 'TrusteeType': win32security.TRUSTEE_IS_USER, 'Identifier': user, }) if effective_mask != effective_mask | mask: return False return True
def get_path_owner(path): ''' Gets the owner of the file or directory passed Args: path (str): The path for which to obtain owner information Returns: str: The owner (group or user) ''' # Return owner security_descriptor = win32security.GetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = security_descriptor.GetSecurityDescriptorOwner() return get_name_from_sid(win32security.ConvertSidToStringSid(owner_sid))
def get_pgid(path, follow_symlinks=True): ''' Return the id of the primary group that owns a given file (Windows only) This function will return the rarely used primary group of a file. This generally has no bearing on permissions unless intentionally configured and is most commonly used to provide Unix compatibility (e.g. Services For Unix, NFS services). Ensure you know what you are doing before using this function. CLI Example: .. code-block:: bash salt '*' file.get_pgid c:\\temp\\test.txt ''' if not os.path.exists(path): return False # Under Windows, if the path is a symlink, the user that owns the symlink is # returned, not the user that owns the file/directory the symlink is # pointing to. This behavior is *different* to *nix, therefore the symlink # is first resolved manually if necessary. Remember symlinks are only # supported on Windows Vista or later. if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) try: secdesc = win32security.GetFileSecurity( path, win32security.GROUP_SECURITY_INFORMATION ) # Not all filesystems mountable within windows # have SecurityDescriptor's. For instance, some mounted # SAMBA shares, or VirtualBox's shared folders. If we # can't load a file descriptor for the file, we default # to "Everyone" - http://support.microsoft.com/kb/243330 except MemoryError: # generic memory error (win2k3+) return 'S-1-1-0' except pywinerror as exc: # Incorrect function error (win2k8+) if exc.winerror == 1 or exc.winerror == 50: return 'S-1-1-0' raise group_sid = secdesc.GetSecurityDescriptorGroup() return win32security.ConvertSidToStringSid(group_sid)
def make_private(path): """ Make `path` accessible only by 'owner'. path: string Path to file or directory to be made private. .. note:: On Windows this requires the pywin32 extension. """ if sys.platform == 'win32': #pragma no cover if not HAVE_PYWIN32: raise ImportError('No pywin32') # Find the SIDs for user and system. username = win32api.GetUserName() # Map Cygwin 'root' to 'Administrator'. Typically these are intended # to be identical, but /etc/passwd might configure them differently. if username == 'root': username = '******' user, domain, type = win32security.LookupAccountName('', username) system, domain, type = win32security.LookupAccountName('', 'System') # Find the DACL part of the Security Descriptor for the file sd = win32security.GetFileSecurity( path, win32security.DACL_SECURITY_INFORMATION) # Create a blank DACL and add the ACEs we want. dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, system) # Put our new DACL into the Security Descriptor and update the file # with the updated SD. sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd) else: mode = 0700 if os.path.isdir(path) else 0600 os.chmod(path, mode) # Read/Write/Execute
def get_file_owner(self, path): """Return the name of the user who owns the file. :param path: path to file to inspect """ path = Path(path) if platform.system() == "Windows": desc = win32security.GetFileSecurity( str(path), win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() name, _, _ = win32security.LookupAccountSid(None, sid) else: sid = path.stat().st_uid name = getpwuid(sid).pw_name return name
def remove_deny_write_permission_acl_on_win_for_file(self, path): if os.name == 'nt': import win32security as w32 import getpass w_user, _, _ = w32.LookupAccountName("", getpass.getuser()) sd = w32.GetFileSecurity(path, w32.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() dacl.DeleteAce(0) sd.SetSecurityDescriptorDacl(1, dacl, 0) w32.SetFileSecurity(path, w32.DACL_SECURITY_INFORMATION, sd) else: raise Exception( "This method should only be called on Windows NT like OS")
def check_owner(file_path): # type: (str) -> bool """ Check if given file is owned by current user. :param str file_path: File path to check :rtype: bool :return: True if given file is owned by current user, False otherwise. """ if POSIX_MODE: return os.stat(file_path).st_uid == os.getuid() # Get owner sid of the file security = win32security.GetFileSecurity(file_path, win32security.OWNER_SECURITY_INFORMATION) user = security.GetSecurityDescriptorOwner() # Compare sids return _get_current_user() == user
def set_file_readable(filename): import win32api import win32security import ntsecuritycon as con users = win32security.ConvertStringSidToSid("S-1-5-32-545") admins = win32security.ConvertStringSidToSid("S-1-5-32-544") 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 findUser(pth): # print "Creater = ", win32api.GetUserNameEx (win32con.NameSamCompatible) thisUserIs = win32api.GetUserNameEx(win32con.NameSamCompatible) thisUserIs = thisUserIs.replace("PROD\\", "") #print "User ID = " + thisUserIs try: sd = win32security.GetFileSecurity( pth, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, type = win32security.LookupAccountSid(None, owner_sid) except: name = "error getting name " + pth return name
def getEmployeeEmail(file): try: sd = win32security.GetFileSecurity (file, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, type = win32security.LookupAccountSid(None, owner_sid) if domain != "INBOX": email = "*****@*****.**" else: email = name+'@inboxinsight.com' print(domain, ' ', name, email) return email except: logging.error(str(datetime.now())+' Employee Cannot be mapped') move_file("Rejected") concludeImport("Failure","No email address","Rejected","*****@*****.**") exit()
def _apply_win_mode(file_path, mode): """ This function converts the given POSIX mode into a Windows ACL list, and applies it to the file given its path. If the given path is a symbolic link, it will resolved to apply the mode on the targeted file. """ file_path = realpath(file_path) # Get owner sid of the file security = win32security.GetFileSecurity(file_path, win32security.OWNER_SECURITY_INFORMATION) user = security.GetSecurityDescriptorOwner() # New DACL, that will overwrite existing one (including inherited permissions) dacl = _generate_dacl(user, mode) # Apply the new DACL security.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION, security)
def WinChmod(filename, acl_list, user=None): """Provide chmod-like functionality for windows. Doco links: goo.gl/n7YR1 goo.gl/rDv81 goo.gl/hDobb Args: filename: target filename for acl acl_list: list of ntsecuritycon acl strings to be applied with bitwise OR. e.g. ["FILE_GENERIC_READ", "FILE_GENERIC_WRITE"] user: username string. If not specified we use the user we are running as. Raises: AttributeError: if a bad permission is passed RuntimeError: if filename doesn't exist """ if user is None: user = win32api.GetUserName() if not os.path.exists(filename): raise RuntimeError("filename %s does not exist" % filename) acl_bitmask = 0 for acl in acl_list: acl_bitmask |= getattr(ntsecuritycon, acl) dacl = win32security.ACL() win_user, _, _ = win32security.LookupAccountName("", user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, acl_bitmask, win_user) security_descriptor = win32security.GetFileSecurity( filename, win32security.DACL_SECURITY_INFORMATION) # Tell windows to set the acl and mark it as explicitly set security_descriptor.SetSecurityDescriptorDacl(DACL_PRESENT, dacl, DACL_DEFAULT) win32security.SetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION, security_descriptor)
def getOwner(fn): ''' takes a filename and return the login ID of the actual owner of the file :param fn: filename of the file tested :type fn: str :return: login ID of the file's owner ''' system_name = platform.system() if system_name in ["Linux", "Darwin"]: import pwd return pwd.getpwuid(os.stat(fn).st_uid).pw_name elif system_name == "Windows": import win32security f = win32security.GetFileSecurity( fn, win32security.OWNER_SECURITY_INFORMATION) (username, domain, sid_name_use) = win32security.LookupAccountSid( None, f.GetSecurityDescriptorOwner()) return username
def get_file_owner(self, file_path): """Returns the user name of the owner of the specified file. @param file_path: The path of the file. @type file_path: str @return: The user name of the owner. @rtype: str """ sd = win32security.GetFileSecurity( file_path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, account_type = win32security.LookupAccountSid( None, owner_sid) if name == "Administrators": return self.__local_administrators else: return "%s\\%s" % (domain, name)
def secure_file(file): if os.name == 'nt': import win32security import ntsecuritycon as con import pdb userx, domain, type = win32security.LookupAccountName("", "Everyone") sd = win32security.GetFileSecurity( file, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl( ) # instead of dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, userx) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION, sd) else: os.chmod(file, 0o600)
def assert_world_no_permissions(file: str) -> None: """ Assert that the given file is not world-readable. :param str file: path of the file to check """ if POSIX_MODE: mode_file_all = os.stat(file).st_mode & 0o007 assert mode_file_all == 0 else: security = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION) dacl = security.GetSecurityDescriptorDacl() mode = dacl.GetEffectiveRightsFromAcl({ 'TrusteeForm': win32security.TRUSTEE_IS_SID, 'TrusteeType': win32security.TRUSTEE_IS_USER, 'Identifier': win32security.ConvertStringSidToSid(EVERYBODY_SID), }) assert not mode
def main(): try: everyone, domain, type = win32security.LookupAccountName("", "Everyone") admins, domain, type = win32security.LookupAccountName("", "Administrators") user, domain, type = win32security.LookupAccountName("", win32api.GetUserName()) if os.path.isfile(FILENAME) open(FILENAME, "w").close() show_cacls(FILENAME) sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ, 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(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd) show_cacls(FILENAME) except Exception as e: print "Error: {}".format(str(e))