如何在 Windows 内核驱动程序中将文本 SID 转换为 SID 结构



我的内核驱动程序应从注册表中读取文本格式的 SID 并将其转换为 SID 结构以供后续使用。

是否有任何用于内核驱动程序的 ConvertStringSidtoSid() 类似物?

我知道我可能会解析文本并手动构建它,但它看起来像通常的任务。无法通过搜索找到任何内容。

没有人回答我的问题,我确实写了一些代码并想分享它。

它适用于我的所有用例。也许它对某人有用:

BOOLEAN
IprParseSubAuthorities(
    _In_ PCWCHAR buffer,
    _Out_ PISID pSid
)
{
    ULONG authority = 0;
    UCHAR count = 0;
    for (USHORT i = 0;; i++)
    {
        if ((buffer[i] >= L'0') && (buffer[i] <= L'9'))
        {
            authority = authority * 10 + (buffer[i] - L'0');
            continue;
        }
        else if (buffer[i] == L'-')
        {
            pSid->SubAuthority[count] = authority;
            authority = 0;
            if (++count >= pSid->SubAuthorityCount)
            {
                return FALSE;
            }
            continue;
        }
        else if (buffer[i] == 0)
        {
            break;
        }
        return FALSE;
    }
    pSid->SubAuthority[count] = authority;
    return TRUE;
}
UCHAR IprGetSubAuthorityCount(
    _In_ PCWCHAR buffer
)
{
    UCHAR count = 1; // buffer should contains at least one authority
    for (UCHAR i = 0;; i++)
    {
        if (buffer[i] == L'-')
        {
            count++;
        }
        else if (buffer[i] == 0)
        {
            break;
        }
    }
    return count;
}
BOOLEAN
IprConvertUnicodeSidtoSid(
    _In_ PUNICODE_STRING UnicodeSid,
    _Out_ PISID* ppSid
)
{
    PCWCHAR PREFIX = L"S-1-5-";
    const USHORT PREFIX_LEN = (USHORT)wcslen(PREFIX);
    SIZE_T result = RtlCompareMemory(PREFIX, UnicodeSid->Buffer, PREFIX_LEN);
    if (result != PREFIX_LEN)
    {
        return FALSE;
    }
    UCHAR subAuthorityCount =
        IprGetSubAuthorityCount(UnicodeSid->Buffer + PREFIX_LEN);
    PISID pSid = ExAllocatePool(PagedPool, sizeof(SID) + sizeof(ULONG) * (subAuthorityCount - 1));
    pSid->Revision = 1;
    pSid->IdentifierAuthority.Value[0] = 0;
    pSid->IdentifierAuthority.Value[1] = 0;
    pSid->IdentifierAuthority.Value[2] = 0;
    pSid->IdentifierAuthority.Value[3] = 0;
    pSid->IdentifierAuthority.Value[4] = 0;
    pSid->IdentifierAuthority.Value[5] = 5;
    pSid->SubAuthorityCount = subAuthorityCount;
    if (!IprParseSubAuthorities(UnicodeSid->Buffer + PREFIX_LEN, pSid))
    {
        ExFreePool(pSid);
        return FALSE;
    }
    if (!RtlValidSid(pSid))
    {
        ExFreePool(pSid);
        return FALSE;
    }
    *ppSid = pSid;
    return TRUE;
}

相关内容

  • 没有找到相关文章

最新更新