- 1 year ago
Why WTSRegisterSessionNotification may fail with Access Denied error?
The WTSRegisterSessionNotification
function is used to register a window to receive notifications when session state changes occur, such as when a user logs on or off. This function may fail with an "Access Denied" error if the calling process does not have the required permissions to register for session notifications.
The WTSRegisterSessionNotification
function requires the SE_TCB_NAME
(Act as part of the operating system) privilege to be held by the calling process. This privilege is normally only held by system processes and services, and not by regular user-mode applications. If the calling process does not have this privilege, the function will fail with an "Access Denied" error.
To fix this issue, the calling process needs to be granted the SE_TCB_NAME
privilege. This can be done using the AdjustTokenPrivileges
function to enable the SE_TCB_NAME
privilege for the process's security token. Here is an example code snippet that demonstrates how to enable the SE_TCB_NAME
privilege:
c++BOOL EnablePrivilege(LPCTSTR lpPrivilegeName)
{
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpPrivilegeName, &luid))
{
CloseHandle(hToken);
return FALSE;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = luid;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
BOOL bResult = AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
CloseHandle(hToken);
return bResult;
}
int main()
{
// Enable the SE_TCB_NAME privilege
EnablePrivilege(SE_TCB_NAME);
// Call WTSRegisterSessionNotification to register for session notifications
// ...
return 0;
}
In this example, the EnablePrivilege
function is used to enable the SE_TCB_NAME
privilege for the current process's security token. The WTSRegisterSessionNotification
function can then be called to register for session notifications without encountering an "Access Denied" error.