考虑在Windows机器上运行一个C#/.NET进程(作为标准用户,没有任何管理员权限),我想让该进程检查登录会话是如何启动的——是通过终端服务/RDP还是交互式控制台登录?
我能找到的只是关于会话当前状态的信息。但我更感兴趣的是它的启动方式(这可能会发生改变)。
我已经花了一些时间研究,但没找到什么有用的东西。
更新1(不起作用)
我决定尝试一种搜索类似“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;
}
}
谢谢!
SECURITY_LOGON_SESSION_DATA
中。 - RbMmGetParentProcess
在这里是绝对没有意义的。我给你精确且可运行的代码。 - RbMm