Check if process user is an administrator c++ - c++

I want to get the process's user name and check if it is a local administrator . Or check directly if the current procees user is a local administrator

Get the current username with GetUserName(), then call NetUserGetInfo() with the server name (NULL for local) and username you just got. Pass it a USER_INFO_1 structure, and then access usri1_priv in the structure. If the value is USER_PRIV_ADMIN, then you'll know that the username is an admin.

Tested on Windows XP SP3, Windows 7 32 bit and 64 bit with admin user and non-admin user.
Code ported from equivalent C# and uses ATL windows security wrapper classes.
#include <atlbase.h>
#include <atlsecurity.h>
// The function returns true if the user who is running the
// application is a member of the Administrators group,
// which does not necessarily mean the process has admin privileges.
bool IsAdministrator(HRESULT &rHr)
{
bool bIsAdmin = false;
try
{
// Open the access token of the current process.
ATL::CAccessToken aToken;
if (!aToken.GetProcessToken(TOKEN_QUERY))
{
throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
::GetLastError());
}
// Query for the access token's group information.
ATL::CTokenGroups groups;
if (!aToken.GetGroups(&groups))
{
throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
::GetLastError());
}
// Iterate through the access token's groups
// looking for a match against the builtin admins group.
ATL::CSid::CSidArray groupSids;
ATL::CAtlArray<DWORD> groupAttribs;
groups.GetSidsAndAttributes(&groupSids, &groupAttribs);
for (UINT i = 0; !bIsAdmin && i < groupSids.GetCount(); ++i)
{
bIsAdmin = groupSids.GetAt(i) == ATL::Sids::Admins();
}
rHr = S_OK;
}
catch (HRESULT hr)
{
rHr = hr;
}
return bIsAdmin;
}

Presuming you're on a Window OS there's a shell function: IsUserAnAdmin
See MSDN article
This article does suggest rolling your own function though, use CheckTokenMembership. There is even a code example to help you along.

Related

TgBot doesn't find owner ban power

I've started programming my own telegram-bot in cpp with tgbot-cpp and I've done the code for the ban. When the code checks if the user has the power to ban, it finds the needed power for admins, but not for the owner of the group. I looked in the documentation if there was a way to find the owner of the group, but I couldn't find it. This is the code section that checks the power.
/* Checks if the client has the permission to ban */
bool hasPermission = false;
for (unsigned i = 0; i < admins.size(); i++) {
if (admins[i]->user->id == message->from->id) {
printf("Admin username: %s\n", admins[i]->user->username.c_str());
printf("Can Restrict: %d\n", admins[i]->canRestrictMembers);
if (admins[i]->canRestrictMembers) {
hasPermission = true;
}
break;
}
}
if (!hasPermission) {
return;
}
When an admin uses the ban command, I get a Can Restrict: 1 in the console, but when the owner uses the command I get a Can Restrict: 0.
Is there a reason why the bot doesn't see the owner's power? Is there a way to look for the owner?
After looking better in the documentations, there is a value status for ChatMember that is setted to creator for the owner of the group. That seems to be the way for checking if someone is the owner or not, avoiding the permission issue

Steamworks checking if a user is logged in

So the code that I've been using to get a user's Steam ID is:
CSteamID uid = SteamUser()->GetSteamID();
uint64 pid = uid.ConvertToUint64();
std::ostringstream sin;
sin << pid;
std::string s = sin.str();
return s.c_str();
This works just fine, but when a user is not logged into Steam, this crashes.
Access violation - code c0000005 (first/second chance not available)
Does Steam provide a function that I can use to check if the user is logged in before running code that depends on the user being logged in? Or is there some sort of try/catch block I can use here to make sure that this does not break and return false if the user is not logged in?
Thanks to #Lightning Racis in Orbit. A simple nullptr check fixed it.
if(SteamUser() == nullptr)
return false;

rootElement->FindFirst(...) fails to find element seen by Inspect

I'm trying to locate a list item contained within the Services window (Start->Run->Services.msc) on Windows. The list item is named "Arc Service" and is easily found using Inspect, but my code fails to locate it. This being a relatively simple case, I feel I must be doing something wrong.
The code in question is:
VARIANT arcServiceNameVariant;
VariantInit(&arcServiceNameVariant);
arcServiceNameVariant.vt = VT_BSTR;
arcServiceNameVariant.bstrVal = L"Arc Service";
CComPtr<IUIAutomationCondition> arcServiceNameCondition;
hr = g_pAutomation->CreatePropertyCondition(UIA_NamePropertyId, arcServiceNameVariant, &arcServiceNameCondition.p);
if(SUCCEEDED(hr)) {
CComPtr<IUIAutomationElement> arcServiceElement;
hr = rootElement->FindFirst(TreeScope_Descendants, arcServiceNameCondition, &arcServiceElement.p);
if(SUCCEEDED(hr)) {
if(arcServiceElement.p) {
logInfo(L"Arc Service element found!");
}
} else {
logInfo(L"FindFirst failed!");
}
} else {
logInfo(L"Failed to create property condition!");
}
The "Arc Service element found!" branch is never entered.
Here are the details from Inspect describing the element:
Any assistance would be greatly appreciated. Thanks!
Quizzically it turns out that running my UIA client as Administrator sees the component, but running as the logged in user does not. For now I can elevate my process, but I'll continue to research the issue for a more detailed explanation.

C2664 cannot convert parameter 1 from from User *const to User in Qt C++

I am new to C++ and Qt, but I have been playing around with it for a couple of days and I need to come up with a basic prototype of my product by Friday, so there is not much time to convert my 7 years of PHP knowledge into C++ knowledge, as I am sure that it takes a lifetime to master C++. I am getting stuck from time to time in the last couple of days due to non-existing knowledge about the small bits and bytes. At this time I have even no idea what to look for on the Internet.
First of all, I am using Qt as my framework to do a simple GUI network client that can talk to my PHP application. I wanted to create a very simple WebAPI class in this application and have the class "webapi". The scenario is very simple, the user starts the application and the applications checks if the user is logged in or not. If not, then it opens up a login dialog. After entering the information (username / password) into the dialog the user object is filled and the method "authenticate" is called.
The authenticate method then calls the fUser method in the webapi class to make a request to the server holding some information to authenticate the user against the server's database.
In code it looks like this:
Savor.cpp:
user = new User();
while ( user->isLoggedIn() != true )
{
LoginDialog loginWindow;
loginWindow.setModal(true);
int result = loginWindow.exec();
if ( result == QDialog::Accepted )
{
user->authenticate(loginWindow.getUsername(), loginWindow.getPassword());
if ( !user->isLoggedIn() )
{
loginWindow.setUsername(loginWindow.getUsername());
loginWindow.exec();
}
}
else
{
exit(1);//exit with code 1
}
}
User.cpp:
void User::authenticate(QString username, QString password)
{
qDebug() << username;
qDebug() << password;
if ( username != "" && password != "")
{
webapi wapi;
loggedIn = wapi.fUser(this);
}
else
{
loggedIn = false;
}
}
webapi.cpp:
/**
Represents the fUser method on the server,
it wants to get a user object
the user will need to be authenticated with this
then all infos about user are transfered (RSA Keypair etc)
* #brief webapi::fUser
* #param username
* #param password
* #return User
*/
bool webapi::fUser(User baseUser)
{
return true;
}
Now you can clearly see that I am not doing anything at the moment in the webapi::fUser method. In fact, I am not even returning what I would like to return. Instead of a boolean I would like to return a User object, actually the same that I got in the first place through the parameter. However, i get a copy constructor error when I do that. (In my savor.h file I have declared a private attribute as a pointer => User *user;)
So the question is, what am I doing wrong when I call the fUser method? Why can I not simply pass the user object itself to the method ? I have not got around to fully understand const, and pointers and when to use what.
With Qt creator I actually use the MS Visual C++ compiler which throws the error as in the title:
C2664 'webapi::fUser' : cannot convert paramter 1 from 'User *const' to 'User'
I have read http://msdn.microsoft.com/en-us/library/s5b150wd(v=vs.71).aspx this page explaining when this happens, the only solutions is the conversion of the object itself.
If thats the case I might approach the entire problem in the wrong way.
I am looking forward to your tips and help on this matter.
Thank you very much.
webapi::fuser takes a User by value, but you are passing it a User* here:
wapi.fUser(this);
Either pass a User:
wapi.fUser(*this);
or change webapi to take a pointer to User.

MAPI_E_NOT_FOUND on OpenMsgStore

I'm trying to open the MessageStore of a user using MAPI. The weird thing is, when I run this a console application, while I'm logged with the user, everything works fine.
But when I run this as a Windows Service I get MAPI_E_NOT_FOUND when trying to open the MessageStore.
I already configured the service to run as the user.
MapiLogonEx seems to work fine and GetMsgStoreTables also gives me the correct results (I verfied that the EntryID of the MessageStore is correct).
Here's my code:
LPMAPITABLE pStoresTbl = NULL;
m_lpMAPISession->GetMsgStoresTable(0, &pStoresTbl);
// Query Collumns
LPSPropTagArray pTags = NULL;
LPSRowSet pRows = NULL;
pStoresTbl->SeekRow(BOOKMARK_BEGINNING,0,NULL);
pStoresTbl->QueryRows(
LONG_MAX,
NULL,
&pRows);
LPSBinary lpEntryID = NULL;
ULONG iprops;
for (iprops = 0; iprops < pRows->aRow[0].cValues; iprops++)
{
SPropValue sProp = pRows->aRow[0].lpProps[iprops];
if (PROP_ID(sProp.ulPropTag) == PROP_ID(PR_ENTRYID))
{
lpEntryID = &sProp.Value.bin;
break;
}
}
lpMDB = NULL;
HRESULT hres = m_lpMAPISession->OpenMsgStore(NULL,
lpEntryID->cb,
(LPENTRYID) lpEntryID->lpb,
NULL,
MDB_NO_DIALOG |
MDB_NO_MAIL | // spooler not notified of our presence
MDB_TEMPORARY | // message store not added to MAPI profile
MAPI_BEST_ACCESS,
&lpMDB);
Is that an Exchange profile? Are you sure you are opening the primary mailbox rather than the PF store?
Dmitry Streblechenko (MVP)
http://www.dimastr.com/
OutlookSpy - Outlook, CDO
and MAPI Developer Tool
Do you pass in the MAPI_NT_SERVICE flag in the MAPIINIT_0 structure when calling MAPIInitialize? I've never not passed it in when running in a service, so I'm not exactly sure what happens if you don't. The MSDN docs say it is required.
MAPI_NT_SERVICE
The caller is
running as a Windows service. Callers
that are not running as a Windows
service should not set this flag;
callers that are running as a service
must set this flag.