From 8e6cd4a42a15eca949c593487d3b9c39261a15c2 Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Tue, 23 Nov 2021 08:18:59 -0800 Subject: [PATCH 1/6] Make System.DirectoryServices use existing p/invokes in Common --- .../Windows/Activeds/Interop.ADsOpenObject.cs | 2 +- .../Advapi32/Interop.ConvertSidToStringSid.cs | 2 +- .../Windows/Advapi32/Interop.LogonUser.cs | 4 +- .../Interop/Windows/NtDll/Interop.NtStatus.cs | 1 + .../Win32/SafeHandles/SafeLibraryHandle.cs | 7 + .../AccountManagement/Utils.cs | 4 +- .../src/Interop/SafeNativeMethods.cs | 5 +- .../src/Interop/UnsafeNativeMethods.cs | 7 +- .../src/System.DirectoryServices.csproj | 83 +++++++- .../ActiveDirectory/ActiveDirectorySite.cs | 6 +- .../ActiveDirectory/DirectoryContext.cs | 31 +-- .../ActiveDirectory/DirectoryServer.cs | 41 ++-- .../ActiveDirectory/DomainController.cs | 10 +- .../ActiveDirectory/Forest.cs | 6 +- .../ForestTrustDomainInformation.cs | 20 +- .../ForestTrustRelationshipInformation.cs | 39 ++-- .../ActiveDirectory/NativeMethods.cs | 20 +- .../ActiveDirectory/SafeHandle.cs | 25 --- .../ActiveDirectory/TrustHelper.cs | 115 ++++++----- .../ActiveDirectory/UnsafeNativeMethods.cs | 164 +-------------- .../ActiveDirectory/Utils.cs | 194 ++++++++---------- 21 files changed, 338 insertions(+), 448 deletions(-) diff --git a/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs b/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs index 2ed72a63ca58c..ee31cd67ab52e 100644 --- a/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs +++ b/src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs @@ -9,6 +9,6 @@ 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); + 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 index 998f854acfd99..de48c70398903 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs @@ -9,6 +9,6 @@ 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); + internal static partial BOOL ConvertSidToStringSid(IntPtr sid, out string stringSid); } } diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs index 7e1155d45ff3e..d15cad8137efc 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs @@ -11,8 +11,8 @@ 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, + string? domain, + string? password, int logonType, int logonProvider, ref IntPtr token); diff --git a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.NtStatus.cs b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.NtStatus.cs index 76715c83be916..43508983609a5 100644 --- a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.NtStatus.cs +++ b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.NtStatus.cs @@ -14,6 +14,7 @@ internal static class StatusOptions internal const uint STATUS_NO_MEMORY = 0xC0000017; internal const uint STATUS_ACCESS_DENIED = 0xC0000022; internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034; + internal const uint STATUS_QUOTA_EXCEEDED = 0xC0000044; internal const uint STATUS_ACCOUNT_RESTRICTION = 0xC000006E; internal const uint STATUS_NONE_MAPPED = 0xC0000073; internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A; diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs index f7a57d09f0db9..0ea2bf741ab4b 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs @@ -1,12 +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; + namespace Microsoft.Win32.SafeHandles { internal sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeLibraryHandle() : base(true) { } + internal SafeLibraryHandle(IntPtr value) : base(true) + { + SetHandle(value); + } + protected override bool ReleaseHandle() { return Interop.Kernel32.FreeLibrary(handle); 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 d631c7a5d6198..cadc34842bfd6 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 @@ -115,8 +115,6 @@ internal static byte[] StringToByteArray(string s) internal static string ConvertSidToSDDL(byte[] sid) { - string sddlSid = null; - // To put the byte[] SID into SDDL, we use ConvertSidToStringSid. // Calling that requires we first copy the SID into native memory. IntPtr pSid = IntPtr.Zero; @@ -125,7 +123,7 @@ internal static string ConvertSidToSDDL(byte[] sid) { pSid = ConvertByteArrayToIntPtr(sid); - if (Interop.Advapi32.ConvertSidToStringSid(pSid, ref sddlSid) != Interop.BOOL.FALSE) + if (Interop.Advapi32.ConvertSidToStringSid(pSid, out string sddlSid) != Interop.BOOL.FALSE) { return sddlSid; } diff --git a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs index bbff66c02c951..3816db06f9b08 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs @@ -9,9 +9,6 @@ namespace System.DirectoryServices.Interop { internal static class SafeNativeMethods { - [DllImport(global::Interop.Libraries.OleAut32, PreserveSig = false)] - public static extern void VariantClear(IntPtr pObject); - [DllImport(global::Interop.Libraries.OleAut32)] public static extern void VariantInit(IntPtr pObject); @@ -99,7 +96,7 @@ private void Advance() } finally { - VariantClear(addr); + global::Interop.OleAut32.VariantClear(addr); } } finally diff --git a/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs index bc8671e126c1a..a0bfff3a4d6ab 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs @@ -4,6 +4,8 @@ using System.Runtime.InteropServices; using System.Security; +using Activeds = Interop.Activeds; + namespace System.DirectoryServices.Interop { @@ -28,14 +30,11 @@ internal struct Variant internal static class UnsafeNativeMethods { - [DllImport(global::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 Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject); } catch (EntryPointNotFoundException) { diff --git a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj index 39d6ef2c2db50..d8ca3951a9aa7 100644 --- a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj +++ b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj @@ -1,4 +1,4 @@ - + true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0 @@ -149,9 +149,88 @@ System.DirectoryServices.ActiveDirectory.DomainController + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index 48281bb491e39..bc3312201f708 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -7,6 +7,8 @@ using System.Text; using System.Diagnostics.CodeAnalysis; +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { [Flags] @@ -1306,7 +1308,7 @@ private void GetDomains() IntPtr info = (IntPtr)0; // call DsReplicaSyncAllW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1348,7 +1350,7 @@ private void GetDomains() finally { // call DsFreeNameResultW - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs index 0ed4b80c55f04..85599095ece37 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs @@ -9,6 +9,11 @@ using System.IO; using System.Diagnostics.CodeAnalysis; +using Microsoft.Win32.SafeHandles; + +using Advapi32 = Interop.Advapi32; +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { public enum DirectoryContextType @@ -31,8 +36,8 @@ public class DirectoryContext private bool _validated; private bool _contextIsValid; - internal static LoadLibrarySafeHandle ADHandle; - internal static LoadLibrarySafeHandle ADAMHandle; + internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADHandle; + internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADAMHandle; #region constructors @@ -559,8 +564,8 @@ internal static string GetLoggedOnDomain() IntPtr pResponseBuffer = IntPtr.Zero; NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse(); int responseBufferLength; - int protocolStatus; - int result; + uint protocolStatus; + uint result; LsaLogonProcessSafeHandle lsaHandle; @@ -594,11 +599,11 @@ internal static string GetLoggedOnDomain() } else { - if (result == NativeMethods.STATUS_QUOTA_EXCEEDED) + if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED) { throw new OutOfMemoryException(); } - else if ((result == 0) && (UnsafeNativeMethods.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION)) + else if ((result == 0) && (Advapi32.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION)) { // If this is a directory user, extract domain info from username if (!Utils.IsSamUser()) @@ -612,7 +617,7 @@ internal static string GetLoggedOnDomain() } else { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus)); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus)); } } } @@ -624,13 +629,13 @@ internal static string GetLoggedOnDomain() } } } - else if (result == NativeMethods.STATUS_QUOTA_EXCEEDED) + else if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED) { throw new OutOfMemoryException(); } else { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result)); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result)); } // If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.), @@ -688,27 +693,27 @@ private static void GetLibraryHandle() { // first get AD handle string systemPath = Environment.SystemDirectory; - IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll"); + IntPtr tempHandle = Kernel32.LoadLibrary(systemPath + "\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } else { - ADHandle = new LoadLibrarySafeHandle(tempHandle); + ADHandle = new SafeLibraryHandle(tempHandle); } // not get the ADAM handle // got to the windows\adam directory DirectoryInfo windowsDirectory = Directory.GetParent(systemPath)!; - tempHandle = UnsafeNativeMethods.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll"); + tempHandle = Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { ADAMHandle = ADHandle; } else { - ADAMHandle = new LoadLibrarySafeHandle(tempHandle); + ADAMHandle = new SafeLibraryHandle(tempHandle); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 24bc8ce837251..17621444ba00e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -2,10 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics; +using Microsoft.Win32.SafeHandles; + +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { public abstract class DirectoryServer : IDisposable @@ -292,10 +295,10 @@ internal void CheckIfDisposed() internal DirectoryContext Context => context; - internal void CheckConsistencyHelper(IntPtr dsHandle, LoadLibrarySafeHandle libHandle) + internal void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle) { // call DsReplicaConsistencyCheck - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaConsistencyCheck"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -308,7 +311,7 @@ internal void CheckConsistencyHelper(IntPtr dsHandle, LoadLibrarySafeHandle libH throw ExceptionHelper.GetExceptionFromErrorCode(result, Name); } - internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string? partition, ref bool advanced, int context, LoadLibrarySafeHandle libHandle) + internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string? partition, ref bool advanced, int context, SafeLibraryHandle libHandle) { IntPtr info = (IntPtr)0; int result = 0; @@ -317,11 +320,11 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar // first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine // call DsReplicaGetInfo2W - functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfo2W"); + functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W"); if (functionPtr == (IntPtr)0) { // a win2k machine which does not have it. - functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW"); + functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -341,7 +344,7 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar if (needToTryAgain && result == DS_REPL_NOTSUPPORTED) { // this is the case that client is xp/win2k3, dc is win2k - functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW"); + functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -390,7 +393,7 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar return info; } - internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, LoadLibrarySafeHandle libHandle) + internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, SafeLibraryHandle libHandle) { int context = 0; int count = 0; @@ -455,7 +458,7 @@ internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle return collection; } - internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle) + internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle) { ReplicationOperationInformation replicationInfo = new ReplicationOperationInformation(); ReplicationOperationCollection collection = new ReplicationOperationCollection(server); @@ -484,7 +487,7 @@ internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, return replicationInfo; } - internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle) + internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle) { ReplicationNeighborCollection collection = new ReplicationNeighborCollection(server); int count = 0; @@ -508,7 +511,7 @@ internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, Directory return collection; } - internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle) + internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle) { ReplicationFailureCollection collection = new ReplicationFailureCollection(server); int count = 0; @@ -531,7 +534,7 @@ internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectorySe return collection; } - internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle) + internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle) { ActiveDirectoryReplicationMetadata collection = new ActiveDirectoryReplicationMetadata(server); int count = 0; @@ -633,7 +636,7 @@ internal bool SyncAllCallbackRoutine(IntPtr data, IntPtr update) } } - internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllFunctionPointer, string partition, SyncFromAllServersOptions option, SyncUpdateCallback? callback, LoadLibrarySafeHandle libHandle) + internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllFunctionPointer, string partition, SyncFromAllServersOptions option, SyncUpdateCallback? callback, SafeLibraryHandle libHandle) { IntPtr errorInfo = (IntPtr)0; @@ -642,7 +645,7 @@ internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallb // we want to return the dn instead of DNS guid // call DsReplicaSyncAllW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncAllW"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -673,16 +676,16 @@ internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallb { // release the memory if (errorInfo != (IntPtr)0) - UnsafeNativeMethods.LocalFree(errorInfo); + Kernel32.LocalFree(errorInfo); } } - private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, LoadLibrarySafeHandle libHandle) + private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHandle libHandle) { if (value != (IntPtr)0) { // call DsReplicaFreeInfo - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaFreeInfo"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -693,7 +696,7 @@ private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, LoadLibrarySa } } - internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, LoadLibrarySafeHandle libHandle) + internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, SafeLibraryHandle libHandle) { int structSize = Marshal.SizeOf(typeof(Guid)); IntPtr unmanagedGuid = (IntPtr)0; @@ -722,7 +725,7 @@ internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, } // call DsReplicaSyncW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs index e0028300fc0de..91a29aa659b4a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -8,6 +8,8 @@ using System.Runtime.InteropServices; using System.Diagnostics; +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { [Flags] @@ -1087,7 +1089,7 @@ private void GetDomainControllerInfo() GetDSHandle(); // call DsGetDomainControllerInfo - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1164,7 +1166,7 @@ private void GetDomainControllerInfo() if (dcInfoPtr != IntPtr.Zero) { // call DsFreeDomainControllerInfo - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1249,7 +1251,7 @@ private ArrayList GetRoles() GetDSHandle(); // Get the roles // call DsListRoles - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1289,7 +1291,7 @@ private ArrayList GetRoles() if (rolesPtr != IntPtr.Zero) { // call DsFreeNameResult - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs index bee105b811159..03a99f40abce8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -8,6 +8,8 @@ using System.Runtime.InteropServices; using System.Diagnostics; +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { public enum ForestMode : int @@ -884,7 +886,7 @@ private ArrayList GetSites() // Get the sites within the forest // call DsListSites - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -921,7 +923,7 @@ private ArrayList GetSites() if (sitesPtr != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs index 1b418b8252f14..ba7bc0c2bc644 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs @@ -4,6 +4,9 @@ using System.Runtime.InteropServices; using System.ComponentModel; +using Advapi32 = Interop.Advapi32; +using BOOL = Interop.BOOL; + namespace System.DirectoryServices.ActiveDirectory { public enum ForestTrustDomainStatus @@ -25,22 +28,15 @@ internal ForestTrustDomainInformation(int flag, LSA_FOREST_TRUST_DOMAIN_INFO dom _status = (ForestTrustDomainStatus)flag; DnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2); NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2); - IntPtr ptr = (IntPtr)0; - int result = UnsafeNativeMethods.ConvertSidToStringSidW(domainInfo.sid, ref ptr); - if (result == 0) - { - throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); - } - try + string sidLocal; + BOOL result = Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal); + if (result == BOOL.FALSE) { - DomainSid = Marshal.PtrToStringUni(ptr)!; - } - finally - { - UnsafeNativeMethods.LocalFree(ptr); + throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } + DomainSid = sidLocal; this.time = time; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs index ae2ccd4144752..958216bc4ef5c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs @@ -5,6 +5,12 @@ using System.Collections; using System.Collections.Specialized; +using Microsoft.Win32.SafeHandles; + +using Advapi32 = Interop.Advapi32; +using BOOL = Interop.BOOL; +using Kernel32 = Interop.Kernel32; + namespace System.DirectoryServices.ActiveDirectory { public class ForestTrustRelationshipInformation : TrustRelationshipInformation @@ -82,7 +88,7 @@ public void Save() int currentCount = 0; IntPtr tmpPtr = (IntPtr)0; IntPtr forestInfo = (IntPtr)0; - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; LSA_UNICODE_STRING trustedDomainName; IntPtr collisionInfo = (IntPtr)0; ArrayList ptrList = new ArrayList(); @@ -187,11 +193,8 @@ public void Save() ForestTrustDomainInformation tmp = _domainInfo[i]; record.Time = tmp.time; IntPtr pSid = (IntPtr)0; - IntPtr stringSid = (IntPtr)0; - stringSid = Marshal.StringToHGlobalUni(tmp.DomainSid); - ptrList.Add(stringSid); - int result = UnsafeNativeMethods.ConvertStringSidToSidW(stringSid, ref pSid); - if (result == 0) + BOOL result = Advapi32.ConvertStringSidToSid(tmp.DomainSid, out pSid); + if (result == BOOL.FALSE) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } @@ -268,7 +271,7 @@ public void Save() impersonated = Utils.Impersonate(context); // get the policy handle - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -276,10 +279,10 @@ public void Save() UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); // call the unmanaged function - int error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo); + uint error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo); if (error != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(error), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(error), serverName); } // there is collision, throw proper exception so user can deal with it @@ -292,7 +295,7 @@ public void Save() error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 0, out collisionInfo); if (error != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)error, serverName); } // now next time property is invoked, we need to go to the server @@ -311,7 +314,7 @@ public void Save() for (int i = 0; i < sidList.Count; i++) { - UnsafeNativeMethods.LocalFree((IntPtr)sidList[i]!); + Kernel32.LocalFree((IntPtr)sidList[i]!); } if (records != (IntPtr)0) @@ -325,7 +328,7 @@ public void Save() } if (collisionInfo != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(collisionInfo); + Advapi32.LsaFreeMemory(collisionInfo); if (target != (IntPtr)0) Marshal.FreeHGlobal(target); @@ -340,7 +343,7 @@ public void Save() private void GetForestTrustInfoHelper() { IntPtr forestTrustInfo = (IntPtr)0; - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; LSA_UNICODE_STRING? tmpName = null; bool impersonated = false; IntPtr targetPtr = (IntPtr)0; @@ -370,16 +373,16 @@ private void GetForestTrustInfoHelper() impersonated = Utils.Impersonate(context); // get the policy handle - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); - int result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo); + uint result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo); // check the result if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); if (win32Error != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } } @@ -440,7 +443,7 @@ private void GetForestTrustInfoHelper() } finally { - UnsafeNativeMethods.LsaFreeMemory(forestTrustInfo); + Advapi32.LsaFreeMemory(forestTrustInfo); } _topLevelNames = tmpTLNs; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs index eba004664bc1f..83cc9c9114d45 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs @@ -457,10 +457,6 @@ internal delegate int DsListRoles( [In] IntPtr dsHandle, [Out] out IntPtr roles); - /*DWORD GetLastError(VOID)*/ - [DllImport(global::Interop.Libraries.Kernel32)] - internal static extern int GetLastError(); - internal const int DnsSrvData = 33; internal const int DnsQueryBypassCache = 8; @@ -490,13 +486,6 @@ internal static extern void DnsRecordListFree( [In] IntPtr dnsResultList, [In] bool dnsFreeType); - /*BOOL GetVersionEx( - LPOSVERSIONINFO lpVersionInfo - );*/ - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetVersionExW", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern bool GetVersionEx( - [In, Out] OSVersionInfoEx ver); - /*DWORD DsCrackNames( HANDLE hDS, DS_NAME_FLAGS flags, @@ -519,7 +508,7 @@ internal delegate int DsCrackNames( PHANDLE LsaHandle );*/ [DllImport(global::Interop.Libraries.Secur32)] - internal static extern int LsaConnectUntrusted( + internal static extern uint LsaConnectUntrusted( [Out] out LsaLogonProcessSafeHandle lsaHandle); internal const int NegGetCallerName = 1; @@ -534,14 +523,14 @@ internal static extern int LsaConnectUntrusted( PNTSTATUS ProtocolStatus );*/ [DllImport(global::Interop.Libraries.Secur32)] - internal static extern int LsaCallAuthenticationPackage( + internal static extern uint LsaCallAuthenticationPackage( [In] LsaLogonProcessSafeHandle lsaHandle, [In] int authenticationPackage, [In] NegotiateCallerNameRequest protocolSubmitBuffer, [In] int submitBufferLength, [Out] out IntPtr protocolReturnBuffer, [Out] out int returnBufferLength, - [Out] out int protocolStatus); + [Out] out uint protocolStatus); /*NTSTATUS LsaFreeReturnBuffer( PVOID Buffer @@ -572,9 +561,6 @@ internal static extern int CompareString( [In] int cchCount1, [In] IntPtr lpString2, [In] int cchCount2); - - [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)] - internal static extern int LsaNtStatusToWinError(int ntStatus); } internal sealed class NativeComInterfaces diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs index af0b09820a11a..62ac4f15c5754 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs @@ -1,23 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Security; using Microsoft.Win32.SafeHandles; namespace System.DirectoryServices.ActiveDirectory { - internal sealed class PolicySafeHandle : SafeHandleZeroOrMinusOneIsInvalid - { - public PolicySafeHandle() : base(true) { } - - internal PolicySafeHandle(IntPtr value) : base(true) - { - SetHandle(value); - } - - protected override bool ReleaseHandle() => UnsafeNativeMethods.LsaClose(handle) == 0; - } - internal sealed class LsaLogonProcessSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public LsaLogonProcessSafeHandle() : base(true) { } @@ -29,16 +16,4 @@ internal LsaLogonProcessSafeHandle(IntPtr value) : base(true) protected override bool ReleaseHandle() => NativeMethods.LsaDeregisterLogonProcess(handle) == 0; } - - internal sealed class LoadLibrarySafeHandle : SafeHandleZeroOrMinusOneIsInvalid - { - public LoadLibrarySafeHandle() : base(true) { } - - internal LoadLibrarySafeHandle(IntPtr value) : base(true) - { - SetHandle(value); - } - - protected override bool ReleaseHandle() => UnsafeNativeMethods.FreeLibrary(handle) != 0; - } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index f03d5a4c448d9..d8fe4579a2455 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -5,6 +5,10 @@ using System.Diagnostics; using System.Security.Cryptography; +using Microsoft.Win32.SafeHandles; + +using Advapi32 = Interop.Advapi32; + namespace System.DirectoryServices.ActiveDirectory { internal enum TRUSTED_INFORMATION_CLASS @@ -57,7 +61,7 @@ internal static class TrustHelper internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string? sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool isForest) { - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; LSA_UNICODE_STRING? trustedDomainName = null; bool impersonated = false; @@ -74,17 +78,17 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string try { // get the policy handle first - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -94,7 +98,7 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } Debug.Assert(buffer != (IntPtr)0); @@ -146,7 +150,7 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); } } catch { throw; } @@ -154,7 +158,7 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string? sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool status, bool isForest) { - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; IntPtr newInfo = (IntPtr)0; LSA_UNICODE_STRING? trustedDomainName = null; @@ -171,7 +175,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string try { // get the policy handle first - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -179,10 +183,10 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); // get the trusted domain information - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -192,7 +196,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } Debug.Assert(buffer != (IntPtr)0); @@ -259,7 +263,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); } return; @@ -273,7 +277,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); if (newInfo != (IntPtr)0) Marshal.FreeHGlobal(newInfo); @@ -284,9 +288,8 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceName, string? targetName, bool isForest) { - PolicySafeHandle? policyHandle = null; + SafeLsaPolicyHandle? policyHandle = null; LSA_UNICODE_STRING? trustedDomainName = null; - int win32Error = 0; bool impersonated = false; IntPtr target = (IntPtr)0; string? serverName = null; @@ -301,7 +304,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN try { // get the policy handle - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + policyHandle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -309,10 +312,10 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); // get trust information - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -322,7 +325,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } Debug.Assert(buffer != (IntPtr)0); @@ -339,14 +342,14 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN result = UnsafeNativeMethods.LsaDeleteTrustedDomain(policyHandle, domainInfo.Sid); if (result != 0) { - win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } } finally { if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); } } finally @@ -363,7 +366,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN internal static void VerifyTrust(DirectoryContext context, string? sourceName, string? targetName, bool isForest, TrustDirection direction, bool forceSecureChannelReset, string? preferredTargetServer) { - PolicySafeHandle? policyHandle = null; + SafeLsaPolicyHandle? policyHandle = null; LSA_UNICODE_STRING? trustedDomainName = null; int win32Error = 0; IntPtr data = (IntPtr)0; @@ -383,7 +386,7 @@ internal static void VerifyTrust(DirectoryContext context, string? sourceName, s try { // get the policy handle - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(policyServerName)); + policyHandle = Utils.GetPolicyHandle(policyServerName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -485,7 +488,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN IntPtr unmanagedPassword = (IntPtr)0; IntPtr info = (IntPtr)0; IntPtr domainHandle = (IntPtr)0; - PolicySafeHandle? policyHandle = null; + SafeLsaPolicyHandle? policyHandle = null; IntPtr unmanagedAuthData = (IntPtr)0; bool impersonated = false; string? serverName = null; @@ -554,12 +557,12 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN // do impersonation and get policy handle impersonated = Utils.Impersonate(sourceContext); - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + policyHandle = Utils.GetPolicyHandle(serverName); - int result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle); + uint result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle); if (result != 0) { - result = UnsafeNativeMethods.LsaNtStatusToWinError(result); + result = Advapi32.LsaNtStatusToWinError(result); if (result == ERROR_ALREADY_EXISTS) { if (isForest) @@ -568,7 +571,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingDomainTrust, sourceName, targetName)); } else - throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)result, serverName); } } finally @@ -580,10 +583,10 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN Marshal.FreeHGlobal(fileTime); if (domainHandle != (IntPtr)0) - UnsafeNativeMethods.LsaClose(domainHandle); + Advapi32.LsaClose(domainHandle); if (info != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(info); + Advapi32.LsaFreeMemory(info); if (unmanagedPassword != (IntPtr)0) Marshal.FreeHGlobal(unmanagedPassword); @@ -597,7 +600,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN internal static string UpdateTrust(DirectoryContext context, string? sourceName, string? targetName, string password, bool isForest) { - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; LSA_UNICODE_STRING? trustedDomainName = null; IntPtr newBuffer = (IntPtr)0; @@ -620,7 +623,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, try { // get the policy handle first - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -628,10 +631,10 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); // get the trusted domain information - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -641,7 +644,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } // get the managed structre representation @@ -697,7 +700,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); } return serverName; @@ -711,7 +714,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); if (newBuffer != (IntPtr)0) Marshal.FreeHGlobal(newBuffer); @@ -731,7 +734,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, internal static void UpdateTrustDirection(DirectoryContext context, string? sourceName, string? targetName, string password, bool isForest, TrustDirection newTrustDirection) { - PolicySafeHandle? handle = null; + SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; LSA_UNICODE_STRING? trustedDomainName = null; IntPtr newBuffer = (IntPtr)0; @@ -753,7 +756,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour try { // get the policy handle first - handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + handle = Utils.GetPolicyHandle(serverName); // get the target name trustedDomainName = new LSA_UNICODE_STRING(); @@ -761,10 +764,10 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); // get the trusted domain information - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -774,7 +777,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } // get the managed structre representation @@ -842,7 +845,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); } return; @@ -856,7 +859,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); if (newBuffer != (IntPtr)0) Marshal.FreeHGlobal(newBuffer); @@ -874,15 +877,15 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour catch { throw; } } - private static void ValidateTrust(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) + private static void ValidateTrust(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) { IntPtr buffer = (IntPtr)0; // get trust information - int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); + uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result); + uint win32Error = Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -892,7 +895,7 @@ private static void ValidateTrust(PolicySafeHandle handle, LSA_UNICODE_STRING tr throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null); } else - throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } Debug.Assert(buffer != (IntPtr)0); @@ -920,7 +923,7 @@ private static void ValidateTrust(PolicySafeHandle handle, LSA_UNICODE_STRING tr finally { if (buffer != (IntPtr)0) - UnsafeNativeMethods.LsaFreeMemory(buffer); + Advapi32.LsaFreeMemory(buffer); } } @@ -982,7 +985,7 @@ internal static string CreateTrustPassword() private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, string? targetName, bool isForest) { - PolicySafeHandle? policyHandle = null; + SafeLsaPolicyHandle? policyHandle = null; IntPtr buffer = (IntPtr)0; bool impersonated = false; string? serverName = null; @@ -995,7 +998,7 @@ private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, strin impersonated = Utils.Impersonate(targetContext); try { - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + policyHandle = Utils.GetPolicyHandle(serverName); } catch (ActiveDirectoryOperationException) { @@ -1007,7 +1010,7 @@ private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, strin // try anonymous Utils.ImpersonateAnonymous(); impersonated = true; - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + policyHandle = Utils.GetPolicyHandle(serverName); } catch (UnauthorizedAccessException) { @@ -1019,13 +1022,13 @@ private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, strin // try anonymous Utils.ImpersonateAnonymous(); impersonated = true; - policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); + policyHandle = Utils.GetPolicyHandle(serverName); } - int result = UnsafeNativeMethods.LsaQueryInformationPolicy(policyHandle, policyDnsDomainInformation, out buffer); + uint result = Advapi32.LsaQueryInformationPolicy(policyHandle.DangerousGetHandle(), policyDnsDomainInformation, ref buffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); } return buffer; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs index 3596b1a5013bd..2a6115ea3f7cd 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs @@ -25,8 +25,8 @@ //} using System.Runtime.InteropServices; -using System.Security; -using System.Text; + +using Microsoft.Win32.SafeHandles; namespace System.DirectoryServices.ActiveDirectory { @@ -594,30 +594,6 @@ internal sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC public Guid DomainGuid; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal sealed class SID_AND_ATTR - { - public IntPtr pSid = IntPtr.Zero; - public int attrs; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal sealed class TOKEN_USER - { - public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR(); - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal 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)] internal sealed class POLICY_ACCOUNT_DOMAIN_INFO { @@ -639,9 +615,6 @@ internal static class UnsafeNativeMethods public delegate int DsReplicaSyncAllW(IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string partition, int flags, SyncReplicaFromAllServersCallback callback, IntPtr data, ref IntPtr error); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "LocalFree")] - public static extern int LocalFree(IntPtr mem); - [DllImport(global::Interop.Libraries.Activeds, EntryPoint = "ADsEncodeBinaryData", CharSet = CharSet.Unicode)] public static extern int ADsEncodeBinaryData(byte[] data, int length, ref IntPtr result); @@ -661,50 +634,23 @@ internal static class UnsafeNativeMethods [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")] public static extern int NetApiBufferFree(IntPtr buffer); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern int LogonUserW(string? lpszUsername, string? lpszDomain, string? lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateLoggedOnUser", SetLastError = true)] - public static extern int ImpersonateLoggedOnUser(IntPtr hToken); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "RevertToSelf", SetLastError = true)] - public static extern int RevertToSelf(); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern int ConvertSidToStringSidW(IntPtr pSid, ref IntPtr stringSid); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern int ConvertStringSidToSidW(IntPtr stringSid, ref IntPtr pSid); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")] - public static extern int LsaSetForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenPolicy")] - public static extern int LsaOpenPolicy(LSA_UNICODE_STRING target, LSA_OBJECT_ATTRIBUTES objectAttributes, int access, out IntPtr handle); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaClose")] - public static extern int LsaClose(IntPtr handle); + public static extern uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")] - public static extern int LsaQueryForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, ref IntPtr ForestTrustInfo); + public static extern uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING target, ref IntPtr ForestTrustInfo); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")] - public static extern int LsaQueryTrustedDomainInfoByName(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaNtStatusToWinError")] - public static extern int LsaNtStatusToWinError(int status); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaFreeMemory")] - public static extern int LsaFreeMemory(IntPtr ptr); + public static extern uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")] - public static extern int LsaSetTrustedDomainInfoByName(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); + public static extern uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenTrustedDomainByName")] - public static extern int LsaOpenTrustedDomainByName(PolicySafeHandle policyHandle, LSA_UNICODE_STRING trustedDomain, int access, ref IntPtr trustedDomainHandle); + public static extern int LsaOpenTrustedDomainByName(SafeLsaPolicyHandle policyHandle, LSA_UNICODE_STRING trustedDomain, int access, ref IntPtr trustedDomainHandle); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")] - public static extern int LsaDeleteTrustedDomain(PolicySafeHandle handle, IntPtr pSid); + public static extern uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid); [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "I_NetLogonControl2", CharSet = CharSet.Unicode)] public static extern int I_NetLogonControl2(string serverName, int FunctionCode, int QueryLevel, IntPtr data, out IntPtr buffer); @@ -712,36 +658,18 @@ internal static class UnsafeNativeMethods [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")] public static extern void GetSystemTimeAsFileTime(IntPtr fileTime); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryInformationPolicy")] - public static extern int LsaQueryInformationPolicy(PolicySafeHandle handle, int infoClass, out IntPtr buffer); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaCreateTrustedDomainEx")] - public static extern int LsaCreateTrustedDomainEx(PolicySafeHandle handle, TRUSTED_DOMAIN_INFORMATION_EX domainEx, TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle); + public static extern uint LsaCreateTrustedDomainEx(SafeLsaPolicyHandle handle, TRUSTED_DOMAIN_INFORMATION_EX domainEx, TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle); [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)] public static extern IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetCurrentThreadId")] - public static extern int GetCurrentThreadId(); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)] public static extern int ImpersonateAnonymousToken(IntPtr token); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CloseHandle")] - public static extern int CloseHandle(IntPtr handle); - [DllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")] public static extern int RtlInitUnicodeString(LSA_UNICODE_STRING result, IntPtr s); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "LoadLibraryW", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern IntPtr LoadLibrary(string name); - - [DllImport(global::Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)] - public static extern uint FreeLibrary(IntPtr libName); - - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetProcAddress", SetLastError = true, BestFitMapping = false)] - public static extern IntPtr GetProcAddress(LoadLibrarySafeHandle hModule, string entryPoint); - /* DWORD DsRoleGetPrimaryDomainInformation( LPCWSTR lpServer, @@ -761,80 +689,6 @@ public static extern int DsRoleGetPrimaryDomainInformation( [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, out IntPtr Buffer); - [DllImport(global::Interop.Libraries.Advapi32)] - public static extern int GetLengthSid(IntPtr sid); - - [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true)] - public static extern bool IsValidSid(IntPtr sid); - - [DllImport(global::Interop.Libraries.Advapi32)] - public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid); - - [DllImport(global::Interop.Libraries.Advapi32)] - public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index); - - [DllImport(global::Interop.Libraries.Advapi32)] - public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid); - - [DllImport(global::Interop.Libraries.Advapi32)] - public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal); - - [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true)] - public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource); - - [DllImport(global::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(global::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(global::Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)] - public static extern IntPtr GetCurrentThread(); - - [DllImport(global::Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)] - public static extern IntPtr GetCurrentProcess(); - - [DllImport(global::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(global::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(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)] - public static extern int LsaQueryInformationPolicy( - IntPtr policyHandle, - int policyInformationClass, - ref IntPtr buffer - ); - - [DllImport(global::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 - ); - /* void DsRoleFreeMemory( PVOID Buffer diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index 69cd0a8f6712f..08420d939c4b6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -7,7 +7,11 @@ using System.Security.Principal; using System.Runtime.InteropServices; using System.Diagnostics; -using System.Globalization; + +using Microsoft.Win32.SafeHandles; + +using Advapi32 = Interop.Advapi32; +using Kernel32 = Interop.Kernel32; namespace System.DirectoryServices.ActiveDirectory { @@ -42,7 +46,7 @@ internal sealed class Utils { private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; private const int LOGON32_PROVIDER_WINNT50 = 3; - private const int POLICY_VIEW_LOCAL_INFORMATION = 0x00000001; + private const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000; private const uint SYNCHRONIZE = 0x00100000; private const uint THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF; @@ -107,7 +111,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) Debug.Assert(distinguishedName != null); // call DsCrackNamesW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -163,7 +167,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) if (results != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -195,7 +199,7 @@ internal static string GetDNFromDnsName(string dnsName) Debug.Assert(dnsName != null); // call DsCrackNamesW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); + IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -231,7 +235,7 @@ internal static string GetDNFromDnsName(string dnsName) if (results != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -606,7 +610,7 @@ internal static void GetDomainAndUsername(DirectoryContext context, out string? } } - internal static IntPtr GetAuthIdentity(DirectoryContext context, LoadLibrarySafeHandle libHandle) + internal static IntPtr GetAuthIdentity(DirectoryContext context, SafeLibraryHandle libHandle) { IntPtr authIdentity; int result = 0; @@ -619,7 +623,7 @@ internal static IntPtr GetAuthIdentity(DirectoryContext context, LoadLibrarySafe // create the credentials // call DsMakePasswordCredentialsW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsMakePasswordCredentialsW"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsMakePasswordCredentialsW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -638,13 +642,13 @@ internal static IntPtr GetAuthIdentity(DirectoryContext context, LoadLibrarySafe return authIdentity; } - internal static void FreeAuthIdentity(IntPtr authIdentity, LoadLibrarySafeHandle libHandle) + internal static void FreeAuthIdentity(IntPtr authIdentity, SafeLibraryHandle libHandle) { // free the credentials object if (authIdentity != IntPtr.Zero) { // call DsMakePasswordCredentialsW - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsFreePasswordCredentials"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsFreePasswordCredentials"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -654,14 +658,14 @@ internal static void FreeAuthIdentity(IntPtr authIdentity, LoadLibrarySafeHandle } } - internal static IntPtr GetDSHandle(string? domainControllerName, string? domainName, IntPtr authIdentity, LoadLibrarySafeHandle libHandle) + internal static IntPtr GetDSHandle(string? domainControllerName, string? domainName, IntPtr authIdentity, SafeLibraryHandle libHandle) { int result = 0; IntPtr handle; // call DsBindWithCred Debug.Assert((domainControllerName != null && domainName == null) || (domainName != null && domainControllerName == null)); - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsBindWithCredW"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsBindWithCredW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -676,13 +680,13 @@ internal static IntPtr GetDSHandle(string? domainControllerName, string? domainN return handle; } - internal static void FreeDSHandle(IntPtr dsHandle, LoadLibrarySafeHandle libHandle) + internal static void FreeDSHandle(IntPtr dsHandle, SafeLibraryHandle libHandle) { // DsUnbind if (dsHandle != IntPtr.Zero) { // call DsUnbind - IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsUnBindW"); + IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsUnBindW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -928,14 +932,14 @@ internal static bool Impersonate(DirectoryContext context) Utils.GetDomainAndUsername(context, out userName, out domainName); - int result = UnsafeNativeMethods.LogonUserW(userName, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken); + int result = Advapi32.LogonUser(userName!, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken); // check the result if (result == 0) throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); try { - result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken); + result = Advapi32.ImpersonateLoggedOnUser(hToken); if (result == 0) { result = Marshal.GetLastWin32Error(); @@ -945,7 +949,7 @@ internal static bool Impersonate(DirectoryContext context) finally { if (hToken != (IntPtr)0) - UnsafeNativeMethods.CloseHandle(hToken); + Kernel32.CloseHandle(hToken); } return true; @@ -953,8 +957,7 @@ internal static bool Impersonate(DirectoryContext context) internal static void ImpersonateAnonymous() { - IntPtr hThread = (IntPtr)0; - hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, UnsafeNativeMethods.GetCurrentThreadId()); + IntPtr hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, Kernel32.GetCurrentThreadId()); if (hThread == (IntPtr)0) throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -967,15 +970,13 @@ internal static void ImpersonateAnonymous() finally { if (hThread != (IntPtr)0) - UnsafeNativeMethods.CloseHandle(hThread); + Kernel32.CloseHandle(hThread); } } internal static void Revert() { - int error = UnsafeNativeMethods.RevertToSelf(); - // function failed - if (error == 0) + if (!Advapi32.RevertToSelf()) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } @@ -1038,34 +1039,18 @@ internal static string GetPolicyServerName(DirectoryContext context, bool isFore return serverName; } - internal static IntPtr GetPolicyHandle(string serverName) + internal static SafeLsaPolicyHandle GetPolicyHandle(string serverName) { - IntPtr handle = (IntPtr)0; - LSA_UNICODE_STRING systemName; - LSA_OBJECT_ATTRIBUTES objectAttribute = new LSA_OBJECT_ATTRIBUTES(); - IntPtr target = (IntPtr)0; - - int mask = POLICY_VIEW_LOCAL_INFORMATION; - - systemName = new LSA_UNICODE_STRING(); - target = Marshal.StringToHGlobalUni(serverName); - UnsafeNativeMethods.RtlInitUnicodeString(systemName, target); + SafeLsaPolicyHandle handle; + global::Interop.OBJECT_ATTRIBUTES objectAttribute = default; - try - { - int result = UnsafeNativeMethods.LsaOpenPolicy(systemName, objectAttribute, mask, out handle); - if (result != 0) - { - throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); - } - - return handle; - } - finally + uint result = Advapi32.LsaOpenPolicy(serverName, ref objectAttribute, (int)Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out handle); + if (result != 0) { - if (target != (IntPtr)0) - Marshal.FreeHGlobal(target); + throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); } + + return handle; } // @@ -2029,7 +2014,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 = Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain); // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs Debug.Assert(success == true); @@ -2056,7 +2041,7 @@ internal static bool IsSamUser() internal static IntPtr GetCurrentUserSid() { - IntPtr pTokenHandle = IntPtr.Zero; + SafeTokenHandle? tokenHandle = null; IntPtr pBuffer = IntPtr.Zero; try @@ -2067,22 +2052,22 @@ internal static IntPtr GetCurrentUserSid() int error = 0; // Get the current thread's token - if (!UnsafeNativeMethods.OpenThreadToken( - UnsafeNativeMethods.GetCurrentThread(), - 0x8, // TOKEN_QUERY + if (!Advapi32.OpenThreadToken( + Kernel32.GetCurrentThread(), + TokenAccessLevels.Query, // TOKEN_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 (!Advapi32.OpenProcessToken( + Kernel32.GetCurrentProcess(), + (int)TokenAccessLevels.Query, + out tokenHandle )) { int lastError = Marshal.GetLastWin32Error(); @@ -2095,18 +2080,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 = Advapi32.GetTokenInformation( + tokenHandle.DangerousGetHandle(), + (uint)Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, 0, - ref neededBufferSize); + out neededBufferSize); int getTokenInfoError = 0; if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER @@ -2117,15 +2102,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 = Advapi32.GetTokenInformation( + tokenHandle.DangerousGetHandle(), + (uint)Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, pBuffer, neededBufferSize, - ref neededBufferSize); + out neededBufferSize); if (!success) { @@ -2135,15 +2120,15 @@ ref pTokenHandle } // Retrieve the user's SID from the user info - TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(TOKEN_USER))!; - IntPtr pUserSid = tokenUser.sidAndAttributes.pSid; // this is a reference into the NATIVE memory (into pBuffer) + global::Interop.TOKEN_USER tokenUser = (global::Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(global::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(Advapi32.IsValidSid(pUserSid)); // Now we make a copy of the SID to return - int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid); + int userSidLength = Advapi32.GetLengthSid(pUserSid); IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength); - success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid); + success = Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); @@ -2155,8 +2140,8 @@ ref pTokenHandle } finally { - if (pTokenHandle != IntPtr.Zero) - UnsafeNativeMethods.CloseHandle(pTokenHandle); + if (tokenHandle != null) + tokenHandle.Dispose(); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); @@ -2165,48 +2150,44 @@ ref pTokenHandle internal static IntPtr GetMachineDomainSid() { - IntPtr pPolicyHandle = IntPtr.Zero; + SafeLsaPolicyHandle? policyHandle = null; IntPtr pBuffer = IntPtr.Zero; - IntPtr pOA = IntPtr.Zero; try { - LSA_OBJECT_ATTRIBUTES oa = new LSA_OBJECT_ATTRIBUTES(); - - pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES))); - Marshal.StructureToPtr(oa, pOA, false); - int err = UnsafeNativeMethods.LsaOpenPolicy( - IntPtr.Zero, - pOA, - 1, // POLICY_VIEW_LOCAL_INFORMATION - ref pPolicyHandle); + global::Interop.OBJECT_ATTRIBUTES oa = default; + uint err = Advapi32.LsaOpenPolicy( + SystemName: null, + ref oa, + (int)Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, + out policyHandle); if (err != 0) { - throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err))); + throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, Advapi32.LsaNtStatusToWinError(err))); } - Debug.Assert(pPolicyHandle != IntPtr.Zero); - err = UnsafeNativeMethods.LsaQueryInformationPolicy( - pPolicyHandle, + Debug.Assert(!policyHandle.IsInvalid); + err = Advapi32.LsaQueryInformationPolicy( + policyHandle.DangerousGetHandle(), 5, // PolicyAccountDomainInformation ref pBuffer); if (err != 0) { - throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err))); + throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, Advapi32.LsaNtStatusToWinError(err))); } Debug.Assert(pBuffer != IntPtr.Zero); POLICY_ACCOUNT_DOMAIN_INFO info = (POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(POLICY_ACCOUNT_DOMAIN_INFO))!; - Debug.Assert(UnsafeNativeMethods.IsValidSid(info.domainSid)); + Debug.Assert(Advapi32.IsValidSid(info.domainSid)); // Now we make a copy of the SID to return - int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid); + int sidLength = Advapi32.GetLengthSid(info.domainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); - bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid); + bool success = Advapi32.CopySid(sidLength, pCopyOfSid, info.domainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); @@ -2218,14 +2199,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); + Advapi32.LsaFreeMemory(pBuffer); } } @@ -2264,15 +2242,15 @@ internal static bool IsMachineDC(string? computerName) internal static SidType ClassifySID(IntPtr pSid) { - Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid)); + Debug.Assert(Advapi32.IsValidSid(pSid)); // Get the issuing authority and the first RID - IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid); + IntPtr pIdentAuth = Advapi32.GetSidIdentifierAuthority(pSid); - SID_IDENTIFIER_AUTHORITY identAuth = - (SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(SID_IDENTIFIER_AUTHORITY))!; + Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = + (Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Advapi32.SID_IDENTIFIER_AUTHORITY))!; - IntPtr pRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, 0); + IntPtr pRid = 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. @@ -2303,9 +2281,9 @@ internal static SidType ClassifySID(IntPtr pSid) internal static int GetLastRidFromSid(IntPtr pSid) { - IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid); + IntPtr pRidCount = Advapi32.GetSidSubAuthorityCount(pSid); int ridCount = Marshal.ReadByte(pRidCount); - IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1); + IntPtr pLastRid = Advapi32.GetSidSubAuthority(pSid, ridCount - 1); int lastRid = Marshal.ReadInt32(pLastRid); return lastRid; From f72e73bc27676872b8170a8fdf7a39080f3b0379 Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Tue, 23 Nov 2021 09:02:10 -0800 Subject: [PATCH 2/6] Use existing structs --- .../AccountManagement/Utils.cs | 6 +- .../AccountManagement/interopt.cs | 6 +- .../ForestTrustRelationshipInformation.cs | 18 +++--- .../ActiveDirectory/NativeMethods.cs | 13 +--- .../ActiveDirectory/TopLevelName.cs | 2 +- .../ActiveDirectory/TrustHelper.cs | 33 ++++------ .../ActiveDirectory/UnsafeNativeMethods.cs | 64 +++++-------------- .../ActiveDirectory/Utils.cs | 6 +- 8 files changed, 50 insertions(+), 98 deletions(-) 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 cadc34842bfd6..a18cdb60d6284 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 @@ -500,12 +500,12 @@ internal static IntPtr GetMachineDomainSid() UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)); - Debug.Assert(Interop.Advapi32.IsValidSid(info.domainSid)); + Debug.Assert(Interop.Advapi32.IsValidSid(info.DomainSid)); // Now we make a copy of the SID to return - int sidLength = Interop.Advapi32.GetLengthSid(info.domainSid); + int sidLength = Interop.Advapi32.GetLengthSid(info.DomainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); - bool success = Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.domainSid); + bool success = Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); 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 d87879d8608d8..2782c8e274bae 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 @@ -436,10 +436,10 @@ public sealed class WKSTA_INFO_100 }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public sealed class POLICY_ACCOUNT_DOMAIN_INFO + public struct POLICY_ACCOUNT_DOMAIN_INFO { - public Interop.UNICODE_INTPTR_STRING domainName; - public IntPtr domainSid = IntPtr.Zero; + public Interop.UNICODE_INTPTR_STRING DomainName; + public IntPtr DomainSid; } } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs index 958216bc4ef5c..ccc1addad7961 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs @@ -10,6 +10,7 @@ using Advapi32 = Interop.Advapi32; using BOOL = Interop.BOOL; using Kernel32 = Interop.Kernel32; +using UNICODE_STRING = Interop.UNICODE_STRING; namespace System.DirectoryServices.ActiveDirectory { @@ -89,7 +90,6 @@ public void Save() IntPtr tmpPtr = (IntPtr)0; IntPtr forestInfo = (IntPtr)0; SafeLsaPolicyHandle? handle = null; - LSA_UNICODE_STRING trustedDomainName; IntPtr collisionInfo = (IntPtr)0; ArrayList ptrList = new ArrayList(); ArrayList sidList = new ArrayList(); @@ -141,10 +141,9 @@ public void Save() record.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName; TopLevelName TLN = _topLevelNames[i]; record.Time = TLN.time; - record.TopLevelName = new LSA_UNICODE_STRING(); ptr = Marshal.StringToHGlobalUni(TLN.Name); ptrList.Add(ptr); - UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr); + UnsafeNativeMethods.RtlInitUnicodeString(out record.TopLevelName, ptr); tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); ptrList.Add(tmpPtr); @@ -171,10 +170,10 @@ public void Save() record.Time.lowPart = currentTime.lower; record.Time.highPart = currentTime.higher; } - record.TopLevelName = new LSA_UNICODE_STRING(); + ptr = Marshal.StringToHGlobalUni(_excludedNames[i]); ptrList.Add(ptr); - UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr); + UnsafeNativeMethods.RtlInitUnicodeString(out record.TopLevelName, ptr); tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); @@ -274,9 +273,9 @@ public void Save() handle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(TargetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // call the unmanaged function uint error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo); @@ -344,7 +343,6 @@ private void GetForestTrustInfoHelper() { IntPtr forestTrustInfo = (IntPtr)0; SafeLsaPolicyHandle? handle = null; - LSA_UNICODE_STRING? tmpName = null; bool impersonated = false; IntPtr targetPtr = (IntPtr)0; string? serverName = null; @@ -363,9 +361,9 @@ private void GetForestTrustInfoHelper() try { // get the target name - tmpName = new LSA_UNICODE_STRING(); + UNICODE_STRING tmpName; targetPtr = Marshal.StringToHGlobalUni(TargetName); - UnsafeNativeMethods.RtlInitUnicodeString(tmpName, targetPtr); + UnsafeNativeMethods.RtlInitUnicodeString(out tmpName, targetPtr); serverName = Utils.GetPolicyServerName(context, true, false, source); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs index 83cc9c9114d45..69e3fad07e608 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs @@ -256,17 +256,6 @@ public OSVersionInfoEx() public byte reserved; } - /*typedef struct _LUID { - DWORD LowPart; - LONG HighPart; - } LUID, *PLUID;*/ - [StructLayout(LayoutKind.Sequential)] - internal sealed class LUID - { - public int LowPart; - public int HighPart; - } - /*typedef struct _NEGOTIATE_CALLER_NAME_REQUEST { ULONG MessageType ; LUID LogonId ; @@ -275,7 +264,7 @@ internal sealed class LUID internal sealed class NegotiateCallerNameRequest { public int messageType; - public LUID? logonId; + public global::Interop.LUID? logonId; } /*typedef struct _NEGOTIATE_CALLER_NAME_RESPONSE { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs index a9eaeac257365..f55e081f0879b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs @@ -19,7 +19,7 @@ public class TopLevelName private TopLevelNameStatus _status; internal readonly LARGE_INTEGER time; - internal TopLevelName(int flag, LSA_UNICODE_STRING val, LARGE_INTEGER time) + internal TopLevelName(int flag, global::Interop.UNICODE_STRING val, LARGE_INTEGER time) { _status = (TopLevelNameStatus)flag; Name = Marshal.PtrToStringUni(val.Buffer, val.Length / 2); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index d8fe4579a2455..a97d8499ab35c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -8,6 +8,7 @@ using Microsoft.Win32.SafeHandles; using Advapi32 = Interop.Advapi32; +using UNICODE_STRING = Interop.UNICODE_STRING; namespace System.DirectoryServices.ActiveDirectory { @@ -63,7 +64,6 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string { SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; - LSA_UNICODE_STRING? trustedDomainName = null; bool impersonated = false; IntPtr target = (IntPtr)0; string? serverName = null; @@ -81,9 +81,9 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string handle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) @@ -161,7 +161,6 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; IntPtr newInfo = (IntPtr)0; - LSA_UNICODE_STRING? trustedDomainName = null; bool impersonated = false; IntPtr target = (IntPtr)0; string? serverName = null; @@ -178,9 +177,9 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string handle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // get the trusted domain information uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); @@ -289,7 +288,6 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceName, string? targetName, bool isForest) { SafeLsaPolicyHandle? policyHandle = null; - LSA_UNICODE_STRING? trustedDomainName = null; bool impersonated = false; IntPtr target = (IntPtr)0; string? serverName = null; @@ -307,9 +305,9 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN policyHandle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // get trust information uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); @@ -367,7 +365,6 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN internal static void VerifyTrust(DirectoryContext context, string? sourceName, string? targetName, bool isForest, TrustDirection direction, bool forceSecureChannelReset, string? preferredTargetServer) { SafeLsaPolicyHandle? policyHandle = null; - LSA_UNICODE_STRING? trustedDomainName = null; int win32Error = 0; IntPtr data = (IntPtr)0; IntPtr ptr = (IntPtr)0; @@ -389,9 +386,9 @@ internal static void VerifyTrust(DirectoryContext context, string? sourceName, s policyHandle = Utils.GetPolicyHandle(policyServerName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // validate the trust existence ValidateTrust(policyHandle, trustedDomainName, sourceName, targetName, isForest, (int)direction, policyServerName); // need to verify direction @@ -602,7 +599,6 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, { SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; - LSA_UNICODE_STRING? trustedDomainName = null; IntPtr newBuffer = (IntPtr)0; bool impersonated = false; LSA_AUTH_INFORMATION? AuthData = null; @@ -626,9 +622,9 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, handle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // get the trusted domain information uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); @@ -736,7 +732,6 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour { SafeLsaPolicyHandle? handle = null; IntPtr buffer = (IntPtr)0; - LSA_UNICODE_STRING? trustedDomainName = null; IntPtr newBuffer = (IntPtr)0; bool impersonated = false; LSA_AUTH_INFORMATION? AuthData = null; @@ -759,9 +754,9 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour handle = Utils.GetPolicyHandle(serverName); // get the target name - trustedDomainName = new LSA_UNICODE_STRING(); + UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); - UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target); + UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); // get the trusted domain information uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); @@ -877,7 +872,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour catch { throw; } } - private static void ValidateTrust(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) + private static void ValidateTrust(SafeLsaPolicyHandle handle, UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) { IntPtr buffer = (IntPtr)0; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs index 2a6115ea3f7cd..93c205095d9ff 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs @@ -28,6 +28,8 @@ using Microsoft.Win32.SafeHandles; +using UNICODE_STRING = Interop.UNICODE_STRING; + namespace System.DirectoryServices.ActiveDirectory { @@ -412,7 +414,7 @@ internal sealed class LSA_FOREST_TRUST_RECORD [FieldOffset(8)] public LARGE_INTEGER Time = null!; [FieldOffset(16)] - public LSA_UNICODE_STRING TopLevelName = null!; + public UNICODE_STRING TopLevelName; [FieldOffset(16)] public LSA_FOREST_TRUST_BINARY_DATA Data = null!; [FieldOffset(16)] @@ -432,14 +434,6 @@ public LARGE_INTEGER() } } - [StructLayout(LayoutKind.Sequential)] - internal sealed class LSA_UNICODE_STRING - { - public short Length; - public short MaximumLength; - public IntPtr Buffer; - } - [StructLayout(LayoutKind.Sequential)] internal sealed class LSA_FOREST_TRUST_DOMAIN_INFO { @@ -459,32 +453,11 @@ internal sealed class LSA_FOREST_TRUST_BINARY_DATA public IntPtr Buffer; } - [StructLayout(LayoutKind.Sequential)] - internal sealed class LSA_OBJECT_ATTRIBUTES - { - internal int Length; - private readonly IntPtr _rootDirectory; - private readonly IntPtr _objectName; - internal int Attributes; - private readonly IntPtr _securityDescriptor; - private readonly IntPtr _securityQualityOfService; - - public LSA_OBJECT_ATTRIBUTES() - { - Length = 0; - _rootDirectory = (IntPtr)0; - _objectName = (IntPtr)0; - Attributes = 0; - _securityDescriptor = (IntPtr)0; - _securityQualityOfService = (IntPtr)0; - } - } - [StructLayout(LayoutKind.Sequential)] internal sealed class TRUSTED_DOMAIN_INFORMATION_EX { - public LSA_UNICODE_STRING? Name; - public LSA_UNICODE_STRING? FlatName; + public UNICODE_STRING Name; + public UNICODE_STRING FlatName; public IntPtr Sid; public int TrustDirection; public int TrustType; @@ -504,7 +477,7 @@ internal sealed class LSA_FOREST_TRUST_COLLISION_RECORD public int Index; public ForestTrustCollisionType Type; public int Flags; - public LSA_UNICODE_STRING Name = null!; + public UNICODE_STRING Name; } [StructLayout(LayoutKind.Sequential)] @@ -548,9 +521,9 @@ internal sealed class LSA_AUTH_INFORMATION [StructLayout(LayoutKind.Sequential)] internal sealed class POLICY_DNS_DOMAIN_INFO { - public LSA_UNICODE_STRING? Name; - public LSA_UNICODE_STRING? DnsDomainName; - public LSA_UNICODE_STRING? DnsForestName; + public UNICODE_STRING Name; + public UNICODE_STRING DnsDomainName; + public UNICODE_STRING DnsForestName; public Guid DomainGuid; public IntPtr Sid; } @@ -595,10 +568,10 @@ internal sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal sealed class POLICY_ACCOUNT_DOMAIN_INFO + internal struct POLICY_ACCOUNT_DOMAIN_INFO { - public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING(); - public IntPtr domainSid = IntPtr.Zero; + public UNICODE_STRING DomainName; + public IntPtr DomainSid; } internal static class UnsafeNativeMethods @@ -635,19 +608,16 @@ internal static class UnsafeNativeMethods public static extern int NetApiBufferFree(IntPtr buffer); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")] - public static extern uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); + public static extern uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")] - public static extern uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING target, ref IntPtr ForestTrustInfo); + public static extern uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, ref IntPtr ForestTrustInfo); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")] - public static extern uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); + public static extern uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")] - public static extern uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); - - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenTrustedDomainByName")] - public static extern int LsaOpenTrustedDomainByName(SafeLsaPolicyHandle policyHandle, LSA_UNICODE_STRING trustedDomain, int access, ref IntPtr trustedDomainHandle); + public static extern uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")] public static extern uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid); @@ -668,7 +638,7 @@ internal static class UnsafeNativeMethods public static extern int ImpersonateAnonymousToken(IntPtr token); [DllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")] - public static extern int RtlInitUnicodeString(LSA_UNICODE_STRING result, IntPtr s); + public static extern int RtlInitUnicodeString(out UNICODE_STRING result, IntPtr s); /* DWORD DsRoleGetPrimaryDomainInformation( diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index 08420d939c4b6..20927221eb1bc 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -2182,12 +2182,12 @@ internal static IntPtr GetMachineDomainSid() POLICY_ACCOUNT_DOMAIN_INFO info = (POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(POLICY_ACCOUNT_DOMAIN_INFO))!; - Debug.Assert(Advapi32.IsValidSid(info.domainSid)); + Debug.Assert(Advapi32.IsValidSid(info.DomainSid)); // Now we make a copy of the SID to return - int sidLength = Advapi32.GetLengthSid(info.domainSid); + int sidLength = Advapi32.GetLengthSid(info.DomainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); - bool success = Advapi32.CopySid(sidLength, pCopyOfSid, info.domainSid); + bool success = Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); From 8b3815e1b5a6d1d0682a7a5e7555c0b6ae508ba6 Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Tue, 23 Nov 2021 09:28:59 -0800 Subject: [PATCH 3/6] Use GeneratedDllImport --- .../src/Interop/SafeNativeMethods.cs | 18 +-- .../src/System.DirectoryServices.csproj | 6 + .../ActiveDirectory/DirectoryContext.cs | 2 +- .../ActiveDirectory/NativeMethods.cs | 140 +++++++++--------- .../ActiveDirectory/TrustHelper.cs | 32 ++-- .../ActiveDirectory/UnsafeNativeMethods.cs | 92 ++++++------ 6 files changed, 147 insertions(+), 143 deletions(-) diff --git a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs index 3816db06f9b08..800f61ec68d49 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs @@ -7,13 +7,13 @@ namespace System.DirectoryServices.Interop { - internal static class SafeNativeMethods + internal static partial class SafeNativeMethods { - [DllImport(global::Interop.Libraries.OleAut32)] - public static extern void VariantInit(IntPtr pObject); + [GeneratedDllImport(global::Interop.Libraries.OleAut32)] + public static partial void VariantInit(IntPtr pObject); - [DllImport(global::Interop.Libraries.Activeds)] - public static extern bool FreeADsMem(IntPtr pVoid); + [GeneratedDllImport(global::Interop.Libraries.Activeds)] + public static partial bool FreeADsMem(IntPtr pVoid); public const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, @@ -22,11 +22,11 @@ public const int ERROR_MORE_DATA = 234, ERROR_SUCCESS = 0; - [DllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)] - public static extern unsafe int ADsGetLastError(out int error, char* errorBuffer, int errorBufferLength, char* nameBuffer, int nameBufferLength); + [GeneratedDllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)] + public static unsafe partial int ADsGetLastError(out int error, char* errorBuffer, int errorBufferLength, char* nameBuffer, int nameBufferLength); - [DllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)] - public static extern int ADsSetLastError(int error, string? errorString, string? provider); + [GeneratedDllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)] + public static partial int ADsSetLastError(int error, string? errorString, string? provider); public class EnumVariant { diff --git a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj index d8ca3951a9aa7..6384fde3186b9 100644 --- a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj +++ b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj @@ -3,6 +3,10 @@ true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0 true + + $(NoWarn);CA1845;CA1846 enable true true @@ -246,6 +250,7 @@ System.DirectoryServices.ActiveDirectory.DomainController + @@ -253,6 +258,7 @@ System.DirectoryServices.ActiveDirectory.DomainController + diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs index 85599095ece37..3d2efcaff3c20 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs @@ -558,7 +558,7 @@ internal static string GetLoggedOnDomain() { string? domainName = null; - NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest(); + NegotiateCallerNameRequest requestBuffer = default; int requestBufferLength = (int)Marshal.SizeOf(requestBuffer); IntPtr pResponseBuffer = IntPtr.Zero; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs index 69e3fad07e608..aa2c34967bbd7 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs @@ -261,10 +261,10 @@ public OSVersionInfoEx() LUID LogonId ; } NEGOTIATE_CALLER_NAME_REQUEST, *PNEGOTIATE_CALLER_NAME_REQUEST ;*/ [StructLayout(LayoutKind.Sequential)] - internal sealed class NegotiateCallerNameRequest + internal struct NegotiateCallerNameRequest { public int messageType; - public global::Interop.LUID? logonId; + public global::Interop.LUID logonId; } /*typedef struct _NEGOTIATE_CALLER_NAME_RESPONSE { @@ -278,7 +278,7 @@ internal sealed class NegotiateCallerNameResponse public string? callerName; } - internal sealed class NativeMethods + internal sealed partial class NativeMethods { // disable public constructor private NativeMethods() { } @@ -309,14 +309,14 @@ private NativeMethods() { } ULONG Flags, PDOMAIN_CONTROLLER_INFO* DomainControllerInfo );*/ - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)] - internal static extern int DsGetDcName( - [In] string? computerName, - [In] string? domainName, - [In] IntPtr domainGuid, - [In] string? siteName, - [In] int flags, - [Out] out IntPtr domainControllerInfo); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)] + internal static partial int DsGetDcName( + string? computerName, + string? domainName, + IntPtr domainGuid, + string? siteName, + int flags, + out IntPtr domainControllerInfo); /* DWORD WINAPI DsGetDcOpen( LPCTSTR DnsName, @@ -327,15 +327,15 @@ internal static extern int DsGetDcName( ULONG DcFlags, PHANDLE RetGetDcContext );*/ - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcOpenW", CharSet = CharSet.Unicode)] - internal static extern int DsGetDcOpen( - [In] string? dnsName, - [In] int optionFlags, - [In] string? siteName, - [In] IntPtr domainGuid, - [In] string? dnsForestName, - [In] int dcFlags, - [Out] out IntPtr retGetDcContext); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcOpenW", CharSet = CharSet.Unicode)] + internal static partial int DsGetDcOpen( + string? dnsName, + int optionFlags, + string? siteName, + IntPtr domainGuid, + string? dnsForestName, + int dcFlags, + out IntPtr retGetDcContext); /*DWORD WINAPI DsGetDcNext( HANDLE GetDcContextHandle, @@ -343,26 +343,26 @@ internal static extern int DsGetDcOpen( LPSOCKET_ADDRESS* SockAddresses, LPTSTR* DnsHostName );*/ - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNextW", CharSet = CharSet.Unicode)] - internal static extern int DsGetDcNext( - [In] IntPtr getDcContextHandle, - [In, Out] ref IntPtr sockAddressCount, - [Out] out IntPtr sockAdresses, - [Out] out IntPtr dnsHostName); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcNextW", CharSet = CharSet.Unicode)] + internal static partial int DsGetDcNext( + IntPtr getDcContextHandle, + ref IntPtr sockAddressCount, + out IntPtr sockAdresses, + out IntPtr dnsHostName); /*void WINAPI DsGetDcClose( HANDLE GetDcContextHandle );*/ - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcCloseW", CharSet = CharSet.Unicode)] - internal static extern void DsGetDcClose( - [In] IntPtr getDcContextHandle); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcCloseW", CharSet = CharSet.Unicode)] + internal static partial void DsGetDcClose( + IntPtr getDcContextHandle); /*NET_API_STATUS NetApiBufferFree( LPVOID Buffer );*/ - [DllImport(global::Interop.Libraries.Netapi32)] - internal static extern int NetApiBufferFree( - [In] IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Netapi32)] + internal static partial int NetApiBufferFree( + IntPtr buffer); /*DWORD DsMakePasswordCredentials( LPTSTR User, @@ -457,23 +457,23 @@ internal delegate int DsListRoles( PDNS_RECORD *ppQueryResultsSet, PVOID *pReserved );*/ - [DllImport(global::Interop.Libraries.Dnsapi, EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode)] - internal static extern int DnsQuery( - [In] string recordName, - [In] short recordType, - [In] int options, - [In] IntPtr servers, - [Out] out IntPtr dnsResultList, - [Out] IntPtr reserved); + [GeneratedDllImport(global::Interop.Libraries.Dnsapi, EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode)] + internal static partial int DnsQuery( + string recordName, + short recordType, + int options, + IntPtr servers, + out IntPtr dnsResultList, + IntPtr reserved); /*VOID WINAPI DnsRecordListFree( PDNS_RECORD pRecordList, DNS_FREE_TYPE FreeType );*/ - [DllImport(global::Interop.Libraries.Dnsapi, CharSet = CharSet.Unicode)] - internal static extern void DnsRecordListFree( - [In] IntPtr dnsResultList, - [In] bool dnsFreeType); + [GeneratedDllImport(global::Interop.Libraries.Dnsapi, CharSet = CharSet.Unicode)] + internal static partial void DnsRecordListFree( + IntPtr dnsResultList, + bool dnsFreeType); /*DWORD DsCrackNames( HANDLE hDS, @@ -496,9 +496,9 @@ internal delegate int DsCrackNames( /*NTSTATUS LsaConnectUntrusted( PHANDLE LsaHandle );*/ - [DllImport(global::Interop.Libraries.Secur32)] - internal static extern uint LsaConnectUntrusted( - [Out] out LsaLogonProcessSafeHandle lsaHandle); + [GeneratedDllImport(global::Interop.Libraries.Secur32)] + internal static partial uint LsaConnectUntrusted( + out LsaLogonProcessSafeHandle lsaHandle); internal const int NegGetCallerName = 1; @@ -511,29 +511,29 @@ internal static extern uint LsaConnectUntrusted( PULONG ReturnBufferLength, PNTSTATUS ProtocolStatus );*/ - [DllImport(global::Interop.Libraries.Secur32)] - internal static extern uint LsaCallAuthenticationPackage( - [In] LsaLogonProcessSafeHandle lsaHandle, - [In] int authenticationPackage, - [In] NegotiateCallerNameRequest protocolSubmitBuffer, - [In] int submitBufferLength, - [Out] out IntPtr protocolReturnBuffer, - [Out] out int returnBufferLength, - [Out] out uint protocolStatus); + [GeneratedDllImport(global::Interop.Libraries.Secur32)] + internal static partial uint LsaCallAuthenticationPackage( + LsaLogonProcessSafeHandle lsaHandle, + int authenticationPackage, + in NegotiateCallerNameRequest protocolSubmitBuffer, + int submitBufferLength, + out IntPtr protocolReturnBuffer, + out int returnBufferLength, + out uint protocolStatus); /*NTSTATUS LsaFreeReturnBuffer( PVOID Buffer );*/ - [DllImport(global::Interop.Libraries.Secur32)] - internal static extern uint LsaFreeReturnBuffer( - [In] IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Secur32)] + internal static partial uint LsaFreeReturnBuffer( + IntPtr buffer); /*NTSTATUS LsaDeregisterLogonProcess( HANDLE LsaHandle );*/ - [DllImport(global::Interop.Libraries.Secur32)] - internal static extern int LsaDeregisterLogonProcess( - [In] IntPtr lsaHandle); + [GeneratedDllImport(global::Interop.Libraries.Secur32)] + internal static partial int LsaDeregisterLogonProcess( + IntPtr lsaHandle); /*int CompareString(LCID Locale, DWORD dwCmpFlags, @@ -542,14 +542,14 @@ internal static extern int LsaDeregisterLogonProcess( DWORD lpString2, DWORD cchCount2 );*/ - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CompareStringW", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern int CompareString( - [In] uint locale, - [In] uint dwCmpFlags, - [In] IntPtr lpString1, - [In] int cchCount1, - [In] IntPtr lpString2, - [In] int cchCount2); + [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CompareStringW", CharSet = CharSet.Unicode, SetLastError = true)] + internal static partial int CompareString( + uint locale, + uint dwCmpFlags, + IntPtr lpString1, + int cchCount1, + IntPtr lpString2, + int cchCount2); } internal sealed class NativeComInterfaces diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index a97d8499ab35c..94c2ae1f2906a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -103,7 +103,7 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string Debug.Assert(buffer != (IntPtr)0); - TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX(); + TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default; Marshal.PtrToStructure(buffer, domainInfo); // validate this is the trust that the user refers to @@ -200,7 +200,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string Debug.Assert(buffer != (IntPtr)0); // get the managed structre representation - TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX(); + TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default; Marshal.PtrToStructure(buffer, domainInfo); // validate this is the trust that the user refers to @@ -330,7 +330,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN try { - TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX(); + TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default; Marshal.PtrToStructure(buffer, domainInfo); // validate this is the trust that the user refers to @@ -479,8 +479,6 @@ internal static void VerifyTrust(DirectoryContext context, string? sourceName, s internal static void CreateTrust(DirectoryContext sourceContext, string? sourceName, DirectoryContext targetContext, string? targetName, bool isForest, TrustDirection direction, string password) { LSA_AUTH_INFORMATION? AuthData = null; - TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null; - TRUSTED_DOMAIN_INFORMATION_EX? tdi = null; IntPtr fileTime = (IntPtr)0; IntPtr unmanagedPassword = (IntPtr)0; IntPtr info = (IntPtr)0; @@ -519,7 +517,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); - AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION(); + TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default; if ((direction & TrustDirection.Inbound) != 0) { AuthInfoEx.IncomingAuthInfos = 1; @@ -534,12 +532,14 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0; } - tdi = new TRUSTED_DOMAIN_INFORMATION_EX(); - tdi.FlatName = domainInfo.Name; - tdi.Name = domainInfo.DnsDomainName; - tdi.Sid = domainInfo.Sid; - tdi.TrustType = TRUST_TYPE_UPLEVEL; - tdi.TrustDirection = (int)direction; + TRUSTED_DOMAIN_INFORMATION_EX tdi = new TRUSTED_DOMAIN_INFORMATION_EX() + { + FlatName = domainInfo.Name, + Name = domainInfo.DnsDomainName, + Sid = domainInfo.Sid, + TrustType = TRUST_TYPE_UPLEVEL, + TrustDirection = (int)direction + }; if (isForest) { tdi.TrustAttributes = TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE; @@ -605,7 +605,6 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, IntPtr fileTime = (IntPtr)0; IntPtr unmanagedPassword = (IntPtr)0; IntPtr unmanagedAuthData = (IntPtr)0; - TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null; TrustDirection direction; IntPtr target = (IntPtr)0; string? serverName = null; @@ -673,7 +672,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); - AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION(); + TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default; if ((direction & TrustDirection.Inbound) != 0) { AuthInfoEx.IncomingAuthInfos = 1; @@ -738,7 +737,6 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour IntPtr fileTime = (IntPtr)0; IntPtr unmanagedPassword = (IntPtr)0; IntPtr unmanagedAuthData = (IntPtr)0; - TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null; IntPtr target = (IntPtr)0; string? serverName = null; @@ -802,7 +800,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); - AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION(); + TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx; if ((newTrustDirection & TrustDirection.Inbound) != 0) { AuthInfoEx.IncomingAuthInfos = 1; @@ -897,7 +895,7 @@ private static void ValidateTrust(SafeLsaPolicyHandle handle, UNICODE_STRING tru try { - TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX(); + TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default; Marshal.PtrToStructure(buffer, domainInfo); // validate this is the trust that the user refers to diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs index 93c205095d9ff..240186f7ff8ab 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs @@ -454,7 +454,7 @@ internal sealed class LSA_FOREST_TRUST_BINARY_DATA } [StructLayout(LayoutKind.Sequential)] - internal sealed class TRUSTED_DOMAIN_INFORMATION_EX + internal struct TRUSTED_DOMAIN_INFORMATION_EX { public UNICODE_STRING Name; public UNICODE_STRING FlatName; @@ -499,7 +499,7 @@ internal sealed class NETLOGON_INFO_2 } [StructLayout(LayoutKind.Sequential)] - internal sealed class TRUSTED_DOMAIN_AUTH_INFORMATION + internal struct TRUSTED_DOMAIN_AUTH_INFORMATION { public int IncomingAuthInfos; public IntPtr IncomingAuthenticationInformation; @@ -537,7 +537,7 @@ internal sealed class TRUSTED_POSIX_OFFSET_INFO [StructLayout(LayoutKind.Sequential)] internal sealed class TRUSTED_DOMAIN_FULL_INFORMATION { - public TRUSTED_DOMAIN_INFORMATION_EX? Information; + public TRUSTED_DOMAIN_INFORMATION_EX Information; internal TRUSTED_POSIX_OFFSET_INFO? PosixOffset; public TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInformation; } @@ -574,7 +574,7 @@ internal struct POLICY_ACCOUNT_DOMAIN_INFO public IntPtr DomainSid; } - internal static class UnsafeNativeMethods + internal static partial class UnsafeNativeMethods { public delegate int DsReplicaConsistencyCheck([In]IntPtr handle, int taskID, int flags); @@ -588,57 +588,57 @@ internal static class UnsafeNativeMethods public delegate int DsReplicaSyncAllW(IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string partition, int flags, SyncReplicaFromAllServersCallback callback, IntPtr data, ref IntPtr error); - [DllImport(global::Interop.Libraries.Activeds, EntryPoint = "ADsEncodeBinaryData", CharSet = CharSet.Unicode)] - public static extern int ADsEncodeBinaryData(byte[] data, int length, ref IntPtr result); + [GeneratedDllImport(global::Interop.Libraries.Activeds, EntryPoint = "ADsEncodeBinaryData", CharSet = CharSet.Unicode)] + public static partial int ADsEncodeBinaryData(byte[] data, int length, ref IntPtr result); - [DllImport(global::Interop.Libraries.Activeds, EntryPoint = "FreeADsMem")] - public static extern bool FreeADsMem(IntPtr pVoid); + [GeneratedDllImport(global::Interop.Libraries.Activeds, EntryPoint = "FreeADsMem")] + public static partial bool FreeADsMem(IntPtr pVoid); - [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetSiteNameW", CharSet = CharSet.Unicode)] - public static extern int DsGetSiteName(string? dcName, ref IntPtr ptr); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetSiteNameW", CharSet = CharSet.Unicode)] + public static partial int DsGetSiteName(string? dcName, ref IntPtr ptr); public delegate int DsListDomainsInSiteW(IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string site, ref IntPtr info); public delegate void DsFreeNameResultW(IntPtr result); - [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsEnumerateDomainTrustsW", CharSet = CharSet.Unicode)] - public static extern int DsEnumerateDomainTrustsW(string serverName, int flags, out IntPtr domains, out int count); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsEnumerateDomainTrustsW", CharSet = CharSet.Unicode)] + public static partial int DsEnumerateDomainTrustsW(string serverName, int flags, out IntPtr domains, out int count); - [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")] - public static extern int NetApiBufferFree(IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")] + public static partial int NetApiBufferFree(IntPtr buffer); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")] - public static extern uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")] + public static partial uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")] - public static extern uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, ref IntPtr ForestTrustInfo); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")] + public static partial uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, ref IntPtr ForestTrustInfo); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")] - public static extern uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")] + public static partial uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")] - public static extern uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")] + public static partial uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")] - public static extern uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")] + public static partial uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid); - [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "I_NetLogonControl2", CharSet = CharSet.Unicode)] - public static extern int I_NetLogonControl2(string serverName, int FunctionCode, int QueryLevel, IntPtr data, out IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "I_NetLogonControl2", CharSet = CharSet.Unicode)] + public static partial int I_NetLogonControl2(string serverName, int FunctionCode, int QueryLevel, IntPtr data, out IntPtr buffer); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")] - public static extern void GetSystemTimeAsFileTime(IntPtr fileTime); + [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")] + public static partial void GetSystemTimeAsFileTime(IntPtr fileTime); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaCreateTrustedDomainEx")] - public static extern uint LsaCreateTrustedDomainEx(SafeLsaPolicyHandle handle, TRUSTED_DOMAIN_INFORMATION_EX domainEx, TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaCreateTrustedDomainEx")] + public static partial uint LsaCreateTrustedDomainEx(SafeLsaPolicyHandle handle, in TRUSTED_DOMAIN_INFORMATION_EX domainEx, in TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle); - [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)] - public static extern IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID); + [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)] + public static partial IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID); - [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)] - public static extern int ImpersonateAnonymousToken(IntPtr token); + [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)] + public static partial int ImpersonateAnonymousToken(IntPtr token); - [DllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")] - public static extern int RtlInitUnicodeString(out UNICODE_STRING result, IntPtr s); + [GeneratedDllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")] + public static partial int RtlInitUnicodeString(out UNICODE_STRING result, IntPtr s); /* DWORD DsRoleGetPrimaryDomainInformation( @@ -647,16 +647,16 @@ DWORD DsRoleGetPrimaryDomainInformation( PBYTE* Buffer ); */ - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)] - public static extern int DsRoleGetPrimaryDomainInformation( + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)] + public static partial int DsRoleGetPrimaryDomainInformation( [MarshalAs(UnmanagedType.LPTStr)] string lpServer, - [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, + DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, out IntPtr Buffer); - [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)] - public static extern int DsRoleGetPrimaryDomainInformation( - [In] IntPtr lpServer, - [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, + [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)] + public static partial int DsRoleGetPrimaryDomainInformation( + IntPtr lpServer, + DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, out IntPtr Buffer); /* @@ -664,8 +664,8 @@ void DsRoleFreeMemory( PVOID Buffer ); */ - [DllImport(global::Interop.Libraries.Netapi32)] - public static extern int DsRoleFreeMemory( - [In] IntPtr buffer); + [GeneratedDllImport(global::Interop.Libraries.Netapi32)] + public static partial int DsRoleFreeMemory( + IntPtr buffer); } } From c9d6265dd6abff66525cd37885e953cd0988f29d Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Wed, 1 Dec 2021 13:30:06 -0800 Subject: [PATCH 4/6] Remove 'using * = Interop.*' --- .../src/Interop/UnsafeNativeMethods.cs | 4 +- .../ActiveDirectory/ActiveDirectorySite.cs | 6 +- .../ActiveDirectory/DirectoryContext.cs | 13 +-- .../ActiveDirectory/DirectoryServer.cs | 18 ++-- .../ActiveDirectory/DomainController.cs | 10 +- .../ActiveDirectory/Forest.cs | 6 +- .../ForestTrustDomainInformation.cs | 7 +- .../ForestTrustRelationshipInformation.cs | 23 ++--- .../ActiveDirectory/TrustHelper.cs | 59 ++++++------ .../ActiveDirectory/UnsafeNativeMethods.cs | 28 +++--- .../ActiveDirectory/Utils.cs | 91 +++++++++---------- 11 files changed, 118 insertions(+), 147 deletions(-) diff --git a/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs index a0bfff3a4d6ab..7b4922c71fece 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs @@ -4,8 +4,6 @@ using System.Runtime.InteropServices; using System.Security; -using Activeds = Interop.Activeds; - namespace System.DirectoryServices.Interop { @@ -34,7 +32,7 @@ public static int ADsOpenObject(string path, string? userName, string? password, { try { - return Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject); + return global::Interop.Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject); } catch (EntryPointNotFoundException) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index bc3312201f708..1307a7ea7b873 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -7,8 +7,6 @@ using System.Text; using System.Diagnostics.CodeAnalysis; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { [Flags] @@ -1308,7 +1306,7 @@ private void GetDomains() IntPtr info = (IntPtr)0; // call DsReplicaSyncAllW - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1350,7 +1348,7 @@ private void GetDomains() finally { // call DsFreeNameResultW - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs index 3d2efcaff3c20..021afb3e35a15 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs @@ -11,9 +11,6 @@ using Microsoft.Win32.SafeHandles; -using Advapi32 = Interop.Advapi32; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { public enum DirectoryContextType @@ -603,7 +600,7 @@ internal static string GetLoggedOnDomain() { throw new OutOfMemoryException(); } - else if ((result == 0) && (Advapi32.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION)) + else if ((result == 0) && (global::Interop.Advapi32.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION)) { // If this is a directory user, extract domain info from username if (!Utils.IsSamUser()) @@ -617,7 +614,7 @@ internal static string GetLoggedOnDomain() } else { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus)); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus)); } } } @@ -635,7 +632,7 @@ internal static string GetLoggedOnDomain() } else { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result)); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result)); } // If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.), @@ -693,7 +690,7 @@ private static void GetLibraryHandle() { // first get AD handle string systemPath = Environment.SystemDirectory; - IntPtr tempHandle = Kernel32.LoadLibrary(systemPath + "\\ntdsapi.dll"); + IntPtr tempHandle = global::Interop.Kernel32.LoadLibrary(systemPath + "\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -706,7 +703,7 @@ private static void GetLibraryHandle() // not get the ADAM handle // got to the windows\adam directory DirectoryInfo windowsDirectory = Directory.GetParent(systemPath)!; - tempHandle = Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll"); + tempHandle = global::Interop.Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { ADAMHandle = ADHandle; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 17621444ba00e..3ca343977a087 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -7,8 +7,6 @@ using Microsoft.Win32.SafeHandles; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { public abstract class DirectoryServer : IDisposable @@ -298,7 +296,7 @@ internal void CheckIfDisposed() internal void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle) { // call DsReplicaConsistencyCheck - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -320,11 +318,11 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar // first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine // call DsReplicaGetInfo2W - functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W"); + functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W"); if (functionPtr == (IntPtr)0) { // a win2k machine which does not have it. - functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -344,7 +342,7 @@ internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondar if (needToTryAgain && result == DS_REPL_NOTSUPPORTED) { // this is the case that client is xp/win2k3, dc is win2k - functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -645,7 +643,7 @@ internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallb // we want to return the dn instead of DNS guid // call DsReplicaSyncAllW - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -676,7 +674,7 @@ internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallb { // release the memory if (errorInfo != (IntPtr)0) - Kernel32.LocalFree(errorInfo); + global::Interop.Kernel32.LocalFree(errorInfo); } } @@ -685,7 +683,7 @@ private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHa if (value != (IntPtr)0) { // call DsReplicaFreeInfo - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -725,7 +723,7 @@ internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, } // call DsReplicaSyncW - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs index 91a29aa659b4a..85591aa108ea2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -8,8 +8,6 @@ using System.Runtime.InteropServices; using System.Diagnostics; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { [Flags] @@ -1089,7 +1087,7 @@ private void GetDomainControllerInfo() GetDSHandle(); // call DsGetDomainControllerInfo - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1166,7 +1164,7 @@ private void GetDomainControllerInfo() if (dcInfoPtr != IntPtr.Zero) { // call DsFreeDomainControllerInfo - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1251,7 +1249,7 @@ private ArrayList GetRoles() GetDSHandle(); // Get the roles // call DsListRoles - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -1291,7 +1289,7 @@ private ArrayList GetRoles() if (rolesPtr != IntPtr.Zero) { // call DsFreeNameResult - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs index 03a99f40abce8..0c393abbbec88 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -8,8 +8,6 @@ using System.Runtime.InteropServices; using System.Diagnostics; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { public enum ForestMode : int @@ -886,7 +884,7 @@ private ArrayList GetSites() // Get the sites within the forest // call DsListSites - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -923,7 +921,7 @@ private ArrayList GetSites() if (sitesPtr != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs index ba7bc0c2bc644..27498d2b86273 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs @@ -4,9 +4,6 @@ using System.Runtime.InteropServices; using System.ComponentModel; -using Advapi32 = Interop.Advapi32; -using BOOL = Interop.BOOL; - namespace System.DirectoryServices.ActiveDirectory { public enum ForestTrustDomainStatus @@ -30,8 +27,8 @@ internal ForestTrustDomainInformation(int flag, LSA_FOREST_TRUST_DOMAIN_INFO dom NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2); string sidLocal; - BOOL result = Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal); - if (result == BOOL.FALSE) + global::Interop.BOOL result = global::Interop.Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal); + if (result == global::Interop.BOOL.FALSE) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs index ccc1addad7961..a209fc175d366 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs @@ -7,11 +7,6 @@ using Microsoft.Win32.SafeHandles; -using Advapi32 = Interop.Advapi32; -using BOOL = Interop.BOOL; -using Kernel32 = Interop.Kernel32; -using UNICODE_STRING = Interop.UNICODE_STRING; - namespace System.DirectoryServices.ActiveDirectory { public class ForestTrustRelationshipInformation : TrustRelationshipInformation @@ -192,8 +187,8 @@ public void Save() ForestTrustDomainInformation tmp = _domainInfo[i]; record.Time = tmp.time; IntPtr pSid = (IntPtr)0; - BOOL result = Advapi32.ConvertStringSidToSid(tmp.DomainSid, out pSid); - if (result == BOOL.FALSE) + global::Interop.BOOL result = global::Interop.Advapi32.ConvertStringSidToSid(tmp.DomainSid, out pSid); + if (result == global::Interop.BOOL.FALSE) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } @@ -273,7 +268,7 @@ public void Save() handle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(TargetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -281,7 +276,7 @@ public void Save() uint error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo); if (error != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(error), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(error), serverName); } // there is collision, throw proper exception so user can deal with it @@ -313,7 +308,7 @@ public void Save() for (int i = 0; i < sidList.Count; i++) { - Kernel32.LocalFree((IntPtr)sidList[i]!); + global::Interop.Kernel32.LocalFree((IntPtr)sidList[i]!); } if (records != (IntPtr)0) @@ -327,7 +322,7 @@ public void Save() } if (collisionInfo != (IntPtr)0) - Advapi32.LsaFreeMemory(collisionInfo); + global::Interop.Advapi32.LsaFreeMemory(collisionInfo); if (target != (IntPtr)0) Marshal.FreeHGlobal(target); @@ -361,7 +356,7 @@ private void GetForestTrustInfoHelper() try { // get the target name - UNICODE_STRING tmpName; + global::Interop.UNICODE_STRING tmpName; targetPtr = Marshal.StringToHGlobalUni(TargetName); UnsafeNativeMethods.RtlInitUnicodeString(out tmpName, targetPtr); @@ -377,7 +372,7 @@ private void GetForestTrustInfoHelper() // check the result if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); if (win32Error != 0) { throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); @@ -441,7 +436,7 @@ private void GetForestTrustInfoHelper() } finally { - Advapi32.LsaFreeMemory(forestTrustInfo); + global::Interop.Advapi32.LsaFreeMemory(forestTrustInfo); } _topLevelNames = tmpTLNs; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index 94c2ae1f2906a..170c757523312 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -7,9 +7,6 @@ using Microsoft.Win32.SafeHandles; -using Advapi32 = Interop.Advapi32; -using UNICODE_STRING = Interop.UNICODE_STRING; - namespace System.DirectoryServices.ActiveDirectory { internal enum TRUSTED_INFORMATION_CLASS @@ -81,14 +78,14 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string handle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -150,7 +147,7 @@ internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); } } catch { throw; } @@ -177,7 +174,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string handle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -185,7 +182,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -262,7 +259,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName); } return; @@ -276,7 +273,7 @@ internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); if (newInfo != (IntPtr)0) Marshal.FreeHGlobal(newInfo); @@ -305,7 +302,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN policyHandle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -313,7 +310,7 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -340,14 +337,14 @@ internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceN result = UnsafeNativeMethods.LsaDeleteTrustedDomain(policyHandle, domainInfo.Sid); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName); } } finally { if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); } } finally @@ -386,7 +383,7 @@ internal static void VerifyTrust(DirectoryContext context, string? sourceName, s policyHandle = Utils.GetPolicyHandle(policyServerName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -559,7 +556,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN uint result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle); if (result != 0) { - result = Advapi32.LsaNtStatusToWinError(result); + result = global::Interop.Advapi32.LsaNtStatusToWinError(result); if (result == ERROR_ALREADY_EXISTS) { if (isForest) @@ -580,10 +577,10 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN Marshal.FreeHGlobal(fileTime); if (domainHandle != (IntPtr)0) - Advapi32.LsaClose(domainHandle); + global::Interop.Advapi32.LsaClose(domainHandle); if (info != (IntPtr)0) - Advapi32.LsaFreeMemory(info); + global::Interop.Advapi32.LsaFreeMemory(info); if (unmanagedPassword != (IntPtr)0) Marshal.FreeHGlobal(unmanagedPassword); @@ -621,7 +618,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, handle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -629,7 +626,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -695,7 +692,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName); } return serverName; @@ -709,7 +706,7 @@ internal static string UpdateTrust(DirectoryContext context, string? sourceName, Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); if (newBuffer != (IntPtr)0) Marshal.FreeHGlobal(newBuffer); @@ -752,7 +749,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour handle = Utils.GetPolicyHandle(serverName); // get the target name - UNICODE_STRING trustedDomainName; + global::Interop.UNICODE_STRING trustedDomainName; target = Marshal.StringToHGlobalUni(targetName); UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target); @@ -760,7 +757,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -838,7 +835,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName); } return; @@ -852,7 +849,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour Marshal.FreeHGlobal(target); if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); if (newBuffer != (IntPtr)0) Marshal.FreeHGlobal(newBuffer); @@ -870,7 +867,7 @@ internal static void UpdateTrustDirection(DirectoryContext context, string? sour catch { throw; } } - private static void ValidateTrust(SafeLsaPolicyHandle handle, UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) + private static void ValidateTrust(SafeLsaPolicyHandle handle, global::Interop.UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName) { IntPtr buffer = (IntPtr)0; @@ -878,7 +875,7 @@ private static void ValidateTrust(SafeLsaPolicyHandle handle, UNICODE_STRING tru uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer); if (result != 0) { - uint win32Error = Advapi32.LsaNtStatusToWinError(result); + uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result); // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND) { @@ -916,7 +913,7 @@ private static void ValidateTrust(SafeLsaPolicyHandle handle, UNICODE_STRING tru finally { if (buffer != (IntPtr)0) - Advapi32.LsaFreeMemory(buffer); + global::Interop.Advapi32.LsaFreeMemory(buffer); } } @@ -1018,10 +1015,10 @@ private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, strin policyHandle = Utils.GetPolicyHandle(serverName); } - uint result = Advapi32.LsaQueryInformationPolicy(policyHandle.DangerousGetHandle(), policyDnsDomainInformation, ref buffer); + uint result = global::Interop.Advapi32.LsaQueryInformationPolicy(policyHandle.DangerousGetHandle(), policyDnsDomainInformation, ref buffer); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName); } return buffer; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs index 240186f7ff8ab..84a9ab066b35e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs @@ -28,8 +28,6 @@ using Microsoft.Win32.SafeHandles; -using UNICODE_STRING = Interop.UNICODE_STRING; - namespace System.DirectoryServices.ActiveDirectory { @@ -414,7 +412,7 @@ internal sealed class LSA_FOREST_TRUST_RECORD [FieldOffset(8)] public LARGE_INTEGER Time = null!; [FieldOffset(16)] - public UNICODE_STRING TopLevelName; + public global::Interop.UNICODE_STRING TopLevelName; [FieldOffset(16)] public LSA_FOREST_TRUST_BINARY_DATA Data = null!; [FieldOffset(16)] @@ -456,8 +454,8 @@ internal sealed class LSA_FOREST_TRUST_BINARY_DATA [StructLayout(LayoutKind.Sequential)] internal struct TRUSTED_DOMAIN_INFORMATION_EX { - public UNICODE_STRING Name; - public UNICODE_STRING FlatName; + public global::Interop.UNICODE_STRING Name; + public global::Interop.UNICODE_STRING FlatName; public IntPtr Sid; public int TrustDirection; public int TrustType; @@ -477,7 +475,7 @@ internal sealed class LSA_FOREST_TRUST_COLLISION_RECORD public int Index; public ForestTrustCollisionType Type; public int Flags; - public UNICODE_STRING Name; + public global::Interop.UNICODE_STRING Name; } [StructLayout(LayoutKind.Sequential)] @@ -521,9 +519,9 @@ internal sealed class LSA_AUTH_INFORMATION [StructLayout(LayoutKind.Sequential)] internal sealed class POLICY_DNS_DOMAIN_INFO { - public UNICODE_STRING Name; - public UNICODE_STRING DnsDomainName; - public UNICODE_STRING DnsForestName; + public global::Interop.UNICODE_STRING Name; + public global::Interop.UNICODE_STRING DnsDomainName; + public global::Interop.UNICODE_STRING DnsForestName; public Guid DomainGuid; public IntPtr Sid; } @@ -570,7 +568,7 @@ internal sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct POLICY_ACCOUNT_DOMAIN_INFO { - public UNICODE_STRING DomainName; + public global::Interop.UNICODE_STRING DomainName; public IntPtr DomainSid; } @@ -608,16 +606,16 @@ internal static partial class UnsafeNativeMethods public static partial int NetApiBufferFree(IntPtr buffer); [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")] - public static partial uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); + public static partial uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo); [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")] - public static partial uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in UNICODE_STRING target, ref IntPtr ForestTrustInfo); + public static partial uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, ref IntPtr ForestTrustInfo); [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")] - public static partial uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); + public static partial uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer); [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")] - public static partial uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); + public static partial uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer); [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")] public static partial uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid); @@ -638,7 +636,7 @@ internal static partial class UnsafeNativeMethods public static partial int ImpersonateAnonymousToken(IntPtr token); [GeneratedDllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")] - public static partial int RtlInitUnicodeString(out UNICODE_STRING result, IntPtr s); + public static partial int RtlInitUnicodeString(out global::Interop.UNICODE_STRING result, IntPtr s); /* DWORD DsRoleGetPrimaryDomainInformation( diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index 20927221eb1bc..6898e76054307 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -10,9 +10,6 @@ using Microsoft.Win32.SafeHandles; -using Advapi32 = Interop.Advapi32; -using Kernel32 = Interop.Kernel32; - namespace System.DirectoryServices.ActiveDirectory { internal struct Component @@ -111,7 +108,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) Debug.Assert(distinguishedName != null); // call DsCrackNamesW - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -167,7 +164,7 @@ internal static string GetDnsNameFromDN(string distinguishedName) if (results != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -199,7 +196,7 @@ internal static string GetDNFromDnsName(string dnsName) Debug.Assert(dnsName != null); // call DsCrackNamesW - IntPtr functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -235,7 +232,7 @@ internal static string GetDNFromDnsName(string dnsName) if (results != IntPtr.Zero) { // call DsFreeNameResultW - functionPtr = Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); + functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -623,7 +620,7 @@ internal static IntPtr GetAuthIdentity(DirectoryContext context, SafeLibraryHand // create the credentials // call DsMakePasswordCredentialsW - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsMakePasswordCredentialsW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsMakePasswordCredentialsW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -648,7 +645,7 @@ internal static void FreeAuthIdentity(IntPtr authIdentity, SafeLibraryHandle lib if (authIdentity != IntPtr.Zero) { // call DsMakePasswordCredentialsW - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsFreePasswordCredentials"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsFreePasswordCredentials"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -665,7 +662,7 @@ internal static IntPtr GetDSHandle(string? domainControllerName, string? domainN // call DsBindWithCred Debug.Assert((domainControllerName != null && domainName == null) || (domainName != null && domainControllerName == null)); - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsBindWithCredW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsBindWithCredW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -686,7 +683,7 @@ internal static void FreeDSHandle(IntPtr dsHandle, SafeLibraryHandle libHandle) if (dsHandle != IntPtr.Zero) { // call DsUnbind - IntPtr functionPtr = Kernel32.GetProcAddress(libHandle, "DsUnBindW"); + IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsUnBindW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -932,14 +929,14 @@ internal static bool Impersonate(DirectoryContext context) Utils.GetDomainAndUsername(context, out userName, out domainName); - int result = Advapi32.LogonUser(userName!, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken); + int result = global::Interop.Advapi32.LogonUser(userName!, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken); // check the result if (result == 0) throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); try { - result = Advapi32.ImpersonateLoggedOnUser(hToken); + result = global::Interop.Advapi32.ImpersonateLoggedOnUser(hToken); if (result == 0) { result = Marshal.GetLastWin32Error(); @@ -949,7 +946,7 @@ internal static bool Impersonate(DirectoryContext context) finally { if (hToken != (IntPtr)0) - Kernel32.CloseHandle(hToken); + global::Interop.Kernel32.CloseHandle(hToken); } return true; @@ -957,7 +954,7 @@ internal static bool Impersonate(DirectoryContext context) internal static void ImpersonateAnonymous() { - IntPtr hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, Kernel32.GetCurrentThreadId()); + IntPtr hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, global::Interop.Kernel32.GetCurrentThreadId()); if (hThread == (IntPtr)0) throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); @@ -970,13 +967,13 @@ internal static void ImpersonateAnonymous() finally { if (hThread != (IntPtr)0) - Kernel32.CloseHandle(hThread); + global::Interop.Kernel32.CloseHandle(hThread); } } internal static void Revert() { - if (!Advapi32.RevertToSelf()) + if (!global::Interop.Advapi32.RevertToSelf()) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } @@ -1044,10 +1041,10 @@ internal static SafeLsaPolicyHandle GetPolicyHandle(string serverName) SafeLsaPolicyHandle handle; global::Interop.OBJECT_ATTRIBUTES objectAttribute = default; - uint result = Advapi32.LsaOpenPolicy(serverName, ref objectAttribute, (int)Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out handle); + uint result = global::Interop.Advapi32.LsaOpenPolicy(serverName, ref objectAttribute, (int)global::Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out handle); if (result != 0) { - throw ExceptionHelper.GetExceptionFromErrorCode((int)Advapi32.LsaNtStatusToWinError(result), serverName); + throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName); } return handle; @@ -2014,7 +2011,7 @@ internal static bool IsSamUser() // Does the user SID have the same domain as the machine SID? bool sameDomain = false; - bool success = Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain); + bool success = global::Interop.Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain); // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs Debug.Assert(success == true); @@ -2052,8 +2049,8 @@ internal static IntPtr GetCurrentUserSid() int error = 0; // Get the current thread's token - if (!Advapi32.OpenThreadToken( - Kernel32.GetCurrentThread(), + if (!global::Interop.Advapi32.OpenThreadToken( + global::Interop.Kernel32.GetCurrentThread(), TokenAccessLevels.Query, // TOKEN_QUERY true, out tokenHandle @@ -2064,8 +2061,8 @@ out tokenHandle Debug.Assert(tokenHandle.IsInvalid); // Current thread doesn't have a token, try the process - if (!Advapi32.OpenProcessToken( - Kernel32.GetCurrentProcess(), + if (!global::Interop.Advapi32.OpenProcessToken( + global::Interop.Kernel32.GetCurrentProcess(), (int)TokenAccessLevels.Query, out tokenHandle )) @@ -2086,9 +2083,9 @@ out tokenHandle // Retrieve the user info from the current thread's token // First, determine how big a buffer we need. - bool success = Advapi32.GetTokenInformation( + bool success = global::Interop.Advapi32.GetTokenInformation( tokenHandle.DangerousGetHandle(), - (uint)Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, + (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, 0, out neededBufferSize); @@ -2105,9 +2102,9 @@ out tokenHandle pBuffer = Marshal.AllocHGlobal((int)neededBufferSize); // Load the user info into the buffer - success = Advapi32.GetTokenInformation( + success = global::Interop.Advapi32.GetTokenInformation( tokenHandle.DangerousGetHandle(), - (uint)Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, + (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser, pBuffer, neededBufferSize, out neededBufferSize); @@ -2123,12 +2120,12 @@ out tokenHandle global::Interop.TOKEN_USER tokenUser = (global::Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(global::Interop.TOKEN_USER))!; IntPtr pUserSid = tokenUser.sidAndAttributes.Sid; // this is a reference into the NATIVE memory (into pBuffer) - Debug.Assert(Advapi32.IsValidSid(pUserSid)); + Debug.Assert(global::Interop.Advapi32.IsValidSid(pUserSid)); // Now we make a copy of the SID to return - int userSidLength = Advapi32.GetLengthSid(pUserSid); + int userSidLength = global::Interop.Advapi32.GetLengthSid(pUserSid); IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength); - success = Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid); + success = global::Interop.Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); @@ -2156,38 +2153,38 @@ internal static IntPtr GetMachineDomainSid() try { global::Interop.OBJECT_ATTRIBUTES oa = default; - uint err = Advapi32.LsaOpenPolicy( + uint err = global::Interop.Advapi32.LsaOpenPolicy( SystemName: null, ref oa, - (int)Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, + (int)global::Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out policyHandle); if (err != 0) { - throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, Advapi32.LsaNtStatusToWinError(err))); + throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, global::Interop.Advapi32.LsaNtStatusToWinError(err))); } Debug.Assert(!policyHandle.IsInvalid); - err = Advapi32.LsaQueryInformationPolicy( + err = global::Interop.Advapi32.LsaQueryInformationPolicy( policyHandle.DangerousGetHandle(), 5, // PolicyAccountDomainInformation ref pBuffer); if (err != 0) { - throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, Advapi32.LsaNtStatusToWinError(err))); + throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, global::Interop.Advapi32.LsaNtStatusToWinError(err))); } Debug.Assert(pBuffer != IntPtr.Zero); POLICY_ACCOUNT_DOMAIN_INFO info = (POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(POLICY_ACCOUNT_DOMAIN_INFO))!; - Debug.Assert(Advapi32.IsValidSid(info.DomainSid)); + Debug.Assert(global::Interop.Advapi32.IsValidSid(info.DomainSid)); // Now we make a copy of the SID to return - int sidLength = Advapi32.GetLengthSid(info.DomainSid); + int sidLength = global::Interop.Advapi32.GetLengthSid(info.DomainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); - bool success = Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid); + bool success = global::Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); @@ -2203,7 +2200,7 @@ internal static IntPtr GetMachineDomainSid() policyHandle.Dispose(); if (pBuffer != IntPtr.Zero) - Advapi32.LsaFreeMemory(pBuffer); + global::Interop.Advapi32.LsaFreeMemory(pBuffer); } } @@ -2242,15 +2239,15 @@ internal static bool IsMachineDC(string? computerName) internal static SidType ClassifySID(IntPtr pSid) { - Debug.Assert(Advapi32.IsValidSid(pSid)); + Debug.Assert(global::Interop.Advapi32.IsValidSid(pSid)); // Get the issuing authority and the first RID - IntPtr pIdentAuth = Advapi32.GetSidIdentifierAuthority(pSid); + IntPtr pIdentAuth = global::Interop.Advapi32.GetSidIdentifierAuthority(pSid); - Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = - (Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Advapi32.SID_IDENTIFIER_AUTHORITY))!; + global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = + (global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY))!; - IntPtr pRid = Advapi32.GetSidSubAuthority(pSid, 0); + IntPtr pRid = global::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. @@ -2281,9 +2278,9 @@ internal static SidType ClassifySID(IntPtr pSid) internal static int GetLastRidFromSid(IntPtr pSid) { - IntPtr pRidCount = Advapi32.GetSidSubAuthorityCount(pSid); + IntPtr pRidCount = global::Interop.Advapi32.GetSidSubAuthorityCount(pSid); int ridCount = Marshal.ReadByte(pRidCount); - IntPtr pLastRid = Advapi32.GetSidSubAuthority(pSid, ridCount - 1); + IntPtr pLastRid = global::Interop.Advapi32.GetSidSubAuthority(pSid, ridCount - 1); int lastRid = Marshal.ReadInt32(pLastRid); return lastRid; From a8a2570fd56ae8be4f1809aa0aa3e8e922891c3d Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Wed, 1 Dec 2021 13:51:37 -0800 Subject: [PATCH 5/6] PR feedback --- .../src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs | 3 ++- .../src/System/DirectoryServices/AccountManagement/interopt.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs index 0ea2bf741ab4b..693c134aea7ef 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs @@ -16,7 +16,8 @@ internal SafeLibraryHandle(IntPtr value) : base(true) protected override bool ReleaseHandle() { - return Interop.Kernel32.FreeLibrary(handle); + System.Runtime.InteropServices.NativeLibrary.Free(handle); + return true; } } } 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 2782c8e274bae..23ef181e99bfd 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 @@ -435,7 +435,7 @@ public sealed class WKSTA_INFO_100 public int wki100_ver_minor; }; - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] public struct POLICY_ACCOUNT_DOMAIN_INFO { public Interop.UNICODE_INTPTR_STRING DomainName; From 7224f176b78b0ff0458613d148cf24a69f3b945b Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Wed, 1 Dec 2021 14:42:31 -0800 Subject: [PATCH 6/6] Switch back to FreeLibrary --- .../src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs index 693c134aea7ef..0ea2bf741ab4b 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs @@ -16,8 +16,7 @@ internal SafeLibraryHandle(IntPtr value) : base(true) protected override bool ReleaseHandle() { - System.Runtime.InteropServices.NativeLibrary.Free(handle); - return true; + return Interop.Kernel32.FreeLibrary(handle); } } }