Esempio n. 1
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var taskName = request.DataStore.GetValue("TaskName");

            TaskCollection tasks = null;

            using (TaskService ts = new TaskService())
            {
                tasks = ts.RootFolder.GetTasks(new Regex(taskName));
                foreach (Task task in tasks)
                {
                    try
                    {
                        RunningTask runningTask = task.Run();
                        return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()));
                    }
                    catch (Exception e)
                    {
                        if (NTHelper.IsCredentialGuardEnabled())
                        {
                            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
                        }

                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "RunningTaskFailed"));
                    }
                }
            }

            // We should never return this
            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
        }
Esempio n. 2
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var taskName = request.DataStore.GetValue("TaskName");

            using (TaskService ts = new TaskService())
            {
                TaskCollection tasks = ts.RootFolder.GetTasks(new Regex(taskName));

                try
                {
                    if (tasks.Exists(taskName))
                    {
                        foreach (Task task in tasks)
                        {
                            if (task.Name.EqualsIgnoreCase(taskName))
                            {
                                if (task.State == TaskState.Running || task.State == TaskState.Queued)
                                {
                                    task.Stop();
                                    NTHelper.KillProcess("azurebcp");
                                }
                                ts.RootFolder.DeleteTask(taskName, false);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    return(new ActionResponse(ActionStatus.Failure, e));
                }

                return(new ActionResponse(ActionStatus.Success));
            }
        }
Esempio n. 3
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string domain        = Environment.GetEnvironmentVariable("USERDOMAIN");
            string user          = Environment.GetEnvironmentVariable("USERNAME");
            string domainAccount = $"{NTHelper.CleanDomain(domain)}\\{NTHelper.CleanUsername(user)}";

            return(new ActionResponse(ActionStatus.Success, domainAccount));
        }
Esempio n. 4
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            const int MAX_RETRIES = 15;

            // This loop tries to avoid an unknown task state, thinking it's transient
            Task task = null;

            for (int i = 0; i <= MAX_RETRIES; i++)
            {
                System.Threading.Thread.Sleep(100);
                task = GetScheduledTask(request.DataStore.GetValue("TaskName"));
                if (task == null)
                {
                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
                }

                if (task.State == TaskState.Unknown)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

            // Let it run
            if (task.State == TaskState.Queued || task.State == TaskState.Running)
            {
                return(new ActionResponse(ActionStatus.InProgress));
            }

            // If we're here, the task completed
            if (task.LastTaskResult == 0)
            {
                return(new ActionResponse(ActionStatus.Success));
            }

            // there was an error since we haven't exited above
            uploadLogs(request);
            if (NTHelper.IsCredentialGuardEnabled())
            {
                return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
            }

            // azurebcp exits with 0, 1, 2, the powershell script might return 1 - anything else must be a Windows error
            Exception e = (uint)task.LastTaskResult > 2 ?
                          new Exception($"Scheduled task exited with code {task.LastTaskResult}", new System.ComponentModel.Win32Exception(task.LastTaskResult)) :
                          new Exception($"Scheduled task exited with code {task.LastTaskResult}");

            ActionResponse response = new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "TaskSchedulerRunFailed");

            response.ExceptionDetail.LogLocation = FileUtility.GetLocalTemplatePath(request.Info.AppName);
            return(response);
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string taskName = request.DataStore.GetValue("TaskName");

            TaskCollection tasks = null;

            using (TaskService ts = new TaskService())
            {
                tasks = ts.RootFolder.GetTasks(new Regex(taskName));

                // We expect only one task to match
                foreach (Task task in tasks)
                {
                    switch (task.LastTaskResult)
                    {
                    case 0: return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()));

                    case 267014:
                        //zipLogs();
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(),
                                                  new Exception("The scheduled task was terminated by the user."),
                                                  "TaskSchedulerRunFailed"));

                    case 411:
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(),
                                                  new Exception("PowerShell version too low - please upgrade to latest version https://msdn.microsoft.com/en-us/powershell/wmf/5.0/requirements"),
                                                  "TaskSchedulerRunFailed"));
                    }

                    if (task.State == TaskState.Running)
                    {
                        return(new ActionResponse(ActionStatus.BatchNoState, JsonUtility.GetEmptyJObject()));
                    }

                    if (NTHelper.IsCredentialGuardEnabled())
                    {
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
                    }

                    //If we've encountered an error, copy the logs, zip them up, and send to blob
                    //zipLogs();

                    ActionResponse response = new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(),
                                                                 new Exception($"Scheduled task exited with code {task.LastTaskResult}"), "TaskSchedulerRunFailed");
                    response.ExceptionDetail.LogLocation = FileUtility.GetLocalTemplatePath(request.Info.AppName);

                    return(response);
                }
            }

            // We should never return this
            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string domain = string.IsNullOrEmpty(request.DataStore.GetValue("ImpersonationDomain"))
                ? Environment.GetEnvironmentVariable("USERDOMAIN")
                : request.DataStore.GetValue("ImpersonationDomain");
            string user = string.IsNullOrEmpty(request.DataStore.GetValue("ImpersonationUsername"))
                ? Environment.GetEnvironmentVariable("USERNAME")
                : request.DataStore.GetValue("ImpersonationUsername");

            string domainAccount = $"{NTHelper.CleanDomain(domain)}\\{NTHelper.CleanUsername(user)}";

            // This will throw an error if the permission cannot be granted
            NTPermissionUtility.SetRight(Environment.MachineName, domainAccount, NTPermissionUtility.LOGON_AS_BATCH_PERM, false);

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()));
        }
Esempio n. 7
0
        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Kill any running azurebcp
            NTHelper.KillProcess("azurebcp");

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            Parallel.ForEach(files, (currentFile) =>
            {
                string temppath = Path.Combine(destDirName, currentFile.Name);
                currentFile.CopyTo(temppath, true);
                FileInfo destination = new FileInfo(temppath);
                try
                {
                    if (destination.AlternateDataStreamExists("Zone.Identifier"))
                    {
                        destination.DeleteAlternateDataStream("Zone.Identifier");
                    }
                }
                catch { }
            });

            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
Esempio n. 8
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            // The status could change if we're patient
            System.Threading.Thread.Sleep(250);

            Task task = GetScheduledTask(request.DataStore.GetValue("TaskName"));

            if (task == null)
            {
                return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
            }

            // Let it run
            if (task.State == TaskState.Queued || task.State == TaskState.Running || task.State == TaskState.Unknown)
            {
                return(new ActionResponse(ActionStatus.InProgress));
            }

            switch (task.LastTaskResult)
            {
            case 0:
                return(new ActionResponse(ActionStatus.Success));

            case 0x00041303:     // SCHED_S_TASK_HAS_NOT_RUN: The task has not yet run.
            case 0x00041325:     // SCHED_S_TASK_QUEUED: The Task Scheduler service has asked the task to run
                return(new ActionResponse(ActionStatus.InProgress));

            default:
                // there was an error since we haven't exited above
                uploadLogs(request);
                if (NTHelper.IsCredentialGuardEnabled())
                {
                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
                }

                // azurebcp exits with 0, 1, 2, the powershell script might return 1 - anything else must be a Windows error
                Exception e = (uint)task.LastTaskResult > 2 ?
                              new Exception($"Scheduled task exited with code {task.LastTaskResult}", new System.ComponentModel.Win32Exception(task.LastTaskResult)) :
                              new Exception($"Scheduled task exited with code {task.LastTaskResult}");

                ActionResponse response = new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "TaskSchedulerRunFailed");
                response.ExceptionDetail.LogLocation = FileUtility.GetLocalTemplatePath(request.Info.AppName);
                return(response);
            }
        }
Esempio n. 9
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string domain   = NTHelper.CleanDomain(request.DataStore.GetValue("ImpersonationDomain"));
            string user     = NTHelper.CleanUsername(request.DataStore.GetValue("ImpersonationUsername"));
            string password = request.DataStore.GetValue("ImpersonationPassword");

            bool        isValid;
            ContextType context = Environment.MachineName.EqualsIgnoreCase(domain) ? ContextType.Machine : ContextType.Domain;

            using (PrincipalContext pc = new PrincipalContext(context, domain))
            {
                // validate the credentials
                isValid = pc.ValidateCredentials(user, password, ContextOptions.Negotiate);
            }

            return(isValid
                ? new ActionResponse(ActionStatus.Success)
                : new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "IncorrectNTCredentials"));
        }
Esempio n. 10
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var taskDescription = request.DataStore.GetValue("TaskDescription");
            var taskFile        = request.DataStore.GetValue("TaskFile");
            var taskName        = request.DataStore.GetValue("TaskName");
            var taskParameters  = request.DataStore.GetValue("TaskParameters");
            var taskProgram     = request.DataStore.GetValue("TaskProgram");
            var taskStartTime   = request.DataStore.GetValue("TaskStartTime");

            var taskUsername = request.DataStore.GetValue("ImpersonationUsername") == null || string.IsNullOrEmpty(request.DataStore.GetValue("ImpersonationUsername"))
                ? WindowsIdentity.GetCurrent().Name
                : NTHelper.CleanDomain(request.DataStore.GetValue("ImpersonationDomain")) + "\\" + NTHelper.CleanUsername(request.DataStore.GetValue("ImpersonationUsername"));
            var taskPassword = request.DataStore.GetValue("ImpersonationPassword") == null || string.IsNullOrEmpty(request.DataStore.GetValue("ImpersonationPassword"))
                ? null
                : request.DataStore.GetValue("ImpersonationPassword");

            if (taskPassword == null)
            {
                return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CreateTaskPasswordMissing"));
            }

            string workingDirectory = request.DataStore.GetValue("TaskDirectory") == null
                ? FileUtility.GetLocalTemplatePath(request.Info.AppName)
                : FileUtility.GetLocalPath(request.DataStore.GetValue("TaskDirectory"));

            bool isPowerShell = taskProgram.EqualsIgnoreCase("powershell");

            using (TaskService ts = new TaskService())
            {
                TaskCollection tasks = ts.RootFolder.GetTasks(new Regex(taskName));
                foreach (Task task in tasks)
                {
                    if (task.Name.EqualsIgnoreCase(taskName))
                    {
                        ts.RootFolder.DeleteTask(taskName);
                    }
                }

                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = taskDescription;
                td.Settings.Compatibility       = TaskCompatibility.V2_1;
                td.RegistrationInfo.Author      = taskUsername;
                td.Principal.RunLevel           = TaskRunLevel.LUA;
                td.Settings.StartWhenAvailable  = true;
                td.Settings.RestartCount        = 3;
                td.Settings.RestartInterval     = TimeSpan.FromMinutes(3);
                td.Settings.MultipleInstances   = TaskInstancesPolicy.IgnoreNew;

                td.Triggers.Add(new DailyTrigger
                {
                    DaysInterval  = 1,
                    StartBoundary = DateTime.Parse(taskStartTime)
                });

                string optionalArguments = string.Empty;

                if (isPowerShell)
                {
                    optionalArguments = Path.Combine(workingDirectory, taskFile);
                }
                else
                {
                    taskProgram = taskFile;
                }

                if (isPowerShell)
                {
                    optionalArguments = $"-ExecutionPolicy Bypass -File \"{optionalArguments}\"";
                }

                if (!string.IsNullOrEmpty(taskParameters))
                {
                    optionalArguments += " " + taskParameters;
                }

                td.Actions.Add(new ExecAction(taskProgram, optionalArguments, workingDirectory));
                ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, taskUsername, taskPassword, TaskLogonType.Password, null);
            }

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()));
        }