System.Security.Principal.Win32.OpenThreadToken C# (CSharp) Method

OpenThreadToken() static private method

static private OpenThreadToken ( TokenAccessLevels dwDesiredAccess, WinSecurityContext dwOpenAs, SafeTokenHandle &phThreadToken ) : int
dwDesiredAccess TokenAccessLevels
dwOpenAs WinSecurityContext
phThreadToken Microsoft.Win32.SafeHandles.SafeTokenHandle
return int
        internal static int OpenThreadToken(TokenAccessLevels dwDesiredAccess, WinSecurityContext dwOpenAs, out SafeTokenHandle phThreadToken)
        {
            int hr = 0;
            bool openAsSelf = true;
            if (dwOpenAs == WinSecurityContext.Thread)
                openAsSelf = false;

            if (!Interop.Advapi32.OpenThreadToken((IntPtr)(-2), dwDesiredAccess, openAsSelf, out phThreadToken))
            {
                if (dwOpenAs == WinSecurityContext.Both)
                {
                    openAsSelf = false;
                    hr = 0;
                    if (!Interop.Advapi32.OpenThreadToken((IntPtr)(-2), dwDesiredAccess, openAsSelf, out phThreadToken))
                        hr = Marshal.GetHRForLastWin32Error();
                }
                else
                {
                    hr = Marshal.GetHRForLastWin32Error();
                }
            }
            if (hr != 0) phThreadToken = null;
            return hr;
        }

Usage Example

Example #1
0
            public TlsContents()
            {
                int  error        = 0;
                int  cachingError = 0;
                bool success      = true;

                if (processHandle.IsInvalid)
                {
                    lock (syncRoot)
                    {
                        if (processHandle.IsInvalid)
                        {
                            SafeTokenHandle localProcessHandle;
                            if (false == Interop.mincore.OpenProcessToken(
                                    Interop.mincore.GetCurrentProcess(),
                                    TokenAccessLevels.Duplicate,
                                    out localProcessHandle))
                            {
                                cachingError = Marshal.GetLastWin32Error();
                                success      = false;
                            }
                            processHandle = localProcessHandle;
                        }
                    }
                }

                try
                {
                    // Make the sequence non-interruptible
                }
                finally
                {
                    try
                    {
                        //
                        // Open the thread token; if there is no thread token, get one from
                        // the process token by impersonating self.
                        //

                        SafeTokenHandle threadHandleBefore = this.threadHandle;
                        error = FCall.OpenThreadToken(
                            TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
                            WinSecurityContext.Process,
                            out this.threadHandle);
                        unchecked { error &= ~(int)0x80070000; }

                        if (error != 0)
                        {
                            if (success == true)
                            {
                                this.threadHandle = threadHandleBefore;

                                if (error != Interop.mincore.Errors.ERROR_NO_TOKEN)
                                {
                                    success = false;
                                }

                                System.Diagnostics.Debug.Assert(this.isImpersonating == false, "Incorrect isImpersonating state");

                                if (success == true)
                                {
                                    error = 0;
                                    if (false == Interop.mincore.DuplicateTokenEx(
                                            processHandle,
                                            TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
                                            IntPtr.Zero,
                                            Interop.mincore.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                                            System.Security.Principal.TokenType.TokenImpersonation,
                                            ref this.threadHandle))
                                    {
                                        error   = Marshal.GetLastWin32Error();
                                        success = false;
                                    }
                                }

                                if (success == true)
                                {
                                    error = FCall.SetThreadToken(this.threadHandle);
                                    unchecked { error &= ~(int)0x80070000; }

                                    if (error != 0)
                                    {
                                        success = false;
                                    }
                                }

                                if (success == true)
                                {
                                    this.isImpersonating = true;
                                }
                            }
                            else
                            {
                                error = cachingError;
                            }
                        }
                        else
                        {
                            success = true;
                        }
                    }
                    finally
                    {
                        if (!success)
                        {
                            Dispose();
                        }
                    }
                }

                if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
                {
                    throw new OutOfMemoryException();
                }
                else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                         error == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (error != 0)
                {
                    System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error));
                    throw new InvalidOperationException();
                }
            }