My windows application may require administrative privileges for some of it's sections. For those cases, I'd like to ask the user for an administrator credentials, and use the following code to impersonate the administrator:
BOOL impersonate(LPTSTR lpszUsername, LPTSTR lpszDomain, LPTSTR lpszPassword) {
BOOL ret = LogonUser(lpszUsername,
lpszDomain,
lpszPassword,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&hToken);
if (ret != TRUE) return FALSE;
OutputDebugString (L"step 1");
ret = ImpersonateLoggedOnUser(hToken);
if (ret != TRUE) return FALSE;
OutputDebugString(L"step 2");
return IsUserAdmin()
}
where the function IsUserAdmin()
has been taken from MSDN , and goes as follow:
BOOL IsUserAdmin(VOID) {
BOOL b;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
b = AllocateAndInitializeSid( &NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if (b) {
if (!CheckTokenMembership(NULL, AdministratorsGroup, &b)) {
b = FALSE;
}
FreeSid(AdministratorsGroup);
}
return(b);
}
Scenario 1:
Running the application from an administrator account.
calling IsUserAdmin() => returns
TRUE
(good)calling impersonate ("non-admin-user" , "domain", "password" ) => returns
FALSE
(good!)
Scenario 2:
Running the application from a non-administrator account, using runas.exe
from an administrator account.
calling IsUserAdmin() => returns
FALSE
(good)calling impersonate ("administrator" , "domain", "password" ) => returns
FALSE
(not good!)
Scenario 3:
Running the application directly from a non-administrator account.
calling IsUserAdmin() => returns
FALSE
(good)calling impersonate ("administrator" , "domain", "password" ) => returns
FALSE
(not good!)
All scenarios print both step 1
and step 2
.
As far as I can tell, the above should have assure impersonation, given the a legitimate credentials. what am I missing here?