Search code examples
c++winapiwindows-servicesaccess-denied

Access denied in application when trying to set event created by service


I have create a Windows Service in c++ that creates an event and then waits for a desktop application to signal it.

This is the event creation code (from the windows service):

CUpdateMonitor::CUpdateMonitor()
{
    PSECURITY_DESCRIPTOR psd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
    InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(psd, TRUE, NULL, FALSE);

    SECURITY_ATTRIBUTES sa = { 0 };
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = psd;
    sa.bInheritHandle = FALSE;

    m_hUpdateAvailableEvent = CreateEvent(&sa, TRUE, FALSE, UPDATE_AVAILABLE_EVENT);
    LocalFree(psd);

    if (m_hUpdateAvailableEvent == NULL)
        throw Win32Exception(GetLastError(), _T("CUpdateMonitor: Failed to create update available event"));
}

This is the desktop application code:

void CClientDlg::OnNotifyUpdate()
{
    HANDLE hEvent = OpenEvent(SYNCHRONIZE, FALSE, UPDATE_AVAILABLE_EVENT); // <-- this works fine
    if (hEvent == NULL)
        MLOGE(_T("Could not open event. Err code: %d"), GetLastError());
    else
    {
        MLOGD(_T("Setting event/Notifying update service"));
        if (!SetEvent(hEvent)) // <-- this return ACCESS_DENIED
        {
            MLOGE(_T("Failed to set update event. Error code: %d"), GetLastError());
            return;
        }

        try
        {
            CSimpleMessageSender msgSender(UPDATE_PIPE_NAME);
            MLOGD(_T("Sending message to update service"));
            msgSender.SendSimpleMessage(_T("stuff"));
        }
        catch (const Win32Exception& w32Ex)
        {
            MLOGE(_T("Could not send message ot update service. Win32Exception:\n%s"), w32Ex.GetErrorMessage().c_str());
        }
    }
}

I manage to open the event, but when I try to set it, I get ACCESS_DENIED.

What am I doing wrong?


Solution

  • Shouldn't you be using EVENT_MODIFY_STATE for the access right? MSND states that EVENT_MODIFY_STATE is needed for SetEvent().