Beispiel #1
0
 private void OncePerComputerPerUser(DtoClientPolicy policy, EntityPolicyHistory history)
 {
     Logger.Debug(policy.Name + " Is Set To Run Once Per Computer Per User.");
     if (history == null)
     {
         Logger.Debug("Policy Has Never Been Run.  Adding To Run List.");
         _policiesToRun.Add(policy);
     }
     else if (policy.ReRunExisting)
     {
         Logger.Debug("Policy Is Set ReRun On Previously Completed Computers.");
         var hashHistory = _policyHistoryServices.GetLastPolicyRunForUserFromHash(policy.Hash, _currentUser);
         if (hashHistory == null)
         {
             Logger.Debug("This Policy's Hash Was Not Found In The History.  Adding To Run List.");
             _policiesToRun.Add(policy);
         }
         else
         {
             Logger.Debug("Policy Last Ran On " + hashHistory.LastRunTime);
             Logger.Debug("This Policy Has Already Ran With Forced ReRun.  Skipping");
         }
     }
     else
     {
         Logger.Debug("Policy Has Already Ran And Has Not Been Forced Run Again.  Skipping.");
         Logger.Debug("Policy Last Ran On " + history.LastRunTime);
     }
 }
Beispiel #2
0
 private void RunSingleModule(DtoClientPolicy policy)
 {
     new APICall().PolicyApi.UpdateLastSocketResult(new DtoStringResponse()
     {
         Value = "Instant Module Started Successfully"
     });
     new PolicyRunner(Toec_Common.Enum.EnumPolicy.Trigger.Checkin).Run(policy);
 }
Beispiel #3
0
 public PolicyCacher(DtoClientPolicy policy)
 {
     _policy                    = policy;
     _call                      = new APICall();
     _fileSystemService         = new ServiceFileSystem();
     _policyResult              = new DtoPolicyResult();
     _policyResult.PolicyResult = EnumPolicy.Result.Success;
     _policyResult.PolicyGuid   = policy.Guid;
     _policyResult.PolicyName   = policy.Name;
     _policyResult.PolicyHash   = policy.Hash;
 }
Beispiel #4
0
 public PolicyExecutor(DtoClientPolicy policy)
 {
     _policyResult               = new DtoPolicyResult();
     _policyResult.PolicyName    = policy.Name;
     _policyResult.PolicyGuid    = policy.Guid;
     _policyResult.PolicyHash    = policy.Hash;
     _policyResult.PolicyResult  = EnumPolicy.Result.Success;
     _policyResult.DeleteCache   = policy.RemoveInstallCache;
     _policyResult.ExecutionType = policy.ExecutionType;
     _policy = policy;
 }
Beispiel #5
0
 private bool IsTriggerStopError(DtoClientPolicy policy)
 {
     if (policy.ErrorAction == EnumPolicy.ErrorAction.AbortCurrentPolicy)
     {
         Logger.Error("Aborting Current Policy");
         return(false);
     }
     if (policy.ErrorAction == EnumPolicy.ErrorAction.AbortRemainingPolicies)
     {
         Logger.Error("Aborting All Remaining Policies");
         return(true);
     }
     return(false);
 }
Beispiel #6
0
        private void SetPolicyLogLevel(DtoClientPolicy policy)
        {
            if (policy.LogLevel == EnumPolicy.LogLevel.Full)
            {
                ((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Debug;
            }
            else if (policy.LogLevel == EnumPolicy.LogLevel.HiddenArguments)
            {
                ((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Info;
            }
            else
            {
                ((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Error;
            }

            ((Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty);
        }
Beispiel #7
0
        private List <int> GetPolicyModuleOrder(DtoClientPolicy policy)
        {
            var list = new List <int>();

            list.AddRange(policy.PrinterModules.Select(module => module.Order));
            list.AddRange(policy.SoftwareModules.Select(module => module.Order));
            list.AddRange(policy.ScriptModules.Select(module => module.Order));
            list.AddRange(policy.FileCopyModules.Select(module => module.Order));
            list.AddRange(policy.CommandModules.Select(module => module.Order));
            list.AddRange(policy.WuModules.Select(module => module.Order));
            list.AddRange(policy.MessageModules.Select(module => module.Order));

            var distictList = list.Distinct().ToList();

            distictList.Sort();
            return(distictList);
        }
Beispiel #8
0
        private void EveryXHours(DtoClientPolicy policy, EntityPolicyHistory history)
        {
            Logger.Debug(policy.Name + " Is Set To Run Every " + policy.SubFrequency + " Hours.");
            if (policy.ReRunExisting)
            {
                Logger.Debug("Policy Is Set ReRun On Previously Completed Computers.");
                var hashHistory = _policyHistoryServices.GetLastPolicyRunFromHash(policy.Hash);
                if (hashHistory == null)
                {
                    Logger.Debug("This Policy's Hash Was Not Found In The History.  Adding To Run List.");
                    _policiesToRun.Add(policy);
                    return;
                }
                else
                {
                    Logger.Debug("Policy Last Ran On " + hashHistory.LastRunTime);
                    Logger.Debug("This Policy Has Already Ran With Forced ReRun.  Skipping");
                    return;
                }
            }
            if (history == null)
            {
                Logger.Debug("Policy Has Never Been Run.  Adding To Run List.");
                _policiesToRun.Add(policy);
            }
            else
            {
                Logger.Debug("Policy Last Ran On " + history.LastRunTime);

                var limit = DateTime.UtcNow - TimeSpan.FromHours(policy.SubFrequency);

                if (history.LastRunTime.ToUniversalTime() < limit)
                {
                    Logger.Debug("It Has Been More Than " + policy.SubFrequency + " Hours Since The Last Run, Adding To Run List.");
                    _policiesToRun.Add(policy);
                }
                else
                {
                    Logger.Debug("This Policy Has Already Ran Within The Last " + policy.SubFrequency + " Hours.  Skipping");
                }
            }
        }
Beispiel #9
0
 private void OncePerDay(DtoClientPolicy policy, EntityPolicyHistory history)
 {
     Logger.Debug(policy.Name + " Is Set To Run Once Per Day.");
     if (policy.ReRunExisting)
     {
         Logger.Debug("Policy Is Set ReRun On Previously Completed Computers.");
         var hashHistory = _policyHistoryServices.GetLastPolicyRunFromHash(policy.Hash);
         if (hashHistory == null)
         {
             Logger.Debug("This Policy's Hash Was Not Found In The History.  Adding To Run List.");
             _policiesToRun.Add(policy);
             return;
         }
         else
         {
             Logger.Debug("Policy Last Ran On " + hashHistory.LastRunTime);
             Logger.Debug("This Policy Has Already Ran With Forced ReRun.  Skipping");
             return;
         }
     }
     if (history == null)
     {
         Logger.Debug("Policy Has Never Been Run.  Adding To Run List.");
         _policiesToRun.Add(policy);
     }
     else
     {
         Logger.Debug("Policy Last Ran On " + history.LastRunTime);
         //A new day is considered midnight, not necessarily 24 hours
         var todayStartTime = Convert.ToDateTime(DateTime.UtcNow.ToShortDateString()).ToUniversalTime();
         if (history.LastRunTime.ToUniversalTime() < todayStartTime)
         {
             Logger.Debug("Midnight Has Passed Since Last Run, Adding To Run List.");
             _policiesToRun.Add(policy);
         }
         else
         {
             Logger.Debug("This Policy Has Already Ran Within The Last Day.  Skipping");
         }
     }
 }
Beispiel #10
0
        private void OncePerWeek(DtoClientPolicy policy, EntityPolicyHistory history)
        {
            Logger.Debug(policy.Name + " Is Set To Run Once Per Week.");
            var currentDayOfWeek = (int)DateTime.Now.DayOfWeek;

            if (policy.ReRunExisting)
            {
                Logger.Debug("Policy Is Set ReRun On Previously Completed Computers.");
                var hashHistory = _policyHistoryServices.GetLastPolicyRunFromHash(policy.Hash);
                if (hashHistory == null)
                {
                    Logger.Debug("This Policy's Hash Was Not Found In The History.");
                    if (policy.FrequencyMissedAction == EnumPolicy.FrequencyMissedAction.NextOpportunity)
                    {
                        Logger.Debug("Policy Missed Action Is Set To Next Opportunity.  Adding To Run List.");
                        _policiesToRun.Add(policy);
                    }
                    else
                    {
                        Logger.Debug("Current Day Of Week: " + currentDayOfWeek);
                        Logger.Debug("Policy Run Day: " + policy.SubFrequency);
                        if (policy.SubFrequency == currentDayOfWeek)
                        {
                            Logger.Debug("Policy Matches Current Run Day.  Adding To Run List.");
                            _policiesToRun.Add(policy);
                        }
                        else
                        {
                            Logger.Debug("Policy's Run Day And Current Day Do Not Match.  Skipping");
                        }
                    }
                    return;
                }
            }

            if (history == null)
            {
                Logger.Debug("Policy Has Never Been Run");
                if (policy.FrequencyMissedAction == EnumPolicy.FrequencyMissedAction.NextOpportunity)
                {
                    Logger.Debug("Missed Action Is Next Opportunity.  Adding To Run List.");
                    _policiesToRun.Add(policy);
                }
                else
                {
                    Logger.Debug("Current Day Of Week: " + currentDayOfWeek);
                    Logger.Debug("Policy Run Day: " + policy.SubFrequency);
                    if (policy.SubFrequency == currentDayOfWeek)
                    {
                        Logger.Debug("Policy Matches Current Run Day.  Adding To Run List.");
                        _policiesToRun.Add(policy);
                    }
                    else
                    {
                        Logger.Debug("Policy's Run Day And Current Day Do Not Match.  Skipping");
                    }
                }
            }
            else
            {
                Logger.Debug("Policy Last Ran On " + history.LastRunTime);
                Logger.Debug("Current Day Of Week: " + currentDayOfWeek);
                Logger.Debug("Policy Run Day: " + policy.SubFrequency);
                if (DateTime.UtcNow - history.LastRunTime.ToUniversalTime() >= TimeSpan.FromDays(1))
                {
                    Logger.Debug("Policy Has Not Run Today.  Checking If It Is Scheduled For Today.");
                    if (policy.FrequencyMissedAction == EnumPolicy.FrequencyMissedAction.ScheduleDayOnly &&
                        policy.SubFrequency == currentDayOfWeek)
                    {
                        Logger.Debug("Policy's Scheduled Run Day Matches Today.  Adding To Run List.");
                        _policiesToRun.Add(policy);
                        return;
                    }
                    else
                    {
                        Logger.Debug("Policy's Run Day And Current Day Do Not Match.  Skipping");
                    }
                }
                if (DateTime.UtcNow - history.LastRunTime.ToUniversalTime() >= TimeSpan.FromDays(7))
                {
                    Logger.Debug("Policy Has Not Run In Over A Week.  Checking Missed Action.");
                    if (policy.FrequencyMissedAction == EnumPolicy.FrequencyMissedAction.NextOpportunity)
                    {
                        Logger.Debug("Missed Action Is Next Opportunity.  Adding To Run List.");
                        _policiesToRun.Add(policy);
                    }
                    else
                    {
                        Logger.Debug("Policy's Run Day And Current Day Do Not Match.  Skipping");
                    }
                }
            }
        }
Beispiel #11
0
        public bool Run(DtoClientPolicy singleModulePolicy = null)
        {
            if (singleModulePolicy == null)
            {
                _policiesToRun = _trigger == EnumPolicy.Trigger.Login
                    ? new APICall().LocalApi.GetLoginPolicies(Environment.UserDomainName + "\\" + Environment.UserName)
                    : new PolicySelector(_trigger, Environment.UserDomainName + "\\" + Environment.UserName).GetPoliciesToExecute();
            }
            else
            {
                _policiesToRun = new DtoTriggerResponse();
                _policiesToRun.Policies.Add(singleModulePolicy);
            }

            if (_policiesToRun == null)
            {
                Logger.Error("Error Trying To Parse Policies. Aborting Trigger: " + _trigger);
                return(false);
            }

            if (_policiesToRun.Policies.Count == 0)
            {
                Logger.Info(string.Format("No Policies For Trigger {0} Were Found For This Computer", _trigger));
                return(true);
            }

            DtoGobalSettings.PolicyIsRunning = true;
            bool cacheFailedWithTriggerStop = false;

            //Check for any conditions that will need cached
            var conditionNeedsCached = false;

            if (_policiesToRun.Policies.Any(x => x.MessageModules.Any()))
            {
                foreach (var messageModule in _policiesToRun.Policies.Select(x => x.MessageModules))
                {
                    if (messageModule.Any(x => x.Condition.Guid != null))
                    {
                        conditionNeedsCached = true;
                        break;
                    }
                }
            }
            if (_policiesToRun.Policies.Any(x => x.PrinterModules.Any()) && !conditionNeedsCached)
            {
                foreach (var printerModule in _policiesToRun.Policies.Select(x => x.PrinterModules))
                {
                    if (printerModule.Any(x => x.Condition.Guid != null))
                    {
                        conditionNeedsCached = true;
                        break;
                    }
                }
            }

            //Check if install of remote access needs cached
            var remotelyNeedsCached = false;

            if (_policiesToRun.Policies.Any(x => x.RemoteAccess == EnumPolicy.RemoteAccess.ForceReinstall))
            {
                remotelyNeedsCached = true;
            }
            else if (new ServiceSystemService().IsRemotelyInstalled())
            {
                remotelyNeedsCached = false;
            }
            else if (_policiesToRun.Policies.Any(x => x.RemoteAccess == EnumPolicy.RemoteAccess.Enabled))
            {
                remotelyNeedsCached = true;
            }

            //cache all policies first if any need cached
            if (_policiesToRun.Policies.Any(x =>
                                            x.SoftwareModules.Any() || x.FileCopyModules.Any() || x.WuModules.Any() || x.ScriptModules.Any() || x.CommandModules.Any()) || conditionNeedsCached || _policiesToRun.Policies.Any(x => x.Condition.Guid != null) || remotelyNeedsCached)
            {
                //grab a download slot
                Logger.Debug("Obtaining A Download Connection.");
                var downloadConRequest = new DtoDownloadConRequest();
                downloadConRequest.ComputerGuid = DtoGobalSettings.ClientIdentity.Guid;
                downloadConRequest.ComputerName = DtoGobalSettings.ClientIdentity.Name;
                downloadConRequest.ComServer    = DtoGobalSettings.ComServer;

                var downloadConnection = new DtoDownloadConnectionResult();
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    downloadConnection = new APICall().LocalApi.CreateDownloadConnection(downloadConRequest);
                }
                else
                {
                    downloadConnection = new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest);
                }
                var conAttempCounter = 0;
                while (downloadConnection.QueueIsFull || !downloadConnection.Success)
                {
                    if (!downloadConnection.Success)
                    {
                        Logger.Error("Could Not Obtain Download Connection. " + downloadConnection.ErrorMessage);
                        DtoGobalSettings.PolicyIsRunning = false;
                        return(true);
                    }
                    if (downloadConnection.QueueIsFull && conAttempCounter == 0)
                    {
                        Logger.Debug("Download Connections Are Full.  Will Retry Continuously Every 1 Minute For The Next 10 Minutes.");
                    }

                    Task.Delay(60 * 1000).Wait();
                    conAttempCounter++;
                    if (conAttempCounter == 10)
                    {
                        Logger.Debug("Download Connections Remain Filled.  Giving Up.  Will Retry At Next Checkin.");
                        return(true);
                    }
                    if (_trigger == EnumPolicy.Trigger.Login)
                    {
                        downloadConnection = new APICall().LocalApi.CreateDownloadConnection(downloadConRequest);
                    }
                    else
                    {
                        downloadConnection = new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest);
                    }
                }

                foreach (var policy in _policiesToRun.Policies)
                {
                    SetPolicyLogLevel(policy);

                    var cacheResult = new PolicyCacher(policy).Cache();
                    if (policy.SkipServerResult)
                    {
                        cacheResult.SkipServerResult = true;
                    }

                    if (policy.ExecutionType == EnumPolicy.ExecutionType.Cache)
                    {
                        _policyResults.Add(cacheResult);
                    }
                    if (cacheResult.PolicyResult != EnumPolicy.Result.Success)
                    {
                        if (IsTriggerStopError(policy))
                        {
                            cacheFailedWithTriggerStop = true;
                            break;
                        }
                    }
                }
                //release the download slot
                Logger.Debug("Releasing The Download Connection.");
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    new APICall().LocalApi.RemoveDownloadConnection(downloadConRequest);
                }
                else
                {
                    new APICall().PolicyApi.RemoveDownloadConnection(downloadConRequest);
                }
            }

            if (!cacheFailedWithTriggerStop)
            {
                foreach (var policy in _policiesToRun.Policies)
                {
                    SetPolicyLogLevel(policy);

                    if (policy.ExecutionType == EnumPolicy.ExecutionType.Cache)
                    {
                        Logger.Debug("Policy's Execution Type Is Cache Only And Will Not Install");
                        continue;
                    }

                    var policyResult = new PolicyExecutor(policy).Execute();
                    if (policy.SkipServerResult)
                    {
                        policyResult.SkipServerResult = true;
                    }
                    _policyResults.Add(policyResult);

                    if (policyResult.PolicyResult == EnumPolicy.Result.Failed)
                    {
                        if (IsTriggerStopError(policy))
                        {
                            break;
                        }
                    }

                    else if (policyResult.PolicyResult == EnumPolicy.Result.Success &&
                             policy.CompletedAction == EnumPolicy.CompletedAction.Reboot)
                    {
                        _reboot = true;
                        break;
                    }
                    else if (policyResult.PolicyResult == EnumPolicy.Result.Success &&
                             policy.CompletedAction == EnumPolicy.CompletedAction.RebootIfNoLogins)
                    {
                        _rebootNoLogins = true;
                        break;
                    }
                }
            }

            Logger.Info("Policies Complete.  Starting Policy Cleanup.");
            DtoGobalSettings.PolicyIsRunning = false;
            RecordResults();

            CleanupCache();

            //restore global log level
            ((Hierarchy)LogManager.GetRepository()).Root.Level = DtoGobalSettings.LogLevel;
            ((Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(
                EventArgs.Empty);

            if (_reboot)
            {
                Logger.Info("Policy Initiated Reboot.  Rebooting Now.");
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    new APICall().LocalApi.LogoutAllUsers();
                }
                else
                {
                    new ServiceUserTracker().LogoutAllUsers();
                }
                Process.Start("shutdown.exe", "/r /t " + DtoGobalSettings.ShutdownDelay);
            }

            if (_rebootNoLogins)
            {
                Logger.Info("Policy Initiated Reboot If No Users Are Logged In.");
                Logger.Info("Checking For Any Logged In Users.");
                if (_trigger != EnumPolicy.Trigger.Login)
                {
                    var users = new ServiceUserLogins().GetUsersLoggedIn();
                    if (users.Count > 0)
                    {
                        Logger.Info("User Found, Reboot Skipped.");
                    }
                    else
                    {
                        Logger.Info("No Users Found, Issuing Reboot Command.");
                        Process.Start("shutdown.exe", "/r /t " + DtoGobalSettings.ShutdownDelay);
                    }
                }
                else
                {
                    Logger.Info("User Found, Policy Is A Login Policy, Reboot Skipped.");
                }
            }
            return(true);
        }
Beispiel #12
0
 public ClientPolicyJson()
 {
     _policyService = new ServicePolicy();
     _clientPolicy  = new DtoClientPolicy();
 }
Beispiel #13
0
 public ModuleRemoteAccess(DtoClientPolicy policy)
 {
     _policy = policy;
 }