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)
Ejemplo n.º 2
0
def remove_empty_srt(srt_path):
    #Error correcting.
    #Becuase of failure of algorithm, a lot of empty srt files are made in various directory.
    srt_file = open(srt_path, 'rb')
    if not srt_file:
        return
    text = srt_file.read()
    if not text:
        if platform.system() is 'Windows':
            userx, domain, type = win32security.LookupAccountName(
                "", "Everyone")
            sd = win32security.GetFileSecurity(
                srt_path, win32security.DACL_SECURITY_INFORMATION)
            dacl = sd.GetSecurityDescriptorDacl()
            dacl.AddAccessAllowedAce(win32security.ACL_REVISION,
                                     con.FILE_ALL_ACCESS, userx)
            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetFileSecurity(
                srt_path, win32security.DACL_SECURITY_INFORMATION, sd)

        else:
            os.chmod(srt_path, stat.S_IWOTH)
        os.remove(srt_path)
        logging.info(
            'The empty srt file is found in directory {}'.format(srt_path))
        return
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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))
Ejemplo n.º 5
0
  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)
Ejemplo n.º 6
0
 def setdacl(path, sid, dacl):
     dsi = win32security.GetFileSecurity(
         path, win32security.DACL_SECURITY_INFORMATION)
     dsi.SetSecurityDescriptorDacl(1, dacl, 0)
     win32security.SetFileSecurity(path,
                                   win32security.DACL_SECURITY_INFORMATION,
                                   dsi)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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)
Ejemplo n.º 10
0
    def grantAccessToFile(self, filePath, userName='******'):
        """
        Allow Permission to userName on a file/directory
        @param file: path of the file/dir
        @param userName: name of the user to add to the acl of the file/dir
        """
        pylabs.q.logger.log('Granting access to file %s' % filePath, 6)

        if pylabs.q.system.fs.isFile(filePath) or pylabs.q.system.fs.isDir(
                filePath):

            info = win32security.DACL_SECURITY_INFORMATION
            sd = win32security.GetFileSecurity(filePath, info)
            acl = self.getFileACL(filePath)
            user, domain, acType = win32security.LookupAccountName(
                "", userName)

            acl.AddAccessAllowedAce(
                win32security.ACL_REVISION, con.FILE_GENERIC_READ
                | con.FILE_GENERIC_WRITE | con.FILE_DELETE_CHILD | con.DELETE
                | win32file.FILE_SHARE_DELETE, user)
            sd.SetSecurityDescriptorDacl(1, acl, 0)
            win32security.SetFileSecurity(
                filePath, win32security.DACL_SECURITY_INFORMATION, sd)

        else:
            pylabs.q.logger.log('File/Directory %s is not valid' % filePath, 6)

            raise IOError('FilePath %s does not exist' % filePath)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
def addFullPerm(filename, user, servername=SERVERNAME):
    """ Give a user full permissions for filename. """
    try:
        sidUser = win32security.LookupAccountName(servername, user)[0]
        sd = win32security.GetFileSecurity( filename, 
                 win32security.DACL_SECURITY_INFORMATION )


        acl = sd.GetSecurityDescriptorDacl()
 
        for aceno in range(acl.GetAceCount()):
            csid = acl.GetAce(aceno)[2]
            if csid == sidUser:
                # We already have access
                if acl.GetAce(aceno)[1] == win32file.FILE_ALL_ACCESS:
                    return 1

        acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, sidUser)

        sd.SetSecurityDescriptorDacl(1, acl, 0)
        win32security.SetFileSecurity( filename, 
                   win32security.DACL_SECURITY_INFORMATION, sd )

    except win32security.error:
        return 0

    return 1
Ejemplo n.º 13
0
    def grantAccessToFile(self, filePath, userName="******"):
        """
        Allow Permission to userName on a file/directory
        @param file: path of the file/dir
        @param userName: name of the user to add to the acl of the file/dir
        """
        self._log_info("Granting access to file %s" % filePath)
        import ntsecuritycon as con

        if j.sal.fs.isFile(filePath) or j.sal.fs.isDir(filePath):

            info = win32security.DACL_SECURITY_INFORMATION
            sd = win32security.GetFileSecurity(filePath, info)
            acl = self.getFileACL(filePath)
            user, domain, acType = win32security.LookupAccountName(
                "", userName)

            acl.AddAccessAllowedAce(
                win32security.ACL_REVISION,
                con.FILE_GENERIC_READ
                | con.FILE_GENERIC_WRITE
                | con.FILE_DELETE_CHILD
                | con.DELETE
                | win32file.FILE_SHARE_DELETE,
                user,
            )
            sd.SetSecurityDescriptorDacl(1, acl, 0)
            win32security.SetFileSecurity(
                filePath, win32security.DACL_SECURITY_INFORMATION, sd)

        else:
            self._log_info("File/Directory %s is not valid" % filePath)

            raise j.exceptions.IO("FilePath %s does not exist" % filePath)
Ejemplo n.º 14
0
 def deny(self):
     try:
         if not os.path.exists(self.file):
             raise WindowsError('Path %s could not be found.' % self.file)
         total = 0
         for x in self.users:
             userx, domain, utype = win32security.LookupAccountName("", x)
             sd = win32security.GetFileSecurity(
                 self.file, win32security.DACL_SECURITY_INFORMATION)
             dacl = sd.GetSecurityDescriptorDacl()
             num_delete = 0
             for index in range(0, dacl.GetAceCount()):
                 ace = dacl.GetAce(index - num_delete)
                 if userx == ace[2]:
                     dacl.DeleteAce(index - num_delete)
                     num_delete += 1
                     total += 1
             if num_delete > 0:
                 sd.SetSecurityDescriptorDacl(1, dacl, 0)
                 win32security.SetFileSecurity(
                     self.file, win32security.DACL_SECURITY_INFORMATION, sd)
         if total > 0:
             return True
     except Exception as err:
         exc_type, exc_obj, exc_tb = sys.exc_info()
         self.log.error(
             "perms.deny failed\n%s, %s, %s, %s" %
             (err, exc_type, exc_obj, traceback.print_tb(exc_tb)))
Ejemplo n.º 15
0
    def chown(path, uid, gid):
        # get the sid for the uid, and the gid
        user = group = None
        import pwd,grp
        for acct in pwd.Query.All():
            id = SID.Identifier(win32security.ConvertSidToStringSid(acct['user_sid']))
            if id == uid and acct.SidType == ntsecuritycon.SidTypeUser:
                user = acct['user_sid']
                break
            continue
        for acct in grp.Query.All():
            id = SID.Identifier(win32security.ConvertSidToStringSid(acct['user_sid']))
            if id == gid and acct.SidType == ntsecuritycon.SidTypeGroup:
                group = acct['user_sid']
                break
            continue

        # ripped from http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html#the-short-version
        sd = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION)

        # grab original owner
        if user is None and uid != -1:
            user = sd.GetSecurityDescriptorOwner()
        if group is None and gid != -1:
            name,domain,_ = win32security.LookupAccountSid(None,user)
            acct = pwd.Query.ByName(domain,name)
            group = pwd.Query.Group(acct)['user_sid']

        if uid != -1:
            sd.SetSecurityDescriptorOwner(user, True)
        if gid != -1:
            sd.SetSecurityDescriptorGroup(group, True)

        res = win32security.SetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION, sd)
        return -1 if res == 0 else 0
Ejemplo n.º 16
0
 def _grantDir(dirpath, securityDescriptor):
     '''Set security on a folder'''
     for dir in j.sal.fs.listDirsInDir(dirpath):
         _grantDir(dir, securityDescriptor)
     for file in j.sal.fs.listFilesInDir(dirpath):
         _grantFile(file, securityDescriptor)
     win32security.SetFileSecurity(dirpath, win32security.DACL_SECURITY_INFORMATION, securityDescriptor)
Ejemplo n.º 17
0
 def set_access_control_string(self, security, information=SecurityInformation.OWNER | SecurityInformation.GROUP | SecurityInformation.DACL):
     '''
     fi.set_access_control_string(security, [infomarion]) -> None
     Applies access control described by a SECURITY string to the file described by the current FileInfo object.
     If non-WinNT system, sets os.chmode(), os.chown(), os.chflags() to security, else use SetFileSecurity(self.original_path, information, security) api function, with security as a SECURITY string
     'information' defaults to SecurityInformation.OWNER | SecurityInformation.GROUP | SecurityInformation.DACL
     '''
     if os.path.exists(self.original_path):
         if isinstance(information, SecurityInformation):
             information = information.value
         if os.name != "nt":
             if information & 0x1:
                 os.chmod(self.original_path, security.st_mode)
             if information & 0x2:
                 os.chown(self.original_path,
                          security.st_uid, security.st_gid)
             if information & 0x4:
                 os.chflags(self.original_path, security.st_flags)
         else:
             try:
                 import win32security
             except:
                 raise NotSupportedException("you need pywin modules")
             try:
                 security = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
                     security, win32security.SDDL_REVISION_1)
                 win32security.SetFileSecurity(
                     self.original_path, information, security)
             except win32security.error as err:
                 raise UnauthorizedAccessException(err)
     else:
         raise FileNotFoundException("'%s' not found" % self.original_path)
Ejemplo n.º 18
0
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'])
Ejemplo n.º 19
0
def add_perm(file, permission, *users):
    """

        ATTENTION : expérimental. Peut mettre le bordel dans les héritages.

        Inspiré de http://stackoverflow.com/questions/28302666/impersonation-for-windows-in-python-3-using-win32security
        Syntaxe :
        add_perm('file', permission, 'u1', 'u2', ..., 'un')
        OU
        add_perm('file', permission, *['u1', 'u2', ..., 'un'])
        OU
        add_perm('file', permission, *('u1', 'u2', ..., 'un'))
    """
    logger = logging.getLogger()

    mask = win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
    sd = win32security.GetFileSecurity(file, mask)
    ownersid = sd.GetSecurityDescriptorOwner()
    dacl = sd.GetSecurityDescriptorDacl()
    heritage = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE | win32security.INHERITED_ACE

    for u in users:
        sid, domain, type = win32security.LookupAccountName('', u)
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, heritage, permission, sid)

    sd.SetSecurityDescriptorDacl(1, dacl, 0)

    win32security.SetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION, sd)
Ejemplo n.º 20
0
 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)
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
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.
    """
    original_path = file_path
    inspected_paths = []  # type: List[str]
    while os.path.islink(file_path):
        link_path = file_path
        file_path = os.readlink(file_path)
        if not os.path.isabs(file_path):
            file_path = os.path.join(os.path.dirname(link_path), file_path)
        if file_path in inspected_paths:
            raise RuntimeError(
                'Error, link {0} is a loop!'.format(original_path))
        inspected_paths.append(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)
Ejemplo n.º 23
0
def set_file_security(path, info, sddl):
    # Create security descriptor
    descriptor = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
        sddl, win32security.SDDL_REVISION_1,
    )

    # Windows api call
    win32security.SetFileSecurity(path, info, descriptor)
Ejemplo n.º 24
0
    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
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
def _copy_win_ownership(src, dst):
    security_src = win32security.GetFileSecurity(src, win32security.OWNER_SECURITY_INFORMATION)
    user_src = security_src.GetSecurityDescriptorOwner()

    security_dst = win32security.GetFileSecurity(dst, win32security.OWNER_SECURITY_INFORMATION)
    # Second parameter indicates, if `False`, that the owner of the file is not provided by some
    # default mechanism, but is explicitly set instead. This is obviously what we are doing here.
    security_dst.SetSecurityDescriptorOwner(user_src, False)

    win32security.SetFileSecurity(dst, win32security.OWNER_SECURITY_INFORMATION, security_dst)
Ejemplo n.º 28
0
    def __call__(self, *args, **kwargs):
        PythonBatchCommandBase.__call__(self, *args, **kwargs)
        if sys.platform == 'darwin':
            # os.chmod is not recursive so call the system's chmod
            if self.recursive:
                self.doing = f"""change mode (recursive) of '{self.path}' to '{self.mode}''"""
                return super().__call__(args, kwargs)
            else:
                resolved_path = utils.ExpandAndResolvePath(self.path)
                path_stats = resolved_path.stat()
                current_mode, current_mode_oct = stat.S_IMODE(
                    path_stats[stat.ST_MODE]), oct(
                        stat.S_IMODE(path_stats[stat.ST_MODE]))
                flags, op = self.parse_symbolic_mode_mac(self.mode, path_stats)
                mode_to_set = flags
                if op == '+':
                    mode_to_set |= current_mode
                elif op == '-':
                    mode_to_set = current_mode & ~flags
                if mode_to_set != current_mode:
                    self.doing = f"""change mode of '{resolved_path}' to '{self.mode}''"""
                    os.chmod(resolved_path, mode_to_set)
                else:
                    self.doing = f"""skip change mode of '{resolved_path}' mode is already '{mode_to_set}''"""

        elif sys.platform == 'win32':
            if self.recursive:
                self.doing = f"""change mode (recursive) of '{self.path}' to '{self.mode}''"""
                self.shell = True
                return super().__call__(args, kwargs)
            else:
                resolved_path = utils.ExpandAndResolvePath(self.path)
                who, perms, operation = self.parse_symbolic_mode_win(self.mode)
                self.doing = f"""change mode of '{resolved_path}' to '{who}, {perms}, {operation}''"""

                # on windows uncheck the read-only flag
                if 'w' in self.mode:
                    os.chmod(resolved_path, stat.S_IWRITE)
                accounts = list()
                for name in who:
                    user, domain, type = win32security.LookupAccountName(
                        "", name)
                    accounts.append(user)

                sd = win32security.GetFileSecurity(
                    os.fspath(resolved_path),
                    win32security.DACL_SECURITY_INFORMATION)
                dacl = sd.GetSecurityDescriptorDacl()
                for account in accounts:
                    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, perms,
                                             account)
                sd.SetSecurityDescriptorDacl(1, dacl, 0)
                win32security.SetFileSecurity(
                    os.fspath(resolved_path),
                    win32security.DACL_SECURITY_INFORMATION, sd)
Ejemplo n.º 29
0
def TakeOwnership(username, folder):
    try:
        account_sid = (win32security.LookupAccountName(None, username))[0]
        print("Setting " + username + " to owner on " + folder)
        sd = win32security.SECURITY_DESCRIPTOR()
        sd.SetSecurityDescriptorOwner(account_sid, 0)
        win32security.SetFileSecurity(folder,
                                      win32security.OWNER_SECURITY_INFORMATION,
                                      sd)
    except Exception as er:
        print("TakeOwnership Exception: %s" % type(er).__name__)
Ejemplo n.º 30
0
def _copy_win_mode(src, dst):
    # Resolve symbolic links
    src = realpath(src)

    # Copy the DACL from src to dst.
    security_src = win32security.GetFileSecurity(src, win32security.DACL_SECURITY_INFORMATION)
    dacl = security_src.GetSecurityDescriptorDacl()

    security_dst = win32security.GetFileSecurity(dst, win32security.DACL_SECURITY_INFORMATION)
    security_dst.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(dst, win32security.DACL_SECURITY_INFORMATION, security_dst)