예제 #1
0
 /// <summary>
 /// Kills the process.
 /// </summary>
 /// <param name="processName">Name of the process.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
 public bool KillProcess(string processName)
 {
     try
     {
         CDFMonitor.LogOutputHandler("DEBUG:KillProcess:enter:" + processName);
         var msQuery = new SelectQuery("SELECT * FROM Win32_Process "
                                       + "Where Name = '" + processName + "'"
                                       + "AND Handle != '" + Process.GetCurrentProcess().Id + "'");
         var searchProcedure = new ManagementObjectSearcher(_manScope, msQuery);
         foreach (ManagementObject item in searchProcedure.Get())
         {
             try
             {
                 item.InvokeMethod("Terminate", null);
             }
             catch (SystemException e)
             {
                 CDFMonitor.LogOutputHandler("DEBUG:KillProcess:exception:" + e.ToString());
                 return(false);
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         CDFMonitor.LogOutputHandler("Fail:KillProcess:exception:" + e.ToString());
         return(false);
     }
 }
예제 #2
0
        /// <summary>
        /// returns formatted string of processname(id). example explorer.exe(123)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetProcessNameFromId(uint id)
        {
            cacheLock.EnterReadLock();
            try
            {
                if ((int)id > 0 && _processList.Exists(p => p.Id == id))
                {
                    return(string.Format("{0}.exe({1})", _processList.First(p => p.Id == id).ProcessName, id));
                }
                else
                {
                    // wake up thread to get new list for next time
                    if (_processListThread.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
                    {
                        _processListThread.Interrupt();
                        _interruptCounter++;
                    }

                    return(id.ToString());
                }
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler(
                    string.Format("DEBUG:Exception:GetProcessNameFromId:{0}", e));

                return(id.ToString());
            }
            finally
            {
                cacheLock.ExitReadLock();
            }
        }
예제 #3
0
        /// <summary>
        /// Files the exists.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public static bool FileExists(string file)
        {
            try
            {
                string tempFilePath = GetFullPath(file);
                if (!string.IsNullOrEmpty(tempFilePath))
                {
                    if (CheckPath(tempFilePath, false))
                    {
                        if (File.Exists(file))
                        {
                            CDFMonitor.LogOutputHandler("DEBUG:FileExists:true:" + file);
                            return(true);
                        }
                    }
                }

                CDFMonitor.LogOutputHandler("DEBUG:FileExists:false:" + file);
                return(false);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:FileExists:exception:" + e.ToString());
                return(false);
            }
        }
예제 #4
0
        /// <summary>
        /// Gets the service config.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <returns>QUERY_SERVICE_CONFIG.</returns>
        public static QueryServiceConfig GetServiceConfig(string serviceName)
        {
            IntPtr scman    = OpenSCManager(ServiceManagerRights.AllAccess);
            IntPtr hService = OpenService(scman, serviceName, ServiceRights.QueryConfig);

            try
            {
                UInt32 dwBytesNeeded = 0;

                // Allocate memory for struct.
                IntPtr ptr = Marshal.AllocHGlobal(4096);

                if (!QueryServiceConfig(hService, ptr, 4096, out dwBytesNeeded))
                {
                    CDFMonitor.LogOutputHandler("Failed to query service config.");
                }

                QueryServiceConfig queryServiceConfig = new QueryServiceConfig();

                // Copy
                Marshal.PtrToStructure(ptr, queryServiceConfig);

                // Free memory for struct.
                Marshal.FreeHGlobal(ptr);
                return(queryServiceConfig);
            }
            finally
            {
                CloseServiceHandle(hService);
                CloseServiceHandle(scman);
            }
        }
예제 #5
0
        /// <summary>
        /// Runs the process.
        /// </summary>
        /// <param name="remoteCommand">The remote command.</param>
        /// <returns>System.Int32.</returns>
        public int RunProcess(string remoteCommand)
        {
            try
            {
                CDFMonitor.LogOutputHandler("Runprocess:enter:" + remoteCommand);

                var objectGetOptions          = new ObjectGetOptions();
                var managementPath            = new ManagementPath("Win32_Process");
                var processClass              = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
                inParams["CommandLine"] = remoteCommand;
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Creation of the process returned: " +
                                            outParams["returnValue"]);
                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Process ID: " + outParams["processId"]);

                return(Convert.ToInt32(outParams["processId"]));
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("Fail:Runprocess:exception:" + e.ToString());
                return(0);
            }
        }
예제 #6
0
        /// <summary>
        /// Populates Process Dictionary with Process ID and Process Name
        /// currently disabled
        /// </summary>
        private void PopulateProcessList()
        {
            cacheLock.EnterUpgradeableReadLock();
            try
            {
                _processList.Clear();

                foreach (Process process in Process.GetProcesses())
                {
                    if (process.Id < 1)
                    {
                        continue;
                    }

                    AddProcessToList(process);
                }
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler(
                    string.Format("DEBUG:Exception:PopulateProcessList:{0}", e));
            }
            finally
            {
                cacheLock.ExitUpgradeableReadLock();
            }
        }
예제 #7
0
        /// <summary>
        /// Prompts for credentials.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="host">The host.</param>
        /// <returns>NetworkCredential.</returns>
        public static NetworkCredential PromptForCredentials(string username, string password, string host)
        {
            CDFMonitor.LogOutputHandler(string.Format("DEBUG:PromptForCredentials: enter:{0}", host));
            if (CDFMonitor.Instance.Config.AppOperators.RunningAsService)
            {
                CDFMonitor.LogOutputHandler("ERROR:PromptForCredentials: called while running as a service. returning");
                return(new NetworkCredential(username, password, host));
            }
            var info = new CREDUI_INFO {
                pszCaptionText = host, pszMessageText = "Please Enter Your Credentials"
            };

            const CREDUI_FLAGS flags = CREDUI_FLAGS.GENERIC_CREDENTIALS |
                                       CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX;

            bool savePwd = false;

            GetCredentials(ref info, host, 0, ref username,
                           ref password, ref savePwd, flags);

            // Get domain  and username from username
            var sbUser = new StringBuilder(MAX_USER_NAME);

            sbUser.Append(username);
            var sbDomain = new StringBuilder(MAX_DOMAIN);

            sbDomain.Append(host);

            if (CredUIParseUserName(username, sbUser, MAX_USER_NAME, sbDomain, MAX_DOMAIN) == CredUIReturnCodes.NO_ERROR)
            {
                return(new NetworkCredential(sbUser.ToString(), password, sbDomain.ToString()));
            }
            return(new NetworkCredential(username, password, host));
        }
예제 #8
0
        /// <summary>
        /// Gets the SYSTEMROOT.
        /// </summary>
        /// <returns>System.String.</returns>
        public string GetSYSTEMROOT()
        {
            try
            {
                string retval                   = string.Empty;
                var    objectGetOptions         = new ObjectGetOptions();
                var    managementPath           = new ManagementPath("Win32_OperatingSystem");
                var    processClass             = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementObjectCollection objs = processClass.GetInstances();
                foreach (ManagementObject obj in objs)
                {
                    retval = obj["WindowsDirectory"].ToString();
                    break;
                }
                objs.Dispose();
                CDFMonitor.LogOutputHandler("DEBUG:GetSYSTEMROOT returned: " + retval);

                return(retval);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("GetSYSTEMROOT exception: " + e.ToString());
                return(string.Empty);
            }
        }
예제 #9
0
        /// <summary>
        /// Sets the se service logon right.
        /// </summary>
        /// <param name="wmi">The WMI.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private bool SetSeServiceLogonRight(WMIServicesManager wmi)
        {
            if (!CDFMonitor.Instance.Config.AppSettings.UseServiceCredentials)
            {
                return(true);
            }

            if (!string.IsNullOrEmpty(_creds.UserName) &&
                _creds.Domain != Properties.Resources.SessionName)
            {
                string userName = _creds.UserName.ToString();
                if (!string.IsNullOrEmpty(_creds.Domain) &&
                    !_creds.UserName.Contains(_creds.Domain))
                {
                    userName = string.Format("{0}\\{1}", _creds.Domain, _creds.UserName);
                }

                // get remote path string path = wmi.GetPath(Properties.Resources.ServiceName);

                int id = wmi.RunProcess(string.Format("{0}\\cdfmonitor\\cdfmonitor.exe /seservicelogonright: {1}", wmi.GetSYSTEMROOT(), userName));
                return(wmi.CheckProcess(_processName, id, true) == 0);
            }
            else
            {
                CDFMonitor.LogOutputHandler("skipping seservicelogonright");
            }

            return(true);
        }
예제 #10
0
        /// <summary>
        /// Sets the association.
        /// </summary>
        /// <param name="file">if specified, path and name of executable to use.</param>
        public static void SetAssociation(string file = null)
        {
            RegistryKey BaseKey;
            RegistryKey OpenMethod;
            RegistryKey Shell;

            RenameSubKey(Registry.ClassesRoot, _extension, _extensionBackup);
            CDFMonitor.LogOutputHandler("SetAssociation:enter");
            BaseKey = Registry.ClassesRoot.CreateSubKey(_extension);
            BaseKey.SetValue("", _keyName);

            OpenMethod = Registry.ClassesRoot.CreateSubKey(_keyName);
            OpenMethod.SetValue("", _fileDescription);

            if (!string.IsNullOrEmpty(file))
            {
                _openWith = file;
            }

            OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + _openWith + "\",0");
            Shell = OpenMethod.CreateSubKey("Shell");
            Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + _openWith + "\"" + " \"%1\"");
            Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + _openWith + "\"" + " \"%1\"");
            BaseKey.Close();
            OpenMethod.Close();
            Shell.Close();

            // Tell explorer the file association has been changed
            SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
        }
예제 #11
0
        /// <summary>
        /// Binds the client socket.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="serverPort">The server port.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private UdpClient BindClientSocket(string serverName, int serverPort)
        {
            UdpClient udpClient = new UdpClient();
            IPAddress serverIpAddress;

            try
            {
                if (WriterEnabled)
                {
                    IPAddress address;
                    if (IPAddress.TryParse(serverName, out address))
                    {
                        serverIpAddress = address;
                    }
                    else
                    {
                        serverIpAddress = Dns.GetHostAddresses(serverName)[0];
                    }

                    CDFMonitor.LogOutputHandler(string.Format("BindClientSocket:binding to:{0}:{1}", serverIpAddress, serverPort));
                    udpClient.Connect(new IPEndPoint(serverIpAddress, serverPort));
                }

                return(udpClient);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("BindClientSocket:exception:" + e.ToString());
                return(null);
            }
        }
예제 #12
0
        /// <summary>
        /// Returns cached ResourceCredential or generates new empty one
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>ResourceCredential.</returns>
        public ResourceCredential GetCredentials(string path)
        {
            string pathKey = path;
            Uri    uri;

            try
            {
                if (Uri.TryCreate(path, UriKind.Absolute, out uri))
                {
                    pathKey = uri.Host;
                }

                if (CredentialsList.ContainsKey(pathKey))
                {
                    return(CredentialsList[pathKey]);
                }
                else
                {
                    return(new ResourceCredential());
                }
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:GetCredentials:Exception:" + e.ToString());
                return(new ResourceCredential());
            }
        }
예제 #13
0
파일: FTP.cs 프로젝트: citrix/CDFMonitor
        // The EndGetResponseCallback method
        // completes a call to BeginGetResponse.
        /// <summary>
        /// Ends the get response callback.
        /// </summary>
        /// <param name="ar">The ar.</param>
        private void EndGetResponseCallback(IAsyncResult ar)
        {
            Status = "AsyncFTP:getting response.";
            CDFMonitor.LogOutputHandler(Status);
            var            state    = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;

                // Signal the main application thread that the operation is complete.
                state.OperationComplete.Set();
            }

            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                //Console.WriteLine("Error getting response.");
                Status = "AsyncFTP:Error getting response.";
                CDFMonitor.LogOutputHandler(Status);
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
예제 #14
0
        /// <summary>
        /// Verifies the trace file output.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="repair">if set to <c>true</c> [repair].</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool VerifyTraceFileOutput(ref string file, bool repair)
        {
            bool retval = true;

            if (_config.Activity == Configuration.ActivityType.TraceToEtl)
            {
                if (string.IsNullOrEmpty(file))
                {
                    CDFMonitor.LogOutputHandler(string.Format("Fail:Trace File Output does not exist but should for this activity type (etl):{0}", _config.AppSettings.Activity));
                    return(false);
                }
            }

            if (_config.Activity == Configuration.ActivityType.TraceToCsv ||
                _config.Activity == Configuration.ActivityType.RegexParseToCsv)
            {
                if (string.IsNullOrEmpty(file))
                {
                    if (repair)
                    {
                        CDFMonitor.LogOutputHandler(string.Format("Fail:Trace File Output is not configured but should for this activity:{0}", _config.Activity));
                        return(false);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler(string.Format("Warning:Trace File Output is not configured for this activity:{0}", _config.Activity));
                    }
                }
            }

            if (_config.Activity == Configuration.ActivityType.TraceToEtl)
            {
                // fix extension regardless of repair
                if (Path.GetExtension(file).ToLower() != ".etl")
                {
                    CDFMonitor.LogOutputHandler(string.Format("Trace File Output does does not have correct extension. fixing:{0}", file));
                    file = Regex.Replace(file, Path.GetExtension(file), ".etl", RegexOptions.IgnoreCase);
                }
            }
            else
            {
                // fix extension regardless of repair
                if (Path.GetExtension(file).ToLower() == ".etl")
                {
                    CDFMonitor.LogOutputHandler(string.Format("Trace File Output does does not have correct extension. fixing:{0}", file));
                    file = Regex.Replace(file, Path.GetExtension(file), ".csv", RegexOptions.IgnoreCase);
                }
            }

            if ((string.IsNullOrEmpty(file) && repair) ||
                (!string.IsNullOrEmpty(file) &&
                 !FileManager.CheckPath(file, true)))
            {
                retval = false;
            }

            retval &= AllLogsUnique();

            return(retval);
        }
예제 #15
0
        /// <summary>
        /// Stops the provided windows service
        /// </summary>
        /// <param name="Name">The service name that will be stopped</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public static bool StopService(string Name)
        {
            CDFMonitor.LogOutputHandler("StopService: entry");
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);

            try
            {
                IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |
                                              ServiceRights.Stop);
                if (hService == IntPtr.Zero)
                {
                    CDFMonitor.LogOutputHandler("Could not open service.");
                    return(false);
                }
                try
                {
                    StopService(hService);
                    return(true);
                }
                finally
                {
                    CDFMonitor.LogOutputHandler("StopService: exit");
                    CloseServiceHandle(hService);
                }
            }
            finally
            {
                CDFMonitor.LogOutputHandler("StopService: exit2");
                CloseServiceHandle(scman);
            }
        }
예제 #16
0
        /// <summary>
        /// Starts reading the ETW session events.
        /// </summary>
        /// <param name="state">The state.</param>
        public void ProcessTrace(object state)
        {
            Debug.Assert(_handle[0] != 0 && NativeMethods.IsValidHandle(_handle[0]),
                         "_handle[0] != 0 && NativeMethods.IsValidHandle(_handle[0])");

            long startFileTime = 0;
            long stopFileTime  = 0;
            uint ret           = 0;

            // Sometimes processtrace will return early presumably due to network issues or latency so keep retrying
            while (_running && _processTraceRetry > 0 && _handle[0] != 0)
            {
                if (_bufferCallback.LogfileHeader.BuffersWritten > 0 &&
                    (_onBufferReadCount == _bufferCallback.BuffersRead))
                {
                    break;
                }

                startFileTime = _bufferCallback.LogfileHeader.StartTime;
                CDFMonitor.LogOutputHandler(string.Format("ProcessTrace (re)starting ProcessTrace:{0}:{1}", startFileTime, _sessionName));
                ret = NativeMethods.ProcessTrace(_handle, _handle.Length, ref startFileTime, ref stopFileTime);
                _processTraceRetry--;

                if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                {
                    return;
                }
            }

            // Only call CloseTrace after ProcessTrace completes
            CloseTrace();
            CDFMonitor.LogOutputHandler("ProcessTrace return: " + ret);
        }
예제 #17
0
        /// <summary>
        /// WMI ctor
        /// </summary>
        /// <param name="remoteMachine">The remote machine.</param>
        /// <param name="rootpath">The rootpath.</param>
        /// <param name="creds">The creds.</param>
        public WMI(string remoteMachine, string rootpath = null, ResourceCredential creds = null)
        {
            try
            {
                // ResourceCredential tempcreds = creds ?? new ResourceCredential();
                ResourceCredential tempcreds = creds.Clone() ?? new ResourceCredential();

                _remoteMachine = remoteMachine;

                if (string.IsNullOrEmpty(rootpath))
                {
                    rootpath = @"\\{0}\ROOT\CIMV2";
                }

                SecureString securePassword = null;
                if (!string.IsNullOrEmpty(tempcreds.UserName) && !string.IsNullOrEmpty(tempcreds.Password) &&
                    CDFMonitor.Instance.Config.AppSettings.UseCredentials)
                {
                    unsafe
                    {
                        // Instantiate a new secure string.
                        fixed(char *pChars = tempcreds.Password.ToCharArray())
                        {
                            securePassword = new SecureString(pChars, tempcreds.Password.Length);
                        }
                    }
                }
                else
                {
                    tempcreds.UserName = null;
                    tempcreds.Password = null;
                    tempcreds.Domain   = null;
                }

                CDFMonitor.LogOutputHandler(string.Format("WMI using credentials: user:{0} domain:{1}", tempcreds.UserName, tempcreds.Domain));

                var options =
                    new ConnectionOptions("MS_409",
                                          string.IsNullOrEmpty(tempcreds.UserName) ? null : tempcreds.UserName,
                                          securePassword,
                                          string.IsNullOrEmpty(tempcreds.Domain)
                                              ? null
                                              : "ntlmdomain:" + tempcreds.Domain,
                                          ImpersonationLevel.Impersonate,
                                          AuthenticationLevel.Default,
                                          true,
                                          null,
                                          new TimeSpan(0, 0, 0, 0, CONNECT_TIMEOUT));

                _manScope = new ManagementScope(String.Format(rootpath, _remoteMachine), options);
                _manScope.Connect();
                Status = true;
                CDFMonitor.LogOutputHandler("DEBUG:WMI initialization: " + Status);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("WMI exception: " + e.ToString());
                Status = false;
            }
        }
예제 #18
0
        /// <summary>
        /// checks given timeout and returns false if timeout has elapsed. sleeps for SLEEP_TIME
        /// returns true if time still available.
        /// </summary>
        /// <param name="sleep">if set to <c>true</c> [sleep].</param>
        /// <param name="machine">The machine.</param>
        /// <param name="currentCount">The current count.</param>
        /// <param name="description">optional string description</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private bool CheckProgress(bool sleep, string machine, int currentCount, string description = null)
        {
            CDFMonitor.LogOutputHandler(string.Format("DEBUG:CheckTimer:enter:{0}:{1}:{2}", sleep, machine, currentCount));

            if (currentCount > _retry && _retry > 0)
            {
                CDFMonitor.LogOutputHandler("CheckTimer: remoteAction retry limit reached. exiting.");
                return(false);
            }

            if (string.IsNullOrEmpty(machine))
            {
                // All machines have been processed so return false
                return(false);
            }

            if (!CDFMonitor.ManageGuiWorker(100 * currentCount / RemoteList.Keys.Count, string.Format(" {0}: {1}: {2}", machine, RemoteList[machine], description)))
            {
                return(false);
            }

            if (sleep && CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
            {
                return(false);
            }

            return(true);
        }
예제 #19
0
        /// <summary>
        /// Checks utility credentials Looks in cache, tries windows cache, and then prompts.
        /// Returns CommandResults.Successful always unless exception.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns>CommandResults.</returns>
        private CommandResults CheckResourceCredentialsUtility(string path, bool force,
                                                               NetworkCredential credentials = null)
        {
            try
            {
                if (CredentialsList.ContainsKey(path) && !force)
                {
                    CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:returning cached authentication status");
                    return(CommandResults.Successful);
                }
                else if (CredentialsList.ContainsKey(path))
                {
                    CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:removing cached authentication");

                    CredentialsList.Remove(path);
                }

                if (string.IsNullOrEmpty(credentials.UserName) && string.IsNullOrEmpty(credentials.Password) && CanPromptForCredentials())
                {
                    credentials = Credentials.PromptForCredentials(credentials.UserName, credentials.Password, path);
                }

                CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:adding cached authentication:" + path);

                return(AddToCredentialList(credentials, path));
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtiltiy:Exception:" + e.ToString());
                return(AddToCredentialList(credentials, path, false, CommandResults.Fail));
            }
        }
예제 #20
0
        /// <summary>
        /// Converts to start mode.
        /// </summary>
        /// <param name="startMode">The start mode.</param>
        /// <param name="sm">The sm.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private bool ConvertToStartMode(string startMode, out WMIServicesManager.StartMode sm)
        {
            sm = new WMIServicesManager.StartMode();
            bool foundmode = false;

            if (string.IsNullOrEmpty(startMode))
            {
                return(false);
            }

            foreach (WMIServicesManager.StartMode mode in Enum.GetValues(typeof(WMIServicesManager.StartMode)))
            {
                if (string.Compare(mode.ToString(), startMode, true) == 0)
                {
                    foundmode = true;
                    sm        = mode;
                    break;
                }
            }

            if (!foundmode)
            {
                CDFMonitor.LogOutputHandler("Fail:ConvertToStartMode: unsuccessful.: " + startMode);
                return(false);
            }

            return(true);
        }
예제 #21
0
        /// <summary>
        /// Connects the unc path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns>System.Int32.</returns>
        private int ConnectUncPath(string path, NetworkCredential credentials)
        {
            CDFMonitor.LogOutputHandler("DEBUG:ConnectUncPath:enter:" + path);
            string userName = credentials.UserName;

            if (!string.IsNullOrEmpty(credentials.Domain))
            {
                userName = string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
            }

            if (GetPathType(path) != ResourceType.Unc)
            {
                return(-1);
            }

            DeterminePathObjType objectType = DeterminePathObj(path);

            if (objectType == DeterminePathObjType.File)
            {
                path = Path.GetDirectoryName(FileManager.GetFullPath(path));
                CDFMonitor.LogOutputHandler("DEBUG:ConnectUncPath:new path:" + path);
            }

            int ret = WindowsNetworking.ConnectToRemote(path,
                                                        userName,
                                                        credentials.Password, false);

            CDFMonitor.LogOutputHandler(string.Format("DEBUG:ConnectToRemote:return:{0}:{1}", path, ret == 0 ? true : false));
            return(ret);
        }
예제 #22
0
        /// <summary>
        /// Uninstalls the service.
        /// </summary>
        /// <param name="svcName">Name of the SVC.</param>
        /// <returns>ReturnValue.</returns>
        public ReturnValue UninstallService(string svcName)
        {
            CDFMonitor.LogOutputHandler("UnInstallService:enter");
            ReturnValue retval = ReturnValue.UnknownFailure;

            string objPath = string.Format("Win32_Service.Name='{0}'", svcName);

            using (ManagementObject service = new ManagementObject(ManScope, new ManagementPath(objPath), new ObjectGetOptions()))
            {
                try
                {
                    ManagementBaseObject outParams = service.InvokeMethod("delete", null, null);

                    retval = (ReturnValue)Enum.Parse(typeof(ReturnValue), outParams["ReturnValue"].ToString());
                    CDFMonitor.LogOutputHandler("UnInstallService:exit:" + retval);
                    return(retval);
                }
                catch (Exception ex)
                {
                    if (ex.Message.ToLower().Trim() == "not found" || ex.GetHashCode() == 41149443)
                    {
                        return(ReturnValue.ServiceNotFound);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("UninstallService:exception:" + ex.ToString());
                        return(ReturnValue.UnknownFailure);
                    }
                }
            }
        }
예제 #23
0
        /// <summary>
        /// adds process to _processList
        /// </summary>
        /// <param name="process"></param>
        private bool AddProcessToList(Process process)
        {
            cacheLock.EnterWriteLock();
            try
            {
                if (_processList.Exists(p => p.Id == process.Id))
                {
                    return(false);
                }

                // special perms for starttime?
                DateTime startTime = DateTime.Now;

                _processList.Add(new ProcessList()
                {
                    Id          = (uint)process.Id,
                    ProcessName = process.ProcessName, // + ".exe",
                    StartTime   = startTime
                });
                return(true);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler(
                    string.Format("DEBUG:Exception:AddProcessToList:{0}", e));
                return(false);
            }
            finally
            {
                cacheLock.ExitWriteLock();
            }
        }
예제 #24
0
        /// <summary>
        /// Reads a package zip file containing specified content and resource files.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool ExtractPackage(string packageName, string outputFolder, bool force = false)
        {
            CDFMonitor.LogOutputHandler("ReadPackage:processing package:" + packageName);

            try
            {
                if (!FileManager.FileExists(packageName))
                {
                    return(false);
                }

                // create subfolder for package files based on package name
                outputFolder = string.Format("{0}\\{1}", outputFolder, Path.GetFileNameWithoutExtension(packageName));

                if (FileManager.CheckPath(outputFolder))
                {
                    if (force)
                    {
                        FileManager.DeleteFolder(outputFolder);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("ReadPackage:output folder exists and no force. returning:" + packageName);
                        return(false);
                    }
                }

                if (!FileManager.CheckPath(outputFolder, true))
                {
                    return(false);
                }

                // Read the Package
                using (ZipPackage package = (ZipPackage)ZipPackage.Open(packageName, FileMode.Open))
                {
                    CDFMonitor.LogOutputHandler("ReadPackage:package open. retrieving parts");
                    foreach (PackagePart pP in package.GetParts())
                    {
                        DecompressStream(pP.GetStream(FileMode.Open, FileAccess.Read),
                                         string.Format("{0}\\{1}", outputFolder, pP.Uri.ToString().TrimStart('/')));
                    }
                }

                if (Directory.GetFiles(outputFolder).Length > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Status = e.ToString();
                CDFMonitor.LogOutputHandler("ReadPackage:exception:" + Status);
                return(false);
            }
        }
예제 #25
0
        /// <summary>
        /// Stars the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StartService(IntPtr hService)
        {
            CDFMonitor.LogOutputHandler("StartService entry.");
            var status = new SERVICE_STATUS();

            StartService(hService, 0, 0);
            WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);
        }
예제 #26
0
 /// <summary>
 /// ctor.
 /// </summary>
 /// <param name="sessionName">Name of the session.</param>
 public EtwTraceConsumer(string sessionName)
 {
     Debug.Assert(!String.IsNullOrEmpty(sessionName), "!String.IsNullOrEmpty(sessionName)");
     CDFMonitor.LogOutputHandler("DEBUG:EtwTraceConsumer.ctor: new trace:" + sessionName);
     _sessionName = sessionName;
     _eventTraceBufferCallback = OnBufferRead;
     _eventCallback            = OnTraceEvent;
 }
예제 #27
0
        /// <summary>
        /// Reads the registry modules.
        /// </summary>
        /// <param name="registryPath">The registry path.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        public Dictionary <string, string> ReadRegistryModules(string registryPath)
        {
            var  registryValues = new Dictionary <string, string>();
            bool hasAccess      = false;
            ManagementBaseObject outVals;

            try
            {
                CDFMonitor.LogOutputHandler("ReadRegistry:enter:" + registryPath);

                var objectGetOptions          = new ObjectGetOptions();
                var managementPath            = new ManagementPath("StdRegProv");
                var processClass              = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("CheckAccess");

                // Add the input parameters.
                // HKLM
                inParams["hDefKey"]     = 2147483650;
                inParams["sSubKeyName"] = registryPath;

                // Enumerate subkeys
                inParams["uRequired"] = 8;

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = processClass.InvokeMethod("CheckAccess", inParams, null);

                hasAccess = (bool)outParams["bGranted"];

                CDFMonitor.LogOutputHandler("bGranted: " + hasAccess);
                CDFMonitor.LogOutputHandler("ReturnValue: " + outParams["ReturnValue"]);

                if (hasAccess)
                {
                    // Read key
                    outVals = processClass.InvokeMethod("EnumKey", inParams, null);
                    var subkeys = (string[])outVals["sNames"];

                    inParams               = processClass.GetMethodParameters("GetStringValue");
                    inParams["hDefKey"]    = 0x80000002; // 2147483650;
                    inParams["sValueName"] = "GUID";

                    foreach (string key in subkeys)
                    {
                        inParams["sSubKeyName"] = registryPath + "\\" + key;
                        outVals = processClass.InvokeMethod("GetStringValue", inParams, null);
                        registryValues.Add((string)outVals["sValue"], key);
                    }
                }

                return(registryValues);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("Fail:ReadRegistry:exception:" + e.ToString());
                return(registryValues);
            }
        }
예제 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FileManager" /> class.
 /// </summary>
 /// <param name="job">The job.</param>
 public LogManager(WriterJob job)
 {
     _job        = job;
     _cdfMonitor = CDFMonitor.Instance;
     LogFileLock = new object();
     // TraceLogs = new string[0];
     Logs = new string[0];
     Init();
 }
예제 #29
0
        /// <summary>
        /// Waits for given service to be in desired state up to TIME_OUT. Returns
        /// ReturnValue.Success if successful.
        /// </summary>
        /// <param name="svcName">service name to wait on</param>
        /// <param name="serviceState">desired state</param>
        /// <returns>ReturnValue.</returns>
        private ReturnValue WaitForServiceState(string svcName, ServiceState serviceState)
        {
            CDFMonitor.LogOutputHandler("WaitForServiceState:enter");
            ReturnValue  retval            = ReturnValue.UnknownFailure;
            DateTime     timeout           = DateTime.Now.Add(new TimeSpan(0, 0, 0, 0, TIME_OUT));
            ServiceState intermediateState = ServiceState.Unknown;
            ServiceState currentState      = ServiceState.Unknown;

            switch (serviceState)
            {
            case ServiceState.Running:
                intermediateState = ServiceState.StartPending;
                break;

            case ServiceState.Stopped:
                intermediateState = ServiceState.StopPending;
                break;

            case ServiceState.Paused:
                intermediateState = ServiceState.PausePending;
                break;

            default:
                break;
            }

            while (DateTime.Now < timeout)
            {
                if ((currentState = GetServiceState(svcName)) == serviceState)
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:exit:success");

                    // even though service may be stopped we need to wait
                    if (serviceState == ServiceState.Stopped && CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                    {
                        return(ReturnValue.False);
                    }

                    return(ReturnValue.Success);
                }

                if (currentState != intermediateState)
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:invalid intermediate state:exit:fail");
                    return(ReturnValue.False);
                }

                if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:exit:fail");
                    return(ReturnValue.False);
                }
            }

            return(retval);
        }
예제 #30
0
        /// <summary>
        /// Uns the deploy.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool UnDeploy()
        {
            bool   retVal      = true;
            string destination = string.Empty;

            int i = 0;

            do
            {
                i++;

                foreach (string machine in new List <string>(RemoteList.Keys))
                {
                    if (RemoteList[machine] == RemoteStatus.UnDeployed)
                    {
                        CDFMonitor.LogOutputHandler(string.Format("UnDeploy: skipping machine {0} because of cached state: {1}", machine, RemoteList[machine]));
                        continue;
                    }

                    CDFMonitor.LogOutputHandler("UnDeploy: processing machine:" + machine + " state:" +
                                                RemoteList[machine].ToString());
                    WMIServicesManager wmi;
                    destination = "\\\\" + machine + "\\admin$\\cdfmonitor";
                    int pid = 0;

                    if (Ping(machine) &&
                        (wmi = new WMIServicesManager(machine, _creds)) != null &&
                        wmi.Status &&
                        (wmi.IsServiceInstalled(Resources.ServiceName) == WMIServicesManager.ReturnValue.True &&
                         wmi.StopService(Resources.ServiceName) == WMIServicesManager.ReturnValue.Success &&
                         wmi.UninstallService(Resources.ServiceName) == WMIServicesManager.ReturnValue.Success)
                        | (FileManager.CheckPath(destination, true)
                           &&
                           ((pid = wmi.RunProcess(string.Format("{0}\\cdfmonitor\\cdfmonitor.exe /clean", wmi.GetSYSTEMROOT()))) != 0
                            & wmi.CheckProcess(_processName, pid, true) == 0) &&
                           FileManager.DeleteFolder(destination, false)))
                    {
                        RemoteList[machine] = RemoteStatus.UnDeployed;
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("Fail:UnDeploy: unsuccessful.");
                        RemoteList[machine] = RemoteStatus.Error;
                        retVal = false;
                    }

                    if (!CheckProgress(false, machine, i))
                    {
                        return(retVal);
                    }
                }
            }while ((RemoteList.Count(v => v.Value == RemoteStatus.UnDeployed)) != RemoteList.Count && CheckProgress(true, string.Empty, i));

            return(retVal);
        }