Jump to content

Retrieving UserName from SessionID


Recommended Posts

What I'm trying is to retrieve LoggedOn username from the SessionID. Following this discusson, I'm found the code below

DWORD dwSessionId = WTSGetActiveConsoleSessionId(); // 0, 1, 2...
if ( dwSessionId == 0xFFFFFFFF ) {
return;
}

HANDLE hToken = NULL;
WTSQueryUserToken(dwSessionId, &hToken);
if ( hToken == NULL ) {
return;
}

HANDLE hDupToken = NULL;
DuplicateToken(hToken, SecurityImpersonation, &hDupToken);
if ( hDuoToken == NULL ) {
CloseHandle(hToken);
return;
}

BOOL bRes = ImpersonateLoggedOnUser(hDupToken);
if ( bRes ) {
// GetUserName here
RevertToSelf();
}

CloseHandle(hDupToken);
CloseHandle(hToken);

I interpreted the code above in AutoIt as shown below

Func GetUserNameFromSessionID($SessionId)
    
    Local $phToken, $ret, $handle, $pDuplicateTokenHandle, $DuplicateTokenHandle, $UserName
    Local Const $SecurityImpersonation = 1

    $ret = DllCall("Wtsapi32.dll", "boolean", "WTSQueryUserToken", "ulong", $SessionId, "ptr*", $phToken)
    $phToken = $ret[2]
    $ret = DllStructCreate("handle ExistingTokenHandle", $phToken)
    $handle = DllStructGetData($ret, "ExistingTokenHandle")
    If $handle = '' Then
        DllCall("Kernel32.dll", "int", "CloseHandle", "ptr", $handle)
        Return
    EndIf
    
    MsgBox(0, "Debug", $handle)
    
    $ret = DllCall("Advapi32.dll", "boolean", "DuplicateToken", "handle", $handle, "int", $SecurityImpersonation, "ptr*", $pDuplicateTokenHandle)
    $DuplicateTokenHandle = $ret[3]
    $ret = DllStructCreate("handle DuplicateTokenHandle", $pDuplicateTokenHandle)
    $DuplicateTokenHandle = DllStructGetData($ret, "DuplicateTokenHandle")
    If $DuplicateTokenHandle = '' Then
        DllCall("Kernel32.dll", "int", "CloseHandle", "ptr", $DuplicateTokenHandle)
        Return
    EndIf
    
    MsgBox(0, "Debug", $DuplicateTokenHandle)
    
    $ret = DllCall("Advapi32.dll", "int", "ImpersonateLoggedOnUser", "ptr", $DuplicateTokenHandle)
    If $ret = True Then
        $UserName = @UserName
    EndIf

    DllCall("Kernel32.dll", "int", "CloseHandle", "ptr", $DuplicateTokenHandle)
    DllCall("Kernel32.dll", "int", "CloseHandle", "ptr", $handle)
    DllCall("Advapi32.dll", "int", "RevertToSelf")
    Return $UserName

EndFunc

MsgBox(0, "Debug", GetUserNameFromSessionID(0))

The only difference I made is to accept SessionID as a parameter instead of obtaining it from a WTSGetActiveConsoleSessionId() call.

But, unfortunately, the function exits from the FIRST Return statement. Clearly, I couldn't convert DllCall()-s properly. Can anybody please review the code snippet & point out the errors?

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

Hi all, I'm constantly fighting with the above piece of code, yet no result. May I expect some DllCall() expert to come forward with some clues in my rescue?

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

@UserName == Lets you get the current user logged in. Is that what you mean?

It's semi-correct. Give it a read.

Also consider facts like "Fast User Switching", "Remote desktop", "Terminal Services".

Again think of the fact that a process can be launched by "impersonating" other users (like what services do with LocalSystem account in most of the cases) or commands like "RunAs" & "CPAU"

Could you define what you mean by Session ID?

Read the following

Edited by HolmesShelock

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

Couldn't you use Qwinsta and just parse who is connected to console?

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Couldn't you use Qwinsta and just parse who is connected to console?

Of course, I could & that would be an easier solution. But there are some systems where QWINSTA is not installed. For those, that approach poses a problem.

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

Then use query session from the command line.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Then use query session from the command line.

Don't know why, but QUERY SESSION is not recognized in my system (Windows XP SP3).

Besides, I personally feel it better to obtain the info programmatically from within my program rather than relying on any external command which creates unnecessary dependency.

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

  • Developers

Use these starting lines to see more info about what is going wrong with the first DLLCall and run it from SciTE:

#include<winapi.au3>
Func GetUserNameFromSessionID($SessionId)

    Local $phToken, $ret, $handle, $pDuplicateTokenHandle, $DuplicateTokenHandle, $UserName
    Local Const $SecurityImpersonation = 1

    $ret = DllCall("Wtsapi32.dll", "boolean", "WTSQueryUserToken", "ulong", $SessionId, "ptr*", $phToken)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : _WinAPI_GetLastError() = ' & _WinAPI_GetLastError() & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $ret[1] = ' & $ret[1] & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $ret[2] = ' & $ret[2] & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Use these starting lines to see more info about what is going wrong with the first DLLCall and run it from SciTE:

Hmm, below is the console log

>"C:\Program Files\AutoIt3\SciTE\..\autoit3.exe" /ErrorStdOut "H:\Experiment\Blocking Internet Access\Impersonate.au3"    
@@ Debug(9) : _WinAPI_GetLastError() = 1314
>Error code: 0
@@ Debug(10) : $ret[1] = 0
>Error code: 0
@@ Debug(11) : $ret[2] = 0x00000000
>Error code: 0
>Exit code: 0    Time: 0.428

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

  • Developers

Well this is what MS has to say about that: ( http://msdn.microsoft.com/en-us/library/aa383840%28v=vs.85%29.aspx )

Return code/value Description

ERROR_PRIVILEGE_NOT_HELD

1314

The caller does not have the SE_TCB_NAME privilege.

This is about getting RDP session info ...right?

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

So what you are looking for is something that will find ALL users connected or have connected to this PC from any source?

No, only to find the name of the corresponding user whose session ID I'm passing to the function.

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

Well this is what MS has to say about that: ( http://msdn.microsoft.com/en-us/library/aa383840%28v=vs.85%29.aspx )

Well, instead of SciTe let me try the code from my service which runs from LocalSystem account & has the required privilege.

This is about getting RDP session info ...right?

Not the entire session info, but the username only.

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

Just a word of caution, Session 0 is only the logged on user pre-Vista, after that I believe the users are in session 1+, might be Windows 7 only but I believe it's also the same in Vista.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Just a word of caution, Session 0 is only the logged on user pre-Vista, after that I believe the users are in session 1+, might be Windows 7 only but I believe it's also the same in Vista.

First of all, my system is Win Xp.

Secondly, I'm retrieving the SessionID from WTSSESSION_NOTIFICATION structure, not hardcoding it within the program.

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

@Jos

When I ran the code from my service, it produced the following

.

.

.

May 24, 2011 : 01:05:52 AM [6416] >> @@ Debug(-1) : _WinAPI_GetLastError() = 0

>Error code: 0

May 24, 2011 : 01:05:52 AM [6416] >> @@ Debug(-1) : $ret[1] = 1

>Error code: 0

May 24, 2011 : 01:05:52 AM [6416] >> @@ Debug(-1) : $ret[2] = 0x00000150

>Error code: 0

.

.

.

May 24, 2011 : 01:06:07 AM [6416] >> @@ Debug(-1) : _WinAPI_GetLastError() = 997

>Error code: 0

May 24, 2011 : 01:06:07 AM [6416] >> @@ Debug(-1) : $ret[1] = 0

>Error code: 0

May 24, 2011 : 01:06:07 AM [6416] >> @@ Debug(-1) : $ret[2] = 0x00000194

>Error code: 0

.

.

.

It perfectly fine as I was switching back & forth between two sessions with ID 0 & 1. $ret[1] were correct in both the cases.

But I couldn't understand, why

  • GetLastError() returned 997 in the second case
  • Execution stopped after the first DllCall()
Am I correct in converting PHANDLE to HANDLE ? Edited by HolmesShelock

[size="2"][font="arial, verdana, tahoma, sans-serif"]ProtectData - A Data Protection software for floppies[/font][/size] [size="2"][hr][/size][size="2"]Sessionchange - A Windows service capable of tracking session change events[/size][size="2"][b][/b][/size]

Link to comment
Share on other sites

  • 11 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...