When a process is elevated how can I get the windows authentication ID of the non elevated session

混江龙づ霸主 提交于 2020-01-15 11:22:25

问题


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.


回答1:


OK, I finally got it to work. These are the steps (not posting the full code, it's quite long) :

  1. Use WMI (ManagementObject) on the win32_process class + the managed Process class recursively to create the current process' ancestry
  2. 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.
  3. 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
  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



来源:https://stackoverflow.com/questions/9873787/when-a-process-is-elevated-how-can-i-get-the-windows-authentication-id-of-the-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!