• caglararli@hotmail.com
  • 05386281520

How to use SetThreadToken for all threads in the current process – C#

Çağlar Arlı      -    15 Views

How to use SetThreadToken for all threads in the current process – C#

I'm experimenting with Windows authentication and impersonation, and I'm trying to set a token for every thread in the current process via SetThreadToken. I'm able to set the SetThreadToken for my current thread that the code runs in with IntPtr.Zero reference.

SetThreadToken(IntPtr.Zero, tImpersonation);

I'm attempting to perform the following to do that for each thread:

ProcessThreadCollection currentProcessThreads = Process.GetCurrentProcess().Threads;

foreach (ProcessThread currentThread in currentProcessThreads)
{
    
    uint tid = (uint)currentThread.Id; // thread ID

    IntPtr targetThread = OpenThread(0x1fffff, false, tid); // open target thread handle with THREAD_ALL_ACCESS
    Console.WriteLine("targetThread: " + targetThread);
    
    SetThreadToken(targetThread, tImpersonation);
    
}

When targetThread is not NULL (meaning OpenThread succeeded), the process crashes with Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. on SetThreadToken.