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);
The end goal is to be able to execute new code in the process with the impersonated token, not only from 1 thread.
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
.
Dave Bucka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.