如何检测当前会话是否是通过远程桌面连接启动的?

3
考虑在Windows机器上运行一个C#/.NET进程(作为标准用户,没有任何管理员权限),我想让该进程检查登录会话是如何启动的——是通过终端服务/RDP还是交互式控制台登录?
我能找到的只是关于会话当前状态的信息。但我更感兴趣的是它的启动方式(这可能会发生改变)。
我已经花了一些时间研究,但没找到什么有用的东西。
更新1(不起作用)
我决定尝试一种搜索类似“rdp”的父进程的方法,并得出以下代码片段:
public static void ShowParentsToRoot()
{
  var process = Process.GetCurrentProcess();

  while (process != null)
  {
    Console.WriteLine($"Process: processID = {process.Id}, processName = {process.ProcessName}");
    process = ParentProcessUtilities.GetParentProcess(process.Id);
  }
}

我从这里借用了GetParentProcess代码。

但是它不能工作。在交互式控制台会话中启动时,它会给我一些类似于:

Process: processID = 11836, processName = My.App
Process: processID = 27800, processName = TOTALCMD64
Process: processID = 6092, processName = explorer

如果在新的mstsc会话中启动(新登录,不同的用户),结果是相同的(PIDs当然是不同的)。有什么建议吗?

更新2(有效)

RbMm提出的解决方案正是所需的。原始代码是C++,因此我努力提供了一个C#版本。

  class StackSample
  {
    [Flags]
    public enum TokenAccess : uint
    {
      STANDARD_RIGHTS_REQUIRED = 0x000F0000,
      TOKEN_ASSIGN_PRIMARY = 0x0001,
      TOKEN_DUPLICATE = 0x0002,
      TOKEN_IMPERSONATE = 0x0004,
      TOKEN_QUERY = 0x0008,
      TOKEN_QUERY_SOURCE = 0x0010,
      TOKEN_ADJUST_PRIVILEGES = 0x0020,
      TOKEN_ADJUST_GROUPS = 0x0040,
      TOKEN_ADJUST_DEFAULT = 0x0080,
      TOKEN_ADJUST_SESSIONID = 0x0100,

      TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
                         TOKEN_ASSIGN_PRIMARY |
                         TOKEN_DUPLICATE |
                         TOKEN_IMPERSONATE |
                         TOKEN_QUERY |
                         TOKEN_QUERY_SOURCE |
                         TOKEN_ADJUST_PRIVILEGES |
                         TOKEN_ADJUST_GROUPS |
                         TOKEN_ADJUST_DEFAULT |
                         TOKEN_ADJUST_SESSIONID
    }

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);

    public enum TOKEN_INFORMATION_CLASS : uint
    {
      TokenUser = 1,
      TokenGroups,
      TokenPrivileges,
      TokenOwner,
      TokenPrimaryGroup,
      TokenDefaultDacl,
      TokenSource,
      TokenType,
      TokenImpersonationLevel,
      TokenStatistics,
      TokenRestrictedSids,
      TokenSessionId,
      TokenGroupsAndPrivileges,
      TokenSessionReference,
      TokenSandBoxInert,
      TokenAuditPolicy,
      TokenOrigin
    }

    public enum TOKEN_TYPE : uint
    {
      TokenPrimary = 0,
      TokenImpersonation
    }

    public enum SECURITY_IMPERSONATION_LEVEL : uint
    {
      SecurityAnonymous = 0,
      SecurityIdentification,
      SecurityImpersonation,
      SecurityDelegation
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct LUID
    {
      public UInt32 LowPart;
      public UInt32 HighPart;
    }

    [StructLayout(LayoutKind.Explicit, Size = 8)]
    public struct LARGE_INTEGER
    {
      [FieldOffset(0)] public Int64 QuadPart;
      [FieldOffset(0)] public UInt32 LowPart;
      [FieldOffset(4)] public Int32 HighPart;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct TOKEN_STATISTICS
    {
      public LUID TokenId;
      public LUID AuthenticationId;
      public LARGE_INTEGER ExpirationTime;
      public TOKEN_TYPE TokenType;
      public SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
      public UInt32 DynamicCharged;
      public UInt32 DynamicAvailable;
      public UInt32 GroupCount;
      public UInt32 PrivilegeCount;
      public LUID ModifiedId;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct LSA_UNICODE_STRING
    {
      public UInt16 Length;
      public UInt16 MaximumLength;
      public IntPtr buffer;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_LOGON_SESSION_DATA
    {
      public UInt32 Size;
      public LUID LoginID;
      public LSA_UNICODE_STRING Username;
      public LSA_UNICODE_STRING LoginDomain;
      public LSA_UNICODE_STRING AuthenticationPackage;
      public SECURITY_LOGON_TYPE LogonType;
      public UInt32 Session;
      public IntPtr PSiD;
      public UInt64 LoginTime;
      public LSA_UNICODE_STRING LogonServer;
      public LSA_UNICODE_STRING DnsDomainName;
      public LSA_UNICODE_STRING Upn;
    }

    public enum SECURITY_LOGON_TYPE : uint
    {
      Interactive = 2, //The security principal is logging on interactively.
      Network, //The security principal is logging using a network.
      Batch, //The logon is for a batch process.
      Service, //The logon is for a service account.
      Proxy, //Not supported.
      Unlock, //The logon is an attempt to unlock a workstation.
      NetworkCleartext, //The logon is a network logon with cleartext credentials.
      NewCredentials, // Allows the caller to clone its current token and specify new credentials for outbound connections.
      RemoteInteractive, // A terminal server session that is both remote and interactive.
      CachedInteractive, // Attempt to use the cached credentials without going out across the network.
      CachedRemoteInteractive, // Same as RemoteInteractive, except used internally for auditing purposes.
      CachedUnlock // The logon is an attempt to unlock a workstation.
    }


    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool GetTokenInformation(
      IntPtr tokenHandle,
      TOKEN_INFORMATION_CLASS tokenInformationClass,
      IntPtr tokenInformation,
      int tokenInformationLength,
      out int returnLength);


    [DllImport("secur32.dll")]
    public static extern uint LsaFreeReturnBuffer(IntPtr buffer);

    [DllImport("Secur32.dll")]
    public static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);


    public static String GetLogonType()
    {
      if (!OpenProcessToken(Process.GetCurrentProcess().Handle, (uint)TokenAccess.TOKEN_QUERY, out var hToken))
      {
        var lastError = Marshal.GetLastWin32Error();
        Debug.Print($"Unable to open process handle. {new Win32Exception(lastError).Message}");

        return null;
      }

      int tokenInfLength = 0;
      GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenStatistics, IntPtr.Zero, tokenInfLength, out tokenInfLength);
      if (Marshal.SizeOf<TOKEN_STATISTICS>() != tokenInfLength)
      {
        var lastError = Marshal.GetLastWin32Error();
        Debug.Print($"Unable to determine token information struct size. {new Win32Exception(lastError).Message}");

        return null;
      }

      IntPtr pTokenInf = Marshal.AllocHGlobal(tokenInfLength);

      if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenStatistics, pTokenInf, tokenInfLength, out tokenInfLength))
      {
        var lastError = Marshal.GetLastWin32Error();
        Debug.Print($"Unable to get token information. {new Win32Exception(lastError).Message}");
        Marshal.FreeHGlobal(pTokenInf);

        return null;
      }

      uint getSessionDataStatus = LsaGetLogonSessionData(IntPtr.Add(pTokenInf, Marshal.SizeOf<LUID>()), out var pSessionData);
      Marshal.FreeHGlobal(pTokenInf);

      if (getSessionDataStatus != 0)
      {
        Debug.Print("Unable to get session data.");

        return null;
      }

      var logonSessionData = Marshal.PtrToStructure<SECURITY_LOGON_SESSION_DATA>(pSessionData);

      LsaFreeReturnBuffer(pSessionData);

      if (Enum.IsDefined(typeof(SECURITY_LOGON_TYPE), logonSessionData.LogonType))
      {
        return logonSessionData.LogonType.ToString();
      }

      Debug.Print("Could not determine logon type.");

      return null;
    }
  }

谢谢!


通过检查父进程ID。获取进程列表并检查您的进程父级是否为rdp。 - jdweng
1
@jdweng - 如果您的进程父级是rdp - 如果您指的是mstsc.exe - 这与rdp会话绝对无关。rdp客户端也可以在非Windows上运行。无论如何,tdp客户端执行进程都不会在rdp会话中运行。 - RbMm
1
@jdweng - 父进程已经可以退出了。这根本不是问题所在。然而,初始登录类型保存在 SECURITY_LOGON_SESSION_DATA 中。 - RbMm
1
在整个进程链中,这里涉及到的是winlogon - userinit - explorer,与rdp服务无关。你无法通过查询父级获得任何信息。 - RbMm
1
调用GetParentProcess在这里是绝对没有意义的。我给你精确且可运行的代码。 - RbMm
显示剩余2条评论
1个回答

1

要检查会话的初始状态(它是如何最初启动的),我们可以调用LsaGetLogonSessionData - 它返回SECURITY_LOGON_SESSION_DATA,其中LogonType是一个SECURITY_LOGON_TYPE值,用于标识登录方法。如果会话是由RDP启动的,则此处将显示RemoteInteractive。可以从TOKEN_STATISTICS结构中的自身令牌获取标识登录会话的LUID - AuthenticationId

HRESULT GetLogonType(SECURITY_LOGON_TYPE& LogonType )
{
    HANDLE hToken;
    HRESULT hr;

    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
    {
        ULONG rcb;
        TOKEN_STATISTICS ts;

        hr = GetTokenInformation(hToken, ::TokenStatistics, &ts, sizeof(ts), &rcb) ? S_OK : HRESULT_FROM_WIN32(GetLastError());

        CloseHandle(hToken);

        if (hr == S_OK)
        {
            PSECURITY_LOGON_SESSION_DATA LogonSessionData;

            hr = HRESULT_FROM_NT(LsaGetLogonSessionData(&ts.AuthenticationId, &LogonSessionData));

            if (0 <= hr)
            {
                LogonType = static_cast<SECURITY_LOGON_TYPE>(LogonSessionData->LogonType);
                LsaFreeReturnBuffer(LogonSessionData);
            }
        }
    }
    else
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
    }

    return hr;
}

请注意,即使在受限制的低完整性进程中,这也可以工作。
BOOLEAN IsRemoteSession;

SECURITY_LOGON_TYPE LogonType;
if (0 <= GetLogonType(LogonType))
{
    IsRemoteSession = LogonType == RemoteInteractive;
}

我之前尝试过,但它并没有回答关键问题——会话是如何启动的。如果我通过RDP登录,然后重新连接交互式地(重新附加到同一会话),你的方法会告诉我该会话是交互式的——这在目前是正确的。然而,它并没有说明它是如何启动的。 - MarKol4
@MarKol4 - 在这种情况下,您需要使用我的函数(LsaGetLogonSessionData)中的GetLogonType - 而WTSQuerySessionInformationW返回会话的当前状态 - LsaGetLogonSessionData返回会话的初始状态(会话是如何启动的)。 - RbMm
@MarKol4 - 抱歉,我不太理解你的问题。请编辑回答。 - RbMm
您的更新答案似乎正是所需的。我在原帖中提供了C#版本。谢谢! - MarKol4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接