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);
}
}
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);
}
}
[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);
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;
// 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);
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;
{
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;
}
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();
public int wki100_ver_minor;
};
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public sealed class POLICY_ACCOUNT_DOMAIN_INFO
+ [StructLayout(LayoutKind.Sequential)]
+ 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;
}
}
}
namespace System.DirectoryServices.Interop
{
- internal static class SafeNativeMethods
+ internal static partial class SafeNativeMethods
{
- [DllImport(global::Interop.Libraries.OleAut32, PreserveSig = false)]
- public static extern void VariantClear(IntPtr pObject);
+ [GeneratedDllImport(global::Interop.Libraries.OleAut32)]
+ public static partial void VariantInit(IntPtr pObject);
- [DllImport(global::Interop.Libraries.OleAut32)]
- public static extern 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,
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
{
}
finally
{
- VariantClear(addr);
+ global::Interop.OleAut32.VariantClear(addr);
}
}
finally
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 global::Interop.Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
}
catch (EntryPointNotFoundException)
{
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
+ <!-- Suppressions to avoid ifdefs:
+ CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
+ CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
+ <NoWarn>$(NoWarn);CA1845;CA1846</NoWarn>
<Nullable>enable</Nullable>
<IsPackable>true</IsPackable>
<AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
<Compile Include="Interop\NativeMethods.cs" />
<Compile Include="Interop\SafeNativeMethods.cs" />
<Compile Include="Interop\UnsafeNativeMethods.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs"
+ Link="Common\Interop\Windows\Interop.BOOL.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOLEAN.cs"
+ Link="Common\Interop\Windows\Interop.BOOLEAN.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
- <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="System\Obsoletions.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs"
+ Link="Common\Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs"
+ Link="Common\Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs"
+ Link="Common\Interop\Windows\Interop.UNICODE_STRING.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Activeds\Interop.ADsOpenObject.cs"
+ Link="Common\Interop\Windows\Activeds\Interop.ADsOpenObject.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CopySid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.CopySid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.EqualDomainSid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.EqualDomainSid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetLengthSid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.GetLengthSid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.GetTokenInformation.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.IsValidSid.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.IsValidSid.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LogonUser.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LogonUser.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaClose.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LsaClose.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenProcessToken.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.OpenProcessToken.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.RevertToSelf.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.RevertToSelf.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs"
+ Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FreeLibrary.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.FreeLibrary.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThread.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThread.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetProcAddress.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.GetProcAddress.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LoadLibrary.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.LoadLibrary.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LocalAlloc.cs"
+ Link="Common\Interop\Windows\Kernel32\Interop.LocalAlloc.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\OleAut32\Interop.VariantClear.cs"
+ Link="Common\Interop\Windows\OleAut32\Interop.VariantClear.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtStatus.cs"
+ Link="Common\Interop\Windows\NtDll\Interop.NtStatus.cs" />
+ <Compile Include="$(CommonPath)Interop\Windows\SspiCli\Interop.TOKENS.cs"
+ Link="Common\Interop\Windows\SspiCli\Interop.TOKENS.cs" />
+ <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs"
+ Link="Common\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs" />
+ <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs"
+ Link="Common\Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs" />
+ <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeTokenHandle.cs"
+ Link="Common\Microsoft\Win32\SafeHandles\SafeTokenHandle.cs" />
+ <Compile Include="$(CommonPath)System\Obsoletions.cs"
+ Link="System\Obsoletions.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" />
<Reference Include="System.Diagnostics.Debug" />
<Reference Include="System.IO.FileSystem" />
<Reference Include="System.IO.FileSystem.AccessControl" />
+ <Reference Include="System.Memory" />
<Reference Include="System.Net.NameResolution" />
<Reference Include="System.Net.Primitives" />
<Reference Include="System.Net.Security" />
<Reference Include="System.Resources.ResourceManager" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.Extensions" />
+ <Reference Include="System.Runtime.CompilerServices.Unsafe" />
<Reference Include="System.Runtime.InteropServices" />
<Reference Include="System.Security.AccessControl" />
<Reference Include="System.Security.Claims" />
IntPtr info = (IntPtr)0;
// call DsReplicaSyncAllW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
finally
{
// call DsFreeNameResultW
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
using System.IO;
using System.Diagnostics.CodeAnalysis;
+using Microsoft.Win32.SafeHandles;
+
namespace System.DirectoryServices.ActiveDirectory
{
public enum DirectoryContextType
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
{
string? domainName = null;
- NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest();
+ NegotiateCallerNameRequest requestBuffer = default;
int requestBufferLength = (int)Marshal.SizeOf(requestBuffer);
IntPtr pResponseBuffer = IntPtr.Zero;
NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse();
int responseBufferLength;
- int protocolStatus;
- int result;
+ uint protocolStatus;
+ uint result;
LsaLogonProcessSafeHandle lsaHandle;
}
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) && (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())
}
else
{
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
}
}
}
}
}
}
- 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)global::Interop.Advapi32.LsaNtStatusToWinError(result));
}
// If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.),
{
// first get AD handle
string systemPath = Environment.SystemDirectory;
- IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll");
+ IntPtr tempHandle = global::Interop.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 = global::Interop.Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
ADAMHandle = ADHandle;
}
else
{
- ADAMHandle = new LoadLibrarySafeHandle(tempHandle);
+ ADAMHandle = new SafeLibraryHandle(tempHandle);
}
}
// 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;
+
namespace System.DirectoryServices.ActiveDirectory
{
public abstract class DirectoryServer : IDisposable
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 = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
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;
// first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
// call DsReplicaGetInfo2W
- functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
if (functionPtr == (IntPtr)0)
{
// a win2k machine which does not have it.
- functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
{
// this is the case that client is xp/win2k3, dc is win2k
- functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
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;
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);
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;
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;
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;
}
}
- 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;
// we want to return the dn instead of DNS guid
// call DsReplicaSyncAllW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncAllW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
{
// release the memory
if (errorInfo != (IntPtr)0)
- UnsafeNativeMethods.LocalFree(errorInfo);
+ global::Interop.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 = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
}
- 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;
}
// call DsReplicaSyncW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
GetDSHandle();
// call DsGetDomainControllerInfo
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (dcInfoPtr != IntPtr.Zero)
{
// call DsFreeDomainControllerInfo
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
GetDSHandle();
// Get the roles
// call DsListRoles
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (rolesPtr != IntPtr.Zero)
{
// call DsFreeNameResult
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
// Get the sites within the forest
// call DsListSites
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (sitesPtr != IntPtr.Zero)
{
// call DsFreeNameResultW
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
_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;
+ global::Interop.BOOL result = global::Interop.Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal);
+ if (result == global::Interop.BOOL.FALSE)
{
- DomainSid = Marshal.PtrToStringUni(ptr)!;
- }
- finally
- {
- UnsafeNativeMethods.LocalFree(ptr);
+ throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
+ DomainSid = sidLocal;
this.time = time;
}
using System.Collections;
using System.Collections.Specialized;
+using Microsoft.Win32.SafeHandles;
+
namespace System.DirectoryServices.ActiveDirectory
{
public class ForestTrustRelationshipInformation : TrustRelationshipInformation
int currentCount = 0;
IntPtr tmpPtr = (IntPtr)0;
IntPtr forestInfo = (IntPtr)0;
- PolicySafeHandle? handle = null;
- LSA_UNICODE_STRING trustedDomainName;
+ SafeLsaPolicyHandle? handle = null;
IntPtr collisionInfo = (IntPtr)0;
ArrayList ptrList = new ArrayList();
ArrayList sidList = new ArrayList();
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);
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);
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)
+ global::Interop.BOOL result = global::Interop.Advapi32.ConvertStringSidToSid(tmp.DomainSid, out pSid);
+ if (result == global::Interop.BOOL.FALSE)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
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();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(TargetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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)global::Interop.Advapi32.LsaNtStatusToWinError(error), serverName);
}
// there is collision, throw proper exception so user can deal with it
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
for (int i = 0; i < sidList.Count; i++)
{
- UnsafeNativeMethods.LocalFree((IntPtr)sidList[i]!);
+ global::Interop.Kernel32.LocalFree((IntPtr)sidList[i]!);
}
if (records != (IntPtr)0)
}
if (collisionInfo != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(collisionInfo);
+ global::Interop.Advapi32.LsaFreeMemory(collisionInfo);
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
private void GetForestTrustInfoHelper()
{
IntPtr forestTrustInfo = (IntPtr)0;
- PolicySafeHandle? handle = null;
- LSA_UNICODE_STRING? tmpName = null;
+ SafeLsaPolicyHandle? handle = null;
bool impersonated = false;
IntPtr targetPtr = (IntPtr)0;
string? serverName = null;
try
{
// get the target name
- tmpName = new LSA_UNICODE_STRING();
+ global::Interop.UNICODE_STRING tmpName;
targetPtr = Marshal.StringToHGlobalUni(TargetName);
- UnsafeNativeMethods.RtlInitUnicodeString(tmpName, targetPtr);
+ UnsafeNativeMethods.RtlInitUnicodeString(out tmpName, targetPtr);
serverName = Utils.GetPolicyServerName(context, true, false, source);
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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
if (win32Error != 0)
{
- throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
}
}
}
finally
{
- UnsafeNativeMethods.LsaFreeMemory(forestTrustInfo);
+ global::Interop.Advapi32.LsaFreeMemory(forestTrustInfo);
}
_topLevelNames = tmpTLNs;
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 ;
} NEGOTIATE_CALLER_NAME_REQUEST, *PNEGOTIATE_CALLER_NAME_REQUEST ;*/
[StructLayout(LayoutKind.Sequential)]
- internal sealed class NegotiateCallerNameRequest
+ internal struct NegotiateCallerNameRequest
{
public int messageType;
- public LUID? logonId;
+ public global::Interop.LUID logonId;
}
/*typedef struct _NEGOTIATE_CALLER_NAME_RESPONSE {
public string? callerName;
}
- internal sealed class NativeMethods
+ internal sealed partial class NativeMethods
{
// disable public constructor
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,
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,
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,
[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;
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);
-
- /*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);
+ [GeneratedDllImport(global::Interop.Libraries.Dnsapi, CharSet = CharSet.Unicode)]
+ internal static partial void DnsRecordListFree(
+ IntPtr dnsResultList,
+ bool dnsFreeType);
/*DWORD DsCrackNames(
HANDLE hDS,
/*NTSTATUS LsaConnectUntrusted(
PHANDLE LsaHandle
);*/
- [DllImport(global::Interop.Libraries.Secur32)]
- internal static extern int LsaConnectUntrusted(
- [Out] out LsaLogonProcessSafeHandle lsaHandle);
+ [GeneratedDllImport(global::Interop.Libraries.Secur32)]
+ internal static partial uint LsaConnectUntrusted(
+ out LsaLogonProcessSafeHandle lsaHandle);
internal const int NegGetCallerName = 1;
PULONG ReturnBufferLength,
PNTSTATUS ProtocolStatus
);*/
- [DllImport(global::Interop.Libraries.Secur32)]
- internal static extern int 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);
+ [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,
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);
-
- [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
- internal static extern int LsaNtStatusToWinError(int ntStatus);
+ [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
// 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) { }
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;
- }
}
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);
using System.Diagnostics;
using System.Security.Cryptography;
+using Microsoft.Win32.SafeHandles;
+
namespace System.DirectoryServices.ActiveDirectory
{
internal enum TRUSTED_INFORMATION_CLASS
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;
IntPtr target = (IntPtr)0;
string? serverName = null;
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();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(targetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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);
- 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
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
}
}
catch { throw; }
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;
bool impersonated = false;
IntPtr target = (IntPtr)0;
string? serverName = null;
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();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(targetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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);
// 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
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo);
if (result != 0)
{
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
}
return;
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
if (newInfo != (IntPtr)0)
Marshal.FreeHGlobal(newInfo);
internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceName, string? targetName, bool isForest)
{
- PolicySafeHandle? policyHandle = null;
- LSA_UNICODE_STRING? trustedDomainName = null;
- int win32Error = 0;
+ SafeLsaPolicyHandle? policyHandle = null;
bool impersonated = false;
IntPtr target = (IntPtr)0;
string? serverName = null;
try
{
// get the policy handle
- policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+ policyHandle = Utils.GetPolicyHandle(serverName);
// get the target name
- trustedDomainName = new LSA_UNICODE_STRING();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(targetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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);
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
result = UnsafeNativeMethods.LsaDeleteTrustedDomain(policyHandle, domainInfo.Sid);
if (result != 0)
{
- win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
- throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+ uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
}
}
finally
{
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
}
}
finally
internal static void VerifyTrust(DirectoryContext context, string? sourceName, string? targetName, bool isForest, TrustDirection direction, bool forceSecureChannelReset, string? preferredTargetServer)
{
- PolicySafeHandle? policyHandle = null;
- LSA_UNICODE_STRING? trustedDomainName = null;
+ SafeLsaPolicyHandle? policyHandle = null;
int win32Error = 0;
IntPtr data = (IntPtr)0;
IntPtr ptr = (IntPtr)0;
try
{
// get the policy handle
- policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(policyServerName));
+ policyHandle = Utils.GetPolicyHandle(policyServerName);
// get the target name
- trustedDomainName = new LSA_UNICODE_STRING();
+ global::Interop.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
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;
IntPtr domainHandle = (IntPtr)0;
- PolicySafeHandle? policyHandle = null;
+ SafeLsaPolicyHandle? policyHandle = null;
IntPtr unmanagedAuthData = (IntPtr)0;
bool impersonated = false;
string? serverName = null;
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;
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;
// 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
if (result == ERROR_ALREADY_EXISTS)
{
if (isForest)
throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingDomainTrust, sourceName, targetName));
}
else
- throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)result, serverName);
}
}
finally
Marshal.FreeHGlobal(fileTime);
if (domainHandle != (IntPtr)0)
- UnsafeNativeMethods.LsaClose(domainHandle);
+ global::Interop.Advapi32.LsaClose(domainHandle);
if (info != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(info);
+ global::Interop.Advapi32.LsaFreeMemory(info);
if (unmanagedPassword != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedPassword);
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;
bool impersonated = false;
LSA_AUTH_INFORMATION? AuthData = null;
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;
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();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(targetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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
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;
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
if (result != 0)
{
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
}
return serverName;
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
if (newBuffer != (IntPtr)0)
Marshal.FreeHGlobal(newBuffer);
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;
bool impersonated = false;
LSA_AUTH_INFORMATION? AuthData = null;
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;
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();
+ global::Interop.UNICODE_STRING trustedDomainName;
target = Marshal.StringToHGlobalUni(targetName);
- UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+ UnsafeNativeMethods.RtlInitUnicodeString(out 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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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
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;
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
if (result != 0)
{
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
}
return;
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
if (newBuffer != (IntPtr)0)
Marshal.FreeHGlobal(newBuffer);
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, global::Interop.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 = global::Interop.Advapi32.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
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);
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
finally
{
if (buffer != (IntPtr)0)
- UnsafeNativeMethods.LsaFreeMemory(buffer);
+ global::Interop.Advapi32.LsaFreeMemory(buffer);
}
}
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;
impersonated = Utils.Impersonate(targetContext);
try
{
- policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+ policyHandle = Utils.GetPolicyHandle(serverName);
}
catch (ActiveDirectoryOperationException)
{
// try anonymous
Utils.ImpersonateAnonymous();
impersonated = true;
- policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+ policyHandle = Utils.GetPolicyHandle(serverName);
}
catch (UnauthorizedAccessException)
{
// 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 = global::Interop.Advapi32.LsaQueryInformationPolicy(policyHandle.DangerousGetHandle(), policyDnsDomainInformation, ref buffer);
if (result != 0)
{
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
}
return buffer;
//}
using System.Runtime.InteropServices;
-using System.Security;
-using System.Text;
+
+using Microsoft.Win32.SafeHandles;
namespace System.DirectoryServices.ActiveDirectory
{
[FieldOffset(8)]
public LARGE_INTEGER Time = null!;
[FieldOffset(16)]
- public LSA_UNICODE_STRING TopLevelName = null!;
+ public global::Interop.UNICODE_STRING TopLevelName;
[FieldOffset(16)]
public LSA_FOREST_TRUST_BINARY_DATA Data = null!;
[FieldOffset(16)]
}
[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
{
public IntPtr sid;
}
[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
+ internal struct TRUSTED_DOMAIN_INFORMATION_EX
{
- public LSA_UNICODE_STRING? Name;
- public LSA_UNICODE_STRING? FlatName;
+ public global::Interop.UNICODE_STRING Name;
+ public global::Interop.UNICODE_STRING FlatName;
public IntPtr Sid;
public int TrustDirection;
public int TrustType;
public int Index;
public ForestTrustCollisionType Type;
public int Flags;
- public LSA_UNICODE_STRING Name = null!;
+ public global::Interop.UNICODE_STRING Name;
}
[StructLayout(LayoutKind.Sequential)]
}
[StructLayout(LayoutKind.Sequential)]
- internal sealed class TRUSTED_DOMAIN_AUTH_INFORMATION
+ internal struct TRUSTED_DOMAIN_AUTH_INFORMATION
{
public int IncomingAuthInfos;
public IntPtr IncomingAuthenticationInformation;
[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 global::Interop.UNICODE_STRING Name;
+ public global::Interop.UNICODE_STRING DnsDomainName;
+ public global::Interop.UNICODE_STRING DnsForestName;
public Guid DomainGuid;
public IntPtr Sid;
}
[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;
}
}
[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
+ internal struct POLICY_ACCOUNT_DOMAIN_INFO
{
- public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
- public IntPtr domainSid = IntPtr.Zero;
+ public global::Interop.UNICODE_STRING DomainName;
+ public IntPtr DomainSid;
}
- internal static class UnsafeNativeMethods
+ internal static partial class UnsafeNativeMethods
{
public delegate int DsReplicaConsistencyCheck([In]IntPtr handle, int taskID, int flags);
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);
+ [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);
-
- [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);
+ [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.Advapi32, EntryPoint = "LsaSetForestTrustInformation")]
- public static extern int LsaSetForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo);
+ [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")]
+ public static partial int NetApiBufferFree(IntPtr buffer);
- [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);
+ [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")]
+ public static partial uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo);
- [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaClose")]
- public static extern int LsaClose(IntPtr handle);
+ [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")]
+ public static partial uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, ref IntPtr ForestTrustInfo);
- [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")]
- public static extern int LsaQueryForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, ref IntPtr ForestTrustInfo);
+ [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")]
+ public static partial uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer);
- [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);
+ [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")]
+ public static partial uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer);
- [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaNtStatusToWinError")]
- public static extern int LsaNtStatusToWinError(int status);
+ [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")]
+ public static partial uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid);
- [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaFreeMemory")]
- public static extern int LsaFreeMemory(IntPtr ptr);
+ [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.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")]
- public static extern int LsaSetTrustedDomainInfoByName(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer);
+ [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")]
+ public static partial void GetSystemTimeAsFileTime(IntPtr fileTime);
- [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenTrustedDomainByName")]
- public static extern int LsaOpenTrustedDomainByName(PolicySafeHandle policyHandle, LSA_UNICODE_STRING trustedDomain, int access, ref IntPtr trustedDomainHandle);
+ [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.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")]
- public static extern int LsaDeleteTrustedDomain(PolicySafeHandle handle, IntPtr pSid);
+ [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)]
+ public static partial IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID);
- [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.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)]
+ public static partial int ImpersonateAnonymousToken(IntPtr token);
- [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);
-
- [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);
+ [GeneratedDllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")]
+ public static partial int RtlInitUnicodeString(out global::Interop.UNICODE_STRING result, IntPtr s);
/*
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);
- [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
);
*/
- [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);
}
}
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Diagnostics;
-using System.Globalization;
+
+using Microsoft.Win32.SafeHandles;
namespace System.DirectoryServices.ActiveDirectory
{
{
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;
Debug.Assert(distinguishedName != null);
// call DsCrackNamesW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (results != IntPtr.Zero)
{
// call DsFreeNameResultW
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
Debug.Assert(dnsName != null);
// call DsCrackNamesW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
if (results != IntPtr.Zero)
{
// call DsFreeNameResultW
- functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+ functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
}
- internal static IntPtr GetAuthIdentity(DirectoryContext context, LoadLibrarySafeHandle libHandle)
+ internal static IntPtr GetAuthIdentity(DirectoryContext context, SafeLibraryHandle libHandle)
{
IntPtr authIdentity;
int result = 0;
// create the credentials
// call DsMakePasswordCredentialsW
- IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsMakePasswordCredentialsW");
+ IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsMakePasswordCredentialsW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
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 = global::Interop.Kernel32.GetProcAddress(libHandle, "DsFreePasswordCredentials");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
}
- 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 = global::Interop.Kernel32.GetProcAddress(libHandle, "DsBindWithCredW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
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 = global::Interop.Kernel32.GetProcAddress(libHandle, "DsUnBindW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
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 = 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 = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken);
+ result = global::Interop.Advapi32.ImpersonateLoggedOnUser(hToken);
if (result == 0)
{
result = Marshal.GetLastWin32Error();
finally
{
if (hToken != (IntPtr)0)
- UnsafeNativeMethods.CloseHandle(hToken);
+ global::Interop.Kernel32.CloseHandle(hToken);
}
return true;
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, global::Interop.Kernel32.GetCurrentThreadId());
if (hThread == (IntPtr)0)
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
finally
{
if (hThread != (IntPtr)0)
- UnsafeNativeMethods.CloseHandle(hThread);
+ global::Interop.Kernel32.CloseHandle(hThread);
}
}
internal static void Revert()
{
- int error = UnsafeNativeMethods.RevertToSelf();
- // function failed
- if (error == 0)
+ if (!global::Interop.Advapi32.RevertToSelf())
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
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);
-
- try
- {
- int result = UnsafeNativeMethods.LsaOpenPolicy(systemName, objectAttribute, mask, out handle);
- if (result != 0)
- {
- throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
- }
+ SafeLsaPolicyHandle handle;
+ global::Interop.OBJECT_ATTRIBUTES objectAttribute = default;
- return handle;
- }
- finally
+ uint result = global::Interop.Advapi32.LsaOpenPolicy(serverName, ref objectAttribute, (int)global::Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out handle);
+ if (result != 0)
{
- if (target != (IntPtr)0)
- Marshal.FreeHGlobal(target);
+ throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
}
+
+ return handle;
}
//
// 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 = global::Interop.Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain);
// Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs
Debug.Assert(success == true);
internal static IntPtr GetCurrentUserSid()
{
- IntPtr pTokenHandle = IntPtr.Zero;
+ SafeTokenHandle? tokenHandle = null;
IntPtr pBuffer = IntPtr.Zero;
try
int error = 0;
// Get the current thread's token
- if (!UnsafeNativeMethods.OpenThreadToken(
- UnsafeNativeMethods.GetCurrentThread(),
- 0x8, // TOKEN_QUERY
+ if (!global::Interop.Advapi32.OpenThreadToken(
+ global::Interop.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 (!global::Interop.Advapi32.OpenProcessToken(
+ global::Interop.Kernel32.GetCurrentProcess(),
+ (int)TokenAccessLevels.Query,
+ out tokenHandle
))
{
int lastError = Marshal.GetLastWin32Error();
}
}
- 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 = global::Interop.Advapi32.GetTokenInformation(
+ tokenHandle.DangerousGetHandle(),
+ (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
IntPtr.Zero,
0,
- ref neededBufferSize);
+ out neededBufferSize);
int getTokenInfoError = 0;
if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER
// 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 = global::Interop.Advapi32.GetTokenInformation(
+ tokenHandle.DangerousGetHandle(),
+ (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
pBuffer,
neededBufferSize,
- ref neededBufferSize);
+ out neededBufferSize);
if (!success)
{
}
// 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(global::Interop.Advapi32.IsValidSid(pUserSid));
// Now we make a copy of the SID to return
- int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid);
+ int userSidLength = global::Interop.Advapi32.GetLengthSid(pUserSid);
IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength);
- success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
+ success = global::Interop.Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
if (!success)
{
int lastError = Marshal.GetLastWin32Error();
}
finally
{
- if (pTokenHandle != IntPtr.Zero)
- UnsafeNativeMethods.CloseHandle(pTokenHandle);
+ if (tokenHandle != null)
+ tokenHandle.Dispose();
if (pBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(pBuffer);
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 = global::Interop.Advapi32.LsaOpenPolicy(
+ SystemName: null,
+ ref oa,
+ (int)global::Interop.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, global::Interop.Advapi32.LsaNtStatusToWinError(err)));
}
- Debug.Assert(pPolicyHandle != IntPtr.Zero);
- err = UnsafeNativeMethods.LsaQueryInformationPolicy(
- pPolicyHandle,
+ Debug.Assert(!policyHandle.IsInvalid);
+ err = global::Interop.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, 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(UnsafeNativeMethods.IsValidSid(info.domainSid));
+ Debug.Assert(global::Interop.Advapi32.IsValidSid(info.DomainSid));
// Now we make a copy of the SID to return
- int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid);
+ int sidLength = global::Interop.Advapi32.GetLengthSid(info.DomainSid);
IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength);
- bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid);
+ bool success = global::Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid);
if (!success)
{
int lastError = Marshal.GetLastWin32Error();
}
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);
+ global::Interop.Advapi32.LsaFreeMemory(pBuffer);
}
}
internal static SidType ClassifySID(IntPtr pSid)
{
- Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid));
+ Debug.Assert(global::Interop.Advapi32.IsValidSid(pSid));
// Get the issuing authority and the first RID
- IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid);
+ IntPtr pIdentAuth = global::Interop.Advapi32.GetSidIdentifierAuthority(pSid);
- SID_IDENTIFIER_AUTHORITY identAuth =
- (SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(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 = UnsafeNativeMethods.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.
internal static int GetLastRidFromSid(IntPtr pSid)
{
- IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid);
+ IntPtr pRidCount = global::Interop.Advapi32.GetSidSubAuthorityCount(pSid);
int ridCount = Marshal.ReadByte(pRidCount);
- IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1);
+ IntPtr pLastRid = global::Interop.Advapi32.GetSidSubAuthority(pSid, ridCount - 1);
int lastRid = Marshal.ReadInt32(pLastRid);
return lastRid;