From ec7b11d4646e63e7588f18954c20c3af1c221921 Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Mon, 22 Nov 2021 09:23:34 -0700 Subject: [PATCH] Make System.DirectoryServices.AccountManagement use GeneratedDllImport (#61805) --- .../Windows/Activeds/Interop.ADsOpenObject.cs | 14 + .../Advapi32/Interop.ConvertSidToStringSid.cs | 14 + .../Advapi32/Interop.ConvertStringSidToSid.cs | 2 +- .../Windows/Advapi32/Interop.CopySid.cs | 14 + .../Advapi32/Interop.EqualDomainSid.cs | 14 + .../Windows/Advapi32/Interop.GetLengthSid.cs | 14 + .../Interop.GetSidIdentifierAuthority.cs | 31 ++ .../Advapi32/Interop.GetTokenInformation.cs | 16 - ...etTokenInformation_SafeLocalAllocHandle.cs | 28 ++ .../Interop.ImpersonateLoggedOnUser_IntPtr.cs | 14 + .../Windows/Advapi32/Interop.IsValidSid.cs | 14 + .../Windows/Advapi32/Interop.LogonUser.cs | 20 + .../Advapi32/Interop.LookupAccountSid.cs | 4 +- .../Windows/Advapi32/Interop.LsaLookupSids.cs | 36 ++ .../Windows/Advapi32/Interop.LsaOpenPolicy.cs | 18 + .../Interop.LsaQueryInformationPolicy.cs | 17 + .../Interop.AuthzGetInformationFromContext.cs | 19 + .../Interop.AuthzInitializeContextFromSid.cs | 28 ++ .../Interop.AuthzInitializeResourceManager.cs | 23 ++ .../Credui/Interop.CredUIParseUserName.cs | 23 ++ .../Dsrole/Interop.DsRoleFreeMemory.cs | 14 + ...terop.DsRoleGetPrimaryDomainInformation.cs | 25 ++ .../Windows/Kernel32/Interop.CloseHandle.cs | 6 +- .../Windows/Logoncli/Interop.DsGetDcName.cs | 20 + .../Netutils/Interop.NetApiBufferFree.cs | 14 + .../Interop/Windows/SspiCli/Interop.TOKENS.cs | 6 + .../Windows/Wkscli/Interop.NetWkstaGetInfo.cs | 14 + ...DirectoryServices.AccountManagement.csproj | 100 ++++- .../AccountManagement/AD/ADStoreCtx.cs | 4 +- .../AD/ADStoreCtx_LoadStore.cs | 4 +- .../AccountManagement/AD/ADStoreCtx_Query.cs | 4 +- .../AccountManagement/AD/SidList.cs | 161 +++----- .../AccountManagement/AuthZSet.cs | 38 +- .../AccountManagement/GlobalDebug.cs | 4 +- .../AccountManagement/NetCred.cs | 10 +- .../AccountManagement/SAM/SAMStoreCtx.cs | 4 +- .../SAM/SAMStoreCtx_LoadStore.cs | 4 +- .../AccountManagement/Utils.cs | 150 ++++--- .../AccountManagement/interopt.cs | 377 +----------------- .../System.Security.Principal.Windows.csproj | 4 + .../System/Security/Principal/NTAccount.cs | 4 +- .../src/System/Security/Principal/SID.cs | 4 +- .../src/System/Security/Principal/Win32.cs | 64 +-- 43 files changed, 703 insertions(+), 695 deletions(-) create mode 100644 src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CopySid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EqualDomainSid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetLengthSid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetSidIdentifierAuthority.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation_SafeLocalAllocHandle.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ImpersonateLoggedOnUser_IntPtr.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaQueryInformationPolicy.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzGetInformationFromContext.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeContextFromSid.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeResourceManager.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Credui/Interop.CredUIParseUserName.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleFreeMemory.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleGetPrimaryDomainInformation.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Logoncli/Interop.DsGetDcName.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Netutils/Interop.NetApiBufferFree.cs create mode 100644 src/libraries/Common/src/Interop/Windows/Wkscli/Interop.NetWkstaGetInfo.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 index 0000000000000..2ed72a63ca58c --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs @@ -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 index 0000000000000..998f854acfd99 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs @@ -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); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSidToSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSidToSid.cs index 492f2d1b763ac..9b9ef01ffcde1 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSidToSid.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSidToSid.cs @@ -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 index 0000000000000..ba978bad6aafb --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CopySid.cs @@ -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 index 0000000000000..2f20584c06849 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EqualDomainSid.cs @@ -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 index 0000000000000..0f97e3842fa7a --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetLengthSid.cs @@ -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 index 0000000000000..a2843215f4de3 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetSidIdentifierAuthority.cs @@ -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); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation.cs index 22ee2407525e2..df3e8f84c58a0 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation.cs @@ -9,22 +9,6 @@ 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); - [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)] internal static partial bool GetTokenInformation( IntPtr TokenHandle, 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 index 0000000000000..57f5422e699b3 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetTokenInformation_SafeLocalAllocHandle.cs @@ -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 index 0000000000000..808294866c707 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ImpersonateLoggedOnUser_IntPtr.cs @@ -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 index 0000000000000..448b68467316f --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs @@ -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 index 0000000000000..7e1155d45ff3e --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs @@ -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); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LookupAccountSid.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LookupAccountSid.cs index 742ba2d25df2c..bf058fb4a774e 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LookupAccountSid.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LookupAccountSid.cs @@ -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, diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaLookupSids.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaLookupSids.cs index 7f935cce14502..2ed2561cffa10 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaLookupSids.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaLookupSids.cs @@ -19,3 +19,39 @@ out SafeLsaMemoryHandle names ); } } + +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 domainList = referencedDomains.Read(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(); + } + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaOpenPolicy.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaOpenPolicy.cs index 879b6d07af1df..861d07ef36e3f 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaOpenPolicy.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaOpenPolicy.cs @@ -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 index 0000000000000..d38ac1c15d363 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaQueryInformationPolicy.cs @@ -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 index 0000000000000..9dc0b02d0b057 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzGetInformationFromContext.cs @@ -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 index 0000000000000..ae70cba32486a --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeContextFromSid.cs @@ -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 index 0000000000000..12a7f808730d2 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Authz/Interop.AuthzInitializeResourceManager.cs @@ -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 index 0000000000000..53ff59eb99bf2 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Credui/Interop.CredUIParseUserName.cs @@ -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 index 0000000000000..45c8e537e66af --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleFreeMemory.cs @@ -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 index 0000000000000..97bff61ca10a2 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Dsrole/Interop.DsRoleGetPrimaryDomainInformation.cs @@ -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); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CloseHandle.cs index 0e4280b39dbf4..1fbd9b7dcbb17 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CloseHandle.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CloseHandle.cs @@ -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 index 0000000000000..37f86adecd38b --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Logoncli/Interop.DsGetDcName.cs @@ -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 index 0000000000000..1f84f9a949b07 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Netutils/Interop.NetApiBufferFree.cs @@ -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); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.TOKENS.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.TOKENS.cs index 00a32bfb5ef03..344c9a73aa749 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.TOKENS.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.TOKENS.cs @@ -47,4 +47,10 @@ internal struct TOKEN_STATISTICS 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 index 0000000000000..bfc103965943e --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Wkscli/Interop.NetWkstaGetInfo.cs @@ -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); + } +} diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj index 7bcd2a56a94d6..0c0804cfc6f10 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj @@ -1,9 +1,13 @@ - + true true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0 $(NoWarn);CA2249 + + $(NoWarn);CA1845;CA1846 annotations true true @@ -87,10 +91,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -103,10 +199,12 @@ + + diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index 4fdd2e20da927..a7e18fa436016 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -1570,7 +1570,7 @@ private string GetGroupDnFromGroupID(byte[] userSid, int primaryGroupId) 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 @@ private string GetGroupDnFromGroupID(byte[] userSid, int primaryGroupId) finally { if (pGroupSid != IntPtr.Zero) - UnsafeNativeMethods.LocalFree(pGroupSid); + Interop.Kernel32.LocalFree(pGroupSid); } if (groupSid != null) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs index 371f8857d27fa..709ccb1601f73 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs @@ -528,7 +528,7 @@ private Principal FindPrincipalByIdentRefHelper( { 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 @@ private Principal FindPrincipalByIdentRefHelper( { 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", diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs index 66e8d5238f27b..fd46f4646e54d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs @@ -597,7 +597,7 @@ protected static bool SecurityIdentityClaimConverterHelper(string urnValue, bool 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 @@ protected static bool SecurityIdentityClaimConverterHelper(string urnValue, bool finally { if (IntPtr.Zero != pBytePtr) - UnsafeNativeMethods.LocalFree(pBytePtr); + Interop.Kernel32.LocalFree(pBytePtr); } StringBuilder stringizedBinarySid = new StringBuilder(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs index a06b3ac12c489..7ecdd63111724 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs @@ -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 @@ internal SidList(List sidListByteFormat, string target, NetCred credenti } } - 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 @@ internal SidList(UnsafeNativeMethods.SID_AND_ATTR[] sidAndAttr) for (int i = 0; i < sidCount; i++) { - pSids[i] = sidAndAttr[i].pSid; + pSids[i] = sidAndAttr[i].Sid; } TranslateSids(null, pSids); @@ -80,141 +77,84 @@ private void TranslateSids(string target, IntPtr[] pSids) 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()); - 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(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 @@ private void TranslateSids(string target, IntPtr[] pSids) 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 @@ private void TranslateSids(string target, IntPtr[] pSids) } 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(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs index 0da4b8b78c542..b69798ae0b6d7 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs @@ -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 @@ internal AuthZSet( 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 @@ internal AuthZSet( 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 @@ out pResManager 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 @@ out pClientContext 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 @@ out pClientContext 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 @@ out pClientContext // 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 @@ out pClientContext 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 @@ internal override object CurrentAsPrincipal // 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 @@ internal override object CurrentAsPrincipal // 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 @@ internal override bool MoveNext() 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) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/GlobalDebug.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/GlobalDebug.cs index 88715147962ca..fd56746418491 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/GlobalDebug.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/GlobalDebug.cs @@ -28,7 +28,7 @@ internal static class GlobalDebug [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 @@ public static void WriteLineIf(bool f, string category, string message, params o [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); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs index e208968250bb7..fa94ac132601e 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/NetCred.cs @@ -66,15 +66,15 @@ private unsafe void SplitUsername(string username, ref string parsedUserName, re // 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. diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 0b27b57d953c0..49ebb3f661805 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -1052,7 +1052,7 @@ private void LoadComputerInfo() 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 @@ private void LoadComputerInfo() finally { if (buffer != IntPtr.Zero) - UnsafeNativeMethods.NetApiBufferFree(buffer); + Interop.Netutils.NetApiBufferFree(buffer); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs index 8a0b28db9da18..005f1ccdd374f 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs @@ -354,7 +354,7 @@ internal override Principal FindPrincipalByIdentRef( { 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 @@ internal override Principal FindPrincipalByIdentRef( { 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", diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs index 65d159fd6c5f8..d631c7a5d6198 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs @@ -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 @@ internal static string ConvertSidToSDDL(byte[] sid) { 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 @@ internal static IntPtr ConvertByteArrayToIntPtr(byte[] bytes) 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 @@ internal static SidType ClassifySID(byte[] sid) 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 @@ internal static SidType ClassifySID(IntPtr pSid) 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 @@ internal static bool IsSamUser() // 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 @@ internal static bool IsSamUser() internal static IntPtr GetCurrentUserSid() { - IntPtr pTokenHandle = IntPtr.Zero; + SafeTokenHandle tokenHandle = null; IntPtr pBuffer = IntPtr.Zero; try @@ -351,22 +349,22 @@ internal static IntPtr GetCurrentUserSid() 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 @@ ref pTokenHandle } } - 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 @@ ref pTokenHandle // 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 @@ ref pTokenHandle } // 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 @@ ref pTokenHandle } finally { - if (pTokenHandle != IntPtr.Zero) - UnsafeNativeMethods.CloseHandle(pTokenHandle); + if (tokenHandle != null) + tokenHandle.Dispose(); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); @@ -464,56 +462,52 @@ ref pTokenHandle 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 @@ internal static IntPtr GetMachineDomainSid() } 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 @@ internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string comput 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 @@ internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string comput finally { if (domainControllerInfoPtr != IntPtr.Zero) - UnsafeNativeMethods.NetApiBufferFree(domainControllerInfoPtr); + Interop.Netutils.NetApiBufferFree(domainControllerInfoPtr); } } @@ -754,7 +745,7 @@ internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToke 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 @@ internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToke 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 @@ internal static void EndImpersonation(IntPtr hUserToken) { 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 @@ internal static bool IsMachineDC(string computerName) 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 @@ internal static bool IsMachineDC(string computerName) finally { if (dsRoleInfoPtr != IntPtr.Zero) - UnsafeNativeMethods.DsRoleFreeMemory(dsRoleInfoPtr); + Interop.Dsrole.DsRoleFreeMemory(dsRoleInfoPtr); } } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs index e8fbd223fd243..d87879d8608d8 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs @@ -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 @@ internal static class Constants 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) { @@ -381,24 +368,6 @@ public enum DSROLE_MACHINE_ROLE DsRole_MemberServerWithSharedAccountDomain } - /* - 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; @@ -424,19 +393,6 @@ public sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC 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 @@ public sealed class DomainControllerInfo 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 @@ public sealed class WKSTA_INFO_100 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(); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj b/src/libraries/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj index 7217065c078e5..831490db6c497 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj +++ b/src/libraries/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj @@ -26,6 +26,8 @@ + + ()); - Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); + ReferencedDomainsPtr.InitializeReferencedDomainsList(); Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count]; SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length); diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs index 025e1c8ef1c7b..99b71b2df3118 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs @@ -1001,7 +1001,7 @@ private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferen // 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 @@ private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferen NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf()); - Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); + ReferencedDomainsPtr.InitializeReferencedDomainsList(); // // Interpret the results and generate NTAccount objects diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs index a4302d97b6a73..af9e86c008036 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs @@ -8,24 +8,6 @@ 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 @@ internal static class Win32 internal static SafeLsaPolicyHandle LsaOpenPolicy( string? systemName, - PolicyRights rights) + Interop.Advapi32.PolicyRights rights) { Interop.OBJECT_ATTRIBUTES attributes = default; @@ -122,7 +104,7 @@ out byte[]? resultSid 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 @@ internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifie } } - /// - /// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST - /// - - 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 domainList = referencedDomains.Read(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 //