Example #1
0
    public static List <ServiceInfo> GetServicesByPID(int pid)
    {
        bool doUpdate = false;

        if (pid == -1) // -1 means get all and we always want a fresh list
        {
            doUpdate = true;
        }
        else
        {
            ServiceCacheLock.EnterReadLock();
            doUpdate = ServiceCacheTime <= DateTime.FromFileTimeUtc(ProcFunc.GetProcessCreationTime(pid)).ToLocalTime();
            ServiceCacheLock.ExitReadLock();
        }
        if (doUpdate)
        {
            RefreshServices();
        }

        ServiceCacheLock.EnterReadLock();
        CloneableList <ServiceInfo> values;

        if (pid == -1)
        {
            values = ServiceCacheByPID.GetAllValues();
        }
        else if (!ServiceCacheByPID.TryGetValue(pid, out values))
        {
            values = null;
        }
        ServiceCacheLock.ExitReadLock();
        return((values != null && values.Count == 0) ? null : values);
    }
Example #2
0
        public void CleanUpProcesses()
        {
            DateTime TimeOut = DateTime.Now.AddMinutes(-1);

            // check all pids and remove all invalid entries
            foreach (var pid in Processes.Keys.ToList())
            {
                var info = Processes[pid];
                if (info.StopTime == null)
                {
                    string filePath = ProcFunc.GetProcessFileNameByPID(pid);
                    if (filePath == null)
                    {
                        info.StopTime = DateTime.Now;
                    }
                    else if (!filePath.Equals(info.filePath, StringComparison.OrdinalIgnoreCase)) // to quick pid reuse
                    {
                        AppLog.Debug("Possible PID conflict (pid {0} reused): {1}", pid, filePath);
                        Processes.Remove(pid);
                    }
                }
                else if (info.StopTime < TimeOut)
                {
                    Processes.Remove(pid);
                }
            }
        }
Example #3
0
        public string GetProcessFileNameByPID(int processID)
        {
            ProcInfo info;

            if (Processes.TryGetValue(processID, out info) && info.StopTime == null)
            {
                return(info.filePath);
            }

            string filePath = ProcFunc.GetProcessFileNameByPID(processID);

            if (filePath == null)
            {
                return(null);
            }

            var startTime = ProcFunc.GetProcessCreationTime(processID);

            if (startTime != 0)
            {
                if (info != null)
                {
                    Processes.Remove(processID);
                }
                Processes.Add(processID, new ProcInfo()
                {
                    filePath = filePath, StartTime = DateTime.FromFileTimeUtc(startTime)
                });
            }

            return(filePath);
        }
Example #4
0
        public ServiceInfo(ServiceController sc)
        {
            ServiceName = sc.ServiceName;
            var ImagePath = GetServiceImagePath(sc.ServiceName);

            ServicePath = ImagePath != null?ProcFunc.GetPathFromCmdLine(ImagePath) : "";

            DisplayName = sc.DisplayName;
            if (sc.Status == ServiceControllerStatus.Stopped)
            {
                LastKnownPID = -1;
            }
            else
            {
                var ssp = GetServiceStatus(sc.ServiceName);
                LastKnownPID = ssp != null ? (int)ssp.dwProcessId : -1;
            }
        }
Example #5
0
        public void Reload()
        {
            Services.Clear();

            Services.Add(new Service()
            {
                Content = Translate.fmt("svc_all"), Value = "*", Group = Translate.fmt("lbl_selec")
            });

            foreach (ServiceController svc in ServiceController.GetServices())
            {
                var ImagePath   = ServiceHelper.GetServiceImagePath(svc.ServiceName);
                var ServicePath = ImagePath != null?ProcFunc.GetPathFromCmdLine(ImagePath) : "";

                Services.Add(new Service()
                {
                    Value = svc.ServiceName, Path = ServicePath, Content = svc.DisplayName + " (" + svc.ServiceName + ")", Group = Translate.fmt("lbl_known")
                });
            }
        }
Example #6
0
    public string GetAppPackageByPID_(int PID)
    {
        // WARNING: this is not consistent with the windows firewall, we need to go by the proces token

        //var process = System.Diagnostics.Process.GetProcessById(PID); // throws error if pid is not found
        var processHandle = ProcFunc.OpenProcess(0x1000 /*PROCESS_QUERY_LIMITED_INFORMATION*/, false, PID);

        if (processHandle == IntPtr.Zero)
        {
            return(null);
        }

        uint          cchLen  = 256;
        StringBuilder sbName  = new StringBuilder((int)cchLen);
        Int32         lResult = GetApplicationUserModelId(processHandle, ref cchLen, sbName);

        if (ERROR_INSUFFICIENT_BUFFER == lResult)
        {
            sbName  = new StringBuilder((int)cchLen);
            lResult = GetApplicationUserModelId(processHandle, ref cchLen, sbName);
        }
        ProcFunc.CloseHandle(processHandle);

        if (lResult != ERROR_SUCCESS)
        {
            return(null);
        }

        string sResult = sbName.ToString();
        int    pos     = sResult.LastIndexOf("!"); // bla!App

        if (pos != -1)
        {
            sResult = sResult.Substring(0, pos);
        }

        return(sResult);
    }
Example #7
0
    public string GetAppPackageSidByPID(int PID)
    {
        //var process = System.Diagnostics.Process.GetProcessById(PID); // throws error if pid is not found
        var processHandle = ProcFunc.OpenProcess(0x1000 /*PROCESS_QUERY_LIMITED_INFORMATION*/, false, PID);

        if (processHandle == IntPtr.Zero)
        {
            return(null);
        }

        string strSID = null;

        IntPtr tokenHandle = IntPtr.Zero;

        if (ProcFunc.OpenProcessToken(processHandle, 8, out tokenHandle))
        {
            int retLen;
            NtQueryInformationToken(tokenHandle, 31 /*TokenAppContainerSid*/, IntPtr.Zero, 0, out retLen);

            IntPtr buffer = Marshal.AllocHGlobal((int)retLen);
            ulong  status = NtQueryInformationToken(tokenHandle, 31 /*TokenAppContainerSid*/, buffer, retLen, out retLen);
            if (status >= 0)
            {
                var appContainerInfo = (TOKEN_APPCONTAINER_INFORMATION)Marshal.PtrToStructure(buffer, typeof(TOKEN_APPCONTAINER_INFORMATION));

                ConvertSidToStringSid(appContainerInfo.Sid, ref strSID);
            }
            Marshal.FreeHGlobal(buffer);

            ProcFunc.CloseHandle(tokenHandle);
        }

        ProcFunc.CloseHandle(processHandle);

        return(strSID);
    }
Example #8
0
        string GetPathFromCmd(string commandLine, int processID, string imageName /*, DateTime timeStamp*/, int parentID = 0)
        {
            if (commandLine.Length == 0)
            {
                return(null);
            }

            string filePath = ProcFunc.GetPathFromCmdLine(commandLine);

            // apparently some processes can be started without a exe name in the command line WTF, anyhow:
            if (!Path.GetFileName(filePath).Equals(imageName, StringComparison.OrdinalIgnoreCase) &&
                !(Path.GetFileName(filePath) + ".exe").Equals(imageName, StringComparison.OrdinalIgnoreCase))
            {
                filePath = imageName;
            }

            // https://reverseengineering.stackexchange.com/questions/3798/c-question-marks-in-paths
            // \?? is a "fake" prefix which refers to per-user Dos devices
            if (filePath.IndexOf(@"\??\") == 0)
            {
                filePath = filePath.Substring(4);
            }

            filePath = Environment.ExpandEnvironmentVariables(filePath);

            if (Path.IsPathRooted(filePath))
            {
                return(filePath);
            }

            // The file path is not fully qualifyed

            // try to get the running processes path
            if (processID != 0)
            {
                //Process proc = null;
                //try { proc = Process.GetProcessById(processID); } catch { }
                //if (proc != null)
                //{
                //var fileName = proc.GetMainModuleFileName();
                var fileName = ProcFunc.GetProcessFileNameByPID(processID);
                if (fileName != null)
                {
                    // ensure its the right process
                    //var startTime = proc.StartTime.ToUniversalTime();
                    //if ((startTime - timeStamp).TotalSeconds < 1)
                    if (Path.GetFileName(fileName).Equals(imageName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(fileName);
                    }
                }
                //}
            }

            // check relative paths based on the parrent process working directory
            string workingDir = ProcessUtilities.GetCurrentDirectory(parentID);

            if (workingDir != null)
            {
                var curPath = Path.Combine(workingDir, filePath);
                if (filePath[0] == '.')
                {
                    curPath = Path.GetFullPath(curPath);
                }

                if (File.Exists(curPath))
                {
                    return(curPath);
                }
                if (File.Exists(curPath + ".exe"))
                {
                    return(curPath + ".exe");
                }
            }

            // if everythign else fails, try to find the process binary using the environment path variable
            if (FindExeInPath(filePath, ref filePath))
            {
                return(filePath);
            }

            return(null);
        }