Get the logon session of a user in C++

谁说我不能喝 提交于 2019-12-03 21:51:17

You can get the logon session associated with a process by using OpenProcessToken followed by GetTokenInformation with the TokenStatistics option. However, this is not a sensible way of finding out whether or not a process was launched using "run as administrator" because there is no straightforward way to determine whether a particular logon session is elevated or not. It is not true that a process launched with "run as administrator" will not have a logon session.

To find out whether a process was "run as administrator" use the TokenElevationType option. This should return TokenElevationTypeFull if and only if "run as administrator" was used.

(One caveat: I'm not certain what TokenElevationType will return if a non-administrative user uses "run as administrator" and then enters an administrator username and password. You should test this scenario. You might want to use TokenElevation rather than TokenElevationType.)

If what you really want to know is whether the process has administrative privilege, you should use CheckTokenMembership instead. Look for the Administrators group. The MSDN documentation has sample code that does exactly this.

The distinction here is what you want to happen if UAC is disabled (and the user is an administrator) or if the user is the local Administrator. In these cases there is no "run as administrator" option, all processes are run with administrator privilege automatically. If you want to detect these cases, use CheckTokenMembership. If you only want to detect the cases where the user explicitly said "run as administrator" use TokenElevationType.

You can call GetCurrentProcess to get a handle to the current process, then use that to call OpenProcessToken to have an access token for the current process. Once you have that, you can call GetTokenInformation to request the TokenSessionId.

Edit:

I just thought of something else you can try: Instead of the session ID, you can request the TokenOwner, and once you have that, you have a security descriptor. You can then call LookupAccountSid to get the account name associated with the descriptor. Then, you can check that against "Administrator" or some such.

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