I need to get the AuthenticationID as returned by GetTokenInformation with the TokenStatistics class for the user that logged in on the station whether I'm elevated or not.
Lemme give you some more info. Suppose I do :
var Result = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenStatistics, TokenInformation, TokenInfLength, out TokenInfLength);
This will allow me to get the AuthenticationID from the TokenInformation structure without problem. Let's say the resulting authenticationID is "00000000-00001234"
Now if I right click Visual Studio and click "Run as administrator", launch my code a second time, the result will be something else, for example "00000000-00001289". But I need "00000000-00001234"
How can I get "00000000-00001234" whether the current process is elevated or not ?
I suppose it's just a matter of finding the right Token to give to GetTokenInformation, but I'm running in circles here ...
Note : I based my code on How to get the logon SID in C# to implement GetTokenInformation and then adapted it to be able to get TokenStatistics.
OK, I finally got it to work. These are the steps (not posting the full code, it's quite long) :
- Use WMI (ManagementObject) on the win32_process class + the managed Process class recursively to create the current process' ancestry
- In my particular case I stop the algorithm when I find the "explorer" process or when I hit an exception, as it's very likely that explorer is not elevated.
- P/Invoke the OpenProcessToken function from advapi32.dll on the ProcessId returned by step 2. This gets you a userToken that can be used to construct a new WindowsIdentity that you can use in step 4
- You can then feed that WindowsIdentity Token property to GetTokenInformation to get back your AuthenticationID.
This is tested and working.
Reference :
- GetTokenInformation : How to get the logon SID in C# (change the function to call TokenStatistics)
- Get parent of process : http://bytes.com/topic/c-sharp/answers/255642-enumerataing-processes-c
- Get WindowsIdentity of a process : http://dotbay.blogspot.fr/2009/06/finding-owner-of-process-in-c.html
If you see any problem with this procedure don't hesitate to comment or post your own answer !
Note : there is a problem if one of the parent process has been killed : WMI will give you the id of a process that does not exist anymore. The nature of the product I'm working has me rebooting explorer from time to time (only during dev), this is how I saw the problem. It's not really an issue for me, but good to know.
Thanks