首页 > 解决方案 > 如何检测当前会话是否通过 RDP 启动?

问题描述

考虑到在 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 会话中启动,结果是相同的(当然 PID 不同)。有什么建议么?

更新 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;
    }
  }

谢谢!

标签: c#windowssessionrdp

解决方案


为了检查会话的初始状态(它是如何初始启动的),我们可以调用LsaGetLogonSessionData- 它返回SECURITY_LOGON_SESSION_DATALogonType一个标识登录方法SECURITY_LOGON_TYPE的值。如果会话由 RDP 启动 - 您在此处获得RemoteInteractive。标识登录会话的 LUID,您可以从 TOKEN_STATISTICS结构内部的自我令牌中获取 - 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;
}

推荐阅读