c++windowswinapiadvapi32

How to enumerate all SIDs to which a specified user privilege has been assigned? c++


I am on Windows and C ++ I would like to recover all SIDs for a given privilege. To recover the SIDs I used the following methods : LsaOpenPolicy, LsaEnumerateAccountsWithUserRight and ConvertSidToStringSidA. The problem comes from the ConvertSidToStringSidA method that returns the error : Invalid SID. Here is the code I used :

    LSA_HANDLE lsaPolicyHandle;
    LSA_OBJECT_ATTRIBUTES lsaObjectAttributes;
    ZeroMemory(&lsaObjectAttributes, sizeof (lsaObjectAttributes));
    NTSTATUS ntStatus;

    ntStatus=LsaOpenPolicy(nullptr,&lsaObjectAttributes, POLICY_ALL_ACCESS, &lsaPolicyHandle);

    //Here ntstatus == ERROR_SUCCESS
    if(ntStatus != ERROR_SUCCESS)
    {
        qDebug()<<"error";
    }
    LSA_UNICODE_STRING lsaUSerRight;
    DWORD64 dwLen=0;
    LPCWSTR pcwStr = L"SeServiceLogonRight";
    dwLen = wcslen(pcwStr);
    lsaUSerRight.Buffer = const_cast<wchar_t*>(pcwStr);
    lsaUSerRight.Length = static_cast<unsigned short>(dwLen) * sizeof(WCHAR);
    lsaUSerRight.MaximumLength= static_cast<unsigned short>(dwLen+1) *sizeof(WCHAR);

    LSA_ENUMERATION_INFORMATION pEnumInfo;
    ULONG ulCount;
    ntStatus=LsaEnumerateAccountsWithUserRight(lsaPolicyHandle,
                                               &lsaUSerRight,
                                               reinterpret_cast<PVOID*>(&pEnumInfo),
                                               &ulCount);
    //Here ntstatus == ERROR_SUCCESS
    if(ntStatus != ERROR_SUCCESS)
    {
       qDebug()<<"error";
    }
    //here pEnumInfo has an adress 0x45FF34c et ulCount = 2
    LPSTR lpStringSid;
    PSID pSid=pEnumInfo.Sid;

   //Here invalid SID  
    BOOL bResultConvert=ConvertSidToStringSidA(pSid, &lpStringSid);

    if(bResultConvert==0)
    {
        qDebug()<<"error";
    }


Solution

  • LsaEnumerateAccountsWithUserRight fills in a pointer to a LSA_ENUMERATION_INFORMATION, so you need to change this:

    LSA_ENUMERATION_INFORMATION pEnumInfo;
    

    to this:

    LSA_ENUMERATION_INFORMATION *pEnumInfo;
    

    and to access the first SID returned, change this:

    PSID pSid=pEnumInfo.Sid;
    

    to this:

    PSID pSid=pEnumInfo->Sid;
    

    Then it works.

    Don't forget to free the structures returned with LsaFreeMemory when you are done with them and clean up with LsaClose.