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); }
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(); } } }