Пример #1
0
def check_inheritance(path, objectType):
    '''
    check a specified path to verify if inheritance is enabled
    returns 'Inheritance' of True/False

    hkey: HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, etc
    path:  path of the registry key to check
    '''

    ret = {'result': False, 'Inheritance': False, 'comment': []}
    dc = daclConstants()
    objectType = dc.getObjectTypeBit(objectType)
    path = dc.processPath(path, objectType)

    try:
        sd = win32security.GetNamedSecurityInfo(
            path, objectType, win32security.DACL_SECURITY_INFORMATION)
        dacls = sd.GetSecurityDescriptorDacl()
    except Exception as e:
        ret['result'] = False
        ret['comment'].append((
            'Error obtaining the Security Descriptor or DACL of the path:  {0}'
        ).format(e))
        return ret

    for counter in range(0, dacls.GetAceCount()):
        ace = dacls.GetAce(counter)
        if (ace[0][1]
                & win32security.INHERITED_ACE) == win32security.INHERITED_ACE:
            ret['Inheritance'] = True
    ret['result'] = True
    return ret
Пример #2
0
def removeReadOnlyAccess(path=None):
    try:
        if os.path.exists(path):
            everyone = win32security.CreateWellKnownSid(
                win32security.WinWorldSid)
            #Delete ace
            sd = win32security.GetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.DACL_SECURITY_INFORMATION)
            dacl = sd.GetSecurityDescriptorDacl(
            )  # instead of dacl = win32security.ACL()
            #print("Ace count=",dacl.GetAceCount())
            num_delete = 0
            for index in range(0, dacl.GetAceCount()):
                ace = dacl.GetAce(index)

            for index in range(0, dacl.GetAceCount()):
                ace = dacl.GetAce(index - num_delete)
                if ace[2] == everyone:
                    dacl.DeleteAce(index - num_delete)
                    num_delete += 1

            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.DACL_SECURITY_INFORMATION, None, None, dacl,
                None)
    except Exception as err:
        print("exeption {}".format(str(err)))
Пример #3
0
 def test_Security_from_string(self):
     with self.test_file() as TEST_FILE:
         sd = win32security.GetNamedSecurityInfo(
             TEST_FILE, win32security.SE_FILE_OBJECT, OPTIONS)
         assert equal(
             sd,
             security.Security.from_string(as_string(sd), options=OPTIONS))
Пример #4
0
def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False):
    '''
    helper function to set the inheritance
    '''
    ret = {'result': False,
           'comment': '',
           'changes': {}}

    if path:
        try:
            sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION)
            tdacl = sd.GetSecurityDescriptorDacl()
            if inheritance:
                if clear:
                    counter = 0
                    removedAces = []
                    while counter < tdacl.GetAceCount():
                        tAce = tdacl.GetAce(counter)
                        if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE:
                            tdacl.DeleteAce(counter)
                            removedAces.append(_ace_to_text(tAce, objectType))
                        else:
                            counter = counter + 1
                    if removedAces:
                        ret['changes']['Removed ACEs'] = removedAces
                else:
                    ret['changes']['Non-Inherited ACEs'] = 'Left in the DACL'
                win32security.SetNamedSecurityInfo(
                    path, objectType,
                    win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION,
                    None, None, tdacl, None)
                ret['changes']['Inheritance'] = 'Enabled'
            else:
                if not copy:
                    counter = 0
                    inheritedAcesRemoved = []
                    while counter < tdacl.GetAceCount():
                        tAce = tdacl.GetAce(counter)
                        if (tAce[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE:
                            tdacl.DeleteAce(counter)
                            inheritedAcesRemoved.append(_ace_to_text(tAce, objectType))
                        else:
                            counter = counter + 1
                    if inheritedAcesRemoved:
                        ret['changes']['Removed ACEs'] = inheritedAcesRemoved
                else:
                    ret['changes']['Previously Inherited ACEs'] = 'Copied to the DACL'
                win32security.SetNamedSecurityInfo(
                    path, objectType,
                    win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION,
                    None, None, tdacl, None)
                ret['changes']['Inheritance'] = 'Disabled'
            ret['result'] = True
        except Exception as e:
            ret['result'] = False
            ret['comment'] = (
                'Error attempting to set the inheritance.  The error was {0}'
                ).format(e)

    return ret
Пример #5
0
    def _detect_win_acls(self, dir_rp, write):
        """
        Test if windows access control lists are supported
        """
        assert dir_rp.conn is Globals.local_connection, (
            "Action only foreseen locally and not over {conn}.".format(
                conn=dir_rp.conn))
        assert dir_rp.lstat(), "Path '{rp}' must exist to test ACLs.".format(
            rp=dir_rp)
        if not Globals.win_acls_active:
            log.Log(
                "Windows ACLs test skipped as rdiff-backup was started "
                "with --no-acls option", log.INFO)
            self.win_acls = None
            return

        try:
            import win32security
            import pywintypes
        except ImportError:
            log.Log(
                "Unable to import win32security module. Windows ACLs not "
                "supported by filesystem at path {pa}".format(pa=dir_rp),
                log.INFO)
            self.win_acls = False
            return
        try:
            sd = win32security.GetNamedSecurityInfo(
                os.fsdecode(dir_rp.path), win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION
                | win32security.GROUP_SECURITY_INFORMATION
                | win32security.DACL_SECURITY_INFORMATION)
            acl = sd.GetSecurityDescriptorDacl()
            acl.GetAceCount()  # to verify that it works
            if write:
                win32security.SetNamedSecurityInfo(
                    os.fsdecode(dir_rp.path), win32security.SE_FILE_OBJECT,
                    win32security.OWNER_SECURITY_INFORMATION
                    | win32security.GROUP_SECURITY_INFORMATION
                    | win32security.DACL_SECURITY_INFORMATION,
                    sd.GetSecurityDescriptorOwner(),
                    sd.GetSecurityDescriptorGroup(),
                    sd.GetSecurityDescriptorDacl(), None)
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to load a Windows ACL. Windows ACLs not supported "
                "by filesystem at path {pa}".format(pa=dir_rp), log.INFO)
            self.win_acls = False
            return

        try:
            acl_win.init_acls()  # FIXME there should be no cross-dependency
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to init win_acls. Windows ACLs not supported by "
                "filesystem at path {pa}".format(pa=dir_rp), log.INFO)
            self.win_acls = False
            return
        self.win_acls = True
Пример #6
0
 def GetSecurity(self, requestedinfo, bdefault):
     """Requests the existing permissions for object"""
     if bdefault:
         return win32security.SECURITY_DESCRIPTOR()
     else:
         return win32security.GetNamedSecurityInfo(self.ServiceName,
                                                   win32security.SE_SERVICE,
                                                   requestedinfo)
Пример #7
0
    def _detect_win_acls(self, dir_rp, write):
        """Test if windows access control lists are supported"""
        assert dir_rp.conn is Globals.local_connection, (
            "Action only foreseen locally and not over {conn}.".format(
                conn=dir_rp.conn))
        assert dir_rp.lstat(), "Path '{rp!s}' must exist to test ACLs.".format(
            rp=dir_rp)
        if Globals.win_acls_active == 0:
            log.Log(
                "Windows ACLs test skipped. rdiff-backup run "
                "with --no-acls option.", 4)
            self.win_acls = 0
            return

        try:
            import win32security
            import pywintypes
        except ImportError:
            log.Log(
                "Unable to import win32security module. Windows ACLs\n"
                "not supported by filesystem at %s" % dir_rp.get_safepath(), 4)
            self.win_acls = 0
            return
        try:
            sd = win32security.GetNamedSecurityInfo(
                os.fsdecode(dir_rp.path), win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION
                | win32security.GROUP_SECURITY_INFORMATION
                | win32security.DACL_SECURITY_INFORMATION)
            acl = sd.GetSecurityDescriptorDacl()
            acl.GetAceCount()  # to verify that it works
            if write:
                win32security.SetNamedSecurityInfo(
                    os.fsdecode(dir_rp.path), win32security.SE_FILE_OBJECT,
                    win32security.OWNER_SECURITY_INFORMATION
                    | win32security.GROUP_SECURITY_INFORMATION
                    | win32security.DACL_SECURITY_INFORMATION,
                    sd.GetSecurityDescriptorOwner(),
                    sd.GetSecurityDescriptorGroup(),
                    sd.GetSecurityDescriptorDacl(), None)
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to load a Windows ACL.\nWindows ACLs not supported "
                "by filesystem at %s" % dir_rp.get_safepath(), 4)
            self.win_acls = 0
            return

        try:
            win_acls.init_acls()
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to init win_acls.\nWindows ACLs not supported by "
                "filesystem at %s" % dir_rp.get_safepath(), 4)
            self.win_acls = 0
            return
        self.win_acls = 1
Пример #8
0
def test_Security_break_dacl_inheritance_no_copy():
    filepath = test_file()
    print "AceCount before", win32security.GetNamedSecurityInfo(
        filepath, win32security.SE_FILE_OBJECT,
        OPTIONS).GetSecurityDescriptorDacl().GetAceCount()
    s = security.security(filepath, options=OPTIONS)
    assert s.dacl.inherited
    s.break_inheritance(copy_first=False, break_dacl=True, break_sacl=False)
    print "dacl", s.dacl.dumped()
    s.to_object()
    sd = win32security.GetNamedSecurityInfo(filepath,
                                            win32security.SE_FILE_OBJECT,
                                            OPTIONS)
    print "AceCount", sd.GetSecurityDescriptorDacl().GetAceCount()
    assert (sd.GetSecurityDescriptorControl()[0]
            & win32security.SE_DACL_PROTECTED)
    assert (not sd.GetSecurityDescriptorControl()[0]
            & win32security.SE_SACL_PROTECTED)
    assert sd.GetSecurityDescriptorDacl().GetAceCount() == 0
Пример #9
0
def createDir(subpath, temp_tpath):
    dacl = win32security.GetNamedSecurityInfo(
        subpath, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION).GetSecurityDescriptorDacl()
    if not os.path.exists(temp_tpath):
        os.makedirs(temp_tpath)
        win32security.SetNamedSecurityInfo(
            temp_tpath, win32security.SE_FILE_OBJECT,
            win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None)
    return dacl
Пример #10
0
def _get_dacl(path, objectType):
    '''
    Gets the DACL of a path
    '''
    try:
        dacl = win32security.GetNamedSecurityInfo(
            path, objectType, win32security.DACL_SECURITY_INFORMATION
            ).GetSecurityDescriptorDacl()
    except Exception:
        dacl = None
    return dacl
Пример #11
0
def test_ace_from_ace_dace():
    sd = win32security.GetNamedSecurityInfo(
        filename, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    raw_ace = dacl.GetAce(0)
    ace = _aces.ACE.from_ace(raw_ace)
    assert isinstance(ace, _aces.DACE)
    assert ace.trustee.pyobject() == everyone
    assert ace.access == ntsecuritycon.FILE_READ_DATA
    assert ace.type == win32security.ACCESS_ALLOWED_ACE_TYPE
Пример #12
0
 def test_ace_from_ace_sace(self):
     sd = win32security.GetNamedSecurityInfo(
         self.filename, win32security.SE_FILE_OBJECT,
         win32security.SACL_SECURITY_INFORMATION)
     sacl = sd.GetSecurityDescriptorSacl()
     raw_ace = sacl.GetAce(0)
     ace = _aces.ACE.from_ace(raw_ace)
     assert isinstance(ace, _aces.SACE)
     assert ace.trustee.pyobject() == everyone
     assert ace.access == ntsecuritycon.FILE_READ_DATA
     assert ace.type == win32security.SYSTEM_AUDIT_ACE_TYPE
Пример #13
0
 def test_security_string_event(self):
     hEvent = win32event.CreateEvent(None, 0, 0, self.GUID)
     try:
         assert equal(
             win32security.GetNamedSecurityInfo(
                 self.GUID, win32security.SE_KERNEL_OBJECT, OPTIONS),
             security.security(self.GUID,
                               security.SE_OBJECT_TYPE.KERNEL_OBJECT,
                               options=OPTIONS))
     finally:
         hEvent.Close()
Пример #14
0
 def GetSecurity(self, requestedinfo, bdefault):
     """Requests the existing permissions for object"""
     if bdefault:
         ## This is invoked if the 'Default' button is pressed (only present if SI_RESET is passed
         ## with the flags in GetObjectInfo). Passing an empty SD with a NULL Dacl
         ##  should cause inherited ACL from parent dir or default dacl from user's token to be used
         return win32security.SECURITY_DESCRIPTOR()
     else:
         ## GetFileSecurity sometimes fails to return flags indicating that an ACE is inherited
         return win32security.GetNamedSecurityInfo(
             self.FileName, win32security.SE_FILE_OBJECT, requestedinfo)
Пример #15
0
def _get_dacl(path, objectType):
    """
    Gets the DACL of a path
    """
    try:
        dacl = win32security.GetNamedSecurityInfo(
            path, objectType,
            win32security.DACL_SECURITY_INFORMATION).GetSecurityDescriptorDacl(
            )
    except Exception:  # pylint: disable=broad-except
        dacl = None
    return dacl
Пример #16
0
    def set_win_acls(self, dir_rp, write):
        """Test if windows access control lists are supported"""
        assert Globals.local_connection is dir_rp.conn
        assert dir_rp.lstat()
        if Globals.win_acls_active == 0:
            log.Log(
                "Windows ACLs test skipped. rdiff-backup run "
                "with --no-acls option.", 4)
            self.win_acls = 0
            return

        try:
            import win32security, pywintypes
        except ImportError:
            log.Log(
                "Unable to import win32security module. Windows ACLs\n"
                "not supported by filesystem at %s" % dir_rp.path, 4)
            self.win_acls = 0
            return
        try:
            sd = win32security.GetNamedSecurityInfo(
                dir_rp.path, win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION
                | win32security.GROUP_SECURITY_INFORMATION
                | win32security.DACL_SECURITY_INFORMATION)
            acl = sd.GetSecurityDescriptorDacl()
            n = acl.GetAceCount()
            if write:
                win32security.SetNamedSecurityInfo(
                    dir_rp.path, win32security.SE_FILE_OBJECT,
                    win32security.OWNER_SECURITY_INFORMATION
                    | win32security.GROUP_SECURITY_INFORMATION
                    | win32security.DACL_SECURITY_INFORMATION,
                    sd.GetSecurityDescriptorOwner(),
                    sd.GetSecurityDescriptorGroup(),
                    sd.GetSecurityDescriptorDacl(), None)
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to load a Windows ACL.\nWindows ACLs not supported "
                "by filesystem at %s" % dir_rp.path, 4)
            self.win_acls = 0
            return

        try:
            win_acls.init_acls()
        except (OSError, AttributeError, pywintypes.error):
            log.Log(
                "Unable to init win_acls.\nWindows ACLs not supported by "
                "filesystem at %s" % dir_rp.path, 4)
            self.win_acls = 0
            return
        self.win_acls = 1
Пример #17
0
def test_Security_break_sacl_inheritance_no_copy():
    s = security.security(TEST_FILE, options=OPTIONS)
    assert s.sacl.inherited
    s.break_inheritance(copy_first=False, break_dacl=False, break_sacl=True)
    s.to_object()
    sd = win32security.GetNamedSecurityInfo(TEST_FILE,
                                            win32security.SE_FILE_OBJECT,
                                            OPTIONS)
    assert (sd.GetSecurityDescriptorControl()[0]
            & win32security.SE_SACL_PROTECTED)
    assert (not sd.GetSecurityDescriptorControl()[0]
            & win32security.SE_DACL_PROTECTED)
    assert sd.GetSecurityDescriptorSacl().GetAceCount() == 0
Пример #18
0
def test_Security_from_object_name():
    hEvent = win32event.CreateEvent(None, 0, 0, GUID)
    try:
        s = security.Security.from_object(
            GUID, security.SE_OBJECT_TYPE.KERNEL_OBJECT, options=OPTIONS)
        assert equal(
            win32security.GetNamedSecurityInfo(GUID,
                                               win32security.SE_KERNEL_OBJECT,
                                               OPTIONS), s)
        assert s.inherit_handle is True
        assert s._originating_object == GUID
        assert s._originating_object_type == win32security.SE_KERNEL_OBJECT
    finally:
        hEvent.Close()
Пример #19
0
 def test_Security_break_dacl_inheritance_copy(self):
     with self.test_file() as TEST_FILE:
         s = security.security(TEST_FILE, options=OPTIONS)
         n_aces = len(s.dacl)
         assert s.dacl.inherited
         s.break_inheritance(copy_first=True,
                             break_dacl=True,
                             break_sacl=False)
         s.to_object()
         sd = win32security.GetNamedSecurityInfo(
             TEST_FILE, win32security.SE_FILE_OBJECT, OPTIONS)
         assert (sd.GetSecurityDescriptorControl()[0]
                 & win32security.SE_DACL_PROTECTED)
         assert (not sd.GetSecurityDescriptorControl()[0]
                 & win32security.SE_SACL_PROTECTED)
         assert sd.GetSecurityDescriptorDacl().GetAceCount() == n_aces
Пример #20
0
def check_inheritance(path, objectType, user=None):
    """
    Check a specified path to verify if inheritance is enabled

    Args:
        path: path of the registry key or file system object to check
        objectType: The type of object (FILE, DIRECTORY, REGISTRY)
        user: if provided, will consider only the ACEs for that user

    Returns (bool): 'Inheritance' of True/False

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' win_dacl.check_inheritance c:\temp directory <username>
    """

    ret = {"result": False, "Inheritance": False, "comment": ""}

    sidRet = _getUserSid(user)

    dc = daclConstants()
    objectType = dc.getObjectTypeBit(objectType)
    path = dc.processPath(path, objectType)

    try:
        sd = win32security.GetNamedSecurityInfo(
            path, objectType, win32security.DACL_SECURITY_INFORMATION)
        dacls = sd.GetSecurityDescriptorDacl()
    except Exception as e:  # pylint: disable=broad-except
        ret["result"] = False
        ret["comment"] = "Error obtaining the Security Descriptor or DACL of the path: {}.".format(
            e)
        return ret

    for counter in range(0, dacls.GetAceCount()):
        ace = dacls.GetAce(counter)
        if (ace[0][1]
                & win32security.INHERITED_ACE) == win32security.INHERITED_ACE:
            if not sidRet["sid"] or ace[2] == sidRet["sid"]:
                ret["Inheritance"] = True
                break

    ret["result"] = True
    return ret
Пример #21
0
def _SetFileSecurity(username, fname, rights, inherit_flags=None):
    import win32security
    import pywintypes
    import ntsecuritycon

    # Returns None if no user, True if changed, False if already had
    # rights.
    if inherit_flags is None:
        inherit_flags = (
            ntsecuritycon.CONTAINER_INHERIT_ACE
            | ntsecuritycon.OBJECT_INHERIT_ACE  # child objects inherit?
        )

    # Overload the 'username' param - allow it to already be a SID.
    if isinstance(username, pywintypes.SIDType):
        user_sid = username
    else:
        try:
            user_sid = win32security.LookupAccountName(None, username)[0]
        except win32security.error:
            return None

    sd = win32security.GetNamedSecurityInfo(
        fname, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION)

    # Walk the dacl, looking for this entry.  Could maybe use
    # GetEffectiveRightsFromACL but that doesn't seem to give inherit
    # info.
    dacl = sd.GetSecurityDescriptorDacl()
    for i in range(dacl.GetAceCount()):
        ace = dacl.GetAce(i)
        ace_type, flags = ace[0]
        sid = ace[-1]

        if (ace_type == win32security.ACCESS_ALLOWED_ACE_TYPE
                and flags & inherit_flags == inherit_flags and ace[1] == rights
                and sid == user_sid):
            return False

    dacl.AddAccessAllowedAceEx(dacl.GetAclRevision(), inherit_flags, rights,
                               user_sid)
    sd = win32security.SetNamedSecurityInfo(
        fname, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None)
    return True
Пример #22
0
 def run(self, entries):
     try:
         sd = win32security.GetNamedSecurityInfo(
             self.file, win32security.SE_FILE_OBJECT,
             win32security.DACL_SECURITY_INFORMATION)
         dacl = sd.GetSecurityDescriptorDacl()
         dacl.SetEntriesInAcl(entries)
         win32security.SetNamedSecurityInfo(
             self.file, win32security.SE_FILE_OBJECT,
             win32security.DACL_SECURITY_INFORMATION
             | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None,
             None, dacl, None)
     except Exception as err:
         exc_type, exc_obj, exc_tb = sys.exc_info()
         self.log.error(
             "perms.run failed\n%s, %s, %s, %s" %
             (err, exc_type, exc_obj, traceback.print_tb(exc_tb)))
Пример #23
0
    def get_sd(self):
        if self.sd is None:
            #sd = None
            try:
                sd = self.sd = win32security.GetNamedSecurityInfo(
                    self.get_name(), win32security.SE_FILE_OBJECT,
                    win32security.OWNER_SECURITY_INFORMATION
                    | win32security.DACL_SECURITY_INFORMATION)
                if self.is_dir():
                    self.sd = wpc.conf.cache.sd('directory', sd)
                else:
                    self.sd = wpc.conf.cache.sd('file', sd)
            except:
                print "WARNING: Can't get security descriptor for file: " + self.get_name(
                )
                self.sd = None

        return self.sd
Пример #24
0
def _AllowNamedObjectAccess(sid, name: str, object_type: int,
                            access_permissions: int) -> None:
    """Allows access to a named object.

  Args:
    sid: A `PySID` representing the SID to grant access to.
    name: Name of the object.
    object_type: A `SE_OBJECT_TYPE` enum value.
    access_permissions: The permissions as a set of biflags using the
      `ACCESS_MASK` format.
  """
    info = win32security.GetNamedSecurityInfo(
        name, object_type, win32security.DACL_SECURITY_INFORMATION)
    dacl = info.GetSecurityDescriptorDacl()
    _AddPermissionToDacl(dacl, sid, access_permissions)
    win32security.SetNamedSecurityInfo(
        name, object_type, win32security.DACL_SECURITY_INFORMATION
        | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None,
        dacl, None)
Пример #25
0
def _win_set_permissions(path, mode, object_type):
    """Set the permissions."""
    # Overview of Windows inheritance:
    # Get/SetNamedSecurityInfo  = Always includes inheritance
    # Get/SetFileSecurity       = Can exclude/disable inheritance
    # Here we read effective permissions with GetNamedSecurityInfo, i.e.,
    # including inherited permissions. However, we'll set permissions with
    # SetFileSecurity and NO_INHERITANCE, to disable inheritance.
    sec_des = win32security.GetNamedSecurityInfo(
        path, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION)
    dacl = sec_des.GetSecurityDescriptorDacl()

    system_ace = None
    for _ in range(0, dacl.GetAceCount()):
        ace = dacl.GetAce(0)
        try:
            if ace[2] and ace[2].IsValid() and win32security.LookupAccountSid(
                    None, ace[2]) == SECURITY_NT_AUTHORITY:
                system_ace = ace
        except pywinerror:
            print("Found orphaned SID:", ace[2])
        dacl.DeleteAce(0)

    if system_ace:
        dacl.AddAccessAllowedAceEx(dacl.GetAclRevision(),
                                   win32security.NO_INHERITANCE, system_ace[1],
                                   system_ace[2])

    sids = win_get_object_sids(path)

    for user_type, sid in enumerate(sids):
        win_perm = convert_stat_to_win(mode, user_type, object_type)

        if win_perm > 0:
            dacl.AddAccessAllowedAceEx(dacl.GetAclRevision(),
                                       win32security.NO_INHERITANCE, win_perm,
                                       sid)

    sec_des.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(path,
                                  win32security.DACL_SECURITY_INFORMATION,
                                  sec_des)
Пример #26
0
    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()
Пример #27
0
def _win_get_permissions(path, object_type):
    """Get the permissions."""
    sec_des = win32security.GetNamedSecurityInfo(
        path, win32security.SE_FILE_OBJECT,
        win32security.DACL_SECURITY_INFORMATION)
    dacl = sec_des.GetSecurityDescriptorDacl()

    sids = win_get_object_sids(path)
    mode = 0

    for index in range(0, dacl.GetAceCount()):
        ace = dacl.GetAce(index)
        if ace[0][0] == win32security.ACCESS_ALLOWED_ACE_TYPE and \
                win32security.LookupAccountSid(None, ace[2]) != \
                SECURITY_NT_AUTHORITY:
            # Not handling win32security.ACCESS_DENIED_ACE_TYPE
            mode = mode | convert_win_to_stat(
                ace[1], win_get_user_type(ace[2], sids), object_type)

    return mode
Пример #28
0
def load_libs():
    # Load win32security
    #
    # Try to open file and ingore the result.  This gets win32security loaded and working.
    # We can then turn off WOW64 and call repeatedly.  If we turn off WOW64 first,
    # win32security will fail to work properly.
    try:
        sd = win32security.GetNamedSecurityInfo(
            ".", win32security.SE_FILE_OBJECT,
            win32security.OWNER_SECURITY_INFORMATION
            | win32security.DACL_SECURITY_INFORMATION)
    except:
        # nothing
        pass

    # Load win32net
    #
    # NetLocalGroupEnum fails with like under Windows 7 64-bit, but not XP 32-bit:
    # pywintypes.error: (127, 'NetLocalGroupEnum', 'The specified procedure could not be found.')
    dummy = win32net.NetLocalGroupEnum(None, 0, 0, 1000)
Пример #29
0
 def test_Security_break_dacl_inheritance_no_copy(self):
     #
     # This is currently failing because, within the test folder,
     # the file created doesn't have inherited ACEs at the point
     # at which the inheritance is broken. Since unherited ACEs are
     # copied regardless, the test fails.
     #
     with self.test_file() as filepath:
         s = security.security(filepath, options=OPTIONS)
         assert s.dacl.inherited
         s.break_inheritance(copy_first=False,
                             break_dacl=True,
                             break_sacl=False)
         s.to_object()
         sd = win32security.GetNamedSecurityInfo(
             filepath, win32security.SE_FILE_OBJECT, OPTIONS)
         self.assertTrue(sd.GetSecurityDescriptorControl()[0]
                         & win32security.SE_DACL_PROTECTED)
         self.assertTrue(not sd.GetSecurityDescriptorControl()[0]
                         & win32security.SE_SACL_PROTECTED)
         self.assertEqual(sd.GetSecurityDescriptorDacl().GetAceCount(), 0)
Пример #30
0
 def check_perm(self):
     try:
         dacl = win32security.GetNamedSecurityInfo(
             self.file, win32security.SE_FILE_OBJECT, win32security.
             DACL_SECURITY_INFORMATION).GetSecurityDescriptorDacl()
         CONVENTIONAL_ACES = {
             win32security.ACCESS_ALLOWED_ACE_TYPE: "ALLOW",
             win32security.ACCESS_DENIED_ACE_TYPE: "DENY"
         }
         for n_ace in range(dacl.GetAceCount()):
             ace = dacl.GetAce(n_ace)
             (ace_type, ace_flags) = ace[0]
             if ace_type in CONVENTIONAL_ACES:
                 mask, sid = ace[1:]
             else:
                 mask, object_type, inherited_object_type, sid = ace[1:]
             name, domain, type = win32security.LookupAccountSid(None, sid)
             if name in self.users:
                 perms = (','.join(
                     self.get_access_mask_str(mask)).split(","))
                 if not "FILE_GENERIC_WRITE" in perms:
                     print(
                         "%s does not have write access. Enableding Write access for user"
                         % name)
                     self.grants.append(name)
                 else:
                     print("%s has write permissions" % name)
                     self.users.remove(name)
         for i in self.users:
             if not i in self.grants:
                 self.grants.append(i)
         print(self.grants)
         if len(self.grants) > 0:
             self.users = self.grants
             self.grant()
     except Exception as err:
         exc_type, exc_obj, exc_tb = sys.exc_info()
         self.log.error(
             "perms.check_perm failed\n%s, %s, %s, %s" %
             (err, exc_type, exc_obj, traceback.print_tb(exc_tb)))