internal static extern bool AccessCheck(
     [In] byte[] securityDescriptor,
     [In] SafeCloseHandle clientToken,
     [In] int desiredAccess,
     [In] GENERIC_MAPPING genericMapping,
     out PRIVILEGE_SET privilegeSet,
     [In, Out] ref uint privilegeSetLength,
     out uint grantedAccess,
     out bool accessStatus);
示例#2
0
 internal static extern bool AccessCheck(
     SecurityDescriptor securityDescriptor,
     IntPtr clientToken,
     int desiredAccess,
     GENERIC_MAPPING genericMapping,
     PRIVILEGE_SET privilegeSet,
     ref int privilegeSetLength,
     out int grandtedAccess,
     [MarshalAs(UnmanagedType.Bool)] out bool accessStatus);
示例#3
0
 public static extern bool AccessCheck(
     [MarshalAs(UnmanagedType.LPArray)]
     byte[] pSecurityDescriptor,
     IntPtr ClientToken,
     uint DesiredAccess,
     [In] ref GENERIC_MAPPING GenericMapping,
     IntPtr PrivilegeSet,
     ref uint PrivilegeSetLength,
     out uint GrantedAccess,
     out bool AccessStatus);
示例#4
0
        public static List <string> GetInheritedFrom(string path, ObjectSecurity sd, bool isContainer)
        {
            var inheritedFrom = new List <string>();

            path = Path.GetLongPath(path);

            uint            returnValue = 0;
            GENERIC_MAPPING genericMap  = new GENERIC_MAPPING();

            genericMap.GenericRead    = (uint)MappedGenericRights.FILE_GENERIC_READ;
            genericMap.GenericWrite   = (uint)MappedGenericRights.FILE_GENERIC_WRITE;
            genericMap.GenericExecute = (uint)MappedGenericRights.FILE_GENERIC_EXECUTE;
            genericMap.GenericAll     = (uint)MappedGenericRights.FILE_GENERIC_ALL;

            var sdBytes  = sd.GetSecurityDescriptorBinaryForm();
            var commonSd = new CommonSecurityDescriptor(isContainer, false, sdBytes, 0);

            var aclBytes = new byte[commonSd.DiscretionaryAcl.BinaryLength];

            commonSd.DiscretionaryAcl.GetBinaryForm(aclBytes, 0);

            var pInheritInfo = Marshal.AllocHGlobal(commonSd.DiscretionaryAcl.Count * Marshal.SizeOf(typeof(PINHERITED_FROM)));

            returnValue = GetInheritanceSource(
                path,
                ResourceType.FileObject,
                SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
                isContainer,
                IntPtr.Zero,
                0,
                aclBytes,
                IntPtr.Zero,
                ref genericMap,
                pInheritInfo
                );

            if (returnValue != 0)
            {
                throw new System.ComponentModel.Win32Exception((int)returnValue);
            }

            for (int i = 0; i < commonSd.DiscretionaryAcl.Count; i++)
            {
                var inheritInfo = pInheritInfo.ElementAt <PINHERITED_FROM>(i);

                inheritedFrom.Add(
                    !string.IsNullOrEmpty(inheritInfo.AncestorName) && inheritInfo.AncestorName.StartsWith(@"\\?\") ? inheritInfo.AncestorName.Substring(4) : inheritInfo.AncestorName
                    );
            }

            FreeInheritedFromArray(pInheritInfo, (ushort)commonSd.DiscretionaryAcl.Count, IntPtr.Zero);
            Marshal.FreeHGlobal(pInheritInfo);

            return(inheritedFrom);
        }
 public static extern UInt32 GetInheritanceSource(
     [MarshalAs(UnmanagedType.LPTStr)] string pObjectName,
     ResourceType ObjectType,
     SECURITY_INFORMATION SecurityInfo,
     [MarshalAs(UnmanagedType.Bool)] bool Container,
     IntPtr pObjectClassGuids,
     UInt32 GuidCount,
     byte[] pAcl,
     IntPtr pfnArray,
     ref GENERIC_MAPPING pGenericMapping,
     IntPtr pInheritArray);
示例#6
0
 public static extern bool AccessCheck
 (
     IntPtr pSecurityDescriptor,
     IntPtr ClientToken,
     uint DesiredAccess,
     ref GENERIC_MAPPING GenericMapping,
     ref PRIVILEGE_SET PrivilegeSet,
     ref int PrivilegeSetLength,
     out uint GrantedAccess,
     out bool AccessStatus
 );
        public static FileSystemRights GetEffectivePermissions(
            WindowsIdentity clientIdentity,
            FileSecurity securityDescriptor)
        {
            bool isAccessAllowed = false;

            byte[]          binaryForm = securityDescriptor.GetSecurityDescriptorBinaryForm();
            SafeCloseHandle newToken   = null;
            SafeCloseHandle token      = new SafeCloseHandle(clientIdentity.Token, false);

            try
            {
                if (IsPrimaryToken(token) &&
                    !DuplicateTokenEx(
                        token,
                        TokenAccessLevels.Query,
                        IntPtr.Zero,
                        SecurityImpersonationLevel.Identification,
                        TokenType.TokenImpersonation,
                        out newToken))
                {
                    int err = Marshal.GetLastWin32Error();
                    CloseInvalidOutSafeHandle(newToken);
                    throw new Win32Exception(err, "DuplicateTokenExFailed");
                }

                GENERIC_MAPPING genericMapping     = new GENERIC_MAPPING();
                PRIVILEGE_SET   structPrivilegeSet = new PRIVILEGE_SET();
                uint            privilegeSetLength = (uint)Marshal.SizeOf(structPrivilegeSet);
                uint            grantedAccess      = 0;
                if (!AccessCheck(
                        binaryForm,
                        newToken ?? token,
                        0x2000000,
                        genericMapping,
                        out structPrivilegeSet,
                        ref privilegeSetLength,
                        out grantedAccess,
                        out isAccessAllowed))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "AccessCheckFailed");
                }

                return((FileSystemRights)grantedAccess);
            }
            finally
            {
                if (newToken != null)
                {
                    newToken.Dispose();
                }
            }
        }
示例#8
0
        static extern Boolean AccessCheck(
            [MarshalAs(UnmanagedType.LPArray)]
            byte[] pSecurityDescriptor,
            IntPtr ClientToken,

            [MarshalAs(UnmanagedType.U4)]
            TokenAccessLevels accessmask,
            [In] ref GENERIC_MAPPING GenericMapping,
            IntPtr PrivilegeSet,
            ref Int32 PrivilegeSetLength,
            out uint GrantedAccess,
            [MarshalAs(UnmanagedType.Bool)]
            out Boolean AccessStatus);
示例#9
0
        public static List <string> GetInheritedFrom(string path, byte[] aclBytes, int aceCount, bool isContainer, SECURITY_INFORMATION aclType)
        {
            var inheritedFrom = new List <string>();

            path = Path.GetLongPath(path);

            uint            returnValue = 0;
            GENERIC_MAPPING genericMap  = new GENERIC_MAPPING();

            genericMap.GenericRead    = (uint)MappedGenericRights.FILE_GENERIC_READ;
            genericMap.GenericWrite   = (uint)MappedGenericRights.FILE_GENERIC_WRITE;
            genericMap.GenericExecute = (uint)MappedGenericRights.FILE_GENERIC_EXECUTE;
            genericMap.GenericAll     = (uint)MappedGenericRights.FILE_GENERIC_ALL;

            var pInheritInfo = Marshal.AllocHGlobal(aceCount * Marshal.SizeOf(typeof(PINHERITED_FROM)));

            returnValue = GetInheritanceSource(
                path,
                ResourceType.FileObject,
                aclType,
                isContainer,
                IntPtr.Zero,
                0,
                aclBytes,
                IntPtr.Zero,
                ref genericMap,
                pInheritInfo
                );

            if (returnValue != 0)
            {
                throw new System.ComponentModel.Win32Exception((int)returnValue);
            }

            for (int i = 0; i < aceCount; i++)
            {
                var inheritInfo = pInheritInfo.ElementAt <PINHERITED_FROM>(i);

                inheritedFrom.Add(
                    !string.IsNullOrEmpty(inheritInfo.AncestorName) && inheritInfo.AncestorName.StartsWith(@"\\?\") ? inheritInfo.AncestorName.Substring(4) : inheritInfo.AncestorName
                    );
            }

            FreeInheritedFromArray(pInheritInfo, (ushort)aceCount, IntPtr.Zero);
            Marshal.FreeHGlobal(pInheritInfo);

            return(inheritedFrom);
        }
示例#10
0
        public void GetAceTest(bool validUser, bool validCred, string urn, string dn, string dc, string domain, string username, string password, string notes)
        {
            var fun = $"{domain}\\{username}";

            var pSD = GetSD(fn);
            var b   = GetSecurityDescriptorDacl(pSD, out var daclPresent, out var pAcl, out var defaulted);

            Assert.That(b, Is.True);
            Assert.That(daclPresent, Is.True);
            Assert.That(pAcl, Is.Not.EqualTo(IntPtr.Zero));
            var hardAcl = ((IntPtr)pAcl).ToStructure <ACL>();
            var ari     = new ACL_REVISION_INFORMATION();

            b = GetAclInformation(pAcl, ref ari, (uint)Marshal.SizeOf(typeof(ACL_REVISION_INFORMATION)), ACL_INFORMATION_CLASS.AclRevisionInformation);
            Assert.That(b, Is.True);
            Assert.That(ari.AclRevision, Is.EqualTo(hardAcl.AclRevision));
            var asi = new ACL_SIZE_INFORMATION();

            b = GetAclInformation(pAcl, ref asi, (uint)Marshal.SizeOf(typeof(ACL_SIZE_INFORMATION)), ACL_INFORMATION_CLASS.AclSizeInformation);
            Assert.That(b, Is.True);
            Assert.That(asi.AceCount, Is.EqualTo(hardAcl.AceCount));
            for (var i = 0U; i < asi.AceCount; i++)
            {
                b = GetAce(pAcl, i, out var pAce);
                Assert.That(b, Is.True);

                var accountSize = 1024;
                var domainSize  = 1024;
                var outuser     = new StringBuilder(accountSize, accountSize);
                var outdomain   = new StringBuilder(domainSize, domainSize);
                b = LookupAccountSid(null, pAce.GetSid(), outuser, ref accountSize, outdomain, ref domainSize, out _);
                Assert.That(b, Is.True);
                TestContext.WriteLine($"Ace{i}: {pAce.GetHeader().AceType}={outdomain}\\{outuser}; {pAce.GetMask()}");
            }

            BuildTrusteeWithName(out var pTrustee, fun);
            Assert.That(GetEffectiveRightsFromAcl(pAcl, pTrustee, out var accessRights), Is.EqualTo(Win32Error.ERROR_NONE_MAPPED).Or.Zero);
            var map     = new GENERIC_MAPPING((uint)Kernel32.FileAccess.FILE_GENERIC_READ, (uint)Kernel32.FileAccess.FILE_GENERIC_WRITE, (uint)Kernel32.FileAccess.FILE_GENERIC_EXECUTE, (uint)Kernel32.FileAccess.FILE_ALL_ACCESS);
            var ifArray = new SafeInheritedFromArray(hardAcl.AceCount);
            var err     = GetInheritanceSource(fn, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, false, null,
                                               0, pAcl, IntPtr.Zero, map, ifArray);

            Assert.That(err, Is.EqualTo(0));
            TestContext.WriteLine($"{hardAcl.AceCount}: {string.Join("; ", ifArray.Results.Select(i => i.ToString()))}");
            Assert.That(() => ifArray.Dispose(), Throws.Nothing);
        }
示例#11
0
        public void GetAceTest(bool validUser, bool validCred, string urn, string dn, string dc, string domain, string username, string password, string notes)
        {
            var fun = $"{domain}\\{username}";

            var pSD = GetSD(fn);
            var b   = GetSecurityDescriptorDacl(pSD, out bool daclPresent, out IntPtr pAcl, out bool defaulted);

            Assert.That(b, Is.True);
            Assert.That(daclPresent, Is.True);
            Assert.That(pAcl, Is.Not.EqualTo(IntPtr.Zero));
            var hardAcl = pAcl.ToStructure <ACL>();
            var ari     = new ACL_REVISION_INFORMATION();

            b = GetAclInformation(pAcl, ref ari, (uint)Marshal.SizeOf(typeof(ACL_REVISION_INFORMATION)), ACL_INFORMATION_CLASS.AclRevisionInformation);
            Assert.That(b, Is.True);
            Assert.That(ari.AclRevision, Is.EqualTo(hardAcl.AclRevision));
            var asi = new ACL_SIZE_INFORMATION();

            b = GetAclInformation(pAcl, ref asi, (uint)Marshal.SizeOf(typeof(ACL_SIZE_INFORMATION)), ACL_INFORMATION_CLASS.AclSizeInformation);
            Assert.That(b, Is.True);
            Assert.That(asi.AceCount, Is.GreaterThan(0));
            Assert.That(asi.AceCount, Is.EqualTo(hardAcl.AceCount));
            b = GetAce(pAcl, 0, out IntPtr pAce);
            Assert.That(b, Is.True);
            var accessRights = 0U;
            var pTrustee     = new TRUSTEE(fun);

            Assert.That(GetEffectiveRightsFromAcl(pAcl, pTrustee, ref accessRights), Is.EqualTo(Win32Error.ERROR_NONE_MAPPED).Or.Zero);

            var map     = new GENERIC_MAPPING((uint)Kernel32.FileAccess.FILE_GENERIC_READ, (uint)Kernel32.FileAccess.FILE_GENERIC_WRITE, (uint)Kernel32.FileAccess.FILE_GENERIC_EXECUTE, (uint)Kernel32.FileAccess.FILE_ALL_ACCESS);
            var ifArray = new SafeInheritedFromArray(hardAcl.AceCount);
            var err     = GetInheritanceSource(fn, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, false, null,
                                               0, pAcl, IntPtr.Zero, ref map, ifArray);

            Assert.That(err, Is.EqualTo(0));
            TestContext.WriteLine($"{hardAcl.AceCount}: {string.Join("; ", ifArray.Results.Select(i => i.ToString()))}");
            Assert.That(() => ifArray.Dispose(), Throws.Nothing);
        }
示例#12
0
        public static IEnumerable <INHERITED_FROM> GetInheritanceSource(string objectName, ResourceType objectType,
                                                                        SECURITY_INFORMATION securityInfo, bool container, IntPtr pAcl, ref GENERIC_MAPPING pGenericMapping)
        {
            var objSize  = Marshal.SizeOf(typeof(INHERITED_FROM));
            var aceCount = GetAceCount(pAcl);

            using (var pInherit = new SafeCoTaskMemHandle(objSize * (int)aceCount))
            {
                var hr = 0;
                try
                {
                    hr = AdvApi32.GetInheritanceSource(objectName, objectType, securityInfo, container, null, 0, pAcl, IntPtr.Zero, ref pGenericMapping, (IntPtr)pInherit);
                    if (hr != 0)
                    {
                        throw new System.ComponentModel.Win32Exception(hr);
                    }
                    return(pInherit.ToIEnum <INHERITED_FROM>((int)aceCount));
                }
                finally
                {
                    if (hr != 0)
                    {
                        FreeInheritedFromArray((IntPtr)pInherit, (ushort)aceCount, IntPtr.Zero);
                    }
                }
            }
        }
示例#13
0
 static extern void MapGenericMask([In, MarshalAs(UnmanagedType.U4)] ref TokenAccessLevels AccessMask,
                                   [In] ref GENERIC_MAPPING map);
示例#14
0
        internal static Boolean hasReadAccess(String path)
        {
            // Obtain the authenticated user's Identity


            WindowsIdentity winId = WindowsIdentity.GetCurrent(TokenAccessLevels.Duplicate | TokenAccessLevels.Query);

            WindowsImpersonationContext ctx = null;
            Int32 statError = new Int32();

            IntPtr dupToken = IntPtr.Zero;

            try
            {
                // Start impersonating
                //ctx = winId.Impersonate(); works but AccessCheck does not like this

                Int32 outPtr;
                //AccessCheck needs a duplicated token!
                DuplicateToken(winId.Token, TokenImpersonationLevel.Impersonation, out outPtr);

                dupToken = new IntPtr(outPtr);
                ctx      = WindowsIdentity.Impersonate(dupToken);
                GENERIC_MAPPING map = new GENERIC_MAPPING();
                map.GenericRead    = 0x80000000;
                map.GenericWrite   = 0x40000000;
                map.GenericExecute = 0x20000000;
                map.GenericAll     = 0x10000000;
                TokenAccessLevels required = TokenAccessLevels.Query | TokenAccessLevels.Read | TokenAccessLevels.AssignPrimary | (TokenAccessLevels)0x00100000; // add synchronization
                MapGenericMask(ref required, ref map);

                uint    status      = new Int32();
                Boolean accesStatus = false;
                // dummy area the size should be 20 we don't do anything with it
                Int32  sizeps = 20;
                IntPtr ps     = Marshal.AllocCoTaskMem(sizeps);

                //AccessControlSections.Owner | AccessControlSections.Group MUST be included,
                //otherwise the descriptor would be seen with ERROR 1338
                var ACE = Directory.GetAccessControl(path,
                                                     AccessControlSections.Access | AccessControlSections.Owner |
                                                     AccessControlSections.Group);

                Boolean success = AccessCheck(ACE.GetSecurityDescriptorBinaryForm(), dupToken, required, ref map,
                                              ps, ref sizeps, out status, out accesStatus);
                Marshal.FreeCoTaskMem(ps);
                if (!success)
                {
                    statError = Marshal.GetLastWin32Error();
                }
                else
                {
                    return(accesStatus);
                }
            }
            // Prevent exceptions from propagating
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
            }

            finally
            {
                // Revert impersonation

                if (ctx != null)
                {
                    ctx.Undo();
                }
                CloseHandle(dupToken);
            }

            if (statError != 0)
            {
                throw new System.ComponentModel.Win32Exception(statError);
            }

            return(false);
        }
示例#15
0
        public static IEnumerable <INHERITED_FROM> GetInheritanceSource(string objectName, System.Security.AccessControl.ResourceType objectType,
                                                                        SECURITY_INFORMATION securityInfo, bool container, IntPtr pAcl, ref GENERIC_MAPPING pGenericMapping)
        {
            var objSize  = Marshal.SizeOf(typeof(INHERITED_FROM));
            var aceCount = GetAceCount(pAcl);

            using (var pInherit = new SafeInheritedFromArray((ushort)aceCount))
            {
                AdvApi32.GetInheritanceSource(objectName, (SE_OBJECT_TYPE)objectType, securityInfo, container, null, 0, pAcl, IntPtr.Zero, ref pGenericMapping, pInherit).ThrowIfFailed();
                return(pInherit.Results);
            }
        }
示例#16
0
        /// <summary>
        /// To check if path can be accessed or not
        /// </summary>
        /// <param name="path">string value - the patch whose access is being checked</param>
        /// <returns>true if alllowed else false</returns>
        public static bool AccessAllowed(string path)
        {
            bool   accessAllowed = false;
            int    lastError;
            IntPtr fileSD = IntPtr.Zero;
            IntPtr token  = IntPtr.Zero;

            try
            {
                // Get the size of the security descriptor for the directory.
                int sdLength = 0;
                if (!GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, fileSD, 0, out sdLength))
                {
                    lastError = Marshal.GetLastWin32Error();
                    if (lastError != ERROR_INSUFFICIENT_BUFFER)
                    {
                        return(accessAllowed);
                    }

                    fileSD = Marshal.AllocHGlobal(sdLength);

                    // Get the security descriptor for the directory.
                    if (!GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, fileSD, sdLength, out sdLength))
                    {
                        lastError = Marshal.GetLastWin32Error();
                        return(accessAllowed);
                    }

                    // We will check to see if the user has read/write access.
                    GENERIC_MAPPING genericMapping = new GENERIC_MAPPING();
                    PRIVILEGE_SET   privSet        = new PRIVILEGE_SET();
                    uint            grantedAccess  = 0;

                    genericMapping.GenericRead    = 0x01;
                    genericMapping.GenericWrite   = 0x02;
                    genericMapping.GenericExecute = 0;
                    genericMapping.GenericAll     = 0x03;

                    uint desiredAccess = 3;

                    privSet.Control        = 0;
                    privSet.PrivilegeCount = 0;
                    int privLen = Marshal.SizeOf(privSet);

                    // Impersonate the current user.
                    if (!ImpersonateSelf(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation))
                    {
                        lastError = Marshal.GetLastWin32Error();
                        return(accessAllowed);
                    }
                    try
                    {
                        // Get the users token.
                        if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, true, ref token))
                        {
                            lastError = Marshal.GetLastWin32Error();
                            return(accessAllowed);
                        }

                        // Check the access for this user.
                        if (!AccessCheck(fileSD, token, desiredAccess, ref genericMapping, ref privSet, ref privLen, ref grantedAccess, ref accessAllowed))
                        {
                            lastError = Marshal.GetLastWin32Error();
                        }
                    }
                    finally
                    {
                        RevertToSelf();
                    }
                }
            }
            finally
            {
                if (fileSD != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(fileSD);
                }

                if (!token.Equals(IntPtr.Zero))
                {
                    CloseHandle(token);
                    token = IntPtr.Zero;
                }
            }

            return(accessAllowed);
        }
示例#17
0
 public static bool AccessAllowed(string path)
 {
     bool accessAllowed = false;
        int lastError;
        IntPtr fileSD = IntPtr.Zero;
        IntPtr token = IntPtr.Zero;
        try
        {
     int sdLength = 0;
     if (!GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, fileSD, 0, out sdLength))
     {
      lastError = Marshal.GetLastWin32Error();
      if (lastError != ERROR_INSUFFICIENT_BUFFER)
      {
       return accessAllowed;
      }
      fileSD = Marshal.AllocHGlobal(sdLength);
      if (!GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, fileSD, sdLength, out sdLength))
      {
       lastError = Marshal.GetLastWin32Error();
       return accessAllowed;
      }
      GENERIC_MAPPING genericMapping = new GENERIC_MAPPING();
      PRIVILEGE_SET privSet = new PRIVILEGE_SET();
      uint grantedAccess = 0;
      genericMapping.GenericRead = 0x01;
      genericMapping.GenericWrite = 0x02;
      genericMapping.GenericExecute = 0;
      genericMapping.GenericAll = 0x03;
      uint desiredAccess = 3;
      privSet.Control = 0;
      privSet.PrivilegeCount = 0;
      int privLen = Marshal.SizeOf(privSet);
      if (!ImpersonateSelf(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation))
      {
       lastError = Marshal.GetLastWin32Error();
       return accessAllowed;
      }
      try
      {
       if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, true, ref token))
       {
        lastError = Marshal.GetLastWin32Error();
        return accessAllowed;
       }
       if (!AccessCheck(fileSD, token, desiredAccess, ref genericMapping, ref privSet, ref privLen, ref grantedAccess, ref accessAllowed))
       {
        lastError = Marshal.GetLastWin32Error();
       }
      }
      finally
      {
       RevertToSelf();
      }
     }
        }
        finally
        {
     if (fileSD != IntPtr.Zero)
     {
      Marshal.FreeHGlobal(fileSD);
     }
     if (!token.Equals(IntPtr.Zero))
     {
      CloseHandle(token);
      token = IntPtr.Zero;
     }
        }
        return accessAllowed;
 }
示例#18
0
 static extern bool AccessCheck(IntPtr pSecurityDescriptor, IntPtr ClientToken, uint DesiredAccess, ref GENERIC_MAPPING GenericMapping, ref PRIVILEGE_SET PrivilegeSet, ref int PrivilegeSetLength, ref uint GrantedAccess, ref bool AccessStatus);
示例#19
0
 public static extern Win32Error GetInheritanceSource([MarshalAs(UnmanagedType.LPTStr)] string pObjectName, SE_OBJECT_TYPE ObjectType,
                                                      SECURITY_INFORMATION SecurityInfo, [MarshalAs(UnmanagedType.Bool)] bool Container,
                                                      [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5, ArraySubType = UnmanagedType.LPStruct), Optional] Guid[] pObjectClassGuids,
                                                      uint GuidCount, [In] IntPtr pAcl, [In] IntPtr pfnArray, [In] ref GENERIC_MAPPING pGenericMapping, SafeInheritedFromArray pInheritArray);
示例#20
0
        internal static Boolean hasReadAccess(String path)
        {
            // Obtain the authenticated user's Identity

            WindowsIdentity winId = WindowsIdentity.GetCurrent(TokenAccessLevels.Duplicate | TokenAccessLevels.Query);

            WindowsImpersonationContext ctx = null;
            Int32 statError = new Int32();

            IntPtr dupToken = IntPtr.Zero;
            try
            {
                // Start impersonating
                //ctx = winId.Impersonate(); works but AccessCheck does not like this

                Int32 outPtr;
                //AccessCheck needs a duplicated token!
                DuplicateToken(winId.Token, TokenImpersonationLevel.Impersonation, out outPtr);

                dupToken = new IntPtr(outPtr);
                ctx = WindowsIdentity.Impersonate(dupToken);
                GENERIC_MAPPING map = new GENERIC_MAPPING();
                map.GenericRead = 0x80000000;
                map.GenericWrite = 0x40000000;
                map.GenericExecute = 0x20000000;
                map.GenericAll = 0x10000000;
                TokenAccessLevels required = TokenAccessLevels.Query | TokenAccessLevels.Read | TokenAccessLevels.AssignPrimary | (TokenAccessLevels)0x00100000; // add synchronization
                MapGenericMask(ref required, ref map);

                uint status = new Int32();
                Boolean accesStatus = false;
                // dummy area the size should be 20 we don't do anything with it
                Int32 sizeps = 20;
                IntPtr ps = Marshal.AllocCoTaskMem(sizeps);

                //AccessControlSections.Owner | AccessControlSections.Group MUST be included,
                //otherwise the descriptor would be seen with ERROR 1338
                var ACE = Directory.GetAccessControl(path,
                    AccessControlSections.Access | AccessControlSections.Owner |
                        AccessControlSections.Group);

                Boolean success = AccessCheck(ACE.GetSecurityDescriptorBinaryForm(), dupToken, required, ref map,
                        ps, ref sizeps, out status, out accesStatus);
                Marshal.FreeCoTaskMem(ps);
                if (!success)
                {
                    statError = Marshal.GetLastWin32Error();
                }
                else
                {
                    return accesStatus;
                }
            }
            // Prevent exceptions from propagating
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
            }

            finally
            {
                // Revert impersonation

                if (ctx != null)
                    ctx.Undo();
                CloseHandle(dupToken);
            }

            if (statError != 0)
            {
                throw new System.ComponentModel.Win32Exception(statError);
            }

            return false;
        }
示例#21
0
 public static extern void MapGenericMask
 (
     ref uint AccessMask,
     ref GENERIC_MAPPING GenericMapping
 );