I am trying to use these features to get the username running the process. Here is the code:
#include
#include
using namespace
Your second call to GetTokenInformation()
is passing the wrong memory address in the 3rd parameter. You are passing the memory address of the to
variable itself, so you are asking GetTokenInformation()
to write into surrounding stack space. You need to pass the memory address that the variable is pointing at instead (the allocated TOKEN_OWNER
structure), so get rid of the &
operator (and the type-cast, which is not necessary):
GetTokenInformation(hToken, TokenOwner, to, len, &len);
You are also not doing any error handling at all, so you don't know if memory is being allocated successfully, or if any API function are failing.
Try this instead:
#include
#include
using namespace std;
int main()
{
DWORD dwError;
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
dwError = GetLastError();
cerr << "OpenProcessToken failed, error " << dwError;
return 0;
}
DWORD len = 0;
if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len))
{
dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
cerr << "GetTokenInformation failed, error " << dwError;
CloseHandle(hToken);
return 0;
}
}
PTOKEN_OWNER to = (PTOKEN_OWNER) LocalAlloc(LPTR, len);
if (!to)
{
dwError = GetLastError();
cerr << "LocalAlloc failed, error " << dwError;
CloseHandle(hToken);
return 0;
}
if (!GetTokenInformation(hToken, TokenOwner, to, len, &len))
{
dwError = GetLastError();
cerr << "GetTokenInformation failed, error " << dwError;
LocalFree(to);
CloseHandle(hToken);
return 0;
}
char nameUser[256] = {0};
char domainName[256] = {0};
DWORD nameUserLen = 256;
DWORD domainNameLen = 256;
SID_NAME_USE snu;
if (!LookupAccountSidA(NULL, to->Owner, nameUser, &nameUserLen, domainName, &domainNameLen, &snu))
{
dwError = GetLastError();
cerr << "LookupAccountSid failed, error " << dwError;
LocalFree(to);
CloseHandle(hToken);
return 0;
}
cout << domainName << '/' << nameUser << endl;
LocalFree(to);
CloseHandle(hToken);
return 0;
}