/// <summary> /// Faster than the version that takes a pid. /// </summary> public static string GetProcessName(IntPtr hProcess) { // Get the handle to the first module in the process. IntPtr[] modules = new IntPtr[1]; uint needed = 0; if (!Psapi.EnumProcessModules(hProcess, modules, (uint)IntPtr.Size, ref needed)) { return(null); } if (needed == 0) { return(null); } IntPtr firstModule = modules[0]; // Get the filename for the module. uint bufsize = Kernel32.MAX_PATH * 4; StringBuilder filename = new StringBuilder((int)bufsize); uint charsReturned = Psapi.GetModuleFileNameEx(hProcess, firstModule, filename, bufsize); if (charsReturned == 0) { return(null); } return(Path.GetFileName(filename.ToString())); }
public static bool LoadModules(IntPtr hProcess, ListModules ModuleType) { //Initialize parameters for EPM uint cbNeeded = 0; Psapi.EnumProcessModulesEx(hProcess, IntPtr.Zero, 0, out cbNeeded, ModuleType); long ArraySize = cbNeeded / IntPtr.Size; IntPtr[] hModules = new IntPtr[ArraySize]; GCHandle GCh = GCHandle.Alloc(hModules, GCHandleType.Pinned); // Don't forget to free this later IntPtr lphModules = GCh.AddrOfPinnedObject(); uint cb = cbNeeded; Psapi.EnumProcessModulesEx(hProcess, lphModules, cb, out cbNeeded, ModuleType); for (int i = 0; i < ArraySize; i++) { MODULE_INFO ModInfo = new MODULE_INFO(); System.Text.StringBuilder lpFileName = new System.Text.StringBuilder(256); System.Text.StringBuilder lpModuleBaseName = new System.Text.StringBuilder(32); Psapi.GetModuleFileNameExW(hProcess, hModules[i], lpFileName, (uint)(lpFileName.Capacity)); Psapi.GetModuleInformation(hProcess, hModules[i], out ModInfo, (uint)(Marshal.SizeOf(ModInfo))); Psapi.GetModuleBaseNameW(hProcess, hModules[i], lpModuleBaseName, (uint)(lpModuleBaseName.Capacity)); DbgHelp.SymLoadModuleEx(hProcess, IntPtr.Zero, lpFileName.ToString(), lpModuleBaseName.ToString(), ModInfo.lpBaseOfDll, (int)ModInfo.SizeOfImage, IntPtr.Zero, 0); } GCh.Free(); return(false); }
public static unsafe IntPtr FindPattern(string module, string pattern) { IntPtr moduleHandle = Kernel32.GetModuleHandle(module); if (moduleHandle == IntPtr.Zero) { return(IntPtr.Zero); } Psapi.MODULEINFO moduleInfo; if (!Psapi.GetModuleInformation(Kernel32.GetCurrentProcess(), moduleHandle, out moduleInfo, sizeof(Psapi.MODULEINFO))) { return(IntPtr.Zero); } uint moduleStart = (uint)moduleInfo.lpBaseOfDll; uint moduleLen = moduleInfo.SizeOfImage; string[] patternStrParts = pattern.Split(' '); bool[] mask = patternStrParts.Select(x => x != "?").ToArray(); byte[] patternBytes = patternStrParts.Select(x => (byte)((x != "?") ? (byte)(Convert.ToInt32(x, 16)) : 0)).ToArray(); for (uint i = 0; i < moduleLen - patternBytes.Length; i++) { if (Compare((byte *)(moduleStart + i), patternBytes, mask)) { return(new IntPtr(moduleStart + i)); } } return(IntPtr.Zero); }
public static string GetMainModuleFileName(this Process process, int buffer = 1024) { var fileNameBuilder = new StringBuilder(buffer); uint code = Psapi.GetModuleFileNameEx(process.Handle, IntPtr.Zero, fileNameBuilder, (uint)fileNameBuilder.Capacity + 1); return(code != 0 ? fileNameBuilder.ToString() : null); }
public long GetPeakMemory() { var pmc = new ProcessMemoryCounters(); pmc.cb = Marshal.SizeOf <ProcessMemoryCounters>(); if (!Psapi.GetProcessMemoryInfo(proc, ref pmc, pmc.cb)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return((long)pmc.PeakWorkingSetSize); }
/// <summary> /// Use this as alternative to builtin Process.GetProcesses() in /// order not to deal with exceptions /// </summary> /// <returns></returns> public static IEnumerable <Process> EnumerateProcesses() { var arraySize = 1024u; var arrayBytesSize = arraySize * sizeof(uint); var processIds = new int[arraySize]; uint bytesCopied; if (!Psapi.EnumProcesses(processIds, arrayBytesSize, out bytesCopied)) { yield break; } if (bytesCopied == 0) { yield break; } if ((bytesCopied & 3) != 0) { yield break; } var numIdsCopied = bytesCopied >> 2; for (var i = 0; i < numIdsCopied; ++i) { var id = processIds[i]; var Handle = Kernel32.OpenProcess(ProcessAccess.QueryInformation, false, id); if (Handle == IntPtr.Zero) { continue; } Kernel32.CloseHandle(Handle); Process process = null; try { process = Process.GetProcessById(id); if (process == null) { continue; } } catch (Exception) { continue; } yield return(process); } }
public string GetWindowName() { try { User32.GetWindowThreadProcessId(Handle, out var lpdwProcessId); var handle = Kernel32.OpenProcess(0x0410, false, lpdwProcessId); var text = new StringBuilder(1000); Psapi.GetModuleFileNameEx(handle, IntPtr.Zero, text, text.Capacity); Kernel32.CloseHandle(handle); return(text.ToString()); } catch (Exception ex) { Log.LogEvent("Window", $"Handle: {Handle}\nCaption: {GetWindowText()}", ex); return(""); } }
public StackCall(IntPtr hProcess, ulong AddrPC, ulong AddrReturn, int ThreadId) { this.ThreadId = ThreadId; this.AddrPC = AddrPC; this.AddrReturn = AddrReturn; System.Text.StringBuilder ReturnedString = new System.Text.StringBuilder(256); IntPtr PcOffset = (IntPtr)Functions.UlongToLong(AddrPC); Psapi.GetMappedFileNameW(hProcess, PcOffset, ReturnedString, (uint)ReturnedString.Capacity); this.MappedFile = ReturnedString.ToString(); IMAGEHLP_SYMBOL64 PcSymbol = Functions.GetSymbolFromAddress(hProcess, AddrPC); this.Symbol = new string(PcSymbol.Name); }
private string GetFileName(IntPtr hModule) { // Alternative to GetModuleFileName() for the module loaded with // LOAD_LIBRARY_AS_DATAFILE option. // Get the file name in the format like: // "\\Device\\HarddiskVolume2\\Windows\\System32\\shell32.dll" string fileName; { var buf = new StringBuilder(MAX_PATH); int len = Psapi.GetMappedFileName( Kernel32.GetCurrentProcess(), hModule, buf, buf.Capacity); if (len == 0) { throw new Win32Exception(); } fileName = buf.ToString(); } // Convert the device name to drive name like: // "C:\\Windows\\System32\\shell32.dll" for (char c = 'A'; c <= 'Z'; ++c) { var drive = c + ":"; var buf = new StringBuilder(MAX_PATH); int len = Kernel32.QueryDosDevice(drive, buf, buf.Capacity); if (len == 0) { continue; } var devPath = buf.ToString(); if (fileName.StartsWith(devPath)) { return(drive + fileName.Substring(devPath.Length)); } } return(fileName); }
async void UpdateIPSessions() { try { while (!cts.IsCancellationRequested) { Kernel32.GetDeviceNameMap(); listView1.BeginUpdate(); sessions = Iphlpapi.GetIPSessions(); IPAddress ipAddress; // add/update items foreach (Iphlpapi.IPSession session in sessions) { // get process info string filePath = ""; int imageIndex = 0; if (processList.ContainsKey(session.OwningPid)) { imageIndex = processList[session.OwningPid].ImageListIndex; filePath = processList[session.OwningPid].Path; } else if (processList.Where(i => i.Value.Path == filePath).Count() > 0) { OwningProcess owningProcess = processList.Where(i => i.Value.Path == filePath).First().Value; processList.TryAdd(session.OwningPid, owningProcess); imageIndex = owningProcess.ImageListIndex; filePath = owningProcess.Path; } else { System.Drawing.Icon icon = null; filePath = Psapi.GetProcessFileName(session.OwningPid); if (filePath != "") { icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath); } if (icon != null) { imageList1.Images.Add(icon); imageIndex = imageList1.Images.Count - 1; OwningProcess owningProcess = new OwningProcess(); owningProcess.Path = filePath; owningProcess.ImageListIndex = imageIndex; processList.TryAdd(session.OwningPid, owningProcess); } } // add process in TV if (!treeView1.Nodes[0].Nodes.ContainsKey(Path.GetFileName(filePath) + " (" + session.OwningPid + ")")) { treeView1.Nodes[0].Nodes.Add(Path.GetFileName(filePath) + " (" + session.OwningPid + ")", Path.GetFileName(filePath) + " (" + session.OwningPid + ")", imageIndex, imageIndex).Parent.Expand(); } // filter if (session.SocketID.LocalEP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && comboBox1.SelectedIndex == 1 || session.SocketID.LocalEP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && comboBox1.SelectedIndex == 0) { continue; } if (treeView1.SelectedNode != null && treeView1.SelectedNode.Parent != null) { if (session.OwningPid != uint.Parse(Regex.Replace(treeView1.SelectedNode.Text, @"^.*\((\d+)\)$", "$1"))) { continue; } } if (filterProtocol.SelectedIndex == 0 && session.SocketID.Protocol != IP.ProtocolFamily.TCP || filterProtocol.SelectedIndex == 1 && session.SocketID.Protocol != IP.ProtocolFamily.UDP) { continue; } // update existing items bool found = false; foreach (ListViewItem item in listView1.Items) { // find item if (session.SocketID.Equals(item.Tag)) { found = true; item.SubItems[6].Text = session.State; IPEndPoint remoteEP; // resolve IP if (resolveIP.Checked) { if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.UDP) { if ((remoteEP = UdpDetector.Table.GetRemoteEP(((IP.SocketID)item.Tag).LocalEP)) != null) { if (!DnsRescords.ContainsKey(remoteEP.Address)) { ResolveIP(remoteEP.Address); } else if (DnsRescords[remoteEP.Address] != "") { item.SubItems[3].Text = DnsRescords[remoteEP.Address]; } } } else if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.TCP) { if (!DnsRescords.ContainsKey(((IP.SocketID)item.Tag).RemoteEP.Address)) { ResolveIP(((IP.SocketID)item.Tag).RemoteEP.Address); } else if (DnsRescords[((IP.SocketID)item.Tag).RemoteEP.Address] != "") { item.SubItems[3].Text = DnsRescords[((IP.SocketID)item.Tag).RemoteEP.Address]; } } } else { if (!IPAddress.TryParse(item.SubItems[3].Text, out ipAddress)) { item.SubItems[3].Text = ((IP.SocketID)item.Tag).RemoteEP.Address.ToString(); } } // update remote UDP EP if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.UDP && (item.SubItems[3].Text == "0.0.0.0" || item.SubItems[3].Text == "::" || item.SubItems[4].Text == "0") && (remoteEP = UdpDetector.Table.GetRemoteEP(((IP.SocketID)item.Tag).LocalEP)) != null) { item.SubItems[3].Text = remoteEP.Address.ToString(); item.SubItems[4].Text = remoteEP.Port.ToString(); } // update bytes if (getBytes.Checked == true) { ByteCounter.ByteTable.Bytes bytes = ByteCounter.Table.GetBytes((IP.SocketID)item.Tag); if (bytes.Received > 0 || bytes.Sent > 0) { item.SubItems[7].Text = Unit.AutoScale(bytes.Received, "B"); item.SubItems[8].Text = Unit.AutoScale(bytes.Sent, "B"); } else { item.SubItems[7].Text = ""; item.SubItems[8].Text = ""; } } } } if (!found) { listView1.Items.Add(new ListViewItem(new string[] { Path.GetFileName(filePath) + " (" + session.OwningPid + ")", session.SocketID.LocalEP.Address.ToString(), session.SocketID.LocalEP.Port.ToString(), session.SocketID.RemoteEP.Address.ToString(), session.SocketID.RemoteEP.Port.ToString(), session.SocketID.Protocol.ToString(), session.State, "", "" }, imageIndex)).Tag = session.SocketID; } } // delete items foreach (ListViewItem item in listView1.Items) { if (!sessions.Any((i) => i.SocketID.Equals(item.Tag)) || item.SubItems[1].Text.Contains(':') && comboBox1.SelectedIndex == 0 || !item.SubItems[1].Text.Contains(':') && comboBox1.SelectedIndex == 1 || filterProtocol.SelectedIndex == 0 && item.SubItems[5].Text != "TCP" || filterProtocol.SelectedIndex == 1 && item.SubItems[5].Text != "UDP") { item.Remove(); } else if (treeView1.SelectedNode != null && treeView1.SelectedNode.Parent != null) { if (item.SubItems[0].Text != treeView1.SelectedNode.Text) { item.Remove(); } } } foreach (KeyValuePair <uint, OwningProcess> process in processList) { if (sessions.Find(i => i.OwningPid == process.Key) == null) { treeView1.Nodes[0].Nodes.RemoveByKey(Path.GetFileName(process.Value.Path) + " (" + process.Key + ")"); OwningProcess value; processList.TryRemove(process.Key, out value); } } foreach (ColumnHeader column in listView1.Columns) { column.Width = -2; } listView1.Sort(); listView1.EndUpdate(); //Unit.Compare("10.5 KB", "10.5 B"); await TaskEx.Delay(1000); } } catch (Exception e) { Global.WriteLog(e.ToString()); } }
public static Dictionary <string, FileVersionInfo> GetDeviceDriversNoMicrosoft() { Dictionary <string, FileVersionInfo> results = new Dictionary <string, FileVersionInfo>(); // ignore ghosts // https://devblogs.microsoft.com/oldnewthing/20160913-00/?p=94305 Regex ignoreGhosts = new Regex("^dump_", RegexOptions.Compiled | RegexOptions.IgnoreCase); // manufacturer/providers to ignore Regex ignoreCompany = new Regex("^Microsoft", RegexOptions.Compiled | RegexOptions.IgnoreCase); string system32 = Environment.SystemDirectory; // Get a list of loaded kernel modules Psapi.EnumDeviceDrivers(null, 0, out var neededBytes); UIntPtr[] drivers = new UIntPtr[neededBytes / UIntPtr.Size]; Psapi.EnumDeviceDrivers(drivers, (UInt32)(drivers.Length * UIntPtr.Size), out neededBytes); // iterate over modules foreach (UIntPtr baseAddr in drivers) { StringBuilder buffer = new StringBuilder(1024); Psapi.GetDeviceDriverBaseName(baseAddr, buffer, (UInt32)buffer.Capacity); if (ignoreGhosts.IsMatch(buffer.ToString())) { continue; } Psapi.GetDeviceDriverFileName(baseAddr, buffer, (UInt32)buffer.Capacity); string pathname = buffer.ToString(); // GetDeviceDriverFileName can return a path in a various number of formats, below code tries to handle them. // https://community.osr.com/discussion/228671/querying-device-driver-list-from-kernel-mode if (pathname.StartsWith("\\??\\")) { pathname = pathname.Remove(0, 4); } if (File.Exists(pathname)) { // intentionally empty } else if (pathname[0] == '\\') { // path could be either in the NtObject namespace or from the filesystem root (without drive) if (File.Exists("\\\\.\\GLOBALROOT" + pathname)) { pathname = "\\\\.\\GLOBALROOT" + pathname; } else if (File.Exists(system32.Substring(0, 2) + pathname)) { pathname = system32.Substring(0, 2) + pathname; } else { Beaprint.GrayPrint($"Ignoring unknown path {pathname}"); continue; } } else { // probably module is a boot driver without a full path if (File.Exists(system32 + "\\drivers\\" + pathname)) { pathname = system32 + "\\drivers\\" + pathname; } else if (File.Exists(system32 + "\\" + pathname)) { pathname = system32 + "\\" + pathname; } else { Beaprint.GrayPrint($"Ignoring unknown path {pathname}"); continue; } } if (!string.IsNullOrEmpty(pathname)) { var info = FileVersionInfo.GetVersionInfo(pathname.ToString()); if (!string.IsNullOrEmpty(info.CompanyName) && !ignoreCompany.IsMatch(info.CompanyName)) { results[pathname] = info; } } } return(results); }
public static int FindInBaseModule(Process process, byte[] pattern, out IntPtr[] offsets, bool wildcard = false, byte wildcardChar = 0xff, bool findAll = false) { List <IntPtr> offsetList = new List <IntPtr>(); offsets = new IntPtr[] { (IntPtr)0 }; //Create a handle to the process IntPtr processHandle = Processthreadsapi.OpenProcess(0x0010 | 0x0020 | 0x0008, false, process.Id); //Initialize the a modInfo struct as new so the size can be safely obtained var modInfo = new Psapi.ModuleInfo(); //Allocated some memory for a ptr IntPtr modInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(modInfo)); //Get the module info for the process base bool ntStatus = Psapi.GetModuleInformation(processHandle, process.MainModule.BaseAddress, modInfoPtr, (uint)Marshal.SizeOf(modInfo)); if (!ntStatus) { return(Marshal.GetLastWin32Error()); } //Convert the ptr to the structure modInfo = (Psapi.ModuleInfo)Marshal.PtrToStructure(modInfoPtr, typeof(Psapi.ModuleInfo)); //Allocate a new buffer based on the size of the image byte[] lpBuffer = new byte[modInfo.SizeOfImage]; //Read the entire image into the buffer ntStatus = Memoryapi.ReadProcessMemory(processHandle, process.MainModule.BaseAddress, lpBuffer, (int)modInfo.SizeOfImage, out IntPtr _); if (!ntStatus) { return(Marshal.GetLastWin32Error()); } for (int i = 0; i < lpBuffer.Length; i++) { //Create a new array to copy potential matches to byte[] tempArray = new byte[pattern.Length]; if (lpBuffer[i] == pattern[0]) { if ((lpBuffer.Length - lpBuffer[i]) < pattern.Length) { continue; } for (int x = 0; x < pattern.Length; x++) { tempArray[x] = lpBuffer[i + x]; } if (wildcard) { bool match = true; for (int x = 0; x < pattern.Length; x++) { if (pattern[x] == tempArray[x] || pattern[x] == wildcardChar) { continue; } else { match = false; break; } } if (match) { offsetList.Add((IntPtr)i); } } else { if (Enumerable.SequenceEqual(tempArray, pattern)) { //Add the index of the byte[] to the offset list offsetList.Add((IntPtr)i); if (!findAll) { break; } } } } } offsets = offsetList.ToArray(); Handleapi.CloseHandle(processHandle); Marshal.FreeHGlobal(modInfoPtr); return(0); }