检查共享目录权限 - C#

6
我想编写一段代码来检查共享目录的权限,我查看了多个解决方案,但当我尝试获取本地目录权限时,这些方案都能够正常工作,但是当我对共享目录进行测试时,它们就失败了。
我正在尝试这个问题中的示例: SOF: checking-for-directory-and-file-write-permissions-in-net,但它只能在本地目录上运行。
例如,我使用了这个类:
 public class CurrentUserSecurity
{
    WindowsIdentity _currentUser;
    WindowsPrincipal _currentPrincipal;

    public CurrentUserSecurity()
    {
        _currentUser = WindowsIdentity.GetCurrent();
        _currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    }

    public bool HasAccess(DirectoryInfo directory, FileSystemRights right)
    {
        // Get the collection of authorization rules that apply to the directory.
        AuthorizationRuleCollection acl = directory.GetAccessControl()
            .GetAccessRules(true, true, typeof(SecurityIdentifier));
        return HasFileOrDirectoryAccess(right, acl);
    }

    public bool HasAccess(FileInfo file, FileSystemRights right)
    {
        // Get the collection of authorization rules that apply to the file.
        AuthorizationRuleCollection acl = file.GetAccessControl()
            .GetAccessRules(true, true, typeof(SecurityIdentifier));
        return HasFileOrDirectoryAccess(right, acl);
    }

    private bool HasFileOrDirectoryAccess(FileSystemRights right,
                                          AuthorizationRuleCollection acl)
    {
        bool allow = false;
        bool inheritedAllow = false;
        bool inheritedDeny = false;

        for (int i = 0; i < acl.Count; i++)
        {
            FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[i];
            // If the current rule applies to the current user.
            if (_currentUser.User.Equals(currentRule.IdentityReference) ||
                _currentPrincipal.IsInRole(
                                (SecurityIdentifier)currentRule.IdentityReference))
            {

                if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
                {
                    if ((currentRule.FileSystemRights & right) == right)
                    {
                        if (currentRule.IsInherited)
                        {
                            inheritedDeny = true;
                        }
                        else
                        { // Non inherited "deny" takes overall precedence.
                            return false;
                        }
                    }
                }
                else if (currentRule.AccessControlType
                                                .Equals(AccessControlType.Allow))
                {
                    if ((currentRule.FileSystemRights & right) == right)
                    {
                        if (currentRule.IsInherited)
                        {
                            inheritedAllow = true;
                        }
                        else
                        {
                            allow = true;
                        }
                    }
                }
            }
        }

        if (allow)
        { // Non inherited "allow" takes precedence over inherited rules.
            return true;
        }
        return inheritedAllow && !inheritedDeny;
    }
}

它检查当前模拟用户对目录或文件的权限。

在检查本地目录时,所有测试用例都能正确通过,但在共享目录中有一些失败,这是我想要解决的问题,那么有没有解决方案呢?

下面的测试用例失败了,尽管该目录没有写入权限:

        [TestMethod]
    public void HasAccess_NotHaveAccess_ReturnsFalse()
    {
        CurrentUserSecurity cus = new CurrentUserSecurity();
        bool result = cus.HasAccess(new DirectoryInfo(@"\\sharedpc\readonly"), System.Security.AccessControl.FileSystemRights.Write);
        Assert.AreEqual(result, false);
    }

1
嗨,deserthero,我尝试了你的代码,一切都正常。你确定在“\sharedpc\readonly”文件夹中为当前用户设置了适当的权限吗? - Mr Rivero
1
嗨,我在下面给出了一个答案,但是我认为这是一个环境问题或只是有点困惑。我理解你的TestMethod返回True,表明用户权限,但那是不正确的吗?1. 你能[编辑]你的问题并提供文件夹权限的截图,2. 指示运行代码WindowsIdentity.GetCurrent的用户帐户名称。3. 请确认您已经尝试使用不同于自己的WindowIdentity进行测试,最简单的方法是https://dev59.com/KXVC5IYBdhLWcg3w-mdO#7250145。谢谢。 - Jeremy Thompson
1
你尝试过这个吗,https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemsecurity.accessrulefactory(v=vs.110).aspx?Get方法可能无法解析嵌套规则或依赖规则,例如应用于组的规则等,该方法可能会给出实际访问规则以进行验证。 - Akash Kava
1个回答

4
你的代码中出现了 WOMM。我鼓励你通过直接使用 Win32 API 来发现标准 .NET 类(在你的环境下)失败的原因,以揭示 BCL 隐藏的潜在问题。希望尝试这种更低级别的方法能够产生错误,以便你得到一些关于 BCL 类存在什么问题的提示,或者可以将其用作解决方法。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

class MainConsole
{
    [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern int NetShareGetInfo(
        [MarshalAs(UnmanagedType.LPWStr)] string serverName,
        [MarshalAs(UnmanagedType.LPWStr)] string netName,
        Int32 level,
        out IntPtr bufPtr);

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetSecurityDescriptorDacl(
        IntPtr pSecurityDescriptor,
        [MarshalAs(UnmanagedType.Bool)] out bool bDaclPresent,
        ref IntPtr pDacl,
        [MarshalAs(UnmanagedType.Bool)] out bool bDaclDefaulted
        );

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetAclInformation(
        IntPtr pAcl,
        ref ACL_SIZE_INFORMATION pAclInformation,
        uint nAclInformationLength,
        ACL_INFORMATION_CLASS dwAclInformationClass
     );

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern int GetAce(
        IntPtr aclPtr,
        int aceIndex,
        out IntPtr acePtr
     );

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern int GetLengthSid(
        IntPtr pSID
     );

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool ConvertSidToStringSid(
        [MarshalAs(UnmanagedType.LPArray)] byte[] pSID,
        out IntPtr ptrSid
     );

    [DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern int NetApiBufferFree(
        IntPtr buffer
     );

    enum SID_NAME_USE
    {
        SidTypeUser = 1,
        SidTypeGroup,
        SidTypeDomain,
        SidTypeAlias,
        SidTypeWellKnownGroup,
        SidTypeDeletedAccount,
        SidTypeInvalid,
        SidTypeUnknown,
        SidTypeComputer
    }

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool LookupAccountSid(
      string lpSystemName,
      [MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
      System.Text.StringBuilder lpName,
      ref uint cchName,
      System.Text.StringBuilder ReferencedDomainName,
      ref uint cchReferencedDomainName,
      out SID_NAME_USE peUse);

    [StructLayout(LayoutKind.Sequential)]
    struct SHARE_INFO_502
    {
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi502_netname;
        public uint shi502_type;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi502_remark;
        public Int32 shi502_permissions;
        public Int32 shi502_max_uses;
        public Int32 shi502_current_uses;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi502_path;
        public IntPtr shi502_passwd;
        public Int32 shi502_reserved;
        public IntPtr shi502_security_descriptor;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct ACL_SIZE_INFORMATION
    {
        public uint AceCount;
        public uint AclBytesInUse;
        public uint AclBytesFree;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct ACE_HEADER
    {
        public byte AceType;
        public byte AceFlags;
        public short AceSize;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct ACCESS_ALLOWED_ACE
    {
        public ACE_HEADER Header;
        public int Mask;
        public int SidStart;
    }

    enum ACL_INFORMATION_CLASS
    {
        AclRevisionInformation = 1,
        AclSizeInformation
    }



    static void Main(string[] args)
    {
        IntPtr bufptr = IntPtr.Zero;
        int err = NetShareGetInfo("ServerName", "ShareName", 502, out bufptr);
        if (0 == err)
        {
            SHARE_INFO_502 shareInfo = (SHARE_INFO_502)Marshal.PtrToStructure(bufptr, typeof(SHARE_INFO_502));

            bool bDaclPresent;
            bool bDaclDefaulted;
            IntPtr pAcl = IntPtr.Zero;
            GetSecurityDescriptorDacl(shareInfo.shi502_security_descriptor, out bDaclPresent, ref pAcl, out bDaclDefaulted);
            if (bDaclPresent)
            {
                ACL_SIZE_INFORMATION AclSize = new ACL_SIZE_INFORMATION();
                GetAclInformation(pAcl, ref AclSize, (uint)Marshal.SizeOf(typeof(ACL_SIZE_INFORMATION)), ACL_INFORMATION_CLASS.AclSizeInformation);
                for (int i = 0; i < AclSize.AceCount; i++)
                {
                    IntPtr pAce;
                    err = GetAce(pAcl, i, out pAce);
                    ACCESS_ALLOWED_ACE ace = (ACCESS_ALLOWED_ACE)Marshal.PtrToStructure(pAce, typeof(ACCESS_ALLOWED_ACE));

                    IntPtr iter = (IntPtr)((long)pAce + (long)Marshal.OffsetOf(typeof(ACCESS_ALLOWED_ACE), "SidStart"));
                    byte[] bSID = null;
                    int size = (int)GetLengthSid(iter);
                    bSID = new byte[size];
                    Marshal.Copy(iter, bSID, 0, size);
                    IntPtr ptrSid;
                    ConvertSidToStringSid(bSID, out ptrSid);
                    string strSID = Marshal.PtrToStringAuto(ptrSid);

                    Console.WriteLine("The details of ACE number {0} are: ", i+1);

                    StringBuilder name = new StringBuilder();
                    uint cchName = (uint)name.Capacity;
                    StringBuilder referencedDomainName = new StringBuilder();
                    uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
                    SID_NAME_USE sidUse;

                    LookupAccountSid(null, bSID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse);

                    Console.WriteLine("Trustee Name: " + name);
                    Console.WriteLine("Domain Name: " + referencedDomainName);

                    if ((ace.Mask & 0x1F01FF) == 0x1F01FF)
                    {
                        Console.WriteLine("Permission: Full Control");
                    }
                    else if ((ace.Mask & 0x1301BF) == 0x1301BF)
                    {
                        Console.WriteLine("Permission: READ and CHANGE");
                    }
                    else if ((ace.Mask & 0x1200A9) == 0x1200A9)
                    {
                        Console.WriteLine("Permission: READ only");
                    }
                    Console.WriteLine("SID: {0} \nHeader AceType: {1} \nAccess Mask: {2} \nHeader AceFlag: {3}", strSID, ace.Header.AceType.ToString(), ace.Mask.ToString(), ace.Header.AceFlags.ToString());
                    Console.WriteLine("\n");
                }
            }
            err = NetApiBufferFree(bufptr);
        }
    }
}

参考: http://blogs.msdn.com/b/dsadsi/archive/2012/03/30/to-read-shared-permissions-of-a-server-resource-in-c-using-netsharegetinfo.aspx

如果可以的话,请在另一个网络上尝试您的代码和这个代码,因为我认为这可能是一些环境问题。


1
很棒的解决方案!但是:在调用GetSecurityDescriptorDacl(...)之前,您必须检查shareInfo.shi502_security_descriptor!= IntPtr.Zero,因为至少对于服务器2016而言,它未设置为管理共享,然后您将收到访问冲突。 - marsh-wiggle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接