public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass) { uint length; if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out length)) { int error = Marshal.GetLastWin32Error(); if (error != (int)Win32Error.ERROR_INSUFFICIENT_BUFFER) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error))); } } SafeHandle buffer = SafeHGlobalHandle.AllocHGlobal(length); try { if (!SafeNativeMethods.GetTokenInformation(token, infoClass, buffer, length, out length)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error))); } } catch { buffer.Dispose(); throw; } return buffer; }
DuplicateTokenEx( [In] SafeCloseHandle ExistingToken, [In] TokenAccessLevels DesiredAccess, [In] IntPtr TokenAttributes, [In] SecurityImpersonationLevel ImpersonationLevel, [In] TokenType TokenType, [Out] out SafeCloseHandle NewToken);
public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass) { uint length; if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out length)) { int error = Marshal.GetLastWin32Error(); if (error != (int)Win32Error.ERROR_INSUFFICIENT_BUFFER) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error))); } } SafeHandle buffer = SafeHGlobalHandle.AllocHGlobal(length); try { if (!SafeNativeMethods.GetTokenInformation(token, infoClass, buffer, length, out length)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error))); } } catch { buffer.Dispose(); throw; } return(buffer); }
public static WindowsIdentity GetProcessIdentity() { SafeCloseHandle tokenHandle = null; lock (lockObject) { try { bool isSuccess = SafeNativeMethods.GetCurrentProcessToken(SafeNativeMethods.GetCurrentProcess(), TokenAccessLevels.Query, out tokenHandle); if (!isSuccess) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(tokenHandle); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenProcessTokenFailed, error))); } processIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle()); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } return(processIdentity); }
public IDisposable Impersonate() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The LastWin32Error can be ignored here. IntPtr threadHandle = SafeNativeMethods.GetCurrentThread(); SafeCloseHandle tokenHandle; if (!SafeNativeMethods.OpenCurrentThreadToken(threadHandle, TokenAccessLevels.Impersonate, true, out tokenHandle)) { int error = Marshal.GetLastWin32Error(); System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(tokenHandle); if (error == (int)System.ServiceModel.ComIntegration.Win32Error.ERROR_NO_TOKEN) { tokenHandle = new SafeCloseHandle(IntPtr.Zero, false); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } } if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(threadHandle)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } return(new ImpersonationContext(threadHandle, tokenHandle)); }
internal static bool IsPrimaryToken(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType)) { int level = Marshal.ReadInt32(buffer.DangerousGetHandle()); return(level == (int)TokenType.TokenPrimary); } }
internal static bool IsPrimaryToken(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType)) { int level = Marshal.ReadInt32(buffer.DangerousGetHandle()); return (level == (int)TokenType.TokenPrimary); } }
AccessCheck( [In] byte[] SecurityDescriptor, [In] SafeCloseHandle ClientToken, [In] int DesiredAccess, [In] GENERIC_MAPPING GenericMapping, [Out] out PRIVILEGE_SET PrivilegeSet, [In, Out] ref uint PrivilegeSetLength, [Out] out uint GrantedAccess, [Out] out bool AccessStatus);
internal static LUID GetModifiedIDLUID(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenStatistics)) { TOKEN_STATISTICS tokenStats = (TOKEN_STATISTICS) Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(TOKEN_STATISTICS)); return tokenStats.ModifiedId; } }
internal static LUID GetModifiedIDLUID(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenStatistics)) { TOKEN_STATISTICS tokenStats = (TOKEN_STATISTICS) Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(TOKEN_STATISTICS)); return(tokenStats.ModifiedId); } }
internal static bool IsAtleastImpersonationToken(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel)) { int level = Marshal.ReadInt32(buffer.DangerousGetHandle()); if (level < (int)SecurityImpersonationLevel.Impersonation) return false; else return true; } }
private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed) { if (null == securityDescriptor) { throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL"); } IsAccessAllowed = false; byte[] BinaryForm = new byte[securityDescriptor.BinaryLength]; securityDescriptor.GetBinaryForm(BinaryForm, 0); SafeCloseHandle ImpersonationToken = null; SafeCloseHandle clientIdentityToken = new SafeCloseHandle(clientIdentity.Token, false); try { if (SecurityUtils.IsPrimaryToken(clientIdentityToken)) { if (!SafeNativeMethods.DuplicateTokenEx(clientIdentityToken, TokenAccessLevels.Query, IntPtr.Zero, SecurityImpersonationLevel.Identification, TokenType.TokenImpersonation, out ImpersonationToken)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(ImpersonationToken); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.DuplicateTokenExFailed, error))); } } GENERIC_MAPPING GenericMapping = new GENERIC_MAPPING(); PRIVILEGE_SET PrivilegeSet = new PRIVILEGE_SET(); uint PrivilegeSetLength = (uint)Marshal.SizeOf(PrivilegeSet); uint GrantedAccess = 0; if (!SafeNativeMethods.AccessCheck(BinaryForm, (ImpersonationToken != null) ? ImpersonationToken : clientIdentityToken, (int)ComRights.EXECUTE, GenericMapping, out PrivilegeSet, ref PrivilegeSetLength, out GrantedAccess, out IsAccessAllowed)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.AccessCheckFailed, error))); } } finally { if (ImpersonationToken != null) { ImpersonationToken.Dispose(); } } }
internal static bool IsAtleastImpersonationToken(SafeCloseHandle token) { using (SafeHandle buffer = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel)) { int level = Marshal.ReadInt32(buffer.DangerousGetHandle()); if (level < (int)SecurityImpersonationLevel.Impersonation) { return(false); } else { return(true); } } }
// This api simply check if the calling thread is process primary thread. // We are not trying to be smart if the impersonation to the same user as // process token since privileges could be different. bool IsImpersonatedContext() { SafeCloseHandle tokenHandle = null; if (!SafeNativeMethods.OpenCurrentThreadToken( SafeNativeMethods.GetCurrentThread(), TokenAccessLevels.Query, true, out tokenHandle)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(tokenHandle); if (error == (int)Win32Error.ERROR_NO_TOKEN) { return(false); } System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(new Win32Exception(error)); return(true); } tokenHandle.Close(); return(true); }
protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateSspiNegotiation(ISspiNegotiation sspiNegotiation) { WindowsSspiNegotiation windowsNegotiation = (WindowsSspiNegotiation)sspiNegotiation; if (windowsNegotiation.IsValidContext == false) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidSspiNegotiation))); } SecurityTraceRecordHelper.TraceServiceSpnego(windowsNegotiation); if (this.IsClientAnonymous) { return(EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance); } using (SafeCloseHandle contextToken = windowsNegotiation.GetContextToken()) { WindowsIdentity windowsIdentity = new WindowsIdentity(contextToken.DangerousGetHandle(), windowsNegotiation.ProtocolName); SecurityUtils.ValidateAnonymityConstraint(windowsIdentity, this.AllowUnauthenticatedCallers); List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1); WindowsClaimSet wic = new WindowsClaimSet(windowsIdentity, windowsNegotiation.ProtocolName, this.extractGroupsForWindowsAccounts, false); policies.Add(new System.IdentityModel.Policy.UnconditionalPolicy(wic, TimeoutHelper.Add(DateTime.UtcNow, base.ServiceTokenLifetime))); return(policies.AsReadOnly()); } }
public IDisposable Impersonate() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The LastWin32Error can be ignored here. IntPtr threadHandle = SafeNativeMethods.GetCurrentThread(); SafeCloseHandle tokenHandle; if (!SafeNativeMethods.OpenCurrentThreadToken(threadHandle, TokenAccessLevels.Impersonate, true, out tokenHandle)) { int error = Marshal.GetLastWin32Error(); System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(tokenHandle); if (error == (int)System.ServiceModel.ComIntegration.Win32Error.ERROR_NO_TOKEN) { tokenHandle = new SafeCloseHandle(IntPtr.Zero, false); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } } if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(threadHandle)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } return new ImpersonationContext(threadHandle, tokenHandle); }
GetCurrentProcessToken( [In] IntPtr ProcessHandle, [In] TokenAccessLevels DesiredAccess, [Out] out SafeCloseHandle TokenHandle);
GetTokenInformation( [In] SafeCloseHandle TokenHandle, [In] TOKEN_INFORMATION_CLASS TokenInformationClass, [In] SafeHandle TokenInformation, [Out] uint TokenInformationLength, [Out] out uint ReturnLength);
SetCurrentThreadToken( [In] IntPtr ThreadHandle, [In] SafeCloseHandle TokenHandle);
OpenCurrentThreadToken( [In] IntPtr ThreadHandle, [In] TokenAccessLevels DesiredAccess, [In] bool OpenAsSelf, [Out] out SafeCloseHandle TokenHandle);
private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed) { if (null == securityDescriptor) { throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL"); } IsAccessAllowed = false; byte[] BinaryForm = new byte[securityDescriptor.BinaryLength]; securityDescriptor.GetBinaryForm(BinaryForm, 0); SafeCloseHandle ImpersonationToken = null; SafeCloseHandle clientIdentityToken = new SafeCloseHandle(clientIdentity.Token, false); try { if (SecurityUtils.IsPrimaryToken(clientIdentityToken)) { if (!SafeNativeMethods.DuplicateTokenEx(clientIdentityToken, TokenAccessLevels.Query, IntPtr.Zero, SecurityImpersonationLevel.Identification, TokenType.TokenImpersonation, out ImpersonationToken)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(ImpersonationToken); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.DuplicateTokenExFailed, error))); } } GENERIC_MAPPING GenericMapping = new GENERIC_MAPPING(); PRIVILEGE_SET PrivilegeSet = new PRIVILEGE_SET(); uint PrivilegeSetLength = (uint)Marshal.SizeOf(PrivilegeSet); uint GrantedAccess = 0; if (!SafeNativeMethods.AccessCheck(BinaryForm, (ImpersonationToken != null) ? ImpersonationToken : clientIdentityToken, (int)ComRights.EXECUTE, GenericMapping, out PrivilegeSet, ref PrivilegeSetLength, out GrantedAccess, out IsAccessAllowed)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.AccessCheckFailed, error))); } } finally { if (ImpersonationToken != null) ImpersonationToken.Dispose(); } }
public ImpersonationContext(IntPtr threadHandle, SafeCloseHandle tokenHandle) { this.threadHandle = threadHandle; this.tokenHandle = tokenHandle; }
public ImpersonationContext(IntPtr threadHandle, SafeCloseHandle tokenHandle) { this.threadHandle = threadHandle; this.tokenHandle = tokenHandle; }
public static WindowsIdentity GetAnonymousIdentity() { SafeCloseHandle tokenHandle = null; bool isImpersonating = false; lock (lockObject) { if (anonymousIdentity == null) { try { try { if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(SafeNativeMethods.GetCurrentThread())) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.ImpersonateAnonymousTokenFailed, error))); } isImpersonating = true; bool revertSuccess; bool isSuccess = SafeNativeMethods.OpenCurrentThreadToken(SafeNativeMethods.GetCurrentThread(), TokenAccessLevels.Query, true, out tokenHandle); if (!isSuccess) { int error = Marshal.GetLastWin32Error(); revertSuccess = SafeNativeMethods.RevertToSelf(); if (false == revertSuccess) { error = Marshal.GetLastWin32Error(); //this requires a failfast since failure to revert impersonation compromises security DiagnosticUtility.FailFast("RevertToSelf() failed with " + error); } isImpersonating = false; Utility.CloseInvalidOutSafeHandle(tokenHandle); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenThreadTokenFailed, error))); } revertSuccess = SafeNativeMethods.RevertToSelf(); if (false == revertSuccess) { int error = Marshal.GetLastWin32Error(); //this requires a failfast since failure to revert impersonation compromises security DiagnosticUtility.FailFast("RevertToSelf() failed with " + error); } isImpersonating = false; using (tokenHandle) { anonymousIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle()); } } finally { if (isImpersonating) { bool revertSuccess = SafeNativeMethods.RevertToSelf(); if (false == revertSuccess) { int error = Marshal.GetLastWin32Error(); //this requires a failfast since failure to revert impersonation compromises security DiagnosticUtility.FailFast("RevertToSelf() failed with " + error); } } } } catch { // Force the finally to run before leaving the method. throw; } } } return(anonymousIdentity); }