【问题标题】:How to get the SID of the current machine?如何获取当前机器的 SID?
【发布时间】:2019-10-16 13:20:08
【问题描述】:

我知道如何获取当前用户的 SID。从概念上讲,答案是:

  • 使用OpenThreadToken(或OpenProcessToken)获取运行用户的安全TOKEN
  • 使用GetTokenInformation获取TOKEN_USER结构
  • 然后TOKEN_USER.Sid 是 Sid

所以在伪代码中:

String GetCurrentUserSid()
{
   // Get the calling thread's access token.
   TOKEN hToken;
   if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, out hToken)
   { 
       if (GetLastError() != ERROR_NO_TOKEN)
          RaiseLastWin32Error();

       // No thread token exists, try again against the process token
       if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out hToken)
          RaiseLastWin32Error();
   }
   try
   {
      // Obtain the size of the user information in the token.
      DWORD cbReturned;
      GetTokenInformation(hToken, TokenUser, nil, 0, out cbReturned);

      //Allocate memory and try again for real
      TOKEN_USER* tiUser = GetMemory(cbReturned);
      if (!GetTokenInformation(hToken, TokenUser, tiUser, cbReturned, out cbReturned))
      RaiseLastWin32Error();
   }
   finally
   {
      CloseHandle(hToken);
   }

   //Convert the structure to a string
   return SidToString(tiUser.User.Sid);
}

但是对于现在的机器怎么办呢?

String GetCurrentMachineSid()
{
   // TODO: Ask Stackoverflow
}

阅读奖励

【问题讨论】:

  • 但是如何 Sysinternals PsGetSid 工具 得到它 - 对你来说好吗?

标签: winapi


【解决方案1】:

You can see the machine SID on your computer by running Sysinternals PsGetSid with no parameters

所以我只是在调试器下查看 PsGetSid 是如何做到这一点的。

它从POLICY_ACCOUNT_DOMAIN_INFO 获取 SID - DomainSid : 指向帐户域的 SID 的指针

代码可以是下一个

LSA_HANDLE PolicyHandle;

LSA_OBJECT_ATTRIBUTES ObjectAttributes = { sizeof(ObjectAttributes) };

NTSTATUS status = LsaOpenPolicy(0, &ObjectAttributes, POLICY_VIEW_LOCAL_INFORMATION, &PolicyHandle);

if (0 <= status)
{
    POLICY_ACCOUNT_DOMAIN_INFO* ppadi;

    status = LsaQueryInformationPolicy(PolicyHandle, PolicyAccountDomainInformation, (void**)&ppadi);

    if (0 <= status)
    {
        PWSTR szSid;
        BOOL b = ConvertSidToStringSidW(ppadi->DomainSid, &szSid);
        LsaFreeMemory(ppadi);

        if (b)
        {
            DbgPrint("%S\n", szSid);
            LocalFree(szSid);
        }
    }

    LsaClose(PolicyHandle);
}

【讨论】:

    猜你喜欢
    • 2010-09-20
    • 2011-11-30
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多