Make System.DirectoryServices.AccountManagement use GeneratedDllImport (#61805)
authorElinor Fung <elfung@microsoft.com>
Mon, 22 Nov 2021 16:23:34 +0000 (09:23 -0700)
committerGitHub <noreply@github.com>
Mon, 22 Nov 2021 16:23:34 +0000 (09:23 -0700)
43 files changed:
src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSidToSid.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CopySid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EqualDomainSid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetLengthSid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetSidIdentifierAuthority.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation_SafeLocalAllocHandle.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ImpersonateLoggedOnUser_IntPtr.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LookupAccountSid.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaLookupSids.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaOpenPolicy.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaQueryInformationPolicy.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzGetInformationFromContext.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeContextFromSid.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeResourceManager.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Credui/Interop.CredUIParseUserName.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleFreeMemory.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleGetPrimaryDomainInformation.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CloseHandle.cs
src/libraries/Common/src/Interop/Windows/Logoncli/Interop.DsGetDcName.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/Netutils/Interop.NetApiBufferFree.cs [new file with mode: 0644]
src/libraries/Common/src/Interop/Windows/SspiCli/Interop.TOKENS.cs
src/libraries/Common/src/Interop/Windows/Wkscli/Interop.NetWkstaGetInfo.cs [new file with mode: 0644]
src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/GlobalDebug.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs
src/libraries/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/NTAccount.cs
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs

diff --git a/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs b/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs
new file mode 100644 (file)
index 0000000..2ed72a6
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Activeds
+    {
+        [DllImport(Interop.Libraries.Activeds, CharSet = CharSet.Unicode, ExactSpelling = true)]
+        internal static extern int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs
new file mode 100644 (file)
index 0000000..998f854
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Libraries.Advapi32, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial BOOL ConvertSidToStringSid(IntPtr sid, ref string stringSid);
+    }
+}
index 492f2d1..9b9ef01 100644 (file)
@@ -9,7 +9,7 @@ internal static partial class Interop
     internal static partial class Advapi32
     {
         [GeneratedDllImport(Interop.Libraries.Advapi32, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
-        internal static partial int ConvertStringSidToSid(
+        internal static partial BOOL ConvertStringSidToSid(
             string stringSid,
             out IntPtr ByteArray);
     }
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CopySid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CopySid.cs
new file mode 100644 (file)
index 0000000..ba978ba
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EqualDomainSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EqualDomainSid.cs
new file mode 100644 (file)
index 0000000..2f20584
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Interop.Libraries.Advapi32)]
+        public static partial bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetLengthSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetLengthSid.cs
new file mode 100644 (file)
index 0000000..0f97e38
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Interop.Libraries.Advapi32)]
+        internal static partial int GetLengthSid(IntPtr sid);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetSidIdentifierAuthority.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetSidIdentifierAuthority.cs
new file mode 100644 (file)
index 0000000..a284321
--- /dev/null
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+        internal struct SID_IDENTIFIER_AUTHORITY
+        {
+            public byte b1;
+            public byte b2;
+            public byte b3;
+            public byte b4;
+            public byte b5;
+            public byte b6;
+        }
+
+        [GeneratedDllImport(Libraries.Advapi32)]
+        internal static partial IntPtr GetSidIdentifierAuthority(IntPtr sid);
+
+        [GeneratedDllImport(Interop.Libraries.Advapi32)]
+        internal static partial IntPtr GetSidSubAuthority(IntPtr sid, int index);
+
+        [GeneratedDllImport(Interop.Libraries.Advapi32)]
+        internal static partial IntPtr GetSidSubAuthorityCount(IntPtr sid);
+    }
+}
index 22ee240..df3e8f8 100644 (file)
@@ -11,22 +11,6 @@ internal static partial class Interop
     {
         [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
         internal static partial bool GetTokenInformation(
-            SafeAccessTokenHandle TokenHandle,
-            uint TokenInformationClass,
-            SafeLocalAllocHandle TokenInformation,
-            uint TokenInformationLength,
-            out uint ReturnLength);
-
-        [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
-        internal static partial bool GetTokenInformation(
-            IntPtr TokenHandle,
-            uint TokenInformationClass,
-            SafeLocalAllocHandle TokenInformation,
-            uint TokenInformationLength,
-            out uint ReturnLength);
-
-        [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
-        internal static partial bool GetTokenInformation(
             IntPtr TokenHandle,
             uint TokenInformationClass,
             IntPtr TokenInformation,
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation_SafeLocalAllocHandle.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation_SafeLocalAllocHandle.cs
new file mode 100644 (file)
index 0000000..57f5422
--- /dev/null
@@ -0,0 +1,28 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool GetTokenInformation(
+            SafeAccessTokenHandle TokenHandle,
+            uint TokenInformationClass,
+            SafeLocalAllocHandle TokenInformation,
+            uint TokenInformationLength,
+            out uint ReturnLength);
+
+        [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool GetTokenInformation(
+            IntPtr TokenHandle,
+            uint TokenInformationClass,
+            SafeLocalAllocHandle TokenInformation,
+            uint TokenInformationLength,
+            out uint ReturnLength);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ImpersonateLoggedOnUser_IntPtr.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ImpersonateLoggedOnUser_IntPtr.cs
new file mode 100644 (file)
index 0000000..8082948
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)]
+        internal static partial int ImpersonateLoggedOnUser(IntPtr userToken);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs
new file mode 100644 (file)
index 0000000..448b684
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool IsValidSid(IntPtr sid);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs
new file mode 100644 (file)
index 0000000..7e1155d
--- /dev/null
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Libraries.Advapi32, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial int LogonUser(
+            string username,
+            string domain,
+            string password,
+            int logonType,
+            int logonProvider,
+            ref IntPtr token);
+    }
+}
index 742ba2d..bf058fb 100644 (file)
@@ -8,8 +8,8 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Interop.Libraries.Advapi32, CharSet = CharSet.Unicode, EntryPoint = "LookupAccountSidW", SetLastError = true)]
-        public static extern unsafe int LookupAccountSid(
+        [GeneratedDllImport(Interop.Libraries.Advapi32, EntryPoint = "LookupAccountSidW", CharSet = CharSet.Unicode, SetLastError = true)]
+        public static unsafe partial int LookupAccountSid(
             string lpSystemName,
             byte[] Sid,
             char* Name,
index 7f935cc..2ed2561 100644 (file)
@@ -19,3 +19,39 @@ internal static partial class Interop
         );
     }
 }
+
+internal static partial class SafeLsaMemoryHandleExtensions
+{
+    public static unsafe void InitializeReferencedDomainsList(this SafeLsaMemoryHandle referencedDomains)
+    {
+        // We don't know the real size of the referenced domains yet, so we need to set an initial
+        // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of
+        // the domains.
+        referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>());
+        Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
+
+        byte* pRdl = null;
+        try
+        {
+            referencedDomains.AcquirePointer(ref pRdl);
+
+            // If there is a trust information list, then the buffer size is the end of that list minus
+            // the beginning of the domain list. Otherwise, then the buffer is just the size of the
+            // referenced domain list structure, which is what we defaulted to.
+            if (domainList.Domains != IntPtr.Zero)
+            {
+                Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains;
+                pTrustInformation = pTrustInformation + domainList.Entries;
+
+                long bufferSize = (byte*)pTrustInformation - pRdl;
+                System.Diagnostics.Debug.Assert(bufferSize > 0, "bufferSize > 0");
+                referencedDomains.Initialize((ulong)bufferSize);
+            }
+        }
+        finally
+        {
+            if (pRdl != null)
+                referencedDomains.ReleasePointer();
+        }
+    }
+}
index 879b6d0..861d07e 100644 (file)
@@ -9,6 +9,24 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
+        [Flags]
+        internal enum PolicyRights
+        {
+            POLICY_VIEW_LOCAL_INFORMATION = 0x00000001,
+            POLICY_VIEW_AUDIT_INFORMATION = 0x00000002,
+            POLICY_GET_PRIVATE_INFORMATION = 0x00000004,
+            POLICY_TRUST_ADMIN = 0x00000008,
+            POLICY_CREATE_ACCOUNT = 0x00000010,
+            POLICY_CREATE_SECRET = 0x00000020,
+            POLICY_CREATE_PRIVILEGE = 0x00000040,
+            POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080,
+            POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100,
+            POLICY_AUDIT_LOG_ADMIN = 0x00000200,
+            POLICY_SERVER_ADMIN = 0x00000400,
+            POLICY_LOOKUP_NAMES = 0x00000800,
+            POLICY_NOTIFICATION = 0x00001000,
+        }
+
         [GeneratedDllImport(Interop.Libraries.Advapi32, EntryPoint = "LsaOpenPolicy", SetLastError = true)]
         private static partial uint LsaOpenPolicy(
             ref UNICODE_STRING SystemName,
diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaQueryInformationPolicy.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaQueryInformationPolicy.cs
new file mode 100644 (file)
index 0000000..d38ac1c
--- /dev/null
@@ -0,0 +1,17 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Advapi32
+    {
+        [GeneratedDllImport(Libraries.Advapi32)]
+        internal static partial uint LsaQueryInformationPolicy(
+            IntPtr policyHandle,
+            int policyInformationClass,
+            ref IntPtr buffer);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzGetInformationFromContext.cs b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzGetInformationFromContext.cs
new file mode 100644 (file)
index 0000000..9dc0b02
--- /dev/null
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Authz
+    {
+        [GeneratedDllImport(Libraries.Authz, SetLastError = true)]
+        internal static partial bool AuthzGetInformationFromContext(
+            IntPtr hAuthzClientContext,
+            int InfoClass,
+            int BufferSize,
+            out int pSizeRequired,
+            IntPtr Buffer);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeContextFromSid.cs b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeContextFromSid.cs
new file mode 100644 (file)
index 0000000..ae70cba
--- /dev/null
@@ -0,0 +1,28 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Authz
+    {
+        internal const int AUTHZ_RM_FLAG_NO_AUDIT = 0x1;
+        internal const int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2;
+        internal const int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION);
+
+        [GeneratedDllImport(Interop.Libraries.Authz, SetLastError = true)]
+        internal static partial bool AuthzInitializeContextFromSid(
+            int Flags,
+            IntPtr UserSid,
+            IntPtr AuthzResourceManager,
+            IntPtr pExpirationTime,
+            Interop.LUID Identitifier,
+            IntPtr DynamicGroupArgs,
+            out IntPtr pAuthzClientContext);
+
+        [GeneratedDllImport(Interop.Libraries.Authz)]
+        internal static partial bool AuthzFreeContext(IntPtr AuthzClientContext);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeResourceManager.cs b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeResourceManager.cs
new file mode 100644 (file)
index 0000000..12a7f80
--- /dev/null
@@ -0,0 +1,23 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Authz
+    {
+        [GeneratedDllImport(Libraries.Authz, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial bool AuthzInitializeResourceManager(
+            int flags,
+            IntPtr pfnAccessCheck,
+            IntPtr pfnComputeDynamicGroups,
+            IntPtr pfnFreeDynamicGroups,
+            string name,
+            out IntPtr rm);
+
+        [GeneratedDllImport(Libraries.Authz)]
+        internal static partial bool AuthzFreeResourceManager(IntPtr rm);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Credui/Interop.CredUIParseUserName.cs b/src/libraries/Common/src/Interop/Windows/Credui/Interop.CredUIParseUserName.cs
new file mode 100644 (file)
index 0000000..53ff59e
--- /dev/null
@@ -0,0 +1,23 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Credui
+    {
+        // These contants were taken from the wincred.h file
+        internal const int CRED_MAX_USERNAME_LENGTH = 514;
+        internal const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338;
+
+        [GeneratedDllImport(Libraries.Credui, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static unsafe partial int CredUIParseUserName(
+            string pszUserName,
+            char* pszUser,
+            uint ulUserMaxChars,
+            char* pszDomain,
+            uint ulDomainMaxChars);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleFreeMemory.cs b/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleFreeMemory.cs
new file mode 100644 (file)
index 0000000..45c8e53
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Dsrole
+    {
+        [GeneratedDllImport(Libraries.Dsrole)]
+        public static partial int DsRoleFreeMemory(IntPtr buffer);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleGetPrimaryDomainInformation.cs b/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleGetPrimaryDomainInformation.cs
new file mode 100644 (file)
index 0000000..97bff61
--- /dev/null
@@ -0,0 +1,25 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Dsrole
+    {
+        internal enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL
+        {
+            DsRolePrimaryDomainInfoBasic = 1,
+            DsRoleUpgradeStatus = 2,
+            DsRoleOperationState = 3,
+            DsRolePrimaryDomainInfoBasicEx = 4
+        }
+
+        [GeneratedDllImport(Libraries.Dsrole, CharSet = CharSet.Unicode, ExactSpelling = true)]
+        internal static partial int DsRoleGetPrimaryDomainInformation(
+            [MarshalAs(UnmanagedType.LPTStr)] string lpServer,
+            DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
+            out IntPtr Buffer);
+    }
+}
index 0e4280b..1fbd9b7 100644 (file)
@@ -8,9 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Kernel32
     {
-#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
-                                                // Disabled since CloseHandle is a QCall in some scenarios and DllImportGenerator doesn't support QCalls.
-        [DllImport(Libraries.Kernel32, SetLastError = true)]
-        internal static extern bool CloseHandle(IntPtr handle);
+        [GeneratedDllImport(Libraries.Kernel32, SetLastError = true)]
+        internal static partial bool CloseHandle(IntPtr handle);
     }
 }
diff --git a/src/libraries/Common/src/Interop/Windows/Logoncli/Interop.DsGetDcName.cs b/src/libraries/Common/src/Interop/Windows/Logoncli/Interop.DsGetDcName.cs
new file mode 100644 (file)
index 0000000..37f86ad
--- /dev/null
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Logoncli
+    {
+        [GeneratedDllImport(Libraries.Logoncli, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode, ExactSpelling = true)]
+        internal static partial int DsGetDcName(
+            string computerName,
+            string domainName,
+            IntPtr domainGuid,
+            string siteName,
+            int flags,
+            out IntPtr domainControllerInfo);
+    }
+}
diff --git a/src/libraries/Common/src/Interop/Windows/Netutils/Interop.NetApiBufferFree.cs b/src/libraries/Common/src/Interop/Windows/Netutils/Interop.NetApiBufferFree.cs
new file mode 100644 (file)
index 0000000..1f84f9a
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Netutils
+    {
+        [GeneratedDllImport(Libraries.Netutils)]
+        internal static partial int NetApiBufferFree(IntPtr buffer);
+    }
+}
index 00a32bf..344c9a7 100644 (file)
@@ -47,4 +47,10 @@ internal static partial class Interop
         internal uint PrivilegeCount;
         internal LUID ModifiedId;
     }
+
+    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+    internal struct TOKEN_USER
+    {
+        public SID_AND_ATTRIBUTES sidAndAttributes;
+    }
 }
diff --git a/src/libraries/Common/src/Interop/Windows/Wkscli/Interop.NetWkstaGetInfo.cs b/src/libraries/Common/src/Interop/Windows/Wkscli/Interop.NetWkstaGetInfo.cs
new file mode 100644 (file)
index 0000000..bfc1039
--- /dev/null
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Wkscli
+    {
+        [GeneratedDllImport(Libraries.Wkscli, CharSet = CharSet.Unicode, ExactSpelling = true)]
+        internal static partial int NetWkstaGetInfo(string server, int level, ref IntPtr buffer);
+    }
+}
index 7bcd2a5..0c0804c 100644 (file)
@@ -1,9 +1,13 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
     <NoWarn>$(NoWarn);CA2249</NoWarn>
+    <!-- Suppressions to avoid ifdefs:
+        CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
+        CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
+    <NoWarn>$(NoWarn);CA1845;CA1846</NoWarn>
     <Nullable>annotations</Nullable>
     <IsPackable>true</IsPackable>
     <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
     <Compile Include="System\DirectoryServices\AccountManagement\IdentityClaim.cs" />
     <Compile Include="System\DirectoryServices\AccountManagement\IdentityReference.cs" />
     <Compile Include="System\DirectoryServices\AccountManagement\UnknownPrincipal.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs"
+             Link="Common\Interop\Windows\Interop.BOOL.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOLEAN.cs"
+             Link="Common\Interop\Windows\Interop.BOOLEAN.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
              Link="Common\Interop\Windows\Interop.Libraries.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs"
+             Link="Common\Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs"
+             Link="Common\Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs"
+             Link="Common\Interop\Windows\Interop.UNICODE_STRING.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Activeds\Interop.ADsOpenObject.cs"
+             Link="Common\Interop\Windows\Activeds\Interop.ADsOpenObject.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CopySid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.CopySid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.EqualDomainSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.EqualDomainSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetLengthSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetLengthSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetTokenInformation.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.IsValidSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.IsValidSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LogonUser.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LogonUser.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LookupAccountSid.cs"
              Link="Common\Interop\Windows\Advapi32\Interop.LookupAccountSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaClose.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaClose.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaLookupSids.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaLookupSids.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenProcessToken.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.OpenProcessToken.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.RevertToSelf.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.RevertToSelf.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Authz\Interop.AuthzGetInformationFromContext.cs"
+             Link="Common\Interop\Windows\Authz\Interop.AuthzGetInformationFromContext.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Authz\Interop.AuthzInitializeContextFromSid.cs"
+             Link="Common\Interop\Windows\Authz\Interop.AuthzInitializeContextFromSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Authz\Interop.AuthzInitializeResourceManager.cs"
+             Link="Common\Interop\Windows\Authz\Interop.AuthzInitializeResourceManager.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Credui\Interop.CredUIParseUserName.cs"
+             Link="Common\Interop\Windows\Credui\Interop.CredUIParseUserName.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Dsrole\Interop.DsRoleFreeMemory.cs"
+             Link="Common\Interop\Windows\Dsrole\Interop.DsRoleFreeMemory.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Dsrole\Interop.DsRoleGetPrimaryDomainInformation.cs"
+             Link="Common\Interop\Windows\Dsrole\Interop.DsRoleGetPrimaryDomainInformation.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThread.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThread.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LocalAlloc.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.LocalAlloc.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Logoncli\Interop.DsGetDcName.cs"
+             Link="Common\Interop\Windows\Logoncli\Interop.DsGetDcName.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Netutils\Interop.NetApiBufferFree.cs"
+             Link="Common\Interop\Windows\Netutils\Interop.NetApiBufferFree.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtStatus.cs"
+             Link="Common\Interop\Windows\NtDll\Interop.NtStatus.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\Interop.LSAStructs.cs"
+             Link="Common\Interop\Windows\SspiCli\Interop.LSAStructs.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\Interop.TOKENS.cs"
+             Link="Common\Interop\Windows\SspiCli\Interop.TOKENS.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Wkscli\Interop.NetWkstaGetInfo.cs"
+             Link="Common\Interop\Windows\Wkscli\Interop.NetWkstaGetInfo.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLsaMemoryHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeLsaMemoryHandle.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeTokenHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeTokenHandle.cs" />
   </ItemGroup>
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Configuration.ConfigurationManager\src\System.Configuration.ConfigurationManager.csproj" />
     <Reference Include="System.ComponentModel.Primitives" />
     <Reference Include="System.Diagnostics.Debug" />
     <Reference Include="System.IO.FileSystem.AccessControl" />
+    <Reference Include="System.Memory" />
     <Reference Include="System.Net.Primitives" />
     <Reference Include="System.Net.Security" />
     <Reference Include="System.Resources.ResourceManager" />
     <Reference Include="System.Runtime" />
+    <Reference Include="System.Runtime.CompilerServices.Unsafe" />
     <Reference Include="System.Runtime.Extensions" />
     <Reference Include="System.Runtime.InteropServices" />
     <Reference Include="System.Security.AccessControl" />
index 4fdd2e2..a7e18fa 100644 (file)
@@ -1570,7 +1570,7 @@ namespace System.DirectoryServices.AccountManagement
                         sddlSid = sddlSid.Substring(0, index) + "-" + ((uint)primaryGroupId).ToString(CultureInfo.InvariantCulture);
 
                         // Now, we convert the SDDL back into a SID
-                        if (UnsafeNativeMethods.ConvertStringSidToSid(sddlSid, ref pGroupSid))
+                        if (Interop.Advapi32.ConvertStringSidToSid(sddlSid, out pGroupSid) != Interop.BOOL.FALSE)
                         {
                             // Now we convert the native SID to a byte[] SID
                             groupSid = Utils.ConvertNativeSidToByteArray(pGroupSid);
@@ -1581,7 +1581,7 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (pGroupSid != IntPtr.Zero)
-                    UnsafeNativeMethods.LocalFree(pGroupSid);
+                    Interop.Kernel32.LocalFree(pGroupSid);
             }
 
             if (groupSid != null)
index 371f885..709ccb1 100644 (file)
@@ -528,7 +528,7 @@ namespace System.DirectoryServices.AccountManagement
                         {
                             pSid = Utils.ConvertByteArrayToIntPtr(sidb);
 
-                            if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
+                            if (Interop.Advapi32.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                             {
                                 GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                         "ADStoreCtx",
@@ -583,7 +583,7 @@ namespace System.DirectoryServices.AccountManagement
                             {
                                 pSid = Utils.ConvertByteArrayToIntPtr(sidb);
 
-                                if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
+                                if (Interop.Advapi32.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                                 {
                                     GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                             "ADStoreCtx",
index 66e8d52..fd46f46 100644 (file)
@@ -597,7 +597,7 @@ namespace System.DirectoryServices.AccountManagement
 
             try
             {
-                if (UnsafeNativeMethods.ConvertStringSidToSid(urnValue, ref pBytePtr))
+                if (Interop.Advapi32.ConvertStringSidToSid(urnValue, out pBytePtr) != Interop.BOOL.FALSE)
                 {
                     // Now we convert the native SID to a byte[] SID
                     sidB = Utils.ConvertNativeSidToByteArray(pBytePtr);
@@ -620,7 +620,7 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (IntPtr.Zero != pBytePtr)
-                    UnsafeNativeMethods.LocalFree(pBytePtr);
+                    Interop.Kernel32.LocalFree(pBytePtr);
             }
 
             StringBuilder stringizedBinarySid = new StringBuilder();
index a06b3ac..7ecdd63 100644 (file)
@@ -1,14 +1,11 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using System.Diagnostics;
 using System.Collections.Generic;
-using System.Globalization;
 using System.Runtime.InteropServices;
-using System.DirectoryServices;
-using System.Text;
-using System.Net;
+
+using Microsoft.Win32.SafeHandles;
 
 namespace System.DirectoryServices.AccountManagement
 {
@@ -50,7 +47,7 @@ namespace System.DirectoryServices.AccountManagement
             }
         }
 
-        internal SidList(UnsafeNativeMethods.SID_AND_ATTR[] sidAndAttr)
+        internal SidList(Interop.SID_AND_ATTRIBUTES[] sidAndAttr)
         {
             GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} Sid+Attr SIDs", sidAndAttr.Length);
 
@@ -60,7 +57,7 @@ namespace System.DirectoryServices.AccountManagement
 
             for (int i = 0; i < sidCount; i++)
             {
-                pSids[i] = sidAndAttr[i].pSid;
+                pSids[i] = sidAndAttr[i].Sid;
             }
 
             TranslateSids(null, pSids);
@@ -80,141 +77,84 @@ namespace System.DirectoryServices.AccountManagement
             int sidCount = pSids.Length;
 
             // Translate the SIDs in bulk
-            IntPtr pOA = IntPtr.Zero;
-            IntPtr pPolicyHandle = IntPtr.Zero;
-
-            IntPtr pDomains = IntPtr.Zero;
-            UnsafeNativeMethods.LSA_TRUST_INFORMATION[] domains;
-
-            IntPtr pNames = IntPtr.Zero;
-            UnsafeNativeMethods.LSA_TRANSLATED_NAME[] names;
-
+            SafeLsaPolicyHandle policyHandle = null;
+            SafeLsaMemoryHandle domainsHandle = null;
+            SafeLsaMemoryHandle namesHandle = null;
             try
             {
                 //
                 // Get the policy handle
                 //
-                UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES();
-
-                pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES)));
-                Marshal.StructureToPtr(oa, pOA, false);
-
-                int err = 0;
-                if (target == null)
-                {
-                    err = UnsafeNativeMethods.LsaOpenPolicy(
-                                    IntPtr.Zero,
-                                    pOA,
-                                    0x800,        // POLICY_LOOKUP_NAMES
-                                    ref pPolicyHandle);
-                }
-                else
-                {
-                    // Build an entry.  Note that LSA_UNICODE_STRING.length is in bytes,
-                    // while PtrToStringUni expects a length in characters.
-                    UnsafeNativeMethods.LSA_UNICODE_STRING_Managed lsaTargetString = new UnsafeNativeMethods.LSA_UNICODE_STRING_Managed();
-                    lsaTargetString.buffer = target;
-                    lsaTargetString.length = (ushort)(target.Length * 2);
-                    lsaTargetString.maximumLength = lsaTargetString.length;
-
-                    IntPtr lsaTargetPr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_UNICODE_STRING)));
-
-                    try
-                    {
-                        Marshal.StructureToPtr(lsaTargetString, lsaTargetPr, false);
-
-                        err = UnsafeNativeMethods.LsaOpenPolicy(
-                                        lsaTargetPr,
-                                        pOA,
-                                        0x800,        // POLICY_LOOKUP_NAMES
-                                        ref pPolicyHandle);
-                    }
-                    finally
-                    {
-                        if (lsaTargetPr != IntPtr.Zero)
-                        {
-                            UnsafeNativeMethods.LSA_UNICODE_STRING lsaTargetUnmanagedPtr =
-                                (UnsafeNativeMethods.LSA_UNICODE_STRING)Marshal.PtrToStructure(lsaTargetPr, typeof(UnsafeNativeMethods.LSA_UNICODE_STRING));
-                            if (lsaTargetUnmanagedPtr.buffer != IntPtr.Zero)
-                            {
-                                Marshal.FreeHGlobal(lsaTargetUnmanagedPtr.buffer);
-                                lsaTargetUnmanagedPtr.buffer = IntPtr.Zero;
-                            }
-                            Marshal.FreeHGlobal(lsaTargetPr);
-                        }
-                    }
-                }
+                Interop.OBJECT_ATTRIBUTES oa = default;
 
+                uint err = Interop.Advapi32.LsaOpenPolicy(
+                                    target,
+                                    ref oa,
+                                    (int)Interop.Advapi32.PolicyRights.POLICY_LOOKUP_NAMES,
+                                    out policyHandle);
                 if (err != 0)
                 {
                     GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err);
 
                     throw new PrincipalOperationException(SR.Format(
                                                                SR.AuthZErrorEnumeratingGroups,
-                                                               SafeNativeMethods.LsaNtStatusToWinError(err)));
+                                                               Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
-                Debug.Assert(pPolicyHandle != IntPtr.Zero);
+                Debug.Assert(!policyHandle.IsInvalid);
 
                 //
                 // Translate the SIDs
                 //
 
-                err = UnsafeNativeMethods.LsaLookupSids(
-                                    pPolicyHandle,
+                err = Interop.Advapi32.LsaLookupSids(
+                                    policyHandle,
                                     sidCount,
                                     pSids,
-                                    out pDomains,
-                                    out pNames);
-
-                // ignore error STATUS_SOME_NOT_MAPPED = 0x00000107 and
-                // STATUS_NONE_MAPPED = 0xC0000073
-                if (err != 0 &&
-                     err != 263 &&
-                     err != -1073741709)
+                                    out domainsHandle,
+                                    out namesHandle);
+
+                // Ignore error STATUS_SOME_NOT_MAPPED and STATUS_NONE_MAPPED
+                if (err != Interop.StatusOptions.STATUS_SUCCESS &&
+                     err != Interop.StatusOptions.STATUS_SOME_NOT_MAPPED &&
+                     err != Interop.StatusOptions.STATUS_NONE_MAPPED)
                 {
                     GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err);
 
                     throw new PrincipalOperationException(SR.Format(
                                                                SR.AuthZErrorEnumeratingGroups,
-                                                               SafeNativeMethods.LsaNtStatusToWinError(err)));
+                                                               Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
                 //
                 // Get the group names in managed form
                 //
-                names = new UnsafeNativeMethods.LSA_TRANSLATED_NAME[sidCount];
-                IntPtr pCurrentName = pNames;
-
-                for (int i = 0; i < sidCount; i++)
-                {
-                    names[i] = (UnsafeNativeMethods.LSA_TRANSLATED_NAME)
-                                    Marshal.PtrToStructure(pCurrentName, typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME));
+                namesHandle.Initialize((uint)sidCount, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
 
-                    pCurrentName = new IntPtr(pCurrentName.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME)));
-                }
+                Interop.LSA_TRANSLATED_NAME[] names = new Interop.LSA_TRANSLATED_NAME[sidCount];
+                namesHandle.ReadArray(0, names, 0, names.Length);
 
                 //
                 // Get the domain names in managed form
                 //
+                domainsHandle.InitializeReferencedDomainsList();
+                Interop.LSA_REFERENCED_DOMAIN_LIST domainList = domainsHandle.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
 
                 // Extract LSA_REFERENCED_DOMAIN_LIST.Entries
 
-                UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST referencedDomains = (UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST)Marshal.PtrToStructure(pDomains, typeof(UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST));
-
-                int domainCount = referencedDomains.entries;
+                int domainCount = domainList.Entries;
 
                 // Extract LSA_REFERENCED_DOMAIN_LIST.Domains, by iterating over the array and marshalling
                 // each native LSA_TRUST_INFORMATION into a managed LSA_TRUST_INFORMATION.
 
-                domains = new UnsafeNativeMethods.LSA_TRUST_INFORMATION[domainCount];
+                Interop.LSA_TRUST_INFORMATION[] domains = new Interop.LSA_TRUST_INFORMATION[domainCount];
 
-                IntPtr pCurrentDomain = referencedDomains.domains;
+                IntPtr pCurrentDomain = domainList.Domains;
 
                 for (int i = 0; i < domainCount; i++)
                 {
-                    domains[i] = (UnsafeNativeMethods.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION));
-                    pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION)));
+                    domains[i] = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(Interop.LSA_TRUST_INFORMATION));
+                    pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(Interop.LSA_TRUST_INFORMATION)));
                 }
 
                 GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount);
@@ -226,22 +166,22 @@ namespace System.DirectoryServices.AccountManagement
 
                 for (int i = 0; i < names.Length; i++)
                 {
-                    UnsafeNativeMethods.LSA_TRANSLATED_NAME name = names[i];
+                    Interop.LSA_TRANSLATED_NAME name = names[i];
 
                     // Build an entry.  Note that LSA_UNICODE_STRING.length is in bytes,
                     // while PtrToStringUni expects a length in characters.
                     SidListEntry entry = new SidListEntry();
 
-                    Debug.Assert(name.name.length % 2 == 0);
-                    entry.name = Marshal.PtrToStringUni(name.name.buffer, name.name.length / 2);
+                    Debug.Assert(name.Name.Length % 2 == 0);
+                    entry.name = Marshal.PtrToStringUni(name.Name.Buffer, name.Name.Length / 2);
 
                     // Get the domain associated with this name
-                    Debug.Assert(name.domainIndex < domains.Length);
-                    if (name.domainIndex >= 0)
+                    Debug.Assert(name.DomainIndex < domains.Length);
+                    if (name.DomainIndex >= 0)
                     {
-                        UnsafeNativeMethods.LSA_TRUST_INFORMATION domain = domains[name.domainIndex];
-                        Debug.Assert(domain.name.length % 2 == 0);
-                        entry.sidIssuerName = Marshal.PtrToStringUni(domain.name.buffer, domain.name.length / 2);
+                        Interop.LSA_TRUST_INFORMATION domain = domains[name.DomainIndex];
+                        Debug.Assert(domain.Name.Length % 2 == 0);
+                        entry.sidIssuerName = Marshal.PtrToStringUni(domain.Name.Buffer, domain.Name.Length / 2);
                     }
 
                     entry.pSid = pSids[i];
@@ -254,17 +194,14 @@ namespace System.DirectoryServices.AccountManagement
             }
             finally
             {
-                if (pDomains != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaFreeMemory(pDomains);
-
-                if (pNames != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaFreeMemory(pNames);
+                if (domainsHandle != null)
+                    domainsHandle.Dispose();
 
-                if (pPolicyHandle != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaClose(pPolicyHandle);
+                if (namesHandle != null)
+                    namesHandle.Dispose();
 
-                if (pOA != IntPtr.Zero)
-                    Marshal.FreeHGlobal(pOA);
+                if (policyHandle != null)
+                    policyHandle.Dispose();
             }
         }
 
index 0da4b8b..b69798a 100644 (file)
@@ -15,7 +15,7 @@ namespace System.DirectoryServices.AccountManagement
 {
     internal sealed class AuthZSet : ResultSet
     {
-        internal AuthZSet(
+        internal unsafe AuthZSet(
                     byte[] userSid,
                     NetCred credentials,
                     ContextOptions contextOptions,
@@ -52,9 +52,7 @@ namespace System.DirectoryServices.AccountManagement
 
             try
             {
-                UnsafeNativeMethods.LUID luid = default;
-                luid.low = 0;
-                luid.high = 0;
+                Interop.LUID luid = default;
 
                 _psMachineSid = new SafeMemoryPtr(Utils.GetMachineDomainSid());
                 _psUserSid = new SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid));
@@ -65,8 +63,8 @@ namespace System.DirectoryServices.AccountManagement
                 GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Initializing resource manager");
 
                 // Create a resource manager
-                f = UnsafeNativeMethods.AuthzInitializeResourceManager(
-                                            UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT,
+                f = Interop.Authz.AuthzInitializeResourceManager(
+                                            Interop.Authz.AUTHZ_RM_FLAG_NO_AUDIT,
                                             IntPtr.Zero,
                                             IntPtr.Zero,
                                             IntPtr.Zero,
@@ -79,7 +77,7 @@ namespace System.DirectoryServices.AccountManagement
                     GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting ctx from SID");
 
                     // Construct a context for the user based on the user's SID
-                    f = UnsafeNativeMethods.AuthzInitializeContextFromSid(
+                    f = Interop.Authz.AuthzInitializeContextFromSid(
                                                 0,                  // default flags
                                                 _psUserSid.DangerousGetHandle(),
                                                 pResManager,
@@ -96,7 +94,7 @@ namespace System.DirectoryServices.AccountManagement
                         GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx");
 
                         // Extract the group SIDs from the user's context.  Determine the size of the buffer we need.
-                        f = UnsafeNativeMethods.AuthzGetInformationFromContext(
+                        f = Interop.Authz.AuthzGetInformationFromContext(
                                                     pClientContext,
                                                     2,                    // AuthzContextInfoGroupsSids
                                                     0,
@@ -113,7 +111,7 @@ namespace System.DirectoryServices.AccountManagement
                             pBuffer = Marshal.AllocHGlobal(bufferSize);
 
                             // Extract the group SIDs from the user's context, into our buffer.0
-                            f = UnsafeNativeMethods.AuthzGetInformationFromContext(
+                            f = Interop.Authz.AuthzGetInformationFromContext(
                                                         pClientContext,
                                                         2,                    // AuthzContextInfoGroupsSids
                                                         bufferSize,
@@ -134,23 +132,23 @@ namespace System.DirectoryServices.AccountManagement
 
                                 // Extract TOKEN_GROUPS.GroupCount
 
-                                UnsafeNativeMethods.TOKEN_GROUPS tokenGroups = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_GROUPS));
+                                Interop.TOKEN_GROUPS tokenGroups = (Interop.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_GROUPS));
 
-                                int groupCount = tokenGroups.groupCount;
+                                uint groupCount = tokenGroups.GroupCount;
 
                                 GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Found {0} groups", groupCount);
 
                                 // Extract TOKEN_GROUPS.Groups, by iterating over the array and marshalling
                                 // each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR.
-                                UnsafeNativeMethods.SID_AND_ATTR[] groups = new UnsafeNativeMethods.SID_AND_ATTR[groupCount];
+                                Interop.SID_AND_ATTRIBUTES[] groups = new Interop.SID_AND_ATTRIBUTES[groupCount];
 
-                                IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - IntPtr.Size);
+                                IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(Interop.TOKEN_GROUPS)) - sizeof(Interop.SID_AND_ATTRIBUTES));
 
                                 for (int i = 0; i < groupCount; i++)
                                 {
-                                    groups[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(currentItem, typeof(UnsafeNativeMethods.SID_AND_ATTR));
+                                    groups[i] = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(currentItem, typeof(Interop.SID_AND_ATTRIBUTES));
 
-                                    currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR)));
+                                    currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(Interop.SID_AND_ATTRIBUTES)));
                                 }
 
                                 _groupSidList = new SidList(groups);
@@ -215,10 +213,10 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (pClientContext != IntPtr.Zero)
-                    UnsafeNativeMethods.AuthzFreeContext(pClientContext);
+                    Interop.Authz.AuthzFreeContext(pClientContext);
 
                 if (pResManager != IntPtr.Zero)
-                    UnsafeNativeMethods.AuthzFreeResourceManager(pResManager);
+                    Interop.Authz.AuthzFreeResourceManager(pResManager);
 
                 if (pBuffer != IntPtr.Zero)
                     Marshal.FreeHGlobal(pBuffer);
@@ -287,7 +285,7 @@ namespace System.DirectoryServices.AccountManagement
                     // Is the SID from the same domain as the user?
                     bool sameDomain = false;
 
-                    bool success = UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain);
+                    bool success = Interop.Advapi32.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain);
 
                     // if failed, psUserSid must not be a domain sid
                     if (!success)
@@ -334,7 +332,7 @@ namespace System.DirectoryServices.AccountManagement
                     // EqualDomainSid will return false if pSid is a BUILTIN SID, but that's okay, we treat those as domain (not local)
                     // groups for domain users.
                     bool inMachineDomain = false;
-                    if (UnsafeNativeMethods.EqualDomainSid(_psMachineSid.DangerousGetHandle(), pSid, ref inMachineDomain))
+                    if (Interop.Advapi32.EqualDomainSid(_psMachineSid.DangerousGetHandle(), pSid, ref inMachineDomain))
                         if (inMachineDomain)
                         {
                             // At this point we know that the group was issued by the local machine.  Now determine if this machine is
@@ -427,7 +425,7 @@ namespace System.DirectoryServices.AccountManagement
                     IntPtr pSid = _groupSidList[_currentGroup].pSid;
 
                     bool sameDomain = false;
-                    if (Utils.ClassifySID(pSid) == SidType.RealObject && UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain))
+                    if (Utils.ClassifySID(pSid) == SidType.RealObject && Interop.Advapi32.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain))
                     {
                         if (sameDomain)
                         {
index 8871514..fd56746 100644 (file)
@@ -28,7 +28,7 @@ namespace System.DirectoryServices.AccountManagement
         [ConditionalAttribute("DEBUG")]
         public static void WriteLineIf(bool f, string category, string message, params object[] args)
         {
-            message = "[" + SafeNativeMethods.GetCurrentThreadId().ToString("x", CultureInfo.InvariantCulture) + "] " + message;
+            message = "[" + Interop.Kernel32.GetCurrentThreadId().ToString("x", CultureInfo.InvariantCulture) + "] " + message;
 
             Debug.WriteLineIf(f, string.Format(CultureInfo.InvariantCulture, message, args), category);
         }
@@ -36,7 +36,7 @@ namespace System.DirectoryServices.AccountManagement
         [ConditionalAttribute("DEBUG")]
         public static void WriteLineIf(bool f, string category, string message)
         {
-            message = "[" + SafeNativeMethods.GetCurrentThreadId().ToString("x", CultureInfo.InvariantCulture) + "] " + message;
+            message = "[" + Interop.Kernel32.GetCurrentThreadId().ToString("x", CultureInfo.InvariantCulture) + "] " + message;
 
             Debug.WriteLineIf(f, message, category);
         }
index e208968..fa94ac1 100644 (file)
@@ -66,15 +66,15 @@ namespace System.DirectoryServices.AccountManagement
 
             // Logon user expects the username in UPN or to have the username and domain split to the separate parameters.
             // It does not work properly with NT4 style name formats.  This function will put the username in the proper format.
-            fixed (char* splitUsername = new char[UnsafeNativeMethods.CRED_MAX_USERNAME_LENGTH])
-            fixed (char* splitDomain = new char[UnsafeNativeMethods.CRED_MAX_DOMAIN_TARGET_LENGTH])
+            fixed (char* splitUsername = new char[Interop.Credui.CRED_MAX_USERNAME_LENGTH])
+            fixed (char* splitDomain = new char[Interop.Credui.CRED_MAX_DOMAIN_TARGET_LENGTH])
             {
-                int result = UnsafeNativeMethods.CredUIParseUserName(
+                int result = Interop.Credui.CredUIParseUserName(
                                                      username,
                                                      splitUsername,
-                                                     UnsafeNativeMethods.CRED_MAX_USERNAME_LENGTH,
+                                                     Interop.Credui.CRED_MAX_USERNAME_LENGTH,
                                                      splitDomain,
-                                                     UnsafeNativeMethods.CRED_MAX_DOMAIN_TARGET_LENGTH);
+                                                     Interop.Credui.CRED_MAX_DOMAIN_TARGET_LENGTH);
 
                 // If CredUiParseUsername fails then username format must have been in a format it does not expect.
                 // Just pass then entire username as the user passed it with a null domain string.
index 0b27b57..49ebb3f 100644 (file)
@@ -1052,7 +1052,7 @@ namespace System.DirectoryServices.AccountManagement
             try
             {
                 // This function takes in a flat or DNS name, and returns the flat name of the computer
-                int err = UnsafeNativeMethods.NetWkstaGetInfo(_machineUserSuppliedName, 100, ref buffer);
+                int err = Interop.Wkscli.NetWkstaGetInfo(_machineUserSuppliedName, 100, ref buffer);
                 if (err == 0)
                 {
                     UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo =
@@ -1072,7 +1072,7 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (buffer != IntPtr.Zero)
-                    UnsafeNativeMethods.NetApiBufferFree(buffer);
+                    Interop.Netutils.NetApiBufferFree(buffer);
             }
         }
 
index 8a0b28d..005f1cc 100644 (file)
@@ -354,7 +354,7 @@ namespace System.DirectoryServices.AccountManagement
                 {
                     pSid = Utils.ConvertByteArrayToIntPtr(sid);
 
-                    if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
+                    if (Interop.Advapi32.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                     {
                         GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                 "SAMStoreCtx",
@@ -419,7 +419,7 @@ namespace System.DirectoryServices.AccountManagement
                         {
                             pSid = Utils.ConvertByteArrayToIntPtr(sid);
 
-                            if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
+                            if (Interop.Advapi32.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                             {
                                 GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                         "SAMStoreCtx",
index 65d159f..d631c7a 100644 (file)
@@ -1,15 +1,13 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using System.Diagnostics;
 using System.Globalization;
 using System.Runtime.InteropServices;
 using System.Text;
-using System.Collections.Generic;
-using System.Net;
 using System.Security.Principal;
-using System.Security;
+
+using Microsoft.Win32.SafeHandles;
 
 namespace System.DirectoryServices.AccountManagement
 {
@@ -127,7 +125,7 @@ namespace System.DirectoryServices.AccountManagement
             {
                 pSid = ConvertByteArrayToIntPtr(sid);
 
-                if (UnsafeNativeMethods.ConvertSidToStringSid(pSid, ref sddlSid))
+                if (Interop.Advapi32.ConvertSidToStringSid(pSid, ref sddlSid) != Interop.BOOL.FALSE)
                 {
                     return sddlSid;
                 }
@@ -178,7 +176,7 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static byte[] ConvertNativeSidToByteArray(IntPtr pSid)
         {
-            int sidLength = UnsafeNativeMethods.GetLengthSid(pSid);
+            int sidLength = Interop.Advapi32.GetLengthSid(pSid);
             byte[] sid = new byte[sidLength];
             Marshal.Copy(pSid, sid, 0, sidLength);
 
@@ -205,15 +203,15 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static SidType ClassifySID(IntPtr pSid)
         {
-            Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid));
+            Debug.Assert(Interop.Advapi32.IsValidSid(pSid));
 
             // Get the issuing authority and the first RID
-            IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid);
+            IntPtr pIdentAuth = Interop.Advapi32.GetSidIdentifierAuthority(pSid);
 
-            UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY identAuth =
-                (UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY));
+            Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth =
+                (Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY));
 
-            IntPtr pRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, 0);
+            IntPtr pRid = Interop.Advapi32.GetSidSubAuthority(pSid, 0);
             int rid = Marshal.ReadInt32(pRid);
 
             // These bit signify that the sid was issued by ADAM.  If so then it can't be a fake sid.
@@ -244,9 +242,9 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static int GetLastRidFromSid(IntPtr pSid)
         {
-            IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid);
+            IntPtr pRidCount = Interop.Advapi32.GetSidSubAuthorityCount(pSid);
             int ridCount = Marshal.ReadByte(pRidCount);
-            IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1);
+            IntPtr pLastRid = Interop.Advapi32.GetSidSubAuthority(pSid, ridCount - 1);
             int lastRid = Marshal.ReadInt32(pLastRid);
 
             return lastRid;
@@ -313,7 +311,7 @@ namespace System.DirectoryServices.AccountManagement
 
                     // Does the user SID have the same domain as the machine SID?
                     bool sameDomain = false;
-                    bool success = UnsafeNativeMethods.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain);
+                    bool success = Interop.Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain);
 
                     // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs
                     Debug.Assert(success == true);
@@ -340,7 +338,7 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static IntPtr GetCurrentUserSid()
         {
-            IntPtr pTokenHandle = IntPtr.Zero;
+            SafeTokenHandle tokenHandle = null;
             IntPtr pBuffer = IntPtr.Zero;
 
             try
@@ -351,22 +349,22 @@ namespace System.DirectoryServices.AccountManagement
                 int error = 0;
 
                 // Get the current thread's token
-                if (!UnsafeNativeMethods.OpenThreadToken(
-                                UnsafeNativeMethods.GetCurrentThread(),
-                                0x8, // TOKEN_QUERY
+                if (!Interop.Advapi32.OpenThreadToken(
+                                Interop.Kernel32.GetCurrentThread(),
+                                TokenAccessLevels.Query,
                                 true,
-                                ref pTokenHandle
+                                out tokenHandle
                                 ))
                 {
                     if ((error = Marshal.GetLastWin32Error()) == 1008) // ERROR_NO_TOKEN
                     {
-                        Debug.Assert(pTokenHandle == IntPtr.Zero);
+                        Debug.Assert(tokenHandle.IsInvalid);
 
                         // Current thread doesn't have a token, try the process
-                        if (!UnsafeNativeMethods.OpenProcessToken(
-                                        UnsafeNativeMethods.GetCurrentProcess(),
-                                        0x8, // TOKEN_QUERY
-                                        ref pTokenHandle
+                        if (!Interop.Advapi32.OpenProcessToken(
+                                        Interop.Kernel32.GetCurrentProcess(),
+                                        (int)TokenAccessLevels.Query,
+                                        out tokenHandle
                                         ))
                         {
                             int lastError = Marshal.GetLastWin32Error();
@@ -383,18 +381,18 @@ namespace System.DirectoryServices.AccountManagement
                     }
                 }
 
-                Debug.Assert(pTokenHandle != IntPtr.Zero);
+                Debug.Assert(!tokenHandle.IsInvalid);
 
-                int neededBufferSize = 0;
+                uint neededBufferSize = 0;
 
                 // Retrieve the user info from the current thread's token
                 // First, determine how big a buffer we need.
-                bool success = UnsafeNativeMethods.GetTokenInformation(
-                                        pTokenHandle,
-                                        1,   // TokenUser
+                bool success = Interop.Advapi32.GetTokenInformation(
+                                        tokenHandle.DangerousGetHandle(),
+                                        (uint)Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
                                         IntPtr.Zero,
                                         0,
-                                        ref neededBufferSize);
+                                        out neededBufferSize);
 
                 int getTokenInfoError = 0;
                 if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER
@@ -407,15 +405,15 @@ namespace System.DirectoryServices.AccountManagement
 
                 // Allocate the necessary buffer.
                 Debug.Assert(neededBufferSize > 0);
-                pBuffer = Marshal.AllocHGlobal(neededBufferSize);
+                pBuffer = Marshal.AllocHGlobal((int)neededBufferSize);
 
                 // Load the user info into the buffer
-                success = UnsafeNativeMethods.GetTokenInformation(
-                                        pTokenHandle,
-                                        1,   // TokenUser
+                success = Interop.Advapi32.GetTokenInformation(
+                                        tokenHandle.DangerousGetHandle(),
+                                        (uint)Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
                                         pBuffer,
                                         neededBufferSize,
-                                        ref neededBufferSize);
+                                        out neededBufferSize);
 
                 if (!success)
                 {
@@ -429,15 +427,15 @@ namespace System.DirectoryServices.AccountManagement
                 }
 
                 // Retrieve the user's SID from the user info
-                UnsafeNativeMethods.TOKEN_USER tokenUser = (UnsafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_USER));
-                IntPtr pUserSid = tokenUser.sidAndAttributes.pSid;   // this is a reference into the NATIVE memory (into pBuffer)
+                Interop.TOKEN_USER tokenUser = (Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_USER));
+                IntPtr pUserSid = tokenUser.sidAndAttributes.Sid;   // this is a reference into the NATIVE memory (into pBuffer)
 
-                Debug.Assert(UnsafeNativeMethods.IsValidSid(pUserSid));
+                Debug.Assert(Interop.Advapi32.IsValidSid(pUserSid));
 
                 // Now we make a copy of the SID to return
-                int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid);
+                int userSidLength = Interop.Advapi32.GetLengthSid(pUserSid);
                 IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength);
-                success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
+                success = Interop.Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
                 if (!success)
                 {
                     int lastError = Marshal.GetLastWin32Error();
@@ -453,8 +451,8 @@ namespace System.DirectoryServices.AccountManagement
             }
             finally
             {
-                if (pTokenHandle != IntPtr.Zero)
-                    UnsafeNativeMethods.CloseHandle(pTokenHandle);
+                if (tokenHandle != null)
+                    tokenHandle.Dispose();
 
                 if (pBuffer != IntPtr.Zero)
                     Marshal.FreeHGlobal(pBuffer);
@@ -464,56 +462,52 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static IntPtr GetMachineDomainSid()
         {
-            IntPtr pPolicyHandle = IntPtr.Zero;
+            SafeLsaPolicyHandle policyHandle = null;
             IntPtr pBuffer = IntPtr.Zero;
-            IntPtr pOA = IntPtr.Zero;
 
             try
             {
-                UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES();
-
-                pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES)));
-                Marshal.StructureToPtr(oa, pOA, false);
-                int err = UnsafeNativeMethods.LsaOpenPolicy(
-                                IntPtr.Zero,
-                                pOA,
-                                1,          // POLICY_VIEW_LOCAL_INFORMATION
-                                ref pPolicyHandle);
+                Interop.OBJECT_ATTRIBUTES oa = default;
 
+                uint err = Interop.Advapi32.LsaOpenPolicy(
+                                SystemName: null,
+                                ref oa,
+                                (int)Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION,
+                                out policyHandle);
                 if (err != 0)
                 {
-                    GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaOpenPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err));
+                    GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaOpenPolicy failed, gle=" + Interop.Advapi32.LsaNtStatusToWinError(err));
 
                     throw new PrincipalOperationException(SR.Format(
                                                                SR.UnableToRetrievePolicy,
-                                                               SafeNativeMethods.LsaNtStatusToWinError(err)));
+                                                               Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
-                Debug.Assert(pPolicyHandle != IntPtr.Zero);
-                err = UnsafeNativeMethods.LsaQueryInformationPolicy(
-                                pPolicyHandle,
+                Debug.Assert(!policyHandle.IsInvalid);
+                err = Interop.Advapi32.LsaQueryInformationPolicy(
+                                policyHandle.DangerousGetHandle(),
                                 5,              // PolicyAccountDomainInformation
                                 ref pBuffer);
 
                 if (err != 0)
                 {
-                    GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaQueryInformationPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err));
+                    GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaQueryInformationPolicy failed, gle=" + Interop.Advapi32.LsaNtStatusToWinError(err));
 
                     throw new PrincipalOperationException(SR.Format(
                                                                SR.UnableToRetrievePolicy,
-                                                               SafeNativeMethods.LsaNtStatusToWinError(err)));
+                                                               Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
                 Debug.Assert(pBuffer != IntPtr.Zero);
                 UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)
                                     Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO));
 
-                Debug.Assert(UnsafeNativeMethods.IsValidSid(info.domainSid));
+                Debug.Assert(Interop.Advapi32.IsValidSid(info.domainSid));
 
                 // Now we make a copy of the SID to return
-                int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid);
+                int sidLength = Interop.Advapi32.GetLengthSid(info.domainSid);
                 IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength);
-                bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid);
+                bool success = Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.domainSid);
                 if (!success)
                 {
                     int lastError = Marshal.GetLastWin32Error();
@@ -529,14 +523,11 @@ namespace System.DirectoryServices.AccountManagement
             }
             finally
             {
-                if (pPolicyHandle != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaClose(pPolicyHandle);
+                if (policyHandle != null)
+                    policyHandle.Dispose();
 
                 if (pBuffer != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaFreeMemory(pBuffer);
-
-                if (pOA != IntPtr.Zero)
-                    Marshal.FreeHGlobal(pOA);
+                    Interop.Advapi32.LsaFreeMemory(pBuffer);
             }
         }
 
@@ -570,7 +561,7 @@ namespace System.DirectoryServices.AccountManagement
 
             try
             {
-                int err = UnsafeNativeMethods.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, flags, out domainControllerInfoPtr);
+                int err = Interop.Logoncli.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, flags, out domainControllerInfoPtr);
 
                 if (err != 0)
                 {
@@ -590,7 +581,7 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (domainControllerInfoPtr != IntPtr.Zero)
-                    UnsafeNativeMethods.NetApiBufferFree(domainControllerInfoPtr);
+                    Interop.Netutils.NetApiBufferFree(domainControllerInfoPtr);
             }
         }
 
@@ -754,7 +745,7 @@ namespace System.DirectoryServices.AccountManagement
 
             GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: trying to impersonate " + userName);
 
-            int result = UnsafeNativeMethods.LogonUser(
+            int result = Interop.Advapi32.LogonUser(
                                             userName,
                                             domainName,
                                             password,
@@ -771,14 +762,14 @@ namespace System.DirectoryServices.AccountManagement
                     SR.Format(SR.UnableToImpersonateCredentials, lastError));
             }
 
-            result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken);
+            result = Interop.Advapi32.ImpersonateLoggedOnUser(hToken);
             if (result == 0)
             {
                 int lastError = Marshal.GetLastWin32Error();
                 GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: ImpersonateLoggedOnUser failed, gle=" + lastError);
 
                 // Close the token the was created above....
-                UnsafeNativeMethods.CloseHandle(hToken);
+                Interop.Kernel32.CloseHandle(hToken);
 
                 throw new PrincipalOperationException(
                     SR.Format(SR.UnableToImpersonateCredentials, lastError));
@@ -792,8 +783,8 @@ namespace System.DirectoryServices.AccountManagement
         {
             GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "Entering EndImpersonation");
 
-            UnsafeNativeMethods.RevertToSelf();
-            UnsafeNativeMethods.CloseHandle(hUserToken);
+            Interop.Advapi32.RevertToSelf();
+            Interop.Kernel32.CloseHandle(hUserToken);
         }
 
         internal static bool IsMachineDC(string computerName)
@@ -803,10 +794,7 @@ namespace System.DirectoryServices.AccountManagement
 
             try
             {
-                if (null == computerName)
-                    err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(null, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr);
-                else
-                    err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(computerName, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr);
+                err = Interop.Dsrole.DsRoleGetPrimaryDomainInformation(computerName, Interop.Dsrole.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr);
 
                 if (err != 0)
                 {
@@ -826,7 +814,7 @@ namespace System.DirectoryServices.AccountManagement
             finally
             {
                 if (dsRoleInfoPtr != IntPtr.Zero)
-                    UnsafeNativeMethods.DsRoleFreeMemory(dsRoleInfoPtr);
+                    Interop.Dsrole.DsRoleFreeMemory(dsRoleInfoPtr);
             }
         }
     }
index e8fbd22..d87879d 100644 (file)
@@ -11,8 +11,6 @@ namespace System.DirectoryServices.AccountManagement
 {
     using System.Runtime.InteropServices;
     using System;
-    using System.Security;
-    using System.Text;
 
     internal static class Constants
     {
@@ -21,24 +19,13 @@ namespace System.DirectoryServices.AccountManagement
         internal static byte[] GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = new byte[] { 0x22, 0xb7, 0x0c, 0x67, 0xd5, 0x6e, 0x4e, 0xfb, 0x91, 0xe9, 0x30, 0x0f, 0xca, 0x3d, 0xc1, 0xaa };
     }
 
-    internal static class SafeNativeMethods
-    {
-        [DllImport(Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThreadId", CharSet = CharSet.Unicode)]
-        public static extern int GetCurrentThreadId();
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
-        public static extern int LsaNtStatusToWinError(int ntStatus);
-    }
-
     internal static class UnsafeNativeMethods
     {
-        [DllImport(Interop.Libraries.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
-        private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
         public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
         {
             try
             {
-                return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
+                return Interop.Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
             }
             catch (EntryPointNotFoundException)
             {
@@ -382,24 +369,6 @@ namespace System.DirectoryServices.AccountManagement
         }
 
         /*
-        typedef enum
-        {
-          DsRolePrimaryDomainInfoBasic,
-          DsRoleUpgradeStatus,
-          DsRoleOperationState,
-          DsRolePrimaryDomainInfoBasicEx
-        }DSROLE_PRIMARY_DOMAIN_INFO_LEVEL;
-        */
-
-        public enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL
-        {
-            DsRolePrimaryDomainInfoBasic = 1,
-            DsRoleUpgradeStatus = 2,
-            DsRoleOperationState = 3,
-            DsRolePrimaryDomainInfoBasicEx = 4
-        }
-
-        /*
          typedef struct _DSROLE_PRIMARY_DOMAIN_INFO_BASIC {
          DSROLE_MACHINE_ROLE MachineRole;
          ULONG Flags;
@@ -424,19 +393,6 @@ namespace System.DirectoryServices.AccountManagement
             public Guid DomainGuid;
         }
 
-        /*
-        DWORD DsRoleGetPrimaryDomainInformation(
-          LPCWSTR lpServer,
-          DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
-          PBYTE* Buffer
-        ); */
-
-        [DllImport(Interop.Libraries.Dsrole, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
-        public static extern int DsRoleGetPrimaryDomainInformation(
-            [MarshalAs(UnmanagedType.LPTStr)] string lpServer,
-            [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
-            out IntPtr Buffer);
-
         /*typedef struct _DOMAIN_CONTROLLER_INFO {
             LPTSTR DomainControllerName;
             LPTSTR DomainControllerAddress;
@@ -462,32 +418,6 @@ namespace System.DirectoryServices.AccountManagement
             public string ClientSiteName;
         }
 
-        /*
-        void DsRoleFreeMemory(
-          PVOID Buffer
-        );
-        */
-        [DllImport(Interop.Libraries.Dsrole)]
-        public static extern int DsRoleFreeMemory(
-            [In] IntPtr buffer);
-
-        /*DWORD DsGetDcName(
-            LPCTSTR ComputerName,
-            LPCTSTR DomainName,
-            GUID* DomainGuid,
-            LPCTSTR SiteName,
-            ULONG Flags,
-            PDOMAIN_CONTROLLER_INFO* DomainControllerInfo
-        );*/
-        [DllImport(Interop.Libraries.Logoncli, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
-        public static extern int DsGetDcName(
-            [In] string computerName,
-            [In] string domainName,
-            [In] IntPtr domainGuid,
-            [In] string siteName,
-            [In] int flags,
-            [Out] out IntPtr domainControllerInfo);
-
         /* typedef struct _WKSTA_INFO_100 {
                 DWORD wki100_platform_id;
                 LMSTR wki100_computername;
@@ -505,314 +435,11 @@ namespace System.DirectoryServices.AccountManagement
             public int wki100_ver_minor;
         };
 
-        [DllImport(Interop.Libraries.Wkscli, CallingConvention = CallingConvention.StdCall, EntryPoint = "NetWkstaGetInfo", CharSet = CharSet.Unicode)]
-        public static extern int NetWkstaGetInfo(string server, int level, ref IntPtr buffer);
-
-        [DllImport(Interop.Libraries.Netutils)]
-        public static extern int NetApiBufferFree(
-            [In] IntPtr buffer);
-
-        //
-        // SID
-        //
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode)]
-        public static extern bool ConvertSidToStringSid(IntPtr sid, ref string stringSid);
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode)]
-        public static extern bool ConvertStringSidToSid(string stringSid, ref IntPtr sid);
-
-        [DllImport(Interop.Libraries.Advapi32)]
-        public static extern int GetLengthSid(IntPtr sid);
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true)]
-        public static extern bool IsValidSid(IntPtr sid);
-
-        [DllImport(Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid);
-
-        [DllImport(Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index);
-
-        [DllImport(Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
-
-        [DllImport(Interop.Libraries.Advapi32)]
-        public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true)]
-        public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
-
-        [DllImport(Interop.Libraries.Kernel32)]
-        public static extern IntPtr LocalFree(IntPtr ptr);
-
-        [DllImport(Interop.Libraries.Credui, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode)]
-        public static extern unsafe int CredUIParseUserName(
-            string pszUserName,
-            char* pszUser,
-            uint ulUserMaxChars,
-            char* pszDomain,
-            uint ulDomainMaxChars);
-
-        // These contants were taken from the wincred.h file
-        public const int CRED_MAX_USERNAME_LENGTH = 514;
-        public const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338;
-
-        //
-        // AuthZ functions
-        //
-
-        internal sealed class AUTHZ_RM_FLAG
-        {
-            private AUTHZ_RM_FLAG() { }
-            public static int AUTHZ_RM_FLAG_NO_AUDIT = 0x1;
-            public static int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2;
-            public static int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION);
-        }
-
-        [DllImport(Interop.Libraries.Authz, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)]
-        public static extern bool AuthzInitializeResourceManager(
-                                        int flags,
-                                        IntPtr pfnAccessCheck,
-                                        IntPtr pfnComputeDynamicGroups,
-                                        IntPtr pfnFreeDynamicGroups,
-                                        string name,
-                                        out IntPtr rm
-                                        );
-
-        /*
-        BOOL WINAPI AuthzInitializeContextFromSid(
-            DWORD Flags,
-            PSID UserSid,
-            AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResourceManager,
-            PLARGE_INTEGER pExpirationTime,
-            LUID Identifier,
-            PVOID DynamicGroupArgs,
-            PAUTHZ_CLIENT_CONTEXT_HANDLE pAuthzClientContext
-        );
-        */
-        [DllImport(Interop.Libraries.Authz, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)]
-        public static extern bool AuthzInitializeContextFromSid(
-                                        int Flags,
-                                        IntPtr UserSid,
-                                        IntPtr AuthzResourceManager,
-                                        IntPtr pExpirationTime,
-                                        LUID Identitifier,
-                                        IntPtr DynamicGroupArgs,
-                                        out IntPtr pAuthzClientContext
-                                        );
-
-        /*
-                [DllImport(Interop.Libraries.Authz, SetLastError=true, CallingConvention=CallingConvention.StdCall, EntryPoint="AuthzInitializeContextFromToken", CharSet=CharSet.Unicode)]
-                static extern public bool AuthzInitializeContextFromToken(
-                                                int Flags,
-                                                IntPtr TokenHandle,
-                                                IntPtr AuthzResourceManager,
-                                                IntPtr pExpirationTime,
-                                                LUID Identitifier,
-                                                IntPtr DynamicGroupArgs,
-                                                out IntPtr pAuthzClientContext
-                                                );
-        */
-        [DllImport(Interop.Libraries.Authz, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzGetInformationFromContext", CharSet = CharSet.Unicode)]
-        public static extern bool AuthzGetInformationFromContext(
-                                        IntPtr hAuthzClientContext,
-                                        int InfoClass,
-                                        int BufferSize,
-                                        out int pSizeRequired,
-                                        IntPtr Buffer
-                                        );
-
-        [DllImport(Interop.Libraries.Authz, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)]
-        public static extern bool AuthzFreeContext(
-                                        IntPtr AuthzClientContext
-                                        );
-
-        [DllImport(Interop.Libraries.Authz, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)]
-        public static extern bool AuthzFreeResourceManager(
-                                        IntPtr rm
-                                        );
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public struct LUID
-        {
-            public int low;
-            public int high;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class TOKEN_GROUPS
-        {
-            public int groupCount;
-            public IntPtr groups = IntPtr.Zero;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class SID_AND_ATTR
-        {
-            public IntPtr pSid = IntPtr.Zero;
-            public int attrs;
-        }
-
-        //
-        // Token
-        //
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class TOKEN_USER
-        {
-            public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR();
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class SID_IDENTIFIER_AUTHORITY
-        {
-            public byte b1;
-            public byte b2;
-            public byte b3;
-            public byte b4;
-            public byte b5;
-            public byte b6;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_OBJECT_ATTRIBUTES
-        {
-            public int length;
-            public IntPtr rootDirectory = IntPtr.Zero;
-            public IntPtr objectName = IntPtr.Zero;
-            public int attributes;
-            public IntPtr securityDescriptor = IntPtr.Zero;
-            public IntPtr securityQualityOfService = IntPtr.Zero;
-        }
-
         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
         public sealed class POLICY_ACCOUNT_DOMAIN_INFO
         {
-            public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
+            public Interop.UNICODE_INTPTR_STRING domainName;
             public IntPtr domainSid = IntPtr.Zero;
         }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_UNICODE_STRING
-        {
-            public ushort length;
-            public ushort maximumLength;
-            public IntPtr buffer = IntPtr.Zero;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_UNICODE_STRING_Managed
-        {
-            public ushort length;
-            public ushort maximumLength;
-            public string buffer;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_TRANSLATED_NAME
-        {
-            public int use;
-            public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
-            public int domainIndex;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_REFERENCED_DOMAIN_LIST
-        {
-            // To stop the compiler from autogenerating a constructor for this class
-            private LSA_REFERENCED_DOMAIN_LIST() { }
-
-            public int entries;
-            public IntPtr domains = IntPtr.Zero;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class LSA_TRUST_INFORMATION
-        {
-            public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
-            private readonly IntPtr _pSid = IntPtr.Zero;
-        }
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)]
-        public static extern bool OpenThreadToken(
-                                        IntPtr threadHandle,
-                                        int desiredAccess,
-                                        bool openAsSelf,
-                                        ref IntPtr tokenHandle
-                                        );
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)]
-        public static extern bool OpenProcessToken(
-                                        IntPtr processHandle,
-                                        int desiredAccess,
-                                        ref IntPtr tokenHandle
-                                        );
-
-        [DllImport(Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)]
-        public static extern bool CloseHandle(IntPtr handle);
-
-        [DllImport(Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)]
-        public static extern IntPtr GetCurrentThread();
-
-        [DllImport(Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)]
-        public static extern IntPtr GetCurrentProcess();
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)]
-        public static extern bool GetTokenInformation(
-                                        IntPtr tokenHandle,
-                                        int tokenInformationClass,
-                                        IntPtr buffer,
-                                        int bufferSize,
-                                        ref int returnLength
-                                        );
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)]
-        public static extern int LsaOpenPolicy(
-                                        IntPtr lsaUnicodeString,
-                                        IntPtr lsaObjectAttributes,
-                                        int desiredAccess,
-                                        ref IntPtr policyHandle);
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)]
-        public static extern int LsaQueryInformationPolicy(
-                                        IntPtr policyHandle,
-                                        int policyInformationClass,
-                                        ref IntPtr buffer
-                                        );
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)]
-        public static extern int LsaLookupSids(
-                                        IntPtr policyHandle,
-                                        int count,
-                                        IntPtr[] sids,
-                                        out IntPtr referencedDomains,
-                                        out IntPtr names
-                                        );
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaFreeMemory", CharSet = CharSet.Unicode)]
-        public static extern int LsaFreeMemory(IntPtr buffer);
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaClose", CharSet = CharSet.Unicode)]
-        public static extern int LsaClose(IntPtr policyHandle);
-
-        //
-        // Impersonation
-        //
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode)]
-        public static extern int LogonUser(
-                                    string lpszUsername,
-                                    string lpszDomain,
-                                    string lpszPassword,
-                                    int dwLogonType,
-                                    int dwLogonProvider,
-                                    ref IntPtr phToken);
-
-        [DllImport(Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ImpersonateLoggedOnUser", CharSet = CharSet.Unicode)]
-        public static extern int ImpersonateLoggedOnUser(IntPtr hToken);
-
-        [DllImport(Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "RevertToSelf", CharSet = CharSet.Unicode)]
-        public static extern int RevertToSelf();
     }
 }
index 7217065..831490d 100644 (file)
@@ -26,6 +26,8 @@
     <Compile Include="System\Security\Principal\WindowsPrincipal.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
              Link="Common\Interop\Windows\Interop.Libraries.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.BOOL.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOLEAN.cs"
              Link="Common\Interop\Windows\Advapi32\Interop.BOOLEAN.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs"
@@ -56,6 +58,8 @@
              Link="Common\Interop\Interop.OpenProcessToken.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation.cs"
              Link="Common\Interop\Interop.GetTokenInformation.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation_SafeLocalAllocHandle.cs"
+             Link="Common\Interop\Interop.GetTokenInformation_SafeLocalAllocHandle.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.DuplicateTokenEx.cs"
              Link="Common\Interop\Interop.DuplicateTokenEx.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.DuplicateHandle_SafeAccessTokenHandle.cs"
index 345e54f..82475e9 100644 (file)
@@ -273,7 +273,7 @@ namespace System.Security.Principal
                 // Open LSA policy (for lookup requires it)
                 //
 
-                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
+                LsaHandle = Win32.LsaOpenPolicy(null, Interop.Advapi32.PolicyRights.POLICY_LOOKUP_NAMES);
 
                 //
                 // Now perform the actual lookup
@@ -324,7 +324,7 @@ namespace System.Security.Principal
                 if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                 {
                     SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_SID2>());
-                    Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
+                    ReferencedDomainsPtr.InitializeReferencedDomainsList();
                     Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                     SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);
 
index 025e1c8..99b71b2 100644 (file)
@@ -1001,7 +1001,7 @@ namespace System.Security.Principal
                 // Open LSA policy (for lookup requires it)
                 //
 
-                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
+                LsaHandle = Win32.LsaOpenPolicy(null, Interop.Advapi32.PolicyRights.POLICY_LOOKUP_NAMES);
 
                 //
                 // Perform the actual lookup
@@ -1040,7 +1040,7 @@ namespace System.Security.Principal
 
 
                 NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
-                Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
+                ReferencedDomainsPtr.InitializeReferencedDomainsList();
 
                 //
                 // Interpret the results and generate NTAccount objects
index a4302d9..af9e86c 100644 (file)
@@ -8,24 +8,6 @@ using System.Runtime.InteropServices;
 
 namespace System.Security.Principal
 {
-    [Flags]
-    internal enum PolicyRights
-    {
-        POLICY_VIEW_LOCAL_INFORMATION = 0x00000001,
-        POLICY_VIEW_AUDIT_INFORMATION = 0x00000002,
-        POLICY_GET_PRIVATE_INFORMATION = 0x00000004,
-        POLICY_TRUST_ADMIN = 0x00000008,
-        POLICY_CREATE_ACCOUNT = 0x00000010,
-        POLICY_CREATE_SECRET = 0x00000020,
-        POLICY_CREATE_PRIVILEGE = 0x00000040,
-        POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080,
-        POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100,
-        POLICY_AUDIT_LOG_ADMIN = 0x00000200,
-        POLICY_SERVER_ADMIN = 0x00000400,
-        POLICY_LOOKUP_NAMES = 0x00000800,
-        POLICY_NOTIFICATION = 0x00001000,
-    }
-
     internal static class Win32
     {
         internal const int FALSE = 0;
@@ -37,7 +19,7 @@ namespace System.Security.Principal
 
         internal static SafeLsaPolicyHandle LsaOpenPolicy(
             string? systemName,
-            PolicyRights rights)
+            Interop.Advapi32.PolicyRights rights)
         {
 
             Interop.OBJECT_ATTRIBUTES attributes = default;
@@ -122,7 +104,7 @@ namespace System.Security.Principal
 
             try
             {
-                if (FALSE == Interop.Advapi32.ConvertStringSidToSid(stringSid, out ByteArray))
+                if (Interop.BOOL.FALSE == Interop.Advapi32.ConvertStringSidToSid(stringSid, out ByteArray))
                 {
                     ErrorCode = Marshal.GetLastWin32Error();
                     goto Error;
@@ -205,48 +187,6 @@ namespace System.Security.Principal
             }
         }
 
-        /// <summary>
-        ///     Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST
-        /// </summary>
-
-        internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains)
-        {
-            Debug.Assert(referencedDomains != null, "referencedDomains != null");
-
-            // We don't know the real size of the referenced domains yet, so we need to set an initial
-            // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of
-            // the domains.
-            referencedDomains!.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>());
-            Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
-
-            unsafe
-            {
-                byte* pRdl = null;
-                try
-                {
-                    referencedDomains.AcquirePointer(ref pRdl);
-
-                    // If there is a trust information list, then the buffer size is the end of that list minus
-                    // the beginning of the domain list. Otherwise, then the buffer is just the size of the
-                    // referenced domain list structure, which is what we defaulted to.
-                    if (domainList.Domains != IntPtr.Zero)
-                    {
-                        Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains;
-                        pTrustInformation = pTrustInformation + domainList.Entries;
-
-                        long bufferSize = (byte*)pTrustInformation - pRdl;
-                        Debug.Assert(bufferSize > 0, "bufferSize > 0");
-                        referencedDomains.Initialize((ulong)bufferSize);
-                    }
-                }
-                finally
-                {
-                    if (pRdl != null)
-                        referencedDomains.ReleasePointer();
-                }
-            }
-        }
-
         //
         // Wrapper around avdapi32.GetWindowsAccountDomainSid
         //