void SetThreadToken(SafeCloseHandle threadToken) { DiagnosticUtility.DebugAssert(!this.isImpersonating, ""); int error = 0; // CER RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (!NativeMethods.SetThreadToken(IntPtr.Zero, threadToken)) { error = Marshal.GetLastWin32Error(); } else { this.isImpersonating = true; } } if (!this.isImpersonating) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } }
public int Revert() { if (!this.isImpersonating) { if (this.needToRevert && !this.initialEnabled) { TOKEN_PRIVILEGE token_privilege; TOKEN_PRIVILEGE token_privilege2; token_privilege.PrivilegeCount = 1; token_privilege.Privilege.Luid = this.luid; token_privilege.Privilege.Attributes = 0; uint returnLength = 0; if (!System.IdentityModel.NativeMethods.AdjustTokenPrivileges(this.threadToken, false, ref token_privilege, TOKEN_PRIVILEGE.Size, out token_privilege2, out returnLength)) { return(Marshal.GetLastWin32Error()); } } this.needToRevert = false; } else { if (!System.IdentityModel.NativeMethods.RevertToSelf()) { return(Marshal.GetLastWin32Error()); } this.isImpersonating = false; } if (this.threadToken != null) { this.threadToken.Close(); this.threadToken = null; } return(0); }
private void EnableTokenPrivilege(SafeCloseHandle threadToken) { TOKEN_PRIVILEGE token_privilege; token_privilege.PrivilegeCount = 1; token_privilege.Privilege.Luid = this.luid; token_privilege.Privilege.Attributes = 2; uint returnLength = 0; bool flag = false; int error = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { TOKEN_PRIVILEGE token_privilege2; flag = System.IdentityModel.NativeMethods.AdjustTokenPrivileges(threadToken, false, ref token_privilege, TOKEN_PRIVILEGE.Size, out token_privilege2, out returnLength); error = Marshal.GetLastWin32Error(); if (flag && (error == 0)) { this.initialEnabled = 0 != (token_privilege2.Privilege.Attributes & 2); this.needToRevert = true; } } if (error == 0x514) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PrivilegeNotHeldException(this.privilege)); } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } }
internal static extern bool LogonUser( [In] string lpszUserName, [In] string lpszDomain, [In] string lpszPassword, [In] uint dwLogonType, [In] uint dwLogonProvider, [Out] out SafeCloseHandle phToken );
internal static extern bool AdjustTokenPrivileges( [In] SafeCloseHandle tokenHandle, [In] bool disableAllPrivileges, [In] ref TOKEN_PRIVILEGE newState, [In] uint bufferLength, [Out] out TOKEN_PRIVILEGE previousState, [Out] out uint returnLength );
internal static extern bool DuplicateTokenEx( [In] SafeCloseHandle existingTokenHandle, [In] TokenAccessLevels desiredAccess, [In] IntPtr tokenAttributes, [In] SECURITY_IMPERSONATION_LEVEL impersonationLevel, [In] TokenType tokenType, [Out] out SafeCloseHandle duplicateTokenHandle );
internal static System.ServiceModel.ComIntegration.LUID GetModifiedIDLUID(SafeCloseHandle token) { using (SafeHandle handle = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenStatistics)) { TOKEN_STATISTICS token_statistics = (TOKEN_STATISTICS) Marshal.PtrToStructure(handle.DangerousGetHandle(), typeof(TOKEN_STATISTICS)); return token_statistics.ModifiedId; } }
public void Enable() { // Note: AdjustTokenPrivileges should not try to adjust if the token is // Primary token (process). Duplicate the process token (impersonation) and // then set token to current thread and unsetting (RevertToSelf) later. DiagnosticUtility.DebugAssert(this.threadToken == null, ""); this.threadToken = GetThreadToken(); EnableTokenPrivilege(this.threadToken); }
internal static extern int LsaLogonUser( [In] SafeLsaLogonProcessHandle LsaHandle, [In] ref UNICODE_INTPTR_STRING OriginName, [In] SecurityLogonType LogonType, [In] uint AuthenticationPackage, [In] IntPtr AuthenticationInformation, [In] uint AuthenticationInformationLength, [In] IntPtr LocalGroups, [In] ref TOKEN_SOURCE SourceContext, [Out] out SafeLsaReturnBufferHandle ProfileBuffer, [Out] out uint ProfileBufferLength, [Out] out LUID LogonId, [Out] out SafeCloseHandle Token, [Out] out QUOTA_LIMITS Quotas, [Out] out int SubStatus );
void EnableTokenPrivilege(SafeCloseHandle threadToken) { DiagnosticUtility.DebugAssert(!this.needToRevert, ""); TOKEN_PRIVILEGE newState; newState.PrivilegeCount = 1; newState.Privilege.Luid = this.luid; newState.Privilege.Attributes = SE_PRIVILEGE_ENABLED; TOKEN_PRIVILEGE previousState; uint previousSize = 0; bool success = false; int error = 0; // CER RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { success = NativeMethods.AdjustTokenPrivileges( threadToken, false, ref newState, TOKEN_PRIVILEGE.Size, out previousState, out previousSize); error = Marshal.GetLastWin32Error(); if (success && error == ERROR_SUCCESS) { this.initialEnabled = (0 != (previousState.Privilege.Attributes & SE_PRIVILEGE_ENABLED)); this.needToRevert = true; } } if (error == ERROR_NOT_ALL_ASSIGNED) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PrivilegeNotHeldException(this.privilege)); } else if (!success) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } }
public int Revert() { if (!this.isImpersonating) { if (this.needToRevert && !this.initialEnabled) { TOKEN_PRIVILEGE newState; newState.PrivilegeCount = 1; newState.Privilege.Luid = this.luid; newState.Privilege.Attributes = SE_PRIVILEGE_DISABLED; TOKEN_PRIVILEGE previousState; uint previousSize = 0; if (!NativeMethods.AdjustTokenPrivileges( this.threadToken, false, ref newState, TOKEN_PRIVILEGE.Size, out previousState, out previousSize)) { return(Marshal.GetLastWin32Error()); } } this.needToRevert = false; } else { if (!NativeMethods.RevertToSelf()) { return(Marshal.GetLastWin32Error()); } this.isImpersonating = false; } if (this.threadToken != null) { this.threadToken.Close(); this.threadToken = null; } return(ERROR_SUCCESS); }
public IDisposable Impersonate() { System.IdentityModel.SafeCloseHandle handle; IntPtr currentThread = SafeNativeMethods.GetCurrentThread(); if (!SafeNativeMethods.OpenCurrentThreadToken(currentThread, TokenAccessLevels.Impersonate, true, out handle)) { int error = Marshal.GetLastWin32Error(); System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(handle); if (error != 0x3f0) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } handle = new System.IdentityModel.SafeCloseHandle(IntPtr.Zero, false); } if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(currentThread)) { int num2 = Marshal.GetLastWin32Error(); throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num2)); } return(new ImpersonationContext(currentThread, handle)); }
protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateSspiNegotiation(ISspiNegotiation sspiNegotiation) { WindowsSspiNegotiation windowsNegotiation = (WindowsSspiNegotiation)sspiNegotiation; if (!windowsNegotiation.IsValidContext) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidSspiNegotiation"))); } SecurityTraceRecordHelper.TraceServiceSpnego(windowsNegotiation); if (base.IsClientAnonymous) { return(System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance); } using (System.IdentityModel.SafeCloseHandle handle = windowsNegotiation.GetContextToken()) { WindowsIdentity identity = new WindowsIdentity(handle.DangerousGetHandle(), windowsNegotiation.ProtocolName); System.ServiceModel.Security.SecurityUtils.ValidateAnonymityConstraint(identity, this.AllowUnauthenticatedCallers); List <IAuthorizationPolicy> list = new List <IAuthorizationPolicy>(1); WindowsClaimSet issuance = new WindowsClaimSet(identity, windowsNegotiation.ProtocolName, this.extractGroupsForWindowsAccounts, false); list.Add(new UnconditionalPolicy(issuance, TimeoutHelper.Add(DateTime.UtcNow, base.ServiceTokenLifetime))); return(list.AsReadOnly()); } }
private void SetThreadToken(SafeCloseHandle threadToken) { int error = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (!System.IdentityModel.NativeMethods.SetThreadToken(IntPtr.Zero, threadToken)) { error = Marshal.GetLastWin32Error(); } else { this.isImpersonating = true; } } if (!this.isImpersonating) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } }
internal int GetSecurityContextToken(out SafeCloseHandle safeHandle) { int num = -2146893055; bool success = false; RuntimeHelpers.PrepareConstrainedRegions(); try { base.DangerousAddRef(ref success); } catch (Exception exception) { if (success) { base.DangerousRelease(); success = false; } if (!(exception is ObjectDisposedException)) { throw; } } finally { if (success) { num = QuerySecurityContextToken(ref this._handle, out safeHandle); base.DangerousRelease(); } else { safeHandle = new SafeCloseHandle(IntPtr.Zero, false); } } return(num); }
public static int QuerySecurityContextToken( SafeDeleteContext context, out SafeCloseHandle token) { return(context.GetSecurityContextToken(out token)); }
internal static extern bool GetCurrentProcessToken([In] IntPtr ProcessHandle, [In] TokenAccessLevels DesiredAccess, out SafeCloseHandle TokenHandle);
internal static extern bool OpenCurrentThreadToken([In] IntPtr ThreadHandle, [In] TokenAccessLevels DesiredAccess, [In] bool OpenAsSelf, out SafeCloseHandle TokenHandle);
private static extern int QuerySecurityContextToken(ref SSPIHandle phContext, out SafeCloseHandle handle);
internal static bool IsPrimaryToken(SafeCloseHandle token) { using (SafeHandle handle = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType)) { return (Marshal.ReadInt32(handle.DangerousGetHandle()) == 1); } }
public ImpersonationContext(IntPtr threadHandle, System.IdentityModel.SafeCloseHandle tokenHandle) { this.threadHandle = threadHandle; this.tokenHandle = tokenHandle; }
public int Revert() { if (!this.isImpersonating) { if (this.needToRevert && !this.initialEnabled) { TOKEN_PRIVILEGE token_privilege; TOKEN_PRIVILEGE token_privilege2; token_privilege.PrivilegeCount = 1; token_privilege.Privilege.Luid = this.luid; token_privilege.Privilege.Attributes = 0; uint returnLength = 0; if (!System.IdentityModel.NativeMethods.AdjustTokenPrivileges(this.threadToken, false, ref token_privilege, TOKEN_PRIVILEGE.Size, out token_privilege2, out returnLength)) { return Marshal.GetLastWin32Error(); } } this.needToRevert = false; } else { if (!System.IdentityModel.NativeMethods.RevertToSelf()) { return Marshal.GetLastWin32Error(); } this.isImpersonating = false; } if (this.threadToken != null) { this.threadToken.Close(); this.threadToken = null; } return 0; }
public void Enable() { this.threadToken = this.GetThreadToken(); this.EnableTokenPrivilege(this.threadToken); }
public int Revert() { if (!this.isImpersonating) { if (this.needToRevert && !this.initialEnabled) { TOKEN_PRIVILEGE newState; newState.PrivilegeCount = 1; newState.Privilege.Luid = this.luid; newState.Privilege.Attributes = SE_PRIVILEGE_DISABLED; TOKEN_PRIVILEGE previousState; uint previousSize = 0; if (!NativeMethods.AdjustTokenPrivileges( this.threadToken, false, ref newState, TOKEN_PRIVILEGE.Size, out previousState, out previousSize)) { return Marshal.GetLastWin32Error(); } } this.needToRevert = false; } else { if (!NativeMethods.RevertToSelf()) { return Marshal.GetLastWin32Error(); } this.isImpersonating = false; } if (this.threadToken != null) { this.threadToken.Close(); this.threadToken = null; } return ERROR_SUCCESS; }
public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass) { uint num; if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out num)) { int error = Marshal.GetLastWin32Error(); if (error != 0x7a) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("GetTokenInfoFailed", new object[] { error }))); } } SafeHandle tokenInformation = SafeHGlobalHandle.AllocHGlobal(num); try { if (!SafeNativeMethods.GetTokenInformation(token, infoClass, tokenInformation, num, out num)) { int num3 = Marshal.GetLastWin32Error(); throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num3, System.ServiceModel.SR.GetString("GetTokenInfoFailed", new object[] { num3 }))); } } catch { tokenInformation.Dispose(); throw; } return tokenInformation; }
internal static bool IsAtleastImpersonationToken(SafeCloseHandle token) { using (SafeHandle handle = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel)) { if (Marshal.ReadInt32(handle.DangerousGetHandle()) < 2) { return false; } return true; } }
internal static extern bool DuplicateTokenEx([In] SafeCloseHandle ExistingToken, [In] TokenAccessLevels DesiredAccess, [In] IntPtr TokenAttributes, [In] SecurityImpersonationLevel ImpersonationLevel, [In] System.ServiceModel.ComIntegration.TokenType TokenType, out SafeCloseHandle NewToken);
internal static extern bool OpenProcessToken([In] IntPtr processToken, [In] TokenAccessLevels desiredAccess, out SafeCloseHandle tokenHandle);
public IDisposable Impersonate() { System.IdentityModel.SafeCloseHandle handle; IntPtr currentThread = SafeNativeMethods.GetCurrentThread(); if (!SafeNativeMethods.OpenCurrentThreadToken(currentThread, TokenAccessLevels.Impersonate, true, out handle)) { int error = Marshal.GetLastWin32Error(); System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(handle); if (error != 0x3f0) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error)); } handle = new System.IdentityModel.SafeCloseHandle(IntPtr.Zero, false); } if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(currentThread)) { int num2 = Marshal.GetLastWin32Error(); throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num2)); } return new ImpersonationContext(currentThread, handle); }
internal static extern bool OpenThreadToken([In] IntPtr threadHandle, [In] TokenAccessLevels desiredAccess, [In] bool openAsSelf, out SafeCloseHandle tokenHandle);
private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed) { if (this.securityDescriptor == null) { throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL"); } IsAccessAllowed = false; byte[] binaryForm = new byte[this.securityDescriptor.BinaryLength]; this.securityDescriptor.GetBinaryForm(binaryForm, 0); SafeCloseHandle newToken = null; SafeCloseHandle token = new SafeCloseHandle(clientIdentity.Token, false); try { if (System.ServiceModel.ComIntegration.SecurityUtils.IsPrimaryToken(token) && !SafeNativeMethods.DuplicateTokenEx(token, TokenAccessLevels.Query, IntPtr.Zero, SecurityImpersonationLevel.Identification, System.ServiceModel.ComIntegration.TokenType.TokenImpersonation, out newToken)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(newToken); throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("DuplicateTokenExFailed", new object[] { error }))); } GENERIC_MAPPING genericMapping = new GENERIC_MAPPING(); PRIVILEGE_SET structure = new PRIVILEGE_SET(); uint privilegeSetLength = (uint) Marshal.SizeOf(structure); uint grantedAccess = 0; if (!SafeNativeMethods.AccessCheck(binaryForm, (newToken != null) ? newToken : token, 1, genericMapping, out structure, ref privilegeSetLength, out grantedAccess, out IsAccessAllowed)) { int num4 = Marshal.GetLastWin32Error(); throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num4, System.ServiceModel.SR.GetString("AccessCheckFailed", new object[] { num4 }))); } } finally { if (newToken != null) { newToken.Dispose(); } } }
internal static extern bool SetThreadToken([In] IntPtr threadHandle, [In] SafeCloseHandle threadToken);
public static int QuerySecurityContextToken(SafeDeleteContext context, out SafeCloseHandle token) { return context.GetSecurityContextToken(out token); }
internal int GetSecurityContextToken(out SafeCloseHandle safeHandle) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. The API returns a error code. status = QuerySecurityContextToken(ref _handle, out safeHandle); DangerousRelease(); } else { safeHandle = new SafeCloseHandle(IntPtr.Zero, false); } } return status; }
internal int GetSecurityContextToken(out SafeCloseHandle safeHandle) { int num = -2146893055; bool success = false; RuntimeHelpers.PrepareConstrainedRegions(); try { base.DangerousAddRef(ref success); } catch (Exception exception) { if (success) { base.DangerousRelease(); success = false; } if (!(exception is ObjectDisposedException)) { throw; } } finally { if (success) { num = QuerySecurityContextToken(ref this._handle, out safeHandle); base.DangerousRelease(); } else { safeHandle = new SafeCloseHandle(IntPtr.Zero, false); } } return num; }