So in basically every job I have had in the last twenty years, I have had to write some code to enable Windows privileges, such as the backup or restore privileges, which are required to import or export registry keys. It’s a pretty common operation and there is a convenient example on MSDN that shows how to do it. I believe that every instance of writing this code I have seen followed the same pattern: Get a thread token, or a process token if there is no thread token, then adjust the privilege on that token. Then undo the whole thing when you no longer need the privilege.

But recently I encountered a situation where there is large-scale threading going on, and this technique really backfires. The threads quickly start to disable privileges that another thread needs, etc. I started to look into a better solution, and realized that I needed a thread token for each thread so that the privileges could be adjusted on that specific thread only. I knew that the way to get a thread token was to impersonate a user, but I didn’t need to be impersonating another user in this case.

Enter the ImpersonateSelf Windows API, which is specifically designed for this situation. The API creates a thread token for the current thread, which then means that the enable privilege code can be safely called against the thread token (NOT the process token). This is a pretty straight-forward process, but based on my experience I don’t think it is commonly done correctly. The code that I have seen everywhere has definitely not been thread-safe.

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

Complete the following to verify your humanity: * Time limit is exhausted. Please reload CAPTCHA.