gpt4 book ai didi

c# - 如何检测当前 session 是否通过 RDP 启动?

转载 作者:可可西里 更新时间:2023-11-01 10:41:02 29 4
gpt4 key购买 nike

考虑到 Windows 机器上有一个正在运行的进程(C#/.NET,以标准用户身份运行 - 没有任何管理权限)我希望该进程检查登录 session 是如何启动的 - 作为终端服务/RDP 或作为交互式登录到控制台?

我所能找到的只是关于 session 的当前状态。但我对它的当前状态(可能会改变)不太感兴趣,而是对它开始的方式感兴趣。

我花了一些时间对此进行挖掘,但找不到任何有用的东西。

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

我从here 借用了GetParentProcess 代码.

而且它不起作用。在交互式控制台 session 中启动时,它给了我类似的东西:

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

如果在新的(新登录,不同的用户)mstsc session 中启动,结果是相同的(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;
}
}

谢谢!

最佳答案

为了检查 session 的初始状态(它是如何开始的)我们可以调用LsaGetLogonSessionData - 它返回 SECURITY_LOGON_SESSION_DATA其中 LogonTypeSECURITY_LOGON_TYPE标识登录方法的值。如果 session 由 RDP 启动 - 你在这里得到 RemoteInteractive。标识登录 session 的 LUID,您可以从 TOKEN_STATISTICS 内的自 token 中获取结构 - 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;
}

关于c# - 如何检测当前 session 是否通过 RDP 启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57536756/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com